]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
d04cdda6e3dc2eeaff75096fa92c25e0e96ecd0e
[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(
271                                 "$ibx->{inboxdir}/msgmap.sqlite3",
272                                 $ibx->{-no_fsync} ? 2 : 1);
273         $mm->{dbh}->begin_work;
274 }
275
276 sub parallel_init ($$) {
277         my ($self, $indexlevel) = @_;
278         $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
279 }
280
281 # idempotent
282 sub idx_init {
283         my ($self, $opt) = @_;
284         return if $self->{idx_shards};
285         my $ibx = $self->{ibx};
286
287         # do not leak read-only FDs to child processes, we only have these
288         # FDs for duplicate detection so they should not be
289         # frequently activated.
290         delete @$ibx{qw(mm search)};
291         $ibx->git->cleanup;
292
293         parallel_init($self, $ibx->{indexlevel});
294         $ibx->with_umask(\&_idx_init, $self, $opt);
295 }
296
297 # returns an array mapping [ epoch => latest_commit ]
298 # latest_commit may be undef if nothing was done to that epoch
299 # $replace_map = { $object_id => $strref, ... }
300 sub _replace_oids ($$$) {
301         my ($self, $mime, $replace_map) = @_;
302         $self->done;
303         my $ibx = $self->{ibx};
304         my $pfx = "$ibx->{inboxdir}/git";
305         my $rewrites = []; # epoch => commit
306         my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
307
308         foreach my $i (0..$max) {
309                 my $git_dir = "$pfx/$i.git";
310                 -d $git_dir or next;
311                 my $git = PublicInbox::Git->new($git_dir);
312                 my $im = $self->import_init($git, 0, 1);
313                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
314                 $im->done;
315         }
316         $rewrites;
317 }
318
319 sub content_hashes ($) {
320         my ($mime) = @_;
321         my @chashes = ( content_hash($mime) );
322
323         # We still support Email::MIME, here, and
324         # Email::MIME->as_string doesn't always round-trip, so we may
325         # use a second content_hash
326         my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
327         push @chashes, $rt if $chashes[0] ne $rt;
328         \@chashes;
329 }
330
331 sub content_matches ($$) {
332         my ($chashes, $existing) = @_;
333         my $chash = content_hash($existing);
334         foreach (@$chashes) {
335                 return 1 if $_ eq $chash
336         }
337         0
338 }
339
340 # used for removing or replacing (purging)
341 sub rewrite_internal ($$;$$$) {
342         my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
343         $self->idx_init;
344         my ($im, $need_reindex, $replace_map);
345         if ($sref) {
346                 $replace_map = {}; # oid => sref
347                 $need_reindex = [] if $new_eml;
348         } else {
349                 $im = $self->importer;
350         }
351         my $oidx = $self->{oidx};
352         my $chashes = content_hashes($old_eml);
353         my $removed = [];
354         my $mids = mids($old_eml);
355
356         # We avoid introducing new blobs into git since the raw content
357         # can be slightly different, so we do not need the user-supplied
358         # message now that we have the mids and content_hash
359         $old_eml = undef;
360         my $mark;
361
362         foreach my $mid (@$mids) {
363                 my %gone; # num => [ smsg, $mime, raw ]
364                 my ($id, $prev);
365                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
366                         my $msg = get_blob($self, $smsg);
367                         if (!defined($msg)) {
368                                 warn "broken smsg for $mid\n";
369                                 next; # continue
370                         }
371                         my $orig = $$msg;
372                         my $cur = PublicInbox::Eml->new($msg);
373                         if (content_matches($chashes, $cur)) {
374                                 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
375                         }
376                 }
377                 my $n = scalar keys %gone;
378                 next unless $n;
379                 if ($n > 1) {
380                         warn "BUG: multiple articles linked to <$mid>\n",
381                                 join(',', sort keys %gone), "\n";
382                 }
383                 foreach my $num (keys %gone) {
384                         my ($smsg, $mime, $orig) = @{$gone{$num}};
385                         # $removed should only be set once assuming
386                         # no bugs in our deduplication code:
387                         $removed = [ undef, $mime, $smsg ];
388                         my $oid = $smsg->{blob};
389                         if ($replace_map) {
390                                 $replace_map->{$oid} = $sref;
391                         } else {
392                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
393                                 $removed->[0] = $mark;
394                         }
395                         $orig = undef;
396                         if ($need_reindex) { # ->replace
397                                 push @$need_reindex, $smsg;
398                         } else { # ->purge or ->remove
399                                 $self->{mm}->num_delete($num);
400                         }
401                         unindex_oid_aux($self, $oid, $mid);
402                 }
403         }
404
405         if (defined $mark) {
406                 my $cmt = $im->get_mark($mark);
407                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
408         }
409         if ($replace_map && scalar keys %$replace_map) {
410                 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
411                 return { rewrites => $rewrites, need_reindex => $need_reindex };
412         }
413         defined($mark) ? $removed : undef;
414 }
415
416 # public (see PublicInbox::Import->remove), but note the 3rd element
417 # (retval[2]) is not part of the stable API shared with Import->remove
418 sub remove {
419         my ($self, $eml, $cmt_msg) = @_;
420         my $r = $self->{ibx}->with_umask(\&rewrite_internal,
421                                                 $self, $eml, $cmt_msg);
422         defined($r) && defined($r->[0]) ? @$r: undef;
423 }
424
425 sub _replace ($$;$$) {
426         my ($self, $old_eml, $new_eml, $sref) = @_;
427         my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
428         my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
429                         $self, $old_eml, undef, $new_eml, $sref) or return;
430
431         my $rewrites = $rewritten->{rewrites};
432         # ->done is called if there are rewrites since we gc+prune from git
433         $self->idx_init if @$rewrites;
434
435         for my $i (0..$#$rewrites) {
436                 defined(my $cmt = $rewrites->[$i]) or next;
437                 $self->{last_commit}->[$i] = $cmt;
438         }
439         $rewritten;
440 }
441
442 # public
443 sub purge {
444         my ($self, $mime) = @_;
445         my $rewritten = _replace($self, $mime, undef, \'') or return;
446         $rewritten->{rewrites}
447 }
448
449 sub _check_mids_match ($$$) {
450         my ($old_list, $new_list, $hdrs) = @_;
451         my %old_mids = map { $_ => 1 } @$old_list;
452         my %new_mids = map { $_ => 1 } @$new_list;
453         my @old = keys %old_mids;
454         my @new = keys %new_mids;
455         my $err = "$hdrs may not be changed when replacing\n";
456         die $err if scalar(@old) != scalar(@new);
457         delete @new_mids{@old};
458         delete @old_mids{@new};
459         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
460 }
461
462 # Changing Message-IDs or References with ->replace isn't supported.
463 # The rules for dealing with messages with multiple or conflicting
464 # Message-IDs are pretty complex and rethreading hasn't been fully
465 # implemented, yet.
466 sub check_mids_match ($$) {
467         my ($old, $new) = @_;
468         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
469         _check_mids_match(references($old), references($new),
470                         'References/In-Reply-To');
471 }
472
473 # public
474 sub replace ($$$) {
475         my ($self, $old_mime, $new_mime) = @_;
476
477         check_mids_match($old_mime, $new_mime);
478
479         # mutt will always add Content-Length:, Status:, Lines: when editing
480         PublicInbox::Import::drop_unwanted_headers($new_mime);
481
482         my $raw = $new_mime->as_string;
483         my $expect_oid = git_sha(1, \$raw)->hexdigest;
484         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
485         my $need_reindex = $rewritten->{need_reindex};
486
487         # just in case we have bugs in deduplication code:
488         my $n = scalar(@$need_reindex);
489         if ($n > 1) {
490                 my $list = join(', ', map {
491                                         "$_->{num}: <$_->{mid}>"
492                                 } @$need_reindex);
493                 warn <<"";
494 W: rewritten $n messages matching content of original message (expected: 1).
495 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
496 W: $list
497
498         }
499
500         # make sure we really got the OID:
501         my ($blob, $type, $bytes) = $self->git->check($expect_oid);
502         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
503
504         # don't leak FDs to Xapian:
505         $self->git->cleanup;
506
507         # reindex modified messages:
508         for my $smsg (@$need_reindex) {
509                 my $new_smsg = bless {
510                         blob => $blob,
511                         num => $smsg->{num},
512                         mid => $smsg->{mid},
513                 }, 'PublicInbox::Smsg';
514                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
515                 $new_smsg->populate($new_mime, $sync);
516                 $new_smsg->set_bytes($raw, $bytes);
517                 do_idx($self, $new_mime, $new_smsg);
518         }
519         $rewritten->{rewrites};
520 }
521
522 sub last_epoch_commit ($$;$) {
523         my ($self, $i, $cmt) = @_;
524         my $v = PublicInbox::Search::SCHEMA_VERSION();
525         $self->{mm}->last_commit_xap($v, $i, $cmt);
526 }
527
528 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
529         my ($self) = @_;
530         defined(my $epoch_max = $self->{epoch_max}) or return;
531         my $last_commit = $self->{last_commit};
532         foreach my $i (0..$epoch_max) {
533                 defined(my $cmt = $last_commit->[$i]) or next;
534                 $last_commit->[$i] = undef;
535                 last_epoch_commit($self, $i, $cmt);
536         }
537 }
538
539 # public
540 sub checkpoint ($;$) {
541         my ($self, $wait) = @_;
542
543         if (my $im = $self->{im}) {
544                 if ($wait) {
545                         $im->barrier;
546                 } else {
547                         $im->checkpoint;
548                 }
549         }
550         my $shards = $self->{idx_shards};
551         if ($shards) {
552                 my $mm = $self->{mm};
553                 my $dbh = $mm->{dbh} if $mm;
554
555                 # SQLite msgmap data is second in importance
556                 $dbh->commit if $dbh;
557
558                 # SQLite overview is third
559                 $self->{oidx}->commit_lazy;
560
561                 # Now deal with Xapian
562
563                 # start commit_txn_lazy asynchronously on all parallel shards
564                 # (non-parallel waits here)
565                 $_->ipc_do('commit_txn_lazy') for @$shards;
566
567                 # transactions started on parallel shards,
568                 # wait for them by issuing an echo command (echo can only
569                 # run after commit_txn_lazy is done)
570                 if ($wait && $self->{parallel}) {
571                         my $i = 0;
572                         for my $shard (@$shards) {
573                                 my $echo = $shard->ipc_do('echo', $i);
574                                 $echo == $i or die <<"";
575 shard[$i] bad echo:$echo != $i waiting for txn commit
576
577                                 ++$i;
578                         }
579                 }
580
581                 my $midx = $self->{midx}; # misc index
582                 if ($midx) {
583                         $midx->commit_txn;
584                         $PublicInbox::Search::X{CLOEXEC_UNSET} and
585                                 $self->git->cleanup;
586                 }
587
588                 # last_commit is special, don't commit these until
589                 # Xapian shards are done:
590                 $dbh->begin_work if $dbh;
591                 set_last_commits($self);
592                 if ($dbh) {
593                         $dbh->commit;
594                         $dbh->begin_work;
595                 }
596         }
597         $self->{total_bytes} += $self->{transact_bytes};
598         $self->{transact_bytes} = 0;
599 }
600
601 # issue a write barrier to ensure all data is visible to other processes
602 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
603 # public
604 sub barrier { checkpoint($_[0], 1) };
605
606 # true if locked and active
607 sub active { !!$_[0]->{im} }
608
609 # public
610 sub done {
611         my ($self) = @_;
612         my $err = '';
613         if (my $im = delete $self->{im}) {
614                 eval { $im->done }; # PublicInbox::Import::done
615                 $err .= "import done: $@\n" if $@;
616         }
617         if (!$err) {
618                 eval { checkpoint($self) };
619                 $err .= "checkpoint: $@\n" if $@;
620         }
621         if (my $mm = delete $self->{mm}) {
622                 my $m = $err ? 'rollback' : 'commit';
623                 eval { $mm->{dbh}->$m };
624                 $err .= "msgmap $m: $@\n" if $@;
625                 eval { $mm->{dbh}->do('PRAGMA optimize') };
626                 $err .= "msgmap optimize: $@\n" if $@;
627         }
628         if ($self->{oidx} && $self->{oidx}->{dbh}) {
629                 if ($err) {
630                         eval { $self->{oidx}->rollback_lazy };
631                         $err .= "overview rollback: $@\n" if $@;
632                 }
633                 eval { $self->{oidx}->{dbh}->do('PRAGMA optimize') };
634                 $err .= "overview optimize: $@\n" if $@;
635         }
636
637         my $shards = delete $self->{idx_shards};
638         if ($shards) {
639                 for (@$shards) {
640                         eval { $_->shard_close };
641                         $err .= "shard close: $@\n" if $@;
642                 }
643         }
644         eval { $self->{oidx}->dbh_close };
645         $err .= "over close: $@\n" if $@;
646         delete $self->{midx};
647         my $nbytes = $self->{total_bytes};
648         $self->{total_bytes} = 0;
649         $self->lock_release(!!$nbytes) if $shards;
650         $self->git->cleanup;
651         die $err if $err;
652 }
653
654 sub importer {
655         my ($self) = @_;
656         my $im = $self->{im};
657         if ($im) {
658                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
659                         return $im;
660                 } else {
661                         $self->{im} = undef;
662                         $im->done;
663                         $im = undef;
664                         $self->checkpoint;
665                         my $dir = $self->{mg}->add_epoch(++$self->{epoch_max});
666                         my $git = PublicInbox::Git->new($dir);
667                         return $self->import_init($git, 0);
668                 }
669         }
670         my $epoch = 0;
671         my $max;
672         my $latest = $self->{ibx}->git_dir_latest(\$max);
673         if (defined $latest) {
674                 my $git = PublicInbox::Git->new($latest);
675                 my $packed_bytes = $git->packed_bytes;
676                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
677
678                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
679                         $epoch = $max + 1;
680                 } else {
681                         $self->{epoch_max} = $max;
682                         return $self->import_init($git, $packed_bytes);
683                 }
684         }
685         $self->{epoch_max} = $epoch;
686         my $dir = $self->{mg}->add_epoch($epoch);
687         $self->import_init(PublicInbox::Git->new($dir), 0);
688 }
689
690 sub import_init {
691         my ($self, $git, $packed_bytes, $tmp) = @_;
692         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
693         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
694         $im->{lock_path} = undef;
695         $im->{path_type} = 'v2';
696         $self->{im} = $im unless $tmp;
697         $im;
698 }
699
700 # XXX experimental
701 sub diff ($$$) {
702         my ($mid, $cur, $new) = @_;
703
704         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXX', TMPDIR => 1);
705         print $ah $cur->as_string or die "print: $!";
706         $ah->flush or die "flush: $!";
707         PublicInbox::Import::drop_unwanted_headers($new);
708         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXX', TMPDIR => 1);
709         print $bh $new->as_string or die "print: $!";
710         $bh->flush or die "flush: $!";
711         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
712         print STDERR "# MID conflict <$mid>\n";
713         my $pid = spawn($cmd, undef, { 1 => 2 });
714         waitpid($pid, 0) == $pid or die "diff did not finish";
715 }
716
717 sub get_blob ($$) {
718         my ($self, $smsg) = @_;
719         if (my $im = $self->{im}) {
720                 my $msg = $im->cat_blob($smsg->{blob});
721                 return $msg if $msg;
722         }
723         # older message, should be in alternates
724         $self->{ibx}->msg_by_smsg($smsg);
725 }
726
727 sub content_exists ($$$) {
728         my ($self, $mime, $mid) = @_;
729         my $oidx = $self->{oidx};
730         my $chashes = content_hashes($mime);
731         my ($id, $prev);
732         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
733                 my $msg = get_blob($self, $smsg);
734                 if (!defined($msg)) {
735                         warn "broken smsg for $mid\n";
736                         next;
737                 }
738                 my $cur = PublicInbox::Eml->new($msg);
739                 return 1 if content_matches($chashes, $cur);
740
741                 # XXX DEBUG_DIFF is experimental and may be removed
742                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
743         }
744         undef;
745 }
746
747 sub atfork_child {
748         my ($self) = @_;
749         if (my $older_siblings = $self->{idx_shards}) {
750                 $_->ipc_sibling_atfork_child for @$older_siblings;
751         }
752         if (my $im = $self->{im}) {
753                 $im->atfork_child;
754         }
755         die "BUG: unexpected mm" if $self->{mm};
756 }
757
758 sub reindex_checkpoint ($$) {
759         my ($self, $sync) = @_;
760
761         $self->git->async_wait_all;
762         $self->update_last_commit($sync);
763         ${$sync->{need_checkpoint}} = 0;
764         my $mm_tmp = $sync->{mm_tmp};
765         $mm_tmp->atfork_prepare if $mm_tmp;
766         die 'BUG: {im} during reindex' if $self->{im};
767         if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
768                 checkpoint($self, 1); # no need to release lock on pure index
769         } else {
770                 $self->done; # release lock
771         }
772
773         if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
774                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
775         }
776
777         # allow -watch or -mda to write...
778         $self->idx_init($sync->{-opt}); # reacquire lock
779         if (my $intvl = $sync->{check_intvl}) { # eidx
780                 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
781         }
782         $mm_tmp->atfork_parent if $mm_tmp;
783 }
784
785 sub index_finalize ($$) {
786         my ($arg, $index) = @_;
787         ++$arg->{self}->{nidx};
788         if (defined(my $cur = $arg->{cur_cmt})) {
789                 ${$arg->{latest_cmt}} = $cur;
790         } elsif ($index) {
791                 die 'BUG: {cur_cmt} missing';
792         } # else { unindexing @leftovers doesn't set {cur_cmt}
793 }
794
795 sub index_oid { # cat_async callback
796         my ($bref, $oid, $type, $size, $arg) = @_;
797         is_bad_blob($oid, $type, $size, $arg->{oid}) and
798                 return index_finalize($arg, 1); # size == 0 purged returns here
799         my $self = $arg->{self};
800         local $self->{current_info} = "$self->{current_info} $oid";
801         my ($num, $mid0);
802         my $eml = PublicInbox::Eml->new($$bref);
803         my $mids = mids($eml);
804         my $chash = content_hash($eml);
805
806         if (scalar(@$mids) == 0) {
807                 warn "E: $oid has no Message-ID, skipping\n";
808                 return;
809         }
810
811         # {unindexed} is unlikely
812         if (my $unindexed = $arg->{unindexed}) {
813                 my $oidbin = pack('H*', $oid);
814                 my $u = $unindexed->{$oidbin};
815                 ($num, $mid0) = splice(@$u, 0, 2) if $u;
816                 if (defined $num) {
817                         $self->{mm}->mid_set($num, $mid0);
818                         if (scalar(@$u) == 0) { # done with current OID
819                                 delete $unindexed->{$oidbin};
820                                 delete($arg->{unindexed}) if !keys(%$unindexed);
821                         }
822                 }
823         }
824         if (!defined($num)) { # reuse if reindexing (or duplicates)
825                 my $oidx = $self->{oidx};
826                 for my $mid (@$mids) {
827                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
828                         last if defined $num;
829                 }
830         }
831         $mid0 //= do { # is this a number we got before?
832                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
833                 defined($num) ? $mids->[0] : undef;
834         };
835         if (!defined($num)) {
836                 for (my $i = $#$mids; $i >= 1; $i--) {
837                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
838                         if (defined($num)) {
839                                 $mid0 = $mids->[$i];
840                                 last;
841                         }
842                 }
843         }
844         if (defined($num)) {
845                 $arg->{mm_tmp}->num_delete($num);
846         } else { # never seen
847                 $num = $self->{mm}->mid_insert($mids->[0]);
848                 if (defined($num)) {
849                         $mid0 = $mids->[0];
850                 } else { # rare, try the rest of them, backwards
851                         for (my $i = $#$mids; $i >= 1; $i--) {
852                                 $num = $self->{mm}->mid_insert($mids->[$i]);
853                                 if (defined($num)) {
854                                         $mid0 = $mids->[$i];
855                                         last;
856                                 }
857                         }
858                 }
859         }
860         if (!defined($num)) {
861                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
862                 return;
863         }
864         ++${$arg->{nr}};
865         my $smsg = bless {
866                 num => $num,
867                 blob => $oid,
868                 mid => $mid0,
869         }, 'PublicInbox::Smsg';
870         $smsg->populate($eml, $arg);
871         $smsg->set_bytes($$bref, $size);
872         if (do_idx($self, $eml, $smsg)) {
873                 ${$arg->{need_checkpoint}} = 1;
874         }
875         index_finalize($arg, 1);
876 }
877
878 # only update last_commit for $i on reindex iff newer than current
879 sub update_last_commit {
880         my ($self, $sync, $stk) = @_;
881         my $unit = $sync->{unit} // return;
882         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
883         defined($latest_cmt) or return;
884         my $last = last_epoch_commit($self, $unit->{epoch});
885         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
886                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
887                 chomp(my $n = $unit->{git}->qx(@cmd));
888                 return if $n ne '' && $n == 0;
889         }
890         # don't rewind if --{since,until,before,after} are in use
891         return if (defined($last) &&
892                         grep(defined, @{$sync->{-opt}}{qw(since until)}) &&
893                         is_ancestor($self->git, $latest_cmt, $last));
894
895         last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
896 }
897
898 sub last_commits {
899         my ($self, $sync) = @_;
900         my $heads = [];
901         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
902                 $heads->[$i] = last_epoch_commit($self, $i);
903         }
904         $heads;
905 }
906
907 # returns a revision range for git-log(1)
908 sub log_range ($$$) {
909         my ($sync, $unit, $tip) = @_;
910         my $opt = $sync->{-opt};
911         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
912         my $i = $unit->{epoch};
913         my $cur = $sync->{ranges}->[$i] or do {
914                 $pr->("$i.git indexing all of $tip\n") if $pr;
915                 return $tip; # all of it
916         };
917
918         # fast equality check to avoid (v)fork+execve overhead
919         if ($cur eq $tip) {
920                 $sync->{ranges}->[$i] = undef;
921                 return;
922         }
923
924         my $range = "$cur..$tip";
925         $pr->("$i.git checking contiguity... ") if $pr;
926         my $git = $unit->{git};
927         if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
928                 $pr->("OK\n") if $pr;
929                 my $n = $git->qx(qw(rev-list --count), $range);
930                 chomp($n);
931                 if ($n == 0) {
932                         $sync->{ranges}->[$i] = undef;
933                         $pr->("$i.git has nothing new\n") if $pr;
934                         return; # nothing to do
935                 }
936                 $pr->("$i.git has $n changes since $cur\n") if $pr;
937         } else {
938                 $pr->("FAIL\n") if $pr;
939                 warn <<"";
940 discontiguous range: $range
941 Rewritten history? (in $git->{git_dir})
942
943                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
944                 if ($base) {
945                         $range = "$base..$tip";
946                         warn "found merge-base: $base\n"
947                 } else {
948                         $range = $tip;
949                         warn "discarding history at $cur\n";
950                 }
951                 warn <<"";
952 reindexing $git->{git_dir}
953 starting at $range
954
955                 # $cur^0 may no longer exist if pruned by git
956                 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
957                         $unit->{unindex_range} = "$base..$cur";
958                 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
959                         $unit->{unindex_range} = "$base..";
960                 } else {
961                         warn "W: unable to unindex before $range\n";
962                 }
963         }
964         $range;
965 }
966
967 # overridden by ExtSearchIdx
968 sub artnum_max { $_[0]->{mm}->num_highwater }
969
970 sub sync_prepare ($$) {
971         my ($self, $sync) = @_;
972         $sync->{ranges} = sync_ranges($self, $sync);
973         my $pr = $sync->{-opt}->{-progress};
974         my $regen_max = 0;
975         my $head = $sync->{ibx}->{ref_head} || 'HEAD';
976         my $pfx;
977         if ($pr) {
978                 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
979                 $pfx //= $sync->{ibx}->{inboxdir};
980         }
981
982         my $reindex_heads;
983         if ($self->{ibx_map}) {
984                 # ExtSearchIdx won't index messages unless they're in
985                 # over.sqlite3 for a given inbox, so don't read beyond
986                 # what's in the per-inbox index.
987                 $reindex_heads = [];
988                 my $v = PublicInbox::Search::SCHEMA_VERSION;
989                 my $mm = $sync->{ibx}->mm;
990                 for my $i (0..$sync->{epoch_max}) {
991                         $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
992                 }
993         } elsif ($sync->{reindex}) { # V2 inbox
994                 # reindex stops at the current heads and we later
995                 # rerun index_sync without {reindex}
996                 $reindex_heads = $self->last_commits($sync);
997         }
998         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
999                 $sync->{index_oid} = $self->can('index_oid');
1000         }
1001         my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1002         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1003                 my $git_dir = "$git_pfx/$i.git";
1004                 -d $git_dir or next; # missing epochs are fine
1005                 my $git = PublicInbox::Git->new($git_dir);
1006                 my $unit = { git => $git, epoch => $i };
1007                 my $tip;
1008                 if ($reindex_heads) {
1009                         $tip = $head = $reindex_heads->[$i] or next;
1010                 } else {
1011                         $tip = $git->qx(qw(rev-parse -q --verify), $head);
1012                         next if $?; # new repo
1013                         chomp $tip;
1014                 }
1015                 my $range = log_range($sync, $unit, $tip) or next;
1016                 # can't use 'rev-list --count' if we use --diff-filter
1017                 $pr->("$pfx $i.git counting $range ... ") if $pr;
1018                 # Don't bump num_highwater on --reindex by using {D}.
1019                 # We intentionally do NOT use {D} in the non-reindex case
1020                 # because we want NNTP article number gaps from unindexed
1021                 # messages to show up in mirrors, too.
1022                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1023                 my $stk = log2stack($sync, $git, $range);
1024                 return 0 if $sync->{quit};
1025                 my $nr = $stk ? $stk->num_records : 0;
1026                 $pr->("$nr\n") if $pr;
1027                 $unit->{stack} = $stk; # may be undef
1028                 unshift @{$sync->{todo}}, $unit;
1029                 $regen_max += $nr;
1030         }
1031         return 0 if $sync->{quit};
1032
1033         # XXX this should not happen unless somebody bypasses checks in
1034         # our code and blindly injects "d" file history into git repos
1035         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1036                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1037                 local $self->{current_info} = 'leftover ';
1038                 my $unindex_oid = $self->can('unindex_oid');
1039                 for my $oid (@leftovers) {
1040                         last if $sync->{quit};
1041                         $oid = unpack('H*', $oid);
1042                         my $req = { %$sync, oid => $oid };
1043                         $self->git->cat_async($oid, $unindex_oid, $req);
1044                 }
1045                 $self->git->async_wait_all;
1046         }
1047         return 0 if $sync->{quit};
1048         if (!$regen_max) {
1049                 $sync->{-regen_fmt} = "%u/?\n";
1050                 return 0;
1051         }
1052
1053         # reindex should NOT see new commits anymore, if we do,
1054         # it's a problem and we need to notice it via die()
1055         my $pad = length($regen_max) + 1;
1056         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1057         $sync->{nr} = \(my $nr = 0);
1058         return -1 if $sync->{reindex};
1059         $regen_max + $self->artnum_max || 0;
1060 }
1061
1062 sub unindex_oid_aux ($$$) {
1063         my ($self, $oid, $mid) = @_;
1064         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1065         return unless $self->{-need_xapian};
1066         for my $num (@removed) {
1067                 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1068         }
1069 }
1070
1071 sub unindex_oid ($$;$) { # git->cat_async callback
1072         my ($bref, $oid, $type, $size, $arg) = @_;
1073         is_bad_blob($oid, $type, $size, $arg->{oid}) and
1074                 return index_finalize($arg, 0);
1075         my $self = $arg->{self};
1076         local $self->{current_info} = "$self->{current_info} $oid";
1077         my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1078         my $mm = $self->{mm};
1079         my $mids = mids(PublicInbox::Eml->new($bref));
1080         undef $$bref;
1081         my $oidx = $self->{oidx};
1082         foreach my $mid (@$mids) {
1083                 my %gone;
1084                 my ($id, $prev);
1085                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1086                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1087                 }
1088                 my $n = scalar(keys(%gone)) or next;
1089                 if ($n > 1) {
1090                         warn "BUG: multiple articles linked to $oid\n",
1091                                 join(',',sort keys %gone), "\n";
1092                 }
1093                 # reuse (num => mid) mapping in ascending numeric order
1094                 for my $num (sort { $a <=> $b } keys %gone) {
1095                         $num += 0;
1096                         if ($unindexed) {
1097                                 my $mid0 = $mm->mid_for($num);
1098                                 my $oidbin = pack('H*', $oid);
1099                                 push @{$unindexed->{$oidbin}}, $num, $mid0;
1100                         }
1101                         $mm->num_delete($num);
1102                 }
1103                 unindex_oid_aux($self, $oid, $mid);
1104         }
1105         index_finalize($arg, 0);
1106 }
1107
1108 sub git { $_[0]->{ibx}->git }
1109
1110 # this is rare, it only happens when we get discontiguous history in
1111 # a mirror because the source used -purge or -edit
1112 sub unindex_todo ($$$) {
1113         my ($self, $sync, $unit) = @_;
1114         my $unindex_range = delete($unit->{unindex_range}) // return;
1115         my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1116         my $before = scalar keys %$unindexed;
1117         # order does not matter, here:
1118         my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1119                                 --no-abbrev --no-renames), $unindex_range);
1120         local $sync->{in_unindex} = 1;
1121         my $unindex_oid = $self->can('unindex_oid');
1122         while (<$fh>) {
1123                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1124                 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1125         }
1126         close $fh or die "git log failed: \$?=$?";
1127         $self->git->async_wait_all;
1128
1129         return unless $sync->{-opt}->{prune};
1130         my $after = scalar keys %$unindexed;
1131         return if $before == $after;
1132
1133         # ensure any blob can not longer be accessed via dumb HTTP
1134         run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1135                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1136 }
1137
1138 sub sync_ranges ($$) {
1139         my ($self, $sync) = @_;
1140         my $reindex = $sync->{reindex};
1141         return $self->last_commits($sync) unless $reindex;
1142         return [] if ref($reindex) ne 'HASH';
1143
1144         my $ranges = $reindex->{from}; # arrayref;
1145         if (ref($ranges) ne 'ARRAY') {
1146                 die 'BUG: $reindex->{from} not an ARRAY';
1147         }
1148         $ranges;
1149 }
1150
1151 sub index_xap_only { # git->cat_async callback
1152         my ($bref, $oid, $type, $size, $smsg) = @_;
1153         my $self = delete $smsg->{self};
1154         my $idx = idx_shard($self, $smsg->{num});
1155         $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1156         $self->{transact_bytes} += $smsg->{bytes};
1157 }
1158
1159 sub index_xap_step ($$$;$) {
1160         my ($self, $sync, $beg, $step) = @_;
1161         my $end = $sync->{art_end};
1162         return if $beg > $end; # nothing to do
1163
1164         $step //= $self->{shards};
1165         my $ibx = $self->{ibx};
1166         if (my $pr = $sync->{-opt}->{-progress}) {
1167                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1168                         "$beg..$end (% $step)\n");
1169         }
1170         for (my $num = $beg; $num <= $end; $num += $step) {
1171                 last if $sync->{quit};
1172                 my $smsg = $ibx->over->get_art($num) or next;
1173                 $smsg->{self} = $self;
1174                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1175                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1176                         ${$sync->{nr}} = $num;
1177                         reindex_checkpoint($self, $sync);
1178                 }
1179         }
1180 }
1181
1182 sub index_todo ($$$) {
1183         my ($self, $sync, $unit) = @_;
1184         return if $sync->{quit};
1185         unindex_todo($self, $sync, $unit);
1186         my $stk = delete($unit->{stack}) or return;
1187         my $all = $self->git;
1188         my $index_oid = $self->can('index_oid');
1189         my $unindex_oid = $self->can('unindex_oid');
1190         my $pfx;
1191         if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1192                 $pfx = "$1 $2"; # v2
1193         } else { # v1
1194                 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1195                 $pfx //= $unit->{git}->{git_dir};
1196         }
1197         local $self->{current_info} = "$pfx ";
1198         local $sync->{latest_cmt} = \(my $latest_cmt);
1199         local $sync->{unit} = $unit;
1200         while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1201                 if ($sync->{quit}) {
1202                         warn "waiting to quit...\n";
1203                         $all->async_wait_all;
1204                         $self->update_last_commit($sync);
1205                         return;
1206                 }
1207                 my $req = {
1208                         %$sync,
1209                         autime => $at,
1210                         cotime => $ct,
1211                         oid => $oid,
1212                         cur_cmt => $cmt
1213                 };
1214                 if ($f eq 'm') {
1215                         if ($sync->{max_size}) {
1216                                 $all->check_async($oid, \&check_size, $req);
1217                         } else {
1218                                 $all->cat_async($oid, $index_oid, $req);
1219                         }
1220                 } elsif ($f eq 'd') {
1221                         $all->cat_async($oid, $unindex_oid, $req);
1222                 }
1223                 if (${$sync->{need_checkpoint}}) {
1224                         reindex_checkpoint($self, $sync);
1225                 }
1226         }
1227         $all->async_wait_all;
1228         $self->update_last_commit($sync, $stk);
1229 }
1230
1231 sub xapian_only {
1232         my ($self, $opt, $sync, $art_beg) = @_;
1233         my $seq = $opt->{'sequential-shard'};
1234         $art_beg //= 0;
1235         local $self->{parallel} = 0 if $seq;
1236         $self->idx_init($opt); # acquire lock
1237         if (my $art_end = $self->{ibx}->mm->max) {
1238                 $sync //= {
1239                         need_checkpoint => \(my $bool = 0),
1240                         -opt => $opt,
1241                         self => $self,
1242                         nr => \(my $nr = 0),
1243                         -regen_fmt => "%u/?\n",
1244                 };
1245                 $sync->{art_end} = $art_end;
1246                 if ($seq || !$self->{parallel}) {
1247                         my $shard_end = $self->{shards} - 1;
1248                         for my $i (0..$shard_end) {
1249                                 last if $sync->{quit};
1250                                 index_xap_step($self, $sync, $art_beg + $i);
1251                                 if ($i != $shard_end) {
1252                                         reindex_checkpoint($self, $sync);
1253                                 }
1254                         }
1255                 } else { # parallel (maybe)
1256                         index_xap_step($self, $sync, $art_beg, 1);
1257                 }
1258         }
1259         $self->git->async_wait_all;
1260         $self->{ibx}->cleanup;
1261         $self->done;
1262 }
1263
1264 # public, called by public-inbox-index
1265 sub index_sync {
1266         my ($self, $opt) = @_;
1267         $opt //= {};
1268         return xapian_only($self, $opt) if $opt->{xapian_only};
1269
1270         my $epoch_max;
1271         my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1272         if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1273                 use Time::HiRes qw(stat);
1274                 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1275                         my $c = $mm[10]; # 10 = ctime (nsec NV)
1276                         my @hd = stat("$latest/refs/heads");
1277                         my @pr = stat("$latest/packed-refs");
1278                         return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1279                 }
1280         }
1281
1282         my $pr = $opt->{-progress};
1283         my $seq = $opt->{'sequential-shard'};
1284         my $art_beg; # the NNTP article number we start xapian_only at
1285         my $idxlevel = $self->{ibx}->{indexlevel};
1286         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1287
1288         $self->idx_init($opt); # acquire lock
1289         $self->{mg}->fill_alternates;
1290         $self->{oidx}->rethread_prepare($opt);
1291         my $sync = {
1292                 need_checkpoint => \(my $bool = 0),
1293                 reindex => $opt->{reindex},
1294                 -opt => $opt,
1295                 self => $self,
1296                 ibx => $self->{ibx},
1297                 epoch_max => $epoch_max,
1298         };
1299         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1300         local $SIG{QUIT} = $quit;
1301         local $SIG{INT} = $quit;
1302         local $SIG{TERM} = $quit;
1303
1304         if (sync_prepare($self, $sync)) {
1305                 # tmp_clone seems to fail if inside a transaction, so
1306                 # we rollback here (because we opened {mm} for reading)
1307                 # Note: we do NOT rely on DBI transactions for atomicity;
1308                 # only for batch performance.
1309                 $self->{mm}->{dbh}->rollback;
1310                 $self->{mm}->{dbh}->begin_work;
1311                 $sync->{mm_tmp} =
1312                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1313
1314                 # xapian_only works incrementally w/o --reindex
1315                 if ($seq && !$opt->{reindex}) {
1316                         $art_beg = $sync->{mm_tmp}->max || -1;
1317                         $art_beg++;
1318                 }
1319         }
1320         # work forwards through history
1321         index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1322         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1323         $self->done;
1324
1325         if (my $nr = $sync->{nr}) {
1326                 my $pr = $sync->{-opt}->{-progress};
1327                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1328         }
1329
1330         my $quit_warn;
1331         # deal with Xapian shards sequentially
1332         if ($seq && delete($sync->{mm_tmp})) {
1333                 if ($sync->{quit}) {
1334                         $quit_warn = 1;
1335                 } else {
1336                         $self->{ibx}->{indexlevel} = $idxlevel;
1337                         xapian_only($self, $opt, $sync, $art_beg);
1338                         $quit_warn = 1 if $sync->{quit};
1339                 }
1340         }
1341
1342         # --reindex on the command-line
1343         if (!$sync->{quit} && $opt->{reindex} &&
1344                         !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} && !$sync->{quit} &&
1357                         !grep(defined, @$opt{qw(since until)})) {
1358                 my %again = %$opt;
1359                 $sync = undef;
1360                 delete @again{qw(rethread reindex -skip_lock)};
1361                 index_sync($self, \%again);
1362                 $opt->{quit} = $again{quit}; # propagate to caller
1363         }
1364         warn <<EOF if $quit_warn;
1365 W: interrupted, --xapian-only --reindex required upon restart
1366 EOF
1367 }
1368
1369 sub ipc_atfork_child {
1370         my ($self) = @_;
1371         if (my $lei = delete $self->{lei}) {
1372                 $lei->_lei_atfork_child;
1373                 my $pkt_op_p = delete $lei->{pkt_op_p};
1374                 close($pkt_op_p->{op_p});
1375         }
1376         $self->SUPER::ipc_atfork_child;
1377 }
1378
1379 1;