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