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