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