]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
a1f6048f3b27113b697baa1c48c41c8e4334bc10
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 # Used to write to V2 inboxes (see L<public-inbox-v2-format(5)>).
6 package PublicInbox::V2Writable;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::Eml;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx qw(log2stack crlf_adjust is_ancestor check_size);
21 use IO::Handle; # ->autoflush
22 use File::Temp ();
23
24 my $OID = qr/[a-f0-9]{40,}/;
25 # an estimate of the post-packed size to the raw uncompressed size
26 my $PACKING_FACTOR = 0.4;
27
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space.  It can also lead to excessive IO latency
31 # and slow things down.  Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
35
36 sub detect_nproc () {
37         # getconf(1) is POSIX, but *NPROCESSORS* vars are not
38         for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
39                 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
40         }
41         for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
42                 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
43         }
44
45         # should we bother with `sysctl hw.ncpu`?  Those only give
46         # us total processor count, not online processor count.
47         undef
48 }
49
50 sub nproc_shards ($) {
51         my ($creat_opt) = @_;
52         my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
53         $n //= $ENV{NPROC};
54         if (!$n) {
55                 # assume 2 cores if not detectable or zero
56                 state $NPROC_DETECTED = detect_nproc() || 2;
57                 $n = $NPROC_DETECTED;
58                 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
59         }
60
61         # subtract for the main process and git-fast-import
62         $n -= 1;
63         $n < 1 ? 1 : $n;
64 }
65
66 sub count_shards ($) {
67         my ($self) = @_;
68         # always load existing shards in case core count changes:
69         # Also, shard count may change while -watch is running
70         my $srch = $self->{ibx}->search or return 0;
71         delete $self->{ibx}->{search};
72         $srch->{nshard} // 0
73 }
74
75 sub new {
76         # $creat may be any true value, or 0/undef.  A hashref is true,
77         # and $creat->{nproc} may be set to an integer
78         my ($class, $v2ibx, $creat) = @_;
79         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
80         my $dir = $v2ibx->assert_usable_dir;
81         unless (-d $dir) {
82                 if ($creat) {
83                         require File::Path;
84                         File::Path::mkpath($dir);
85                 } else {
86                         die "$dir does not exist\n";
87                 }
88         }
89         $v2ibx->umask_prepare;
90
91         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
92         my $self = {
93                 ibx => $v2ibx,
94                 im => undef, #  PublicInbox::Import
95                 parallel => 1,
96                 transact_bytes => 0,
97                 total_bytes => 0,
98                 current_info => '',
99                 xpfx => $xpfx,
100                 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
101                 lock_path => "$dir/inbox.lock",
102                 # limit each git repo (epoch) to 1GB or so
103                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
104                 last_commit => [], # git epoch -> commit
105         };
106         $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
107         $self->{shards} = count_shards($self) || nproc_shards($creat);
108         bless $self, $class;
109 }
110
111 # public (for now?)
112 sub init_inbox {
113         my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
114         if (defined $shards) {
115                 $self->{parallel} = 0 if $shards == 0;
116                 $self->{shards} = $shards if $shards > 0;
117         }
118         $self->idx_init;
119         $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
120         my $epoch_max = -1;
121         git_dir_latest($self, \$epoch_max);
122         if (defined $skip_epoch && $epoch_max == -1) {
123                 $epoch_max = $skip_epoch;
124         }
125         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
126         $self->done;
127 }
128
129 # returns undef on duplicate or spam
130 # mimics Import::add and wraps it for v2
131 sub add {
132         my ($self, $eml, $check_cb) = @_;
133         $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
134 }
135
136 # indexes a message, returns true if checkpointing is needed
137 sub do_idx ($$$$) {
138         my ($self, $msgref, $mime, $smsg) = @_;
139         $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
140         $self->{oidx}->add_overview($mime, $smsg);
141         my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
142         $idx->index_raw($msgref, $mime, $smsg);
143         my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
144         $n >= $self->{batch_bytes};
145 }
146
147 sub _add {
148         my ($self, $mime, $check_cb) = @_;
149
150         # spam check:
151         if ($check_cb) {
152                 $mime = $check_cb->($mime, $self->{ibx}) or return;
153         }
154
155         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
156         # as does SQLite 3.4.1+ (released in 2007-07-20), and
157         # Xapian 1.3.2+ (released 2015-03-15).
158         # For the most part, we can spawn git-fast-import without
159         # leaking FDs to it...
160         $self->idx_init;
161
162         my ($num, $mid0) = v2_num_for($self, $mime);
163         defined $num or return; # duplicate
164         defined $mid0 or die "BUG: \$mid0 undefined\n";
165         my $im = $self->importer;
166         my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
167         my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
168         $cmt = $im->get_mark($cmt);
169         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
170
171         my $msgref = delete $smsg->{-raw_email};
172         if (do_idx($self, $msgref, $mime, $smsg)) {
173                 $self->checkpoint;
174         }
175
176         $cmt;
177 }
178
179 sub v2_num_for {
180         my ($self, $mime) = @_;
181         my $mids = mids($mime);
182         if (@$mids) {
183                 my $mid = $mids->[0];
184                 my $num = $self->{mm}->mid_insert($mid);
185                 if (defined $num) { # common case
186                         return ($num, $mid);
187                 }
188
189                 # crap, Message-ID is already known, hope somebody just resent:
190                 foreach my $m (@$mids) {
191                         # read-only lookup now safe to do after above barrier
192                         # easy, don't store duplicates
193                         # note: do not add more diagnostic info here since
194                         # it gets noisy on public-inbox-watch restarts
195                         return () if content_exists($self, $mime, $m);
196                 }
197
198                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
199                 # or NNTP article number), use that article number if it's
200                 # not in Over.
201                 my $altid = $self->{ibx}->{altid};
202                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
203                         my $num = $self->{mm}->num_for($mid);
204
205                         if (defined $num && !$self->{oidx}->get_art($num)) {
206                                 return ($num, $mid);
207                         }
208                 }
209
210                 # very unlikely:
211                 warn "<$mid> reused for mismatched content\n";
212
213                 # try the rest of the mids
214                 for(my $i = $#$mids; $i >= 1; $i--) {
215                         my $m = $mids->[$i];
216                         $num = $self->{mm}->mid_insert($m);
217                         if (defined $num) {
218                                 warn "alternative <$m> for <$mid> found\n";
219                                 return ($num, $m);
220                         }
221                 }
222         }
223         # none of the existing Message-IDs are good, generate a new one:
224         v2_num_for_harder($self, $mime);
225 }
226
227 sub v2_num_for_harder {
228         my ($self, $eml) = @_;
229
230         my $dig = content_digest($eml);
231         my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
232         my $num = $self->{mm}->mid_insert($mid0);
233         unless (defined $num) {
234                 # it's hard to spoof the last Received: header
235                 my @recvd = $eml->header_raw('Received');
236                 $dig->add("Received: $_") foreach (@recvd);
237                 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
238                 $num = $self->{mm}->mid_insert($mid0);
239
240                 # fall back to a random Message-ID and give up determinism:
241                 until (defined($num)) {
242                         $dig->add(rand);
243                         $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
244                         warn "using random Message-ID <$mid0> as fallback\n";
245                         $num = $self->{mm}->mid_insert($mid0);
246                 }
247         }
248         PublicInbox::Import::append_mid($eml, $mid0);
249         ($num, $mid0);
250 }
251
252 sub idx_shard {
253         my ($self, $shard_i) = @_;
254         $self->{idx_shards}->[$shard_i];
255 }
256
257 sub _idx_init { # with_umask callback
258         my ($self, $opt) = @_;
259         $self->lock_acquire unless $opt && $opt->{-skip_lock};
260         $self->{oidx}->create;
261
262         # xcpdb can change shard count while -watch is idle
263         my $nshards = count_shards($self);
264         $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
265         $self->{batch_bytes} = $opt->{batch_size} //
266                                 $PublicInbox::SearchIdx::BATCH_BYTES;
267         $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
268
269         # need to create all shards before initializing msgmap FD
270         # idx_shards must be visible to all forked processes
271         my $max = $self->{shards} - 1;
272         my $idx = $self->{idx_shards} = [];
273         push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
274
275         # Now that all subprocesses are up, we can open the FDs
276         # for SQLite:
277         my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
278                                 "$self->{ibx}->{inboxdir}/msgmap.sqlite3",
279                                 $self->{ibx}->{-no_fsync} ? 2 : 1);
280         $mm->{dbh}->begin_work;
281 }
282
283 # idempotent
284 sub idx_init {
285         my ($self, $opt) = @_;
286         return if $self->{idx_shards};
287         my $ibx = $self->{ibx};
288
289         # do not leak read-only FDs to child processes, we only have these
290         # FDs for duplicate detection so they should not be
291         # frequently activated.
292         delete @$ibx{qw(mm search)};
293         $ibx->git->cleanup;
294
295         $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
296         if ($self->{parallel}) {
297                 pipe(my ($r, $w)) or die "pipe failed: $!";
298                 # pipe for barrier notifications doesn't need to be big,
299                 # 1031: F_SETPIPE_SZ
300                 fcntl($w, 1031, 4096) if $^O eq 'linux';
301                 $self->{bnote} = [ $r, $w ];
302                 $w->autoflush(1);
303         }
304
305         $ibx->umask_prepare;
306         $ibx->with_umask(\&_idx_init, $self, $opt);
307 }
308
309 # returns an array mapping [ epoch => latest_commit ]
310 # latest_commit may be undef if nothing was done to that epoch
311 # $replace_map = { $object_id => $strref, ... }
312 sub _replace_oids ($$$) {
313         my ($self, $mime, $replace_map) = @_;
314         $self->done;
315         my $pfx = "$self->{ibx}->{inboxdir}/git";
316         my $rewrites = []; # epoch => commit
317         my $max = $self->{epoch_max};
318
319         unless (defined($max)) {
320                 defined(my $latest = git_dir_latest($self, \$max)) or return;
321                 $self->{epoch_max} = $max;
322         }
323
324         foreach my $i (0..$max) {
325                 my $git_dir = "$pfx/$i.git";
326                 -d $git_dir or next;
327                 my $git = PublicInbox::Git->new($git_dir);
328                 my $im = $self->import_init($git, 0, 1);
329                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
330                 $im->done;
331         }
332         $rewrites;
333 }
334
335 sub content_hashes ($) {
336         my ($mime) = @_;
337         my @chashes = ( content_hash($mime) );
338
339         # We still support Email::MIME, here, and
340         # Email::MIME->as_string doesn't always round-trip, so we may
341         # use a second content_hash
342         my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
343         push @chashes, $rt if $chashes[0] ne $rt;
344         \@chashes;
345 }
346
347 sub content_matches ($$) {
348         my ($chashes, $existing) = @_;
349         my $chash = content_hash($existing);
350         foreach (@$chashes) {
351                 return 1 if $_ eq $chash
352         }
353         0
354 }
355
356 # used for removing or replacing (purging)
357 sub rewrite_internal ($$;$$$) {
358         my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
359         $self->idx_init;
360         my ($im, $need_reindex, $replace_map);
361         if ($sref) {
362                 $replace_map = {}; # oid => sref
363                 $need_reindex = [] if $new_eml;
364         } else {
365                 $im = $self->importer;
366         }
367         my $oidx = $self->{oidx};
368         my $chashes = content_hashes($old_eml);
369         my $removed = [];
370         my $mids = mids($old_eml);
371
372         # We avoid introducing new blobs into git since the raw content
373         # can be slightly different, so we do not need the user-supplied
374         # message now that we have the mids and content_hash
375         $old_eml = undef;
376         my $mark;
377
378         foreach my $mid (@$mids) {
379                 my %gone; # num => [ smsg, $mime, raw ]
380                 my ($id, $prev);
381                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
382                         my $msg = get_blob($self, $smsg);
383                         if (!defined($msg)) {
384                                 warn "broken smsg for $mid\n";
385                                 next; # continue
386                         }
387                         my $orig = $$msg;
388                         my $cur = PublicInbox::Eml->new($msg);
389                         if (content_matches($chashes, $cur)) {
390                                 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
391                         }
392                 }
393                 my $n = scalar keys %gone;
394                 next unless $n;
395                 if ($n > 1) {
396                         warn "BUG: multiple articles linked to <$mid>\n",
397                                 join(',', sort keys %gone), "\n";
398                 }
399                 foreach my $num (keys %gone) {
400                         my ($smsg, $mime, $orig) = @{$gone{$num}};
401                         # $removed should only be set once assuming
402                         # no bugs in our deduplication code:
403                         $removed = [ undef, $mime, $smsg ];
404                         my $oid = $smsg->{blob};
405                         if ($replace_map) {
406                                 $replace_map->{$oid} = $sref;
407                         } else {
408                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
409                                 $removed->[0] = $mark;
410                         }
411                         $orig = undef;
412                         if ($need_reindex) { # ->replace
413                                 push @$need_reindex, $smsg;
414                         } else { # ->purge or ->remove
415                                 $self->{mm}->num_delete($num);
416                         }
417                         unindex_oid_remote($self, $oid, $mid);
418                 }
419         }
420
421         if (defined $mark) {
422                 my $cmt = $im->get_mark($mark);
423                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
424         }
425         if ($replace_map && scalar keys %$replace_map) {
426                 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
427                 return { rewrites => $rewrites, need_reindex => $need_reindex };
428         }
429         defined($mark) ? $removed : undef;
430 }
431
432 # public (see PublicInbox::Import->remove), but note the 3rd element
433 # (retval[2]) is not part of the stable API shared with Import->remove
434 sub remove {
435         my ($self, $eml, $cmt_msg) = @_;
436         my $r = $self->{ibx}->with_umask(\&rewrite_internal,
437                                                 $self, $eml, $cmt_msg);
438         defined($r) && defined($r->[0]) ? @$r: undef;
439 }
440
441 sub _replace ($$;$$) {
442         my ($self, $old_eml, $new_eml, $sref) = @_;
443         my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
444         my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
445                         $self, $old_eml, undef, $new_eml, $sref) or return;
446
447         my $rewrites = $rewritten->{rewrites};
448         # ->done is called if there are rewrites since we gc+prune from git
449         $self->idx_init if @$rewrites;
450
451         for my $i (0..$#$rewrites) {
452                 defined(my $cmt = $rewrites->[$i]) or next;
453                 $self->{last_commit}->[$i] = $cmt;
454         }
455         $rewritten;
456 }
457
458 # public
459 sub purge {
460         my ($self, $mime) = @_;
461         my $rewritten = _replace($self, $mime, undef, \'') or return;
462         $rewritten->{rewrites}
463 }
464
465 # returns the git object_id of $fh, does not write the object to FS
466 sub git_hash_raw ($$) {
467         my ($self, $raw) = @_;
468         # grab the expected OID we have to reindex:
469         pipe(my($in, $w)) or die "pipe: $!";
470         my $git_dir = $self->{ibx}->git->{git_dir};
471         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
472         my $r = popen_rd($cmd, undef, { 0 => $in });
473         print $w $$raw or die "print \$w: $!";
474         close $w or die "close \$w: $!";
475         local $/ = "\n";
476         chomp(my $oid = <$r>);
477         close $r or die "git hash-object failed: $?";
478         $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
479         $oid;
480 }
481
482 sub _check_mids_match ($$$) {
483         my ($old_list, $new_list, $hdrs) = @_;
484         my %old_mids = map { $_ => 1 } @$old_list;
485         my %new_mids = map { $_ => 1 } @$new_list;
486         my @old = keys %old_mids;
487         my @new = keys %new_mids;
488         my $err = "$hdrs may not be changed when replacing\n";
489         die $err if scalar(@old) != scalar(@new);
490         delete @new_mids{@old};
491         delete @old_mids{@new};
492         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
493 }
494
495 # Changing Message-IDs or References with ->replace isn't supported.
496 # The rules for dealing with messages with multiple or conflicting
497 # Message-IDs are pretty complex and rethreading hasn't been fully
498 # implemented, yet.
499 sub check_mids_match ($$) {
500         my ($old, $new) = @_;
501         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
502         _check_mids_match(references($old), references($new),
503                         'References/In-Reply-To');
504 }
505
506 # public
507 sub replace ($$$) {
508         my ($self, $old_mime, $new_mime) = @_;
509
510         check_mids_match($old_mime, $new_mime);
511
512         # mutt will always add Content-Length:, Status:, Lines: when editing
513         PublicInbox::Import::drop_unwanted_headers($new_mime);
514
515         my $raw = $new_mime->as_string;
516         my $expect_oid = git_hash_raw($self, \$raw);
517         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
518         my $need_reindex = $rewritten->{need_reindex};
519
520         # just in case we have bugs in deduplication code:
521         my $n = scalar(@$need_reindex);
522         if ($n > 1) {
523                 my $list = join(', ', map {
524                                         "$_->{num}: <$_->{mid}>"
525                                 } @$need_reindex);
526                 warn <<"";
527 W: rewritten $n messages matching content of original message (expected: 1).
528 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
529 W: $list
530
531         }
532
533         # make sure we really got the OID:
534         my ($blob, $type, $bytes) = $self->{ibx}->git->check($expect_oid);
535         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
536
537         # don't leak FDs to Xapian:
538         $self->{ibx}->git->cleanup;
539
540         # reindex modified messages:
541         for my $smsg (@$need_reindex) {
542                 my $new_smsg = bless {
543                         blob => $blob,
544                         raw_bytes => $bytes,
545                         num => $smsg->{num},
546                         mid => $smsg->{mid},
547                 }, 'PublicInbox::Smsg';
548                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
549                 $new_smsg->populate($new_mime, $sync);
550                 do_idx($self, \$raw, $new_mime, $new_smsg);
551         }
552         $rewritten->{rewrites};
553 }
554
555 sub last_epoch_commit ($$;$) {
556         my ($self, $i, $cmt) = @_;
557         my $v = PublicInbox::Search::SCHEMA_VERSION();
558         $self->{mm}->last_commit_xap($v, $i, $cmt);
559 }
560
561 sub set_last_commits ($) {
562         my ($self) = @_;
563         defined(my $epoch_max = $self->{epoch_max}) or return;
564         my $last_commit = $self->{last_commit};
565         foreach my $i (0..$epoch_max) {
566                 defined(my $cmt = $last_commit->[$i]) or next;
567                 $last_commit->[$i] = undef;
568                 last_epoch_commit($self, $i, $cmt);
569         }
570 }
571
572 sub barrier_init {
573         my ($self, $n) = @_;
574         $self->{bnote} or return;
575         --$n;
576         my $barrier = { map { $_ => 1 } (0..$n) };
577 }
578
579 sub barrier_wait {
580         my ($self, $barrier) = @_;
581         my $bnote = $self->{bnote} or return;
582         my $r = $bnote->[0];
583         while (scalar keys %$barrier) {
584                 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
585                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
586                 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
587         }
588 }
589
590 # public
591 sub checkpoint ($;$) {
592         my ($self, $wait) = @_;
593
594         if (my $im = $self->{im}) {
595                 if ($wait) {
596                         $im->barrier;
597                 } else {
598                         $im->checkpoint;
599                 }
600         }
601         my $shards = $self->{idx_shards};
602         if ($shards) {
603                 my $dbh = $self->{mm}->{dbh};
604
605                 # SQLite msgmap data is second in importance
606                 $dbh->commit;
607
608                 # SQLite overview is third
609                 $self->{oidx}->commit_lazy;
610
611                 # Now deal with Xapian
612                 if ($wait) {
613                         my $barrier = $self->barrier_init(scalar @$shards);
614
615                         # each shard needs to issue a barrier command
616                         $_->shard_barrier for @$shards;
617
618                         # wait for each Xapian shard
619                         $self->barrier_wait($barrier);
620                 } else {
621                         $_->shard_commit for @$shards;
622                 }
623
624                 # last_commit is special, don't commit these until
625                 # remote shards are done:
626                 $dbh->begin_work;
627                 set_last_commits($self);
628                 $dbh->commit;
629
630                 $dbh->begin_work;
631         }
632         $self->{total_bytes} += $self->{transact_bytes};
633         $self->{transact_bytes} = 0;
634 }
635
636 # issue a write barrier to ensure all data is visible to other processes
637 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
638 # public
639 sub barrier { checkpoint($_[0], 1) };
640
641 # true if locked and active
642 sub active { !!$_[0]->{im} }
643
644 # public
645 sub done {
646         my ($self) = @_;
647         my $err = '';
648         if (my $im = delete $self->{im}) {
649                 eval { $im->done }; # PublicInbox::Import::done
650                 $err .= "import done: $@\n" if $@;
651         }
652         if (!$err) {
653                 eval { checkpoint($self) };
654                 $err .= "checkpoint: $@\n" if $@;
655         }
656         if (my $mm = delete $self->{mm}) {
657                 my $m = $err ? 'rollback' : 'commit';
658                 eval { $mm->{dbh}->$m };
659                 $err .= "msgmap $m: $@\n" if $@;
660         }
661         my $shards = delete $self->{idx_shards};
662         if ($shards) {
663                 for (@$shards) {
664                         eval { $_->shard_close };
665                         $err .= "shard close: $@\n" if $@;
666                 }
667         }
668         eval { $self->{oidx}->dbh_close };
669         $err .= "over close: $@\n" if $@;
670         delete $self->{bnote};
671         my $nbytes = $self->{total_bytes};
672         $self->{total_bytes} = 0;
673         $self->lock_release(!!$nbytes) if $shards;
674         $self->{ibx}->git->cleanup;
675         die $err if $err;
676 }
677
678 sub fill_alternates ($$) {
679         my ($self, $epoch) = @_;
680
681         my $pfx = "$self->{ibx}->{inboxdir}/git";
682         my $all = "$self->{ibx}->{inboxdir}/all.git";
683         PublicInbox::Import::init_bare($all) unless -d $all;
684         my $info_dir = "$all/objects/info";
685         my $alt = "$info_dir/alternates";
686         my (%alt, $new);
687         my $mode = 0644;
688         if (-e $alt) {
689                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
690                 $mode = (stat($fh))[2] & 07777;
691
692                 # we assign a sort score to every alternate and favor
693                 # the newest (highest numbered) one because loose objects
694                 # require scanning epochs and only the latest epoch is
695                 # expected to see loose objects
696                 my $score;
697                 my $other = 0; # in case admin adds non-epoch repos
698                 %alt = map {;
699                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
700                                 $score = $1 + 0;
701                         } else {
702                                 $score = --$other;
703                         }
704                         $_ => $score;
705                 } split(/\n+/, do { local $/; <$fh> });
706         }
707
708         foreach my $i (0..$epoch) {
709                 my $dir = "../../git/$i.git/objects";
710                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
711                         $alt{$dir} = $i;
712                         $new = 1;
713                 }
714         }
715         return unless $new;
716
717         my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
718         my $tmp = $fh->filename;
719         print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
720                 or die "print $tmp: $!\n";
721         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
722         close $fh or die "close $tmp $!\n";
723         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
724         $fh->unlink_on_destroy(0);
725 }
726
727 sub git_init {
728         my ($self, $epoch) = @_;
729         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
730         PublicInbox::Import::init_bare($git_dir);
731         my @cmd = (qw/git config/, "--file=$git_dir/config",
732                         'include.path', '../../all.git/config');
733         PublicInbox::Import::run_die(\@cmd);
734         fill_alternates($self, $epoch);
735         $git_dir
736 }
737
738 sub git_dir_latest {
739         my ($self, $max) = @_;
740         $$max = -1;
741         my $pfx = "$self->{ibx}->{inboxdir}/git";
742         return unless -d $pfx;
743         my $latest;
744         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
745         while (defined(my $git_dir = readdir($dh))) {
746                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
747                 if ($1 > $$max) {
748                         $$max = $1;
749                         $latest = "$pfx/$git_dir";
750                 }
751         }
752         $latest;
753 }
754
755 sub importer {
756         my ($self) = @_;
757         my $im = $self->{im};
758         if ($im) {
759                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
760                         return $im;
761                 } else {
762                         $self->{im} = undef;
763                         $im->done;
764                         $im = undef;
765                         $self->checkpoint;
766                         my $git_dir = $self->git_init(++$self->{epoch_max});
767                         my $git = PublicInbox::Git->new($git_dir);
768                         return $self->import_init($git, 0);
769                 }
770         }
771         my $epoch = 0;
772         my $max;
773         my $latest = git_dir_latest($self, \$max);
774         if (defined $latest) {
775                 my $git = PublicInbox::Git->new($latest);
776                 my $packed_bytes = $git->packed_bytes;
777                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
778
779                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
780                         $epoch = $max + 1;
781                 } else {
782                         $self->{epoch_max} = $max;
783                         return $self->import_init($git, $packed_bytes);
784                 }
785         }
786         $self->{epoch_max} = $epoch;
787         $latest = $self->git_init($epoch);
788         $self->import_init(PublicInbox::Git->new($latest), 0);
789 }
790
791 sub import_init {
792         my ($self, $git, $packed_bytes, $tmp) = @_;
793         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
794         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
795         $im->{lock_path} = undef;
796         $im->{path_type} = 'v2';
797         $self->{im} = $im unless $tmp;
798         $im;
799 }
800
801 # XXX experimental
802 sub diff ($$$) {
803         my ($mid, $cur, $new) = @_;
804
805         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
806         print $ah $cur->as_string or die "print: $!";
807         $ah->flush or die "flush: $!";
808         PublicInbox::Import::drop_unwanted_headers($new);
809         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
810         print $bh $new->as_string or die "print: $!";
811         $bh->flush or die "flush: $!";
812         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
813         print STDERR "# MID conflict <$mid>\n";
814         my $pid = spawn($cmd, undef, { 1 => 2 });
815         waitpid($pid, 0) == $pid or die "diff did not finish";
816 }
817
818 sub get_blob ($$) {
819         my ($self, $smsg) = @_;
820         if (my $im = $self->{im}) {
821                 my $msg = $im->cat_blob($smsg->{blob});
822                 return $msg if $msg;
823         }
824         # older message, should be in alternates
825         $self->{ibx}->msg_by_smsg($smsg);
826 }
827
828 sub content_exists ($$$) {
829         my ($self, $mime, $mid) = @_;
830         my $oidx = $self->{oidx};
831         my $chashes = content_hashes($mime);
832         my ($id, $prev);
833         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
834                 my $msg = get_blob($self, $smsg);
835                 if (!defined($msg)) {
836                         warn "broken smsg for $mid\n";
837                         next;
838                 }
839                 my $cur = PublicInbox::Eml->new($msg);
840                 return 1 if content_matches($chashes, $cur);
841
842                 # XXX DEBUG_DIFF is experimental and may be removed
843                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
844         }
845         undef;
846 }
847
848 sub atfork_child {
849         my ($self) = @_;
850         if (my $shards = $self->{idx_shards}) {
851                 $_->atfork_child foreach @$shards;
852         }
853         if (my $im = $self->{im}) {
854                 $im->atfork_child;
855         }
856         die "unexpected mm" if $self->{mm};
857         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
858         $self->{bnote}->[1];
859 }
860
861 sub reindex_checkpoint ($$) {
862         my ($self, $sync) = @_;
863
864         $self->{ibx}->git->cleanup; # *async_wait
865         ${$sync->{need_checkpoint}} = 0;
866         my $mm_tmp = $sync->{mm_tmp};
867         $mm_tmp->atfork_prepare if $mm_tmp;
868         $self->done; # release lock
869
870         if (my $pr = $sync->{-opt}->{-progress}) {
871                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
872         }
873
874         # allow -watch or -mda to write...
875         $self->idx_init($sync->{-opt}); # reacquire lock
876         $mm_tmp->atfork_parent if $mm_tmp;
877 }
878
879 sub index_oid { # cat_async callback
880         my ($bref, $oid, $type, $size, $arg) = @_;
881         return if $size == 0; # purged
882         my ($num, $mid0);
883         my $eml = PublicInbox::Eml->new($$bref);
884         my $mids = mids($eml);
885         my $chash = content_hash($eml);
886         my $self = $arg->{v2w};
887
888         if (scalar(@$mids) == 0) {
889                 warn "E: $oid has no Message-ID, skipping\n";
890                 return;
891         }
892
893         # {unindexed} is unlikely
894         if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
895                 $num = delete($unindexed->{$mids->[0]});
896                 if (defined $num) {
897                         $mid0 = $mids->[0];
898                         $self->{mm}->mid_set($num, $mid0);
899                         delete($arg->{unindexed}) if !keys(%$unindexed);
900                 }
901         }
902         if (!defined($num)) { # reuse if reindexing (or duplicates)
903                 my $oidx = $self->{oidx};
904                 for my $mid (@$mids) {
905                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
906                         last if defined $num;
907                 }
908         }
909         $mid0 //= do { # is this a number we got before?
910                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
911                 defined($num) ? $mids->[0] : undef;
912         };
913         if (!defined($num)) {
914                 for (my $i = $#$mids; $i >= 1; $i--) {
915                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
916                         if (defined($num)) {
917                                 $mid0 = $mids->[$i];
918                                 last;
919                         }
920                 }
921         }
922         if (defined($num)) {
923                 $arg->{mm_tmp}->num_delete($num);
924         } else { # never seen
925                 $num = $self->{mm}->mid_insert($mids->[0]);
926                 if (defined($num)) {
927                         $mid0 = $mids->[0];
928                 } else { # rare, try the rest of them, backwards
929                         for (my $i = $#$mids; $i >= 1; $i--) {
930                                 $num = $self->{mm}->mid_insert($mids->[$i]);
931                                 if (defined($num)) {
932                                         $mid0 = $mids->[$i];
933                                         last;
934                                 }
935                         }
936                 }
937         }
938         if (!defined($num)) {
939                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
940                 return;
941         }
942         ++${$arg->{nr}};
943         my $smsg = bless {
944                 raw_bytes => $size,
945                 num => $num,
946                 blob => $oid,
947                 mid => $mid0,
948         }, 'PublicInbox::Smsg';
949         $smsg->populate($eml, $arg);
950         if (do_idx($self, $bref, $eml, $smsg)) {
951                 ${$arg->{need_checkpoint}} = 1;
952         }
953 }
954
955 # only update last_commit for $i on reindex iff newer than current
956 sub update_last_commit ($$$$) {
957         my ($self, $git, $i, $cmt) = @_;
958         my $last = last_epoch_commit($self, $i);
959         if (defined $last && is_ancestor($git, $last, $cmt)) {
960                 my @cmd = (qw(rev-list --count), "$last..$cmt");
961                 chomp(my $n = $git->qx(@cmd));
962                 return if $n ne '' && $n == 0;
963         }
964         last_epoch_commit($self, $i, $cmt);
965 }
966
967 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
968
969 sub last_commits ($$) {
970         my ($self, $epoch_max) = @_;
971         my $heads = [];
972         for (my $i = $epoch_max; $i >= 0; $i--) {
973                 $heads->[$i] = last_epoch_commit($self, $i);
974         }
975         $heads;
976 }
977
978 # returns a revision range for git-log(1)
979 sub log_range ($$$$$) {
980         my ($self, $sync, $git, $i, $tip) = @_;
981         my $opt = $sync->{-opt};
982         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
983         my $cur = $sync->{ranges}->[$i] or do {
984                 $pr->("$i.git indexing all of $tip\n") if $pr;
985                 return $tip; # all of it
986         };
987
988         # fast equality check to avoid (v)fork+execve overhead
989         if ($cur eq $tip) {
990                 $sync->{ranges}->[$i] = undef;
991                 return;
992         }
993
994         my $range = "$cur..$tip";
995         $pr->("$i.git checking contiguity... ") if $pr;
996         if (is_ancestor($git, $cur, $tip)) { # common case
997                 $pr->("OK\n") if $pr;
998                 my $n = $git->qx(qw(rev-list --count), $range);
999                 chomp($n);
1000                 if ($n == 0) {
1001                         $sync->{ranges}->[$i] = undef;
1002                         $pr->("$i.git has nothing new\n") if $pr;
1003                         return; # nothing to do
1004                 }
1005                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1006         } else {
1007                 $pr->("FAIL\n") if $pr;
1008                 warn <<"";
1009 discontiguous range: $range
1010 Rewritten history? (in $git->{git_dir})
1011
1012                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1013                 if ($base) {
1014                         $range = "$base..$tip";
1015                         warn "found merge-base: $base\n"
1016                 } else {
1017                         $range = $tip;
1018                         warn "discarding history at $cur\n";
1019                 }
1020                 warn <<"";
1021 reindexing $git->{git_dir} starting at
1022 $range
1023
1024                 $sync->{unindex_range}->{$i} = "$base..$cur";
1025         }
1026         $range;
1027 }
1028
1029 sub sync_prepare ($$$) {
1030         my ($self, $sync, $epoch_max) = @_;
1031         my $pr = $sync->{-opt}->{-progress};
1032         my $regen_max = 0;
1033         my $head = $self->{ibx}->{ref_head} || 'refs/heads/master';
1034
1035         # reindex stops at the current heads and we later rerun index_sync
1036         # without {reindex}
1037         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1038
1039         for (my $i = $epoch_max; $i >= 0; $i--) {
1040                 my $git_dir = git_dir_n($self, $i);
1041                 -d $git_dir or next; # missing epochs are fine
1042                 my $git = PublicInbox::Git->new($git_dir);
1043                 if ($reindex_heads) {
1044                         $head = $reindex_heads->[$i] or next;
1045                 }
1046                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1047
1048                 next if $?; # new repo
1049                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1050                 # can't use 'rev-list --count' if we use --diff-filter
1051                 $pr->("$i.git counting $range ... ") if $pr;
1052                 # Don't bump num_highwater on --reindex by using {D}.
1053                 # We intentionally do NOT use {D} in the non-reindex case
1054                 # because we want NNTP article number gaps from unindexed
1055                 # messages to show up in mirrors, too.
1056                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1057                 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1058                 my $nr = $stk ? $stk->num_records : 0;
1059                 $pr->("$nr\n") if $pr;
1060                 $sync->{stacks}->[$i] = $stk if $stk;
1061                 $regen_max += $nr;
1062         }
1063
1064         # XXX this should not happen unless somebody bypasses checks in
1065         # our code and blindly injects "d" file history into git repos
1066         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1067                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1068                 my $arg = { v2w => $self };
1069                 my $all = $self->{ibx}->git;
1070                 for my $oid (@leftovers) {
1071                         $oid = unpack('H*', $oid);
1072                         $self->{current_info} = "leftover $oid";
1073                         $all->cat_async($oid, \&unindex_oid, $arg);
1074                 }
1075                 $all->cat_async_wait;
1076         }
1077         if (!$regen_max && !keys(%{$self->{unindex_range}})) {
1078                 $sync->{-regen_fmt} = "%u/?\n";
1079                 return 0;
1080         }
1081
1082         # reindex should NOT see new commits anymore, if we do,
1083         # it's a problem and we need to notice it via die()
1084         my $pad = length($regen_max) + 1;
1085         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1086         $sync->{nr} = \(my $nr = 0);
1087         return -1 if $sync->{reindex};
1088         $regen_max + $self->{mm}->num_highwater() || 0;
1089 }
1090
1091 sub unindex_oid_remote ($$$) {
1092         my ($self, $oid, $mid) = @_;
1093         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1094         for my $num (@removed) {
1095                 my $idx = idx_shard($self, $num % $self->{shards});
1096                 $idx->shard_remove($oid, $num);
1097         }
1098 }
1099
1100 sub unindex_oid ($$;$) { # git->cat_async callback
1101         my ($bref, $oid, $type, $size, $sync) = @_;
1102         my $self = $sync->{v2w};
1103         my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1104         my $mm = $self->{mm};
1105         my $mids = mids(PublicInbox::Eml->new($bref));
1106         undef $$bref;
1107         my $oidx = $self->{oidx};
1108         foreach my $mid (@$mids) {
1109                 my %gone;
1110                 my ($id, $prev);
1111                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1112                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1113                 }
1114                 my $n = scalar(keys(%gone)) or next;
1115                 if ($n > 1) {
1116                         warn "BUG: multiple articles linked to $oid\n",
1117                                 join(',',sort keys %gone), "\n";
1118                 }
1119                 foreach my $num (keys %gone) {
1120                         if ($unindexed) {
1121                                 my $mid0 = $mm->mid_for($num);
1122                                 $unindexed->{$mid0} = $num;
1123                         }
1124                         $mm->num_delete($num);
1125                 }
1126                 unindex_oid_remote($self, $oid, $mid);
1127         }
1128 }
1129
1130 # this is rare, it only happens when we get discontiguous history in
1131 # a mirror because the source used -purge or -edit
1132 sub unindex ($$$$) {
1133         my ($self, $sync, $git, $unindex_range) = @_;
1134         my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1135         my $before = scalar keys %$unindexed;
1136         # order does not matter, here:
1137         my @cmd = qw(log --raw -r
1138                         --no-notes --no-color --no-abbrev --no-renames);
1139         my $fh = $git->popen(@cmd, $unindex_range);
1140         my $all = $self->{ibx}->git;
1141         local $sync->{in_unindex} = 1;
1142         while (<$fh>) {
1143                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1144                 $all->cat_async($1, \&unindex_oid, $sync);
1145         }
1146         close $fh or die "git log failed: \$?=$?";
1147         $all->cat_async_wait;
1148
1149         return unless $sync->{-opt}->{prune};
1150         my $after = scalar keys %$unindexed;
1151         return if $before == $after;
1152
1153         # ensure any blob can not longer be accessed via dumb HTTP
1154         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1155                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1156 }
1157
1158 sub sync_ranges ($$$) {
1159         my ($self, $sync, $epoch_max) = @_;
1160         my $reindex = $sync->{reindex};
1161
1162         return last_commits($self, $epoch_max) unless $reindex;
1163         return [] if ref($reindex) ne 'HASH';
1164
1165         my $ranges = $reindex->{from}; # arrayref;
1166         if (ref($ranges) ne 'ARRAY') {
1167                 die 'BUG: $reindex->{from} not an ARRAY';
1168         }
1169         $ranges;
1170 }
1171
1172 sub index_xap_only { # git->cat_async callback
1173         my ($bref, $oid, $type, $size, $smsg) = @_;
1174         my $self = $smsg->{v2w};
1175         my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
1176         $smsg->{raw_bytes} = $size;
1177         $idx->index_raw($bref, undef, $smsg);
1178         $self->{transact_bytes} += $size;
1179 }
1180
1181 sub index_xap_step ($$$;$) {
1182         my ($self, $sync, $beg, $step) = @_;
1183         my $end = $sync->{art_end};
1184         return if $beg > $end; # nothing to do
1185
1186         $step //= $self->{shards};
1187         my $ibx = $self->{ibx};
1188         if (my $pr = $sync->{-opt}->{-progress}) {
1189                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1190                         "$beg..$end (% $step)\n");
1191         }
1192         for (my $num = $beg; $num <= $end; $num += $step) {
1193                 my $smsg = $ibx->over->get_art($num) or next;
1194                 $smsg->{v2w} = $self;
1195                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1196                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1197                         ${$sync->{nr}} = $num;
1198                         reindex_checkpoint($self, $sync);
1199                 }
1200         }
1201 }
1202
1203 sub index_epoch ($$$) {
1204         my ($self, $sync, $i) = @_;
1205
1206         my $git_dir = git_dir_n($self, $i);
1207         -d $git_dir or return; # missing epochs are fine
1208         my $git = PublicInbox::Git->new($git_dir);
1209         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1210                 unindex($self, $sync, $git, $unindex_range);
1211         }
1212         defined(my $stk = $sync->{stacks}->[$i]) or return;
1213         $sync->{stacks}->[$i] = undef;
1214         my $all = $self->{ibx}->git;
1215         while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1216                 $self->{current_info} = "$i.git $oid";
1217                 if ($f eq 'm') {
1218                         my $arg = { %$sync, autime => $at, cotime => $ct };
1219                         if ($sync->{max_size}) {
1220                                 $all->check_async($oid, \&check_size, $arg);
1221                         } else {
1222                                 $all->cat_async($oid, \&index_oid, $arg);
1223                         }
1224                 } elsif ($f eq 'd') {
1225                         $all->cat_async($oid, \&unindex_oid, $sync);
1226                 }
1227                 if (${$sync->{need_checkpoint}}) {
1228                         reindex_checkpoint($self, $sync);
1229                 }
1230         }
1231         $all->check_async_wait;
1232         $all->cat_async_wait;
1233         update_last_commit($self, $git, $i, $stk->{latest_cmt});
1234 }
1235
1236 sub xapian_only {
1237         my ($self, $opt, $sync, $art_beg) = @_;
1238         my $seq = $opt->{sequential_shard};
1239         $art_beg //= 0;
1240         local $self->{parallel} = 0 if $seq;
1241         $self->idx_init($opt); # acquire lock
1242         if (my $art_end = $self->{ibx}->mm->max) {
1243                 $sync //= {
1244                         need_checkpoint => \(my $bool = 0),
1245                         -opt => $opt,
1246                         v2w => $self,
1247                         nr => \(my $nr = 0),
1248                         -regen_fmt => "%u/?\n",
1249                 };
1250                 $sync->{art_end} = $art_end;
1251                 if ($seq || !$self->{parallel}) {
1252                         my $shard_end = $self->{shards} - 1;
1253                         for my $i (0..$shard_end) {
1254                                 index_xap_step($self, $sync, $art_beg + $i);
1255                                 if ($i != $shard_end) {
1256                                         reindex_checkpoint($self, $sync);
1257                                 }
1258                         }
1259                 } else { # parallel (maybe)
1260                         index_xap_step($self, $sync, $art_beg, 1);
1261                 }
1262         }
1263         $self->{ibx}->git->cat_async_wait;
1264         $self->done;
1265 }
1266
1267 # public, called by public-inbox-index
1268 sub index_sync {
1269         my ($self, $opt) = @_;
1270         $opt //= $_[1] //= {};
1271         goto \&xapian_only if $opt->{xapian_only};
1272
1273         my $pr = $opt->{-progress};
1274         my $epoch_max;
1275         my $latest = git_dir_latest($self, \$epoch_max);
1276         return unless defined $latest;
1277
1278         my $seq = $opt->{sequential_shard};
1279         my $art_beg; # the NNTP article number we start xapian_only at
1280         my $idxlevel = $self->{ibx}->{indexlevel};
1281         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1282
1283         $self->idx_init($opt); # acquire lock
1284         fill_alternates($self, $epoch_max);
1285         $self->{oidx}->rethread_prepare($opt);
1286         my $sync = {
1287                 need_checkpoint => \(my $bool = 0),
1288                 unindex_range => {}, # EPOCH => oid_old..oid_new
1289                 reindex => $opt->{reindex},
1290                 -opt => $opt,
1291                 v2w => $self,
1292         };
1293         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1294         if (sync_prepare($self, $sync, $epoch_max)) {
1295                 # tmp_clone seems to fail if inside a transaction, so
1296                 # we rollback here (because we opened {mm} for reading)
1297                 # Note: we do NOT rely on DBI transactions for atomicity;
1298                 # only for batch performance.
1299                 $self->{mm}->{dbh}->rollback;
1300                 $self->{mm}->{dbh}->begin_work;
1301                 $sync->{mm_tmp} =
1302                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1303
1304                 # xapian_only works incrementally w/o --reindex
1305                 if ($seq && !$opt->{reindex}) {
1306                         $art_beg = $sync->{mm_tmp}->max;
1307                         $art_beg++ if defined($art_beg);
1308                 }
1309         }
1310         if ($sync->{max_size} = $opt->{max_size}) {
1311                 $sync->{index_oid} = \&index_oid;
1312         }
1313         # work forwards through history
1314         index_epoch($self, $sync, $_) for (0..$epoch_max);
1315         $self->{oidx}->rethread_done($opt);
1316         $self->done;
1317
1318         if (my $nr = $sync->{nr}) {
1319                 my $pr = $sync->{-opt}->{-progress};
1320                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1321         }
1322
1323         # deal with Xapian shards sequentially
1324         if ($seq && delete($sync->{mm_tmp})) {
1325                 $self->{ibx}->{indexlevel} = $idxlevel;
1326                 xapian_only($self, $opt, $sync, $art_beg);
1327         }
1328
1329         # --reindex on the command-line
1330         if ($opt->{reindex} && !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1331                 $self->lock_acquire;
1332                 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1333                 if (my $xdb = $s0->idx_acquire) {
1334                         my $n = $xdb->get_metadata('has_threadid');
1335                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1336                 }
1337                 $s0->idx_release;
1338                 $self->lock_release;
1339         }
1340
1341         # reindex does not pick up new changes, so we rerun w/o it:
1342         if ($opt->{reindex}) {
1343                 my %again = %$opt;
1344                 $sync = undef;
1345                 delete @again{qw(rethread reindex -skip_lock)};
1346                 index_sync($self, \%again);
1347         }
1348 }
1349
1350 1;