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