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