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