]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
searchidx: all indexers check for bad blobs
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
4 # This interface wraps and mimics PublicInbox::Import
5 # Used to write to V2 inboxes (see L<public-inbox-v2-format(5)>).
6 package PublicInbox::V2Writable;
7 use strict;
8 use v5.10.1;
9 use parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::Eml;
12 use PublicInbox::Git;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx qw(log2stack crlf_adjust is_ancestor check_size
21         is_bad_blob);
22 use IO::Handle; # ->autoflush
23 use File::Temp ();
24
25 my $OID = qr/[a-f0-9]{40,}/;
26 # an estimate of the post-packed size to the raw uncompressed size
27 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         if (my $ibx = $self->{ibx}) {
70                 # always load existing shards in case core count changes:
71                 # Also, shard count may change while -watch is running
72                 my $srch = $ibx->search or return 0;
73                 delete $ibx->{search};
74                 $srch->{nshard} // 0
75         } else { # ExtSearchIdx
76                 $self->{nshard} // do {
77                         if ($self->xdb_sharded) {
78                                 $self->{nshard} // die 'BUG: {nshard} unset';
79                         } else {
80                                 0;
81                         }
82                 }
83         }
84 }
85
86 sub new {
87         # $creat may be any true value, or 0/undef.  A hashref is true,
88         # and $creat->{nproc} may be set to an integer
89         my ($class, $v2ibx, $creat) = @_;
90         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
91         my $dir = $v2ibx->assert_usable_dir;
92         unless (-d $dir) {
93                 if ($creat) {
94                         require File::Path;
95                         File::Path::mkpath($dir);
96                 } else {
97                         die "$dir does not exist\n";
98                 }
99         }
100         $v2ibx->umask_prepare;
101
102         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
103         my $self = {
104                 ibx => $v2ibx,
105                 im => undef, #  PublicInbox::Import
106                 parallel => 1,
107                 transact_bytes => 0,
108                 total_bytes => 0,
109                 current_info => '',
110                 xpfx => $xpfx,
111                 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
112                 lock_path => "$dir/inbox.lock",
113                 # limit each git repo (epoch) to 1GB or so
114                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
115                 last_commit => [], # git epoch -> commit
116         };
117         $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
118         $self->{shards} = count_shards($self) || nproc_shards($creat);
119         bless $self, $class;
120 }
121
122 # public (for now?)
123 sub init_inbox {
124         my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
125         if (defined $shards) {
126                 $self->{parallel} = 0 if $shards == 0;
127                 $self->{shards} = $shards if $shards > 0;
128         }
129         $self->idx_init;
130         $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
131         my $epoch_max = -1;
132         $self->{ibx}->git_dir_latest(\$epoch_max);
133         if (defined $skip_epoch && $epoch_max == -1) {
134                 $epoch_max = $skip_epoch;
135         }
136         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
137         $self->done;
138 }
139
140 # returns undef on duplicate or spam
141 # mimics Import::add and wraps it for v2
142 sub add {
143         my ($self, $eml, $check_cb) = @_;
144         $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
145 }
146
147 sub idx_shard ($$) {
148         my ($self, $num) = @_;
149         $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
150 }
151
152 # indexes a message, returns true if checkpointing is needed
153 sub do_idx ($$$$) {
154         my ($self, $msgref, $mime, $smsg) = @_;
155         $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
156         $self->{oidx}->add_overview($mime, $smsg);
157         my $idx = idx_shard($self, $smsg->{num});
158         $idx->index_raw($msgref, $mime, $smsg);
159         my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
160         $n >= $self->{batch_bytes};
161 }
162
163 sub _add {
164         my ($self, $mime, $check_cb) = @_;
165
166         # spam check:
167         if ($check_cb) {
168                 $mime = $check_cb->($mime, $self->{ibx}) or return;
169         }
170
171         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
172         # as does SQLite 3.4.1+ (released in 2007-07-20), and
173         # Xapian 1.3.2+ (released 2015-03-15).
174         # For the most part, we can spawn git-fast-import without
175         # leaking FDs to it...
176         $self->idx_init;
177
178         my ($num, $mid0) = v2_num_for($self, $mime);
179         defined $num or return; # duplicate
180         defined $mid0 or die "BUG: \$mid0 undefined\n";
181         my $im = $self->importer;
182         my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
183         my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
184         $cmt = $im->get_mark($cmt);
185         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
186
187         my $msgref = delete $smsg->{-raw_email};
188         if (do_idx($self, $msgref, $mime, $smsg)) {
189                 $self->checkpoint;
190         }
191
192         $cmt;
193 }
194
195 sub v2_num_for {
196         my ($self, $mime) = @_;
197         my $mids = mids($mime);
198         if (@$mids) {
199                 my $mid = $mids->[0];
200                 my $num = $self->{mm}->mid_insert($mid);
201                 if (defined $num) { # common case
202                         return ($num, $mid);
203                 }
204
205                 # crap, Message-ID is already known, hope somebody just resent:
206                 foreach my $m (@$mids) {
207                         # read-only lookup now safe to do after above barrier
208                         # easy, don't store duplicates
209                         # note: do not add more diagnostic info here since
210                         # it gets noisy on public-inbox-watch restarts
211                         return () if content_exists($self, $mime, $m);
212                 }
213
214                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
215                 # or NNTP article number), use that article number if it's
216                 # not in Over.
217                 my $altid = $self->{ibx}->{altid};
218                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
219                         my $num = $self->{mm}->num_for($mid);
220
221                         if (defined $num && !$self->{oidx}->get_art($num)) {
222                                 return ($num, $mid);
223                         }
224                 }
225
226                 # very unlikely:
227                 warn "<$mid> reused for mismatched content\n";
228
229                 # try the rest of the mids
230                 for(my $i = $#$mids; $i >= 1; $i--) {
231                         my $m = $mids->[$i];
232                         $num = $self->{mm}->mid_insert($m);
233                         if (defined $num) {
234                                 warn "alternative <$m> for <$mid> found\n";
235                                 return ($num, $m);
236                         }
237                 }
238         }
239         # none of the existing Message-IDs are good, generate a new one:
240         v2_num_for_harder($self, $mime);
241 }
242
243 sub v2_num_for_harder {
244         my ($self, $eml) = @_;
245
246         my $dig = content_digest($eml);
247         my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
248         my $num = $self->{mm}->mid_insert($mid0);
249         unless (defined $num) {
250                 # it's hard to spoof the last Received: header
251                 my @recvd = $eml->header_raw('Received');
252                 $dig->add("Received: $_") foreach (@recvd);
253                 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
254                 $num = $self->{mm}->mid_insert($mid0);
255
256                 # fall back to a random Message-ID and give up determinism:
257                 until (defined($num)) {
258                         $dig->add(rand);
259                         $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
260                         warn "using random Message-ID <$mid0> as fallback\n";
261                         $num = $self->{mm}->mid_insert($mid0);
262                 }
263         }
264         PublicInbox::Import::append_mid($eml, $mid0);
265         ($num, $mid0);
266 }
267
268 sub _idx_init { # with_umask callback
269         my ($self, $opt) = @_;
270         $self->lock_acquire unless $opt && $opt->{-skip_lock};
271         $self->{oidx}->create;
272
273         # xcpdb can change shard count while -watch is idle
274         my $nshards = count_shards($self);
275         $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
276         $self->{batch_bytes} = $opt->{batch_size} //
277                                 $PublicInbox::SearchIdx::BATCH_BYTES;
278         $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
279
280         # need to create all shards before initializing msgmap FD
281         # idx_shards must be visible to all forked processes
282         my $max = $self->{shards} - 1;
283         my $idx = $self->{idx_shards} = [];
284         push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
285         my $ibx = $self->{ibx} or return; # ExtIdxSearch
286
287         # Now that all subprocesses are up, we can open the FDs
288         # for SQLite:
289         my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
290                                 "$ibx->{inboxdir}/msgmap.sqlite3",
291                                 $ibx->{-no_fsync} ? 2 : 1);
292         $mm->{dbh}->begin_work;
293 }
294
295 sub parallel_init ($$) {
296         my ($self, $indexlevel) = @_;
297         if (($indexlevel // 'full') eq 'basic') {
298                 $self->{parallel} = 0;
299         } else {
300                 pipe(my ($r, $w)) or die "pipe failed: $!";
301                 # pipe for barrier notifications doesn't need to be big,
302                 # 1031: F_SETPIPE_SZ
303                 fcntl($w, 1031, 4096) if $^O eq 'linux';
304                 $self->{bnote} = [ $r, $w ];
305                 $w->autoflush(1);
306         }
307 }
308
309 # idempotent
310 sub idx_init {
311         my ($self, $opt) = @_;
312         return if $self->{idx_shards};
313         my $ibx = $self->{ibx};
314
315         # do not leak read-only FDs to child processes, we only have these
316         # FDs for duplicate detection so they should not be
317         # frequently activated.
318         delete @$ibx{qw(mm search)};
319         $ibx->git->cleanup;
320
321         parallel_init($self, $ibx->{indexlevel});
322         $ibx->umask_prepare;
323         $ibx->with_umask(\&_idx_init, $self, $opt);
324 }
325
326 # returns an array mapping [ epoch => latest_commit ]
327 # latest_commit may be undef if nothing was done to that epoch
328 # $replace_map = { $object_id => $strref, ... }
329 sub _replace_oids ($$$) {
330         my ($self, $mime, $replace_map) = @_;
331         $self->done;
332         my $ibx = $self->{ibx};
333         my $pfx = "$ibx->{inboxdir}/git";
334         my $rewrites = []; # epoch => commit
335         my $max = $self->{epoch_max};
336
337         unless (defined($max)) {
338                 defined(my $latest = $ibx->git_dir_latest(\$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 $oidx = $self->{oidx};
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 = $oidx->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_aux($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->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->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->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 ($) { # this is NOT for ExtSearchIdx
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 $mm = $self->{mm};
622                 my $dbh = $mm->{dbh} if $mm;
623
624                 # SQLite msgmap data is second in importance
625                 $dbh->commit if $dbh;
626
627                 # SQLite overview is third
628                 $self->{oidx}->commit_lazy;
629
630                 # Now deal with Xapian
631                 if ($wait) {
632                         my $barrier = barrier_init($self, scalar @$shards);
633
634                         # each shard needs to issue a barrier command
635                         $_->shard_barrier for @$shards;
636
637                         # wait for each Xapian shard
638                         barrier_wait($self, $barrier);
639                 } else {
640                         $_->shard_commit for @$shards;
641                 }
642
643                 my $midx = $self->{midx}; # misc index
644                 $midx->commit_txn if $midx;
645
646                 # last_commit is special, don't commit these until
647                 # Xapian shards are done:
648                 $dbh->begin_work if $dbh;
649                 set_last_commits($self);
650                 if ($dbh) {
651                         $dbh->commit;
652                         $dbh->begin_work;
653                 }
654                 $midx->begin_txn if $midx;
655         }
656         $self->{total_bytes} += $self->{transact_bytes};
657         $self->{transact_bytes} = 0;
658 }
659
660 # issue a write barrier to ensure all data is visible to other processes
661 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
662 # public
663 sub barrier { checkpoint($_[0], 1) };
664
665 # true if locked and active
666 sub active { !!$_[0]->{im} }
667
668 # public
669 sub done {
670         my ($self) = @_;
671         my $err = '';
672         if (my $im = delete $self->{im}) {
673                 eval { $im->done }; # PublicInbox::Import::done
674                 $err .= "import done: $@\n" if $@;
675         }
676         if (!$err) {
677                 eval { checkpoint($self) };
678                 $err .= "checkpoint: $@\n" if $@;
679         }
680         if (my $mm = delete $self->{mm}) {
681                 my $m = $err ? 'rollback' : 'commit';
682                 eval { $mm->{dbh}->$m };
683                 $err .= "msgmap $m: $@\n" if $@;
684         }
685         my $shards = delete $self->{idx_shards};
686         if ($shards) {
687                 for (@$shards) {
688                         eval { $_->shard_close };
689                         $err .= "shard close: $@\n" if $@;
690                 }
691         }
692         eval { $self->{oidx}->dbh_close };
693         $err .= "over close: $@\n" if $@;
694         delete $self->{midx};
695         delete $self->{bnote};
696         my $nbytes = $self->{total_bytes};
697         $self->{total_bytes} = 0;
698         $self->lock_release(!!$nbytes) if $shards;
699         $self->git->cleanup;
700         die $err if $err;
701 }
702
703 sub write_alternates ($$$) {
704         my ($info_dir, $mode, $out) = @_;
705         my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
706         my $tmp = $fh->filename;
707         print $fh @$out or die "print $tmp: $!\n";
708         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
709         close $fh or die "close $tmp $!\n";
710         my $alt = "$info_dir/alternates";
711         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
712         $fh->unlink_on_destroy(0);
713 }
714
715 sub fill_alternates ($$) {
716         my ($self, $epoch) = @_;
717
718         my $pfx = "$self->{ibx}->{inboxdir}/git";
719         my $all = "$self->{ibx}->{inboxdir}/all.git";
720         PublicInbox::Import::init_bare($all) unless -d $all;
721         my $info_dir = "$all/objects/info";
722         my $alt = "$info_dir/alternates";
723         my (%alt, $new);
724         my $mode = 0644;
725         if (-e $alt) {
726                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
727                 $mode = (stat($fh))[2] & 07777;
728
729                 # we assign a sort score to every alternate and favor
730                 # the newest (highest numbered) one because loose objects
731                 # require scanning epochs and only the latest epoch is
732                 # expected to see loose objects
733                 my $score;
734                 my $other = 0; # in case admin adds non-epoch repos
735                 %alt = map {;
736                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
737                                 $score = $1 + 0;
738                         } else {
739                                 $score = --$other;
740                         }
741                         $_ => $score;
742                 } split(/\n+/, do { local $/; <$fh> });
743         }
744
745         foreach my $i (0..$epoch) {
746                 my $dir = "../../git/$i.git/objects";
747                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
748                         $alt{$dir} = $i;
749                         $new = 1;
750                 }
751         }
752         return unless $new;
753         write_alternates($info_dir, $mode,
754                 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
755 }
756
757 sub git_init {
758         my ($self, $epoch) = @_;
759         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
760         PublicInbox::Import::init_bare($git_dir);
761         my @cmd = (qw/git config/, "--file=$git_dir/config",
762                         'include.path', '../../all.git/config');
763         PublicInbox::Import::run_die(\@cmd);
764         fill_alternates($self, $epoch);
765         $git_dir
766 }
767
768 sub importer {
769         my ($self) = @_;
770         my $im = $self->{im};
771         if ($im) {
772                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
773                         return $im;
774                 } else {
775                         $self->{im} = undef;
776                         $im->done;
777                         $im = undef;
778                         $self->checkpoint;
779                         my $git_dir = $self->git_init(++$self->{epoch_max});
780                         my $git = PublicInbox::Git->new($git_dir);
781                         return $self->import_init($git, 0);
782                 }
783         }
784         my $epoch = 0;
785         my $max;
786         my $latest = $self->{ibx}->git_dir_latest(\$max);
787         if (defined $latest) {
788                 my $git = PublicInbox::Git->new($latest);
789                 my $packed_bytes = $git->packed_bytes;
790                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
791
792                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
793                         $epoch = $max + 1;
794                 } else {
795                         $self->{epoch_max} = $max;
796                         return $self->import_init($git, $packed_bytes);
797                 }
798         }
799         $self->{epoch_max} = $epoch;
800         $latest = $self->git_init($epoch);
801         $self->import_init(PublicInbox::Git->new($latest), 0);
802 }
803
804 sub import_init {
805         my ($self, $git, $packed_bytes, $tmp) = @_;
806         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
807         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
808         $im->{lock_path} = undef;
809         $im->{path_type} = 'v2';
810         $self->{im} = $im unless $tmp;
811         $im;
812 }
813
814 # XXX experimental
815 sub diff ($$$) {
816         my ($mid, $cur, $new) = @_;
817
818         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
819         print $ah $cur->as_string or die "print: $!";
820         $ah->flush or die "flush: $!";
821         PublicInbox::Import::drop_unwanted_headers($new);
822         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
823         print $bh $new->as_string or die "print: $!";
824         $bh->flush or die "flush: $!";
825         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
826         print STDERR "# MID conflict <$mid>\n";
827         my $pid = spawn($cmd, undef, { 1 => 2 });
828         waitpid($pid, 0) == $pid or die "diff did not finish";
829 }
830
831 sub get_blob ($$) {
832         my ($self, $smsg) = @_;
833         if (my $im = $self->{im}) {
834                 my $msg = $im->cat_blob($smsg->{blob});
835                 return $msg if $msg;
836         }
837         # older message, should be in alternates
838         $self->{ibx}->msg_by_smsg($smsg);
839 }
840
841 sub content_exists ($$$) {
842         my ($self, $mime, $mid) = @_;
843         my $oidx = $self->{oidx};
844         my $chashes = content_hashes($mime);
845         my ($id, $prev);
846         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
847                 my $msg = get_blob($self, $smsg);
848                 if (!defined($msg)) {
849                         warn "broken smsg for $mid\n";
850                         next;
851                 }
852                 my $cur = PublicInbox::Eml->new($msg);
853                 return 1 if content_matches($chashes, $cur);
854
855                 # XXX DEBUG_DIFF is experimental and may be removed
856                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
857         }
858         undef;
859 }
860
861 sub atfork_child {
862         my ($self) = @_;
863         if (my $shards = $self->{idx_shards}) {
864                 $_->atfork_child foreach @$shards;
865         }
866         if (my $im = $self->{im}) {
867                 $im->atfork_child;
868         }
869         die "unexpected mm" if $self->{mm};
870         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
871         $self->{bnote}->[1];
872 }
873
874 sub reindex_checkpoint ($$) {
875         my ($self, $sync) = @_;
876
877         $self->git->async_wait_all;
878         $self->update_last_commit($sync);
879         ${$sync->{need_checkpoint}} = 0;
880         my $mm_tmp = $sync->{mm_tmp};
881         $mm_tmp->atfork_prepare if $mm_tmp;
882         die 'BUG: {im} during reindex' if $self->{im};
883         if ($self->{ibx_map}) {
884                 checkpoint($self, 1); # no need to release lock on pure index
885         } else {
886                 $self->done; # release lock
887         }
888
889         if (my $pr = $sync->{-opt}->{-progress}) {
890                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
891         }
892
893         # allow -watch or -mda to write...
894         $self->idx_init($sync->{-opt}); # reacquire lock
895         $mm_tmp->atfork_parent if $mm_tmp;
896 }
897
898 sub index_oid { # cat_async callback
899         my ($bref, $oid, $type, $size, $arg) = @_;
900         return if is_bad_blob($oid, $type, $size, $arg->{oid});
901         my $self = $arg->{self};
902         local $self->{current_info} = "$self->{current_info} $oid";
903         return if $size == 0; # purged
904         my ($num, $mid0);
905         my $eml = PublicInbox::Eml->new($$bref);
906         my $mids = mids($eml);
907         my $chash = content_hash($eml);
908
909         if (scalar(@$mids) == 0) {
910                 warn "E: $oid has no Message-ID, skipping\n";
911                 return;
912         }
913
914         # {unindexed} is unlikely
915         if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
916                 $num = delete($unindexed->{$mids->[0]});
917                 if (defined $num) {
918                         $mid0 = $mids->[0];
919                         $self->{mm}->mid_set($num, $mid0);
920                         delete($arg->{unindexed}) if !keys(%$unindexed);
921                 }
922         }
923         if (!defined($num)) { # reuse if reindexing (or duplicates)
924                 my $oidx = $self->{oidx};
925                 for my $mid (@$mids) {
926                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
927                         last if defined $num;
928                 }
929         }
930         $mid0 //= do { # is this a number we got before?
931                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
932                 defined($num) ? $mids->[0] : undef;
933         };
934         if (!defined($num)) {
935                 for (my $i = $#$mids; $i >= 1; $i--) {
936                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
937                         if (defined($num)) {
938                                 $mid0 = $mids->[$i];
939                                 last;
940                         }
941                 }
942         }
943         if (defined($num)) {
944                 $arg->{mm_tmp}->num_delete($num);
945         } else { # never seen
946                 $num = $self->{mm}->mid_insert($mids->[0]);
947                 if (defined($num)) {
948                         $mid0 = $mids->[0];
949                 } else { # rare, try the rest of them, backwards
950                         for (my $i = $#$mids; $i >= 1; $i--) {
951                                 $num = $self->{mm}->mid_insert($mids->[$i]);
952                                 if (defined($num)) {
953                                         $mid0 = $mids->[$i];
954                                         last;
955                                 }
956                         }
957                 }
958         }
959         if (!defined($num)) {
960                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
961                 return;
962         }
963         ++${$arg->{nr}};
964         my $smsg = bless {
965                 raw_bytes => $size,
966                 num => $num,
967                 blob => $oid,
968                 mid => $mid0,
969         }, 'PublicInbox::Smsg';
970         $smsg->populate($eml, $arg);
971         if (do_idx($self, $bref, $eml, $smsg)) {
972                 ${$arg->{need_checkpoint}} = 1;
973         }
974         ${$arg->{latest_cmt}} = $arg->{cur_cmt} // die 'BUG: {cur_cmt} missing';
975 }
976
977 # only update last_commit for $i on reindex iff newer than current
978 sub update_last_commit {
979         my ($self, $sync, $stk) = @_;
980         my $unit = $sync->{unit} // return;
981         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
982         defined($latest_cmt) or return;
983         my $last = last_epoch_commit($self, $unit->{epoch});
984         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
985                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
986                 chomp(my $n = $unit->{git}->qx(@cmd));
987                 return if $n ne '' && $n == 0;
988         }
989         last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
990 }
991
992 sub last_commits {
993         my ($self, $sync) = @_;
994         my $heads = [];
995         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
996                 $heads->[$i] = last_epoch_commit($self, $i);
997         }
998         $heads;
999 }
1000
1001 # returns a revision range for git-log(1)
1002 sub log_range ($$$) {
1003         my ($sync, $unit, $tip) = @_;
1004         my $opt = $sync->{-opt};
1005         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1006         my $i = $unit->{epoch};
1007         my $cur = $sync->{ranges}->[$i] or do {
1008                 $pr->("$i.git indexing all of $tip\n") if $pr;
1009                 return $tip; # all of it
1010         };
1011
1012         # fast equality check to avoid (v)fork+execve overhead
1013         if ($cur eq $tip) {
1014                 $sync->{ranges}->[$i] = undef;
1015                 return;
1016         }
1017
1018         my $range = "$cur..$tip";
1019         $pr->("$i.git checking contiguity... ") if $pr;
1020         my $git = $unit->{git};
1021         if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1022                 $pr->("OK\n") if $pr;
1023                 my $n = $git->qx(qw(rev-list --count), $range);
1024                 chomp($n);
1025                 if ($n == 0) {
1026                         $sync->{ranges}->[$i] = undef;
1027                         $pr->("$i.git has nothing new\n") if $pr;
1028                         return; # nothing to do
1029                 }
1030                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1031         } else {
1032                 $pr->("FAIL\n") if $pr;
1033                 warn <<"";
1034 discontiguous range: $range
1035 Rewritten history? (in $git->{git_dir})
1036
1037                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1038                 if ($base) {
1039                         $range = "$base..$tip";
1040                         warn "found merge-base: $base\n"
1041                 } else {
1042                         $range = $tip;
1043                         warn "discarding history at $cur\n";
1044                 }
1045                 warn <<"";
1046 reindexing $git->{git_dir}
1047 starting at $range
1048
1049                 # $cur^0 may no longer exist if pruned by git
1050                 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1051                         $unit->{unindex_range} = "$base..$cur";
1052                 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1053                         $unit->{unindex_range} = "$base..";
1054                 } else {
1055                         warn "W: unable to unindex before $range\n";
1056                 }
1057         }
1058         $range;
1059 }
1060
1061 # overridden by ExtSearchIdx
1062 sub artnum_max { $_[0]->{mm}->num_highwater }
1063
1064 sub sync_prepare ($$) {
1065         my ($self, $sync) = @_;
1066         $sync->{ranges} = sync_ranges($self, $sync);
1067         my $pr = $sync->{-opt}->{-progress};
1068         my $regen_max = 0;
1069         my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1070         my $pfx;
1071         if ($pr) {
1072                 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1073                 $pfx //= $sync->{ibx}->{inboxdir};
1074         }
1075
1076         # reindex stops at the current heads and we later rerun index_sync
1077         # without {reindex}
1078         my $reindex_heads = $self->last_commits($sync) if $sync->{reindex};
1079
1080         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1081                 $sync->{index_oid} = $self->can('index_oid');
1082         }
1083         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1084                 my $git_dir = $sync->{ibx}->git_dir_n($i);
1085                 -d $git_dir or next; # missing epochs are fine
1086                 my $git = PublicInbox::Git->new($git_dir);
1087                 my $unit = { git => $git, epoch => $i };
1088                 if ($reindex_heads) {
1089                         $head = $reindex_heads->[$i] or next;
1090                 }
1091                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1092                 next if $?; # new repo
1093
1094                 my $range = log_range($sync, $unit, $tip) or next;
1095                 # can't use 'rev-list --count' if we use --diff-filter
1096                 $pr->("$pfx $i.git counting $range ... ") if $pr;
1097                 # Don't bump num_highwater on --reindex by using {D}.
1098                 # We intentionally do NOT use {D} in the non-reindex case
1099                 # because we want NNTP article number gaps from unindexed
1100                 # messages to show up in mirrors, too.
1101                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1102                 my $stk = log2stack($sync, $git, $range);
1103                 return 0 if $sync->{quit};
1104                 my $nr = $stk ? $stk->num_records : 0;
1105                 $pr->("$nr\n") if $pr;
1106                 $unit->{stack} = $stk; # may be undef
1107                 unshift @{$sync->{todo}}, $unit;
1108                 $regen_max += $nr;
1109         }
1110         return 0 if $sync->{quit};
1111
1112         # XXX this should not happen unless somebody bypasses checks in
1113         # our code and blindly injects "d" file history into git repos
1114         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1115                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1116                 local $self->{current_info} = 'leftover ';
1117                 my $unindex_oid = $self->can('unindex_oid');
1118                 for my $oid (@leftovers) {
1119                         last if $sync->{quit};
1120                         $oid = unpack('H*', $oid);
1121                         my $req = { %$sync, oid => $oid };
1122                         $self->git->cat_async($oid, $unindex_oid, $req);
1123                 }
1124                 $self->git->cat_async_wait;
1125         }
1126         return 0 if $sync->{quit};
1127         if (!$regen_max) {
1128                 $sync->{-regen_fmt} = "%u/?\n";
1129                 return 0;
1130         }
1131
1132         # reindex should NOT see new commits anymore, if we do,
1133         # it's a problem and we need to notice it via die()
1134         my $pad = length($regen_max) + 1;
1135         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1136         $sync->{nr} = \(my $nr = 0);
1137         return -1 if $sync->{reindex};
1138         $regen_max + $self->artnum_max || 0;
1139 }
1140
1141 sub unindex_oid_aux ($$$) {
1142         my ($self, $oid, $mid) = @_;
1143         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1144         for my $num (@removed) {
1145                 my $idx = idx_shard($self, $num);
1146                 $idx->shard_remove($num);
1147         }
1148 }
1149
1150 sub unindex_oid ($$;$) { # git->cat_async callback
1151         my ($bref, $oid, $type, $size, $sync) = @_;
1152         return if is_bad_blob($oid, $type, $size, $sync->{oid});
1153         my $self = $sync->{self};
1154         local $self->{current_info} = "$self->{current_info} $oid";
1155         my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1156         my $mm = $self->{mm};
1157         my $mids = mids(PublicInbox::Eml->new($bref));
1158         undef $$bref;
1159         my $oidx = $self->{oidx};
1160         foreach my $mid (@$mids) {
1161                 my %gone;
1162                 my ($id, $prev);
1163                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1164                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1165                 }
1166                 my $n = scalar(keys(%gone)) or next;
1167                 if ($n > 1) {
1168                         warn "BUG: multiple articles linked to $oid\n",
1169                                 join(',',sort keys %gone), "\n";
1170                 }
1171                 foreach my $num (keys %gone) {
1172                         if ($unindexed) {
1173                                 my $mid0 = $mm->mid_for($num);
1174                                 $unindexed->{$mid0} = $num;
1175                         }
1176                         $mm->num_delete($num);
1177                 }
1178                 unindex_oid_aux($self, $oid, $mid);
1179         }
1180 }
1181
1182 sub git { $_[0]->{ibx}->git }
1183
1184 # this is rare, it only happens when we get discontiguous history in
1185 # a mirror because the source used -purge or -edit
1186 sub unindex_todo ($$$) {
1187         my ($self, $sync, $unit) = @_;
1188         my $unindex_range = delete($unit->{unindex_range}) // return;
1189         my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1190         my $before = scalar keys %$unindexed;
1191         # order does not matter, here:
1192         my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1193                                 --no-abbrev --no-renames), $unindex_range);
1194         local $sync->{in_unindex} = 1;
1195         my $unindex_oid = $self->can('unindex_oid');
1196         while (<$fh>) {
1197                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1198                 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1199         }
1200         close $fh or die "git log failed: \$?=$?";
1201         $self->git->cat_async_wait;
1202
1203         return unless $sync->{-opt}->{prune};
1204         my $after = scalar keys %$unindexed;
1205         return if $before == $after;
1206
1207         # ensure any blob can not longer be accessed via dumb HTTP
1208         PublicInbox::Import::run_die(['git',
1209                 "--git-dir=$unit->{git}->{git_dir}",
1210                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1211 }
1212
1213 sub sync_ranges ($$) {
1214         my ($self, $sync) = @_;
1215         my $reindex = $sync->{reindex};
1216         return $self->last_commits($sync) unless $reindex;
1217         return [] if ref($reindex) ne 'HASH';
1218
1219         my $ranges = $reindex->{from}; # arrayref;
1220         if (ref($ranges) ne 'ARRAY') {
1221                 die 'BUG: $reindex->{from} not an ARRAY';
1222         }
1223         $ranges;
1224 }
1225
1226 sub index_xap_only { # git->cat_async callback
1227         my ($bref, $oid, $type, $size, $smsg) = @_;
1228         my $self = $smsg->{self};
1229         my $idx = idx_shard($self, $smsg->{num});
1230         $smsg->{raw_bytes} = $size;
1231         $idx->index_raw($bref, undef, $smsg);
1232         $self->{transact_bytes} += $size;
1233 }
1234
1235 sub index_xap_step ($$$;$) {
1236         my ($self, $sync, $beg, $step) = @_;
1237         my $end = $sync->{art_end};
1238         return if $beg > $end; # nothing to do
1239
1240         $step //= $self->{shards};
1241         my $ibx = $self->{ibx};
1242         if (my $pr = $sync->{-opt}->{-progress}) {
1243                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1244                         "$beg..$end (% $step)\n");
1245         }
1246         for (my $num = $beg; $num <= $end; $num += $step) {
1247                 last if $sync->{quit};
1248                 my $smsg = $ibx->over->get_art($num) or next;
1249                 $smsg->{self} = $self;
1250                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1251                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1252                         ${$sync->{nr}} = $num;
1253                         reindex_checkpoint($self, $sync);
1254                 }
1255         }
1256 }
1257
1258 sub index_todo ($$$) {
1259         my ($self, $sync, $unit) = @_;
1260         return if $sync->{quit};
1261         unindex_todo($self, $sync, $unit);
1262         my $stk = delete($unit->{stack}) or return;
1263         my $all = $self->git;
1264         my $index_oid = $self->can('index_oid');
1265         my $unindex_oid = $self->can('unindex_oid');
1266         my $pfx;
1267         if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1268                 $pfx = "$1 $2"; # v2
1269         } else { # v1
1270                 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1271                 $pfx //= $unit->{git}->{git_dir};
1272         }
1273         local $self->{current_info} = "$pfx ";
1274         local $sync->{latest_cmt} = \(my $latest_cmt);
1275         local $sync->{unit} = $unit;
1276         while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1277                 if ($sync->{quit}) {
1278                         warn "waiting to quit...\n";
1279                         $all->async_wait_all;
1280                         $self->update_last_commit($sync);
1281                         return;
1282                 }
1283                 my $req = {
1284                         %$sync,
1285                         autime => $at,
1286                         cotime => $ct,
1287                         oid => $oid,
1288                         cur_cmt => $cmt
1289                 };
1290                 if ($f eq 'm') {
1291                         if ($sync->{max_size}) {
1292                                 $all->check_async($oid, \&check_size, $req);
1293                         } else {
1294                                 $all->cat_async($oid, $index_oid, $req);
1295                         }
1296                 } elsif ($f eq 'd') {
1297                         $all->cat_async($oid, $unindex_oid, $req);
1298                 }
1299                 if (${$sync->{need_checkpoint}}) {
1300                         reindex_checkpoint($self, $sync);
1301                 }
1302         }
1303         $all->async_wait_all;
1304         $self->update_last_commit($sync, $stk);
1305 }
1306
1307 sub xapian_only {
1308         my ($self, $opt, $sync, $art_beg) = @_;
1309         my $seq = $opt->{sequential_shard};
1310         $art_beg //= 0;
1311         local $self->{parallel} = 0 if $seq;
1312         $self->idx_init($opt); # acquire lock
1313         if (my $art_end = $self->{ibx}->mm->max) {
1314                 $sync //= {
1315                         need_checkpoint => \(my $bool = 0),
1316                         -opt => $opt,
1317                         self => $self,
1318                         nr => \(my $nr = 0),
1319                         -regen_fmt => "%u/?\n",
1320                 };
1321                 $sync->{art_end} = $art_end;
1322                 if ($seq || !$self->{parallel}) {
1323                         my $shard_end = $self->{shards} - 1;
1324                         for my $i (0..$shard_end) {
1325                                 last if $sync->{quit};
1326                                 index_xap_step($self, $sync, $art_beg + $i);
1327                                 if ($i != $shard_end) {
1328                                         reindex_checkpoint($self, $sync);
1329                                 }
1330                         }
1331                 } else { # parallel (maybe)
1332                         index_xap_step($self, $sync, $art_beg, 1);
1333                 }
1334         }
1335         $self->git->cat_async_wait;
1336         $self->done;
1337 }
1338
1339 # public, called by public-inbox-index
1340 sub index_sync {
1341         my ($self, $opt) = @_;
1342         $opt //= {};
1343         return xapian_only($self, $opt) if $opt->{xapian_only};
1344
1345         my $pr = $opt->{-progress};
1346         my $epoch_max;
1347         my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1348         return unless defined $latest;
1349
1350         my $seq = $opt->{sequential_shard};
1351         my $art_beg; # the NNTP article number we start xapian_only at
1352         my $idxlevel = $self->{ibx}->{indexlevel};
1353         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1354
1355         $self->idx_init($opt); # acquire lock
1356         fill_alternates($self, $epoch_max);
1357         $self->{oidx}->rethread_prepare($opt);
1358         my $sync = {
1359                 need_checkpoint => \(my $bool = 0),
1360                 reindex => $opt->{reindex},
1361                 -opt => $opt,
1362                 self => $self,
1363                 ibx => $self->{ibx},
1364                 epoch_max => $epoch_max,
1365         };
1366         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1367         local $SIG{QUIT} = $quit;
1368         local $SIG{INT} = $quit;
1369         local $SIG{TERM} = $quit;
1370
1371         if (sync_prepare($self, $sync)) {
1372                 # tmp_clone seems to fail if inside a transaction, so
1373                 # we rollback here (because we opened {mm} for reading)
1374                 # Note: we do NOT rely on DBI transactions for atomicity;
1375                 # only for batch performance.
1376                 $self->{mm}->{dbh}->rollback;
1377                 $self->{mm}->{dbh}->begin_work;
1378                 $sync->{mm_tmp} =
1379                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1380
1381                 # xapian_only works incrementally w/o --reindex
1382                 if ($seq && !$opt->{reindex}) {
1383                         $art_beg = $sync->{mm_tmp}->max || -1;
1384                         $art_beg++;
1385                 }
1386         }
1387         # work forwards through history
1388         index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1389         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1390         $self->done;
1391
1392         if (my $nr = $sync->{nr}) {
1393                 my $pr = $sync->{-opt}->{-progress};
1394                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1395         }
1396
1397         my $quit_warn;
1398         # deal with Xapian shards sequentially
1399         if ($seq && delete($sync->{mm_tmp})) {
1400                 if ($sync->{quit}) {
1401                         $quit_warn = 1;
1402                 } else {
1403                         $self->{ibx}->{indexlevel} = $idxlevel;
1404                         xapian_only($self, $opt, $sync, $art_beg);
1405                         $quit_warn = 1 if $sync->{quit};
1406                 }
1407         }
1408
1409         # --reindex on the command-line
1410         if (!$sync->{quit} && $opt->{reindex} &&
1411                         !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1412                 $self->lock_acquire;
1413                 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1414                 if (my $xdb = $s0->idx_acquire) {
1415                         my $n = $xdb->get_metadata('has_threadid');
1416                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1417                 }
1418                 $s0->idx_release;
1419                 $self->lock_release;
1420         }
1421
1422         # reindex does not pick up new changes, so we rerun w/o it:
1423         if ($opt->{reindex} && !$sync->{quit}) {
1424                 my %again = %$opt;
1425                 $sync = undef;
1426                 delete @again{qw(rethread reindex -skip_lock)};
1427                 index_sync($self, \%again);
1428                 $opt->{quit} = $again{quit}; # propagate to caller
1429         }
1430         warn <<EOF if $quit_warn;
1431 W: interrupted, --xapian-only --reindex required upon restart
1432 EOF
1433 }
1434
1435 1;