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