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