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