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