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