]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
025487d2155c70fdafbc4b86a4e277739532901e
[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 PublicInbox::IPC);
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 git_sha);
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 sub _check_mids_match ($$$) {
451         my ($old_list, $new_list, $hdrs) = @_;
452         my %old_mids = map { $_ => 1 } @$old_list;
453         my %new_mids = map { $_ => 1 } @$new_list;
454         my @old = keys %old_mids;
455         my @new = keys %new_mids;
456         my $err = "$hdrs may not be changed when replacing\n";
457         die $err if scalar(@old) != scalar(@new);
458         delete @new_mids{@old};
459         delete @old_mids{@new};
460         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
461 }
462
463 # Changing Message-IDs or References with ->replace isn't supported.
464 # The rules for dealing with messages with multiple or conflicting
465 # Message-IDs are pretty complex and rethreading hasn't been fully
466 # implemented, yet.
467 sub check_mids_match ($$) {
468         my ($old, $new) = @_;
469         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
470         _check_mids_match(references($old), references($new),
471                         'References/In-Reply-To');
472 }
473
474 # public
475 sub replace ($$$) {
476         my ($self, $old_mime, $new_mime) = @_;
477
478         check_mids_match($old_mime, $new_mime);
479
480         # mutt will always add Content-Length:, Status:, Lines: when editing
481         PublicInbox::Import::drop_unwanted_headers($new_mime);
482
483         my $raw = $new_mime->as_string;
484         my $expect_oid = git_sha(1, \$raw)->hexdigest;
485         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
486         my $need_reindex = $rewritten->{need_reindex};
487
488         # just in case we have bugs in deduplication code:
489         my $n = scalar(@$need_reindex);
490         if ($n > 1) {
491                 my $list = join(', ', map {
492                                         "$_->{num}: <$_->{mid}>"
493                                 } @$need_reindex);
494                 warn <<"";
495 W: rewritten $n messages matching content of original message (expected: 1).
496 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
497 W: $list
498
499         }
500
501         # make sure we really got the OID:
502         my ($blob, $type, $bytes) = $self->git->check($expect_oid);
503         $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
504
505         # don't leak FDs to Xapian:
506         $self->git->cleanup;
507
508         # reindex modified messages:
509         for my $smsg (@$need_reindex) {
510                 my $new_smsg = bless {
511                         blob => $blob,
512                         num => $smsg->{num},
513                         mid => $smsg->{mid},
514                 }, 'PublicInbox::Smsg';
515                 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
516                 $new_smsg->populate($new_mime, $sync);
517                 $new_smsg->set_bytes($raw, $bytes);
518                 do_idx($self, $new_mime, $new_smsg);
519         }
520         $rewritten->{rewrites};
521 }
522
523 sub last_epoch_commit ($$;$) {
524         my ($self, $i, $cmt) = @_;
525         my $v = PublicInbox::Search::SCHEMA_VERSION();
526         $self->{mm}->last_commit_xap($v, $i, $cmt);
527 }
528
529 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
530         my ($self) = @_;
531         defined(my $epoch_max = $self->{epoch_max}) or return;
532         my $last_commit = $self->{last_commit};
533         foreach my $i (0..$epoch_max) {
534                 defined(my $cmt = $last_commit->[$i]) or next;
535                 $last_commit->[$i] = undef;
536                 last_epoch_commit($self, $i, $cmt);
537         }
538 }
539
540 # public
541 sub checkpoint ($;$) {
542         my ($self, $wait) = @_;
543
544         if (my $im = $self->{im}) {
545                 if ($wait) {
546                         $im->barrier;
547                 } else {
548                         $im->checkpoint;
549                 }
550         }
551         my $shards = $self->{idx_shards};
552         if ($shards) {
553                 my $mm = $self->{mm};
554                 my $dbh = $mm->{dbh} if $mm;
555
556                 # SQLite msgmap data is second in importance
557                 $dbh->commit if $dbh;
558
559                 # SQLite overview is third
560                 $self->{oidx}->commit_lazy;
561
562                 # Now deal with Xapian
563
564                 # start commit_txn_lazy asynchronously on all parallel shards
565                 # (non-parallel waits here)
566                 $_->ipc_do('commit_txn_lazy') for @$shards;
567
568                 # transactions started on parallel shards,
569                 # wait for them by issuing an echo command (echo can only
570                 # run after commit_txn_lazy is done)
571                 if ($wait && $self->{parallel}) {
572                         my $i = 0;
573                         for my $shard (@$shards) {
574                                 my $echo = $shard->ipc_do('echo', $i);
575                                 $echo == $i or die <<"";
576 shard[$i] bad echo:$echo != $i waiting for txn commit
577
578                                 ++$i;
579                         }
580                 }
581
582                 my $midx = $self->{midx}; # misc index
583                 if ($midx) {
584                         $midx->commit_txn;
585                         $PublicInbox::Search::X{CLOEXEC_UNSET} and
586                                 $self->git->cleanup;
587                 }
588
589                 # last_commit is special, don't commit these until
590                 # Xapian shards are done:
591                 $dbh->begin_work if $dbh;
592                 set_last_commits($self);
593                 if ($dbh) {
594                         $dbh->commit;
595                         $dbh->begin_work;
596                 }
597         }
598         $self->{total_bytes} += $self->{transact_bytes};
599         $self->{transact_bytes} = 0;
600 }
601
602 # issue a write barrier to ensure all data is visible to other processes
603 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
604 # public
605 sub barrier { checkpoint($_[0], 1) };
606
607 # true if locked and active
608 sub active { !!$_[0]->{im} }
609
610 # public
611 sub done {
612         my ($self) = @_;
613         my $err = '';
614         if (my $im = delete $self->{im}) {
615                 eval { $im->done }; # PublicInbox::Import::done
616                 $err .= "import done: $@\n" if $@;
617         }
618         if (!$err) {
619                 eval { checkpoint($self) };
620                 $err .= "checkpoint: $@\n" if $@;
621         }
622         if (my $mm = delete $self->{mm}) {
623                 my $m = $err ? 'rollback' : 'commit';
624                 eval { $mm->{dbh}->$m };
625                 $err .= "msgmap $m: $@\n" if $@;
626         }
627         my $shards = delete $self->{idx_shards};
628         if ($shards) {
629                 for (@$shards) {
630                         eval { $_->shard_close };
631                         $err .= "shard close: $@\n" if $@;
632                 }
633         }
634         eval { $self->{oidx}->dbh_close };
635         $err .= "over close: $@\n" if $@;
636         delete $self->{midx};
637         my $nbytes = $self->{total_bytes};
638         $self->{total_bytes} = 0;
639         $self->lock_release(!!$nbytes) if $shards;
640         $self->git->cleanup;
641         die $err if $err;
642 }
643
644 sub write_alternates ($$$) {
645         my ($info_dir, $mode, $out) = @_;
646         my $fh = File::Temp->new(TEMPLATE => 'alt-XXXX', DIR => $info_dir);
647         my $tmp = $fh->filename;
648         print $fh @$out or die "print $tmp: $!\n";
649         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
650         close $fh or die "close $tmp $!\n";
651         my $alt = "$info_dir/alternates";
652         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
653         $fh->unlink_on_destroy(0);
654 }
655
656 sub fill_alternates ($$) {
657         my ($self, $epoch) = @_;
658
659         my $pfx = "$self->{ibx}->{inboxdir}/git";
660         my $all = "$self->{ibx}->{inboxdir}/all.git";
661         PublicInbox::Import::init_bare($all) unless -d $all;
662         my $info_dir = "$all/objects/info";
663         my $alt = "$info_dir/alternates";
664         my (%alt, $new);
665         my $mode = 0644;
666         if (-e $alt) {
667                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
668                 $mode = (stat($fh))[2] & 07777;
669
670                 # we assign a sort score to every alternate and favor
671                 # the newest (highest numbered) one because loose objects
672                 # require scanning epochs and only the latest epoch is
673                 # expected to see loose objects
674                 my $score;
675                 my $other = 0; # in case admin adds non-epoch repos
676                 %alt = map {;
677                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
678                                 $score = $1 + 0;
679                         } else {
680                                 $score = --$other;
681                         }
682                         $_ => $score;
683                 } split(/\n+/, do { local $/; <$fh> });
684         }
685
686         foreach my $i (0..$epoch) {
687                 my $dir = "../../git/$i.git/objects";
688                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
689                         $alt{$dir} = $i;
690                         $new = 1;
691                 }
692         }
693         return unless $new;
694         write_alternates($info_dir, $mode,
695                 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
696 }
697
698 sub git_init {
699         my ($self, $epoch) = @_;
700         my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
701         PublicInbox::Import::init_bare($git_dir);
702         run_die([qw(git config), "--file=$git_dir/config",
703                 qw(include.path ../../all.git/config)]);
704         fill_alternates($self, $epoch);
705         $git_dir
706 }
707
708 sub importer {
709         my ($self) = @_;
710         my $im = $self->{im};
711         if ($im) {
712                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
713                         return $im;
714                 } else {
715                         $self->{im} = undef;
716                         $im->done;
717                         $im = undef;
718                         $self->checkpoint;
719                         my $git_dir = $self->git_init(++$self->{epoch_max});
720                         my $git = PublicInbox::Git->new($git_dir);
721                         return $self->import_init($git, 0);
722                 }
723         }
724         my $epoch = 0;
725         my $max;
726         my $latest = $self->{ibx}->git_dir_latest(\$max);
727         if (defined $latest) {
728                 my $git = PublicInbox::Git->new($latest);
729                 my $packed_bytes = $git->packed_bytes;
730                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
731
732                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
733                         $epoch = $max + 1;
734                 } else {
735                         $self->{epoch_max} = $max;
736                         return $self->import_init($git, $packed_bytes);
737                 }
738         }
739         $self->{epoch_max} = $epoch;
740         $latest = $self->git_init($epoch);
741         $self->import_init(PublicInbox::Git->new($latest), 0);
742 }
743
744 sub import_init {
745         my ($self, $git, $packed_bytes, $tmp) = @_;
746         my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
747         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
748         $im->{lock_path} = undef;
749         $im->{path_type} = 'v2';
750         $self->{im} = $im unless $tmp;
751         $im;
752 }
753
754 # XXX experimental
755 sub diff ($$$) {
756         my ($mid, $cur, $new) = @_;
757
758         my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXX', TMPDIR => 1);
759         print $ah $cur->as_string or die "print: $!";
760         $ah->flush or die "flush: $!";
761         PublicInbox::Import::drop_unwanted_headers($new);
762         my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXX', TMPDIR => 1);
763         print $bh $new->as_string or die "print: $!";
764         $bh->flush or die "flush: $!";
765         my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
766         print STDERR "# MID conflict <$mid>\n";
767         my $pid = spawn($cmd, undef, { 1 => 2 });
768         waitpid($pid, 0) == $pid or die "diff did not finish";
769 }
770
771 sub get_blob ($$) {
772         my ($self, $smsg) = @_;
773         if (my $im = $self->{im}) {
774                 my $msg = $im->cat_blob($smsg->{blob});
775                 return $msg if $msg;
776         }
777         # older message, should be in alternates
778         $self->{ibx}->msg_by_smsg($smsg);
779 }
780
781 sub content_exists ($$$) {
782         my ($self, $mime, $mid) = @_;
783         my $oidx = $self->{oidx};
784         my $chashes = content_hashes($mime);
785         my ($id, $prev);
786         while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
787                 my $msg = get_blob($self, $smsg);
788                 if (!defined($msg)) {
789                         warn "broken smsg for $mid\n";
790                         next;
791                 }
792                 my $cur = PublicInbox::Eml->new($msg);
793                 return 1 if content_matches($chashes, $cur);
794
795                 # XXX DEBUG_DIFF is experimental and may be removed
796                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
797         }
798         undef;
799 }
800
801 sub atfork_child {
802         my ($self) = @_;
803         if (my $older_siblings = $self->{idx_shards}) {
804                 $_->ipc_sibling_atfork_child for @$older_siblings;
805         }
806         if (my $im = $self->{im}) {
807                 $im->atfork_child;
808         }
809         die "BUG: unexpected mm" if $self->{mm};
810 }
811
812 sub reindex_checkpoint ($$) {
813         my ($self, $sync) = @_;
814
815         $self->git->async_wait_all;
816         $self->update_last_commit($sync);
817         ${$sync->{need_checkpoint}} = 0;
818         my $mm_tmp = $sync->{mm_tmp};
819         $mm_tmp->atfork_prepare if $mm_tmp;
820         die 'BUG: {im} during reindex' if $self->{im};
821         if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
822                 checkpoint($self, 1); # no need to release lock on pure index
823         } else {
824                 $self->done; # release lock
825         }
826
827         if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
828                 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
829         }
830
831         # allow -watch or -mda to write...
832         $self->idx_init($sync->{-opt}); # reacquire lock
833         if (my $intvl = $sync->{check_intvl}) { # eidx
834                 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
835         }
836         $mm_tmp->atfork_parent if $mm_tmp;
837 }
838
839 sub index_finalize ($$) {
840         my ($arg, $index) = @_;
841         ++$arg->{self}->{nidx};
842         if (defined(my $cur = $arg->{cur_cmt})) {
843                 ${$arg->{latest_cmt}} = $cur;
844         } elsif ($index) {
845                 die 'BUG: {cur_cmt} missing';
846         } # else { unindexing @leftovers doesn't set {cur_cmt}
847 }
848
849 sub index_oid { # cat_async callback
850         my ($bref, $oid, $type, $size, $arg) = @_;
851         is_bad_blob($oid, $type, $size, $arg->{oid}) and
852                 return index_finalize($arg, 1); # size == 0 purged returns here
853         my $self = $arg->{self};
854         local $self->{current_info} = "$self->{current_info} $oid";
855         my ($num, $mid0);
856         my $eml = PublicInbox::Eml->new($$bref);
857         my $mids = mids($eml);
858         my $chash = content_hash($eml);
859
860         if (scalar(@$mids) == 0) {
861                 warn "E: $oid has no Message-ID, skipping\n";
862                 return;
863         }
864
865         # {unindexed} is unlikely
866         if (my $unindexed = $arg->{unindexed}) {
867                 my $oidbin = pack('H*', $oid);
868                 my $u = $unindexed->{$oidbin};
869                 ($num, $mid0) = splice(@$u, 0, 2) if $u;
870                 if (defined $num) {
871                         $self->{mm}->mid_set($num, $mid0);
872                         if (scalar(@$u) == 0) { # done with current OID
873                                 delete $unindexed->{$oidbin};
874                                 delete($arg->{unindexed}) if !keys(%$unindexed);
875                         }
876                 }
877         }
878         if (!defined($num)) { # reuse if reindexing (or duplicates)
879                 my $oidx = $self->{oidx};
880                 for my $mid (@$mids) {
881                         ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
882                         last if defined $num;
883                 }
884         }
885         $mid0 //= do { # is this a number we got before?
886                 $num = $arg->{mm_tmp}->num_for($mids->[0]);
887                 defined($num) ? $mids->[0] : undef;
888         };
889         if (!defined($num)) {
890                 for (my $i = $#$mids; $i >= 1; $i--) {
891                         $num = $arg->{mm_tmp}->num_for($mids->[$i]);
892                         if (defined($num)) {
893                                 $mid0 = $mids->[$i];
894                                 last;
895                         }
896                 }
897         }
898         if (defined($num)) {
899                 $arg->{mm_tmp}->num_delete($num);
900         } else { # never seen
901                 $num = $self->{mm}->mid_insert($mids->[0]);
902                 if (defined($num)) {
903                         $mid0 = $mids->[0];
904                 } else { # rare, try the rest of them, backwards
905                         for (my $i = $#$mids; $i >= 1; $i--) {
906                                 $num = $self->{mm}->mid_insert($mids->[$i]);
907                                 if (defined($num)) {
908                                         $mid0 = $mids->[$i];
909                                         last;
910                                 }
911                         }
912                 }
913         }
914         if (!defined($num)) {
915                 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
916                 return;
917         }
918         ++${$arg->{nr}};
919         my $smsg = bless {
920                 num => $num,
921                 blob => $oid,
922                 mid => $mid0,
923         }, 'PublicInbox::Smsg';
924         $smsg->populate($eml, $arg);
925         $smsg->set_bytes($$bref, $size);
926         if (do_idx($self, $eml, $smsg)) {
927                 ${$arg->{need_checkpoint}} = 1;
928         }
929         index_finalize($arg, 1);
930 }
931
932 # only update last_commit for $i on reindex iff newer than current
933 sub update_last_commit {
934         my ($self, $sync, $stk) = @_;
935         my $unit = $sync->{unit} // return;
936         my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
937         defined($latest_cmt) or return;
938         my $last = last_epoch_commit($self, $unit->{epoch});
939         if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
940                 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
941                 chomp(my $n = $unit->{git}->qx(@cmd));
942                 return if $n ne '' && $n == 0;
943         }
944         last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
945 }
946
947 sub last_commits {
948         my ($self, $sync) = @_;
949         my $heads = [];
950         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
951                 $heads->[$i] = last_epoch_commit($self, $i);
952         }
953         $heads;
954 }
955
956 # returns a revision range for git-log(1)
957 sub log_range ($$$) {
958         my ($sync, $unit, $tip) = @_;
959         my $opt = $sync->{-opt};
960         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
961         my $i = $unit->{epoch};
962         my $cur = $sync->{ranges}->[$i] or do {
963                 $pr->("$i.git indexing all of $tip\n") if $pr;
964                 return $tip; # all of it
965         };
966
967         # fast equality check to avoid (v)fork+execve overhead
968         if ($cur eq $tip) {
969                 $sync->{ranges}->[$i] = undef;
970                 return;
971         }
972
973         my $range = "$cur..$tip";
974         $pr->("$i.git checking contiguity... ") if $pr;
975         my $git = $unit->{git};
976         if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
977                 $pr->("OK\n") if $pr;
978                 my $n = $git->qx(qw(rev-list --count), $range);
979                 chomp($n);
980                 if ($n == 0) {
981                         $sync->{ranges}->[$i] = undef;
982                         $pr->("$i.git has nothing new\n") if $pr;
983                         return; # nothing to do
984                 }
985                 $pr->("$i.git has $n changes since $cur\n") if $pr;
986         } else {
987                 $pr->("FAIL\n") if $pr;
988                 warn <<"";
989 discontiguous range: $range
990 Rewritten history? (in $git->{git_dir})
991
992                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
993                 if ($base) {
994                         $range = "$base..$tip";
995                         warn "found merge-base: $base\n"
996                 } else {
997                         $range = $tip;
998                         warn "discarding history at $cur\n";
999                 }
1000                 warn <<"";
1001 reindexing $git->{git_dir}
1002 starting at $range
1003
1004                 # $cur^0 may no longer exist if pruned by git
1005                 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1006                         $unit->{unindex_range} = "$base..$cur";
1007                 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1008                         $unit->{unindex_range} = "$base..";
1009                 } else {
1010                         warn "W: unable to unindex before $range\n";
1011                 }
1012         }
1013         $range;
1014 }
1015
1016 # overridden by ExtSearchIdx
1017 sub artnum_max { $_[0]->{mm}->num_highwater }
1018
1019 sub sync_prepare ($$) {
1020         my ($self, $sync) = @_;
1021         $sync->{ranges} = sync_ranges($self, $sync);
1022         my $pr = $sync->{-opt}->{-progress};
1023         my $regen_max = 0;
1024         my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1025         my $pfx;
1026         if ($pr) {
1027                 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1028                 $pfx //= $sync->{ibx}->{inboxdir};
1029         }
1030
1031         my $reindex_heads;
1032         if ($self->{ibx_map}) {
1033                 # ExtSearchIdx won't index messages unless they're in
1034                 # over.sqlite3 for a given inbox, so don't read beyond
1035                 # what's in the per-inbox index.
1036                 $reindex_heads = [];
1037                 my $v = PublicInbox::Search::SCHEMA_VERSION;
1038                 my $mm = $sync->{ibx}->mm;
1039                 for my $i (0..$sync->{epoch_max}) {
1040                         $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1041                 }
1042         } elsif ($sync->{reindex}) { # V2 inbox
1043                 # reindex stops at the current heads and we later
1044                 # rerun index_sync without {reindex}
1045                 $reindex_heads = $self->last_commits($sync);
1046         }
1047         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1048                 $sync->{index_oid} = $self->can('index_oid');
1049         }
1050         my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1051         for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1052                 my $git_dir = "$git_pfx/$i.git";
1053                 -d $git_dir or next; # missing epochs are fine
1054                 my $git = PublicInbox::Git->new($git_dir);
1055                 my $unit = { git => $git, epoch => $i };
1056                 my $tip;
1057                 if ($reindex_heads) {
1058                         $tip = $head = $reindex_heads->[$i] or next;
1059                 } else {
1060                         $tip = $git->qx(qw(rev-parse -q --verify), $head);
1061                         next if $?; # new repo
1062                         chomp $tip;
1063                 }
1064                 my $range = log_range($sync, $unit, $tip) or next;
1065                 # can't use 'rev-list --count' if we use --diff-filter
1066                 $pr->("$pfx $i.git counting $range ... ") if $pr;
1067                 # Don't bump num_highwater on --reindex by using {D}.
1068                 # We intentionally do NOT use {D} in the non-reindex case
1069                 # because we want NNTP article number gaps from unindexed
1070                 # messages to show up in mirrors, too.
1071                 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1072                 my $stk = log2stack($sync, $git, $range);
1073                 return 0 if $sync->{quit};
1074                 my $nr = $stk ? $stk->num_records : 0;
1075                 $pr->("$nr\n") if $pr;
1076                 $unit->{stack} = $stk; # may be undef
1077                 unshift @{$sync->{todo}}, $unit;
1078                 $regen_max += $nr;
1079         }
1080         return 0 if $sync->{quit};
1081
1082         # XXX this should not happen unless somebody bypasses checks in
1083         # our code and blindly injects "d" file history into git repos
1084         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1085                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1086                 local $self->{current_info} = 'leftover ';
1087                 my $unindex_oid = $self->can('unindex_oid');
1088                 for my $oid (@leftovers) {
1089                         last if $sync->{quit};
1090                         $oid = unpack('H*', $oid);
1091                         my $req = { %$sync, oid => $oid };
1092                         $self->git->cat_async($oid, $unindex_oid, $req);
1093                 }
1094                 $self->git->cat_async_wait;
1095         }
1096         return 0 if $sync->{quit};
1097         if (!$regen_max) {
1098                 $sync->{-regen_fmt} = "%u/?\n";
1099                 return 0;
1100         }
1101
1102         # reindex should NOT see new commits anymore, if we do,
1103         # it's a problem and we need to notice it via die()
1104         my $pad = length($regen_max) + 1;
1105         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1106         $sync->{nr} = \(my $nr = 0);
1107         return -1 if $sync->{reindex};
1108         $regen_max + $self->artnum_max || 0;
1109 }
1110
1111 sub unindex_oid_aux ($$$) {
1112         my ($self, $oid, $mid) = @_;
1113         my @removed = $self->{oidx}->remove_oid($oid, $mid);
1114         return unless $self->{-need_xapian};
1115         for my $num (@removed) {
1116                 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1117         }
1118 }
1119
1120 sub unindex_oid ($$;$) { # git->cat_async callback
1121         my ($bref, $oid, $type, $size, $arg) = @_;
1122         is_bad_blob($oid, $type, $size, $arg->{oid}) and
1123                 return index_finalize($arg, 0);
1124         my $self = $arg->{self};
1125         local $self->{current_info} = "$self->{current_info} $oid";
1126         my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1127         my $mm = $self->{mm};
1128         my $mids = mids(PublicInbox::Eml->new($bref));
1129         undef $$bref;
1130         my $oidx = $self->{oidx};
1131         foreach my $mid (@$mids) {
1132                 my %gone;
1133                 my ($id, $prev);
1134                 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1135                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1136                 }
1137                 my $n = scalar(keys(%gone)) or next;
1138                 if ($n > 1) {
1139                         warn "BUG: multiple articles linked to $oid\n",
1140                                 join(',',sort keys %gone), "\n";
1141                 }
1142                 # reuse (num => mid) mapping in ascending numeric order
1143                 for my $num (sort { $a <=> $b } keys %gone) {
1144                         $num += 0;
1145                         if ($unindexed) {
1146                                 my $mid0 = $mm->mid_for($num);
1147                                 my $oidbin = pack('H*', $oid);
1148                                 push @{$unindexed->{$oidbin}}, $num, $mid0;
1149                         }
1150                         $mm->num_delete($num);
1151                 }
1152                 unindex_oid_aux($self, $oid, $mid);
1153         }
1154         index_finalize($arg, 0);
1155 }
1156
1157 sub git { $_[0]->{ibx}->git }
1158
1159 # this is rare, it only happens when we get discontiguous history in
1160 # a mirror because the source used -purge or -edit
1161 sub unindex_todo ($$$) {
1162         my ($self, $sync, $unit) = @_;
1163         my $unindex_range = delete($unit->{unindex_range}) // return;
1164         my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1165         my $before = scalar keys %$unindexed;
1166         # order does not matter, here:
1167         my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1168                                 --no-abbrev --no-renames), $unindex_range);
1169         local $sync->{in_unindex} = 1;
1170         my $unindex_oid = $self->can('unindex_oid');
1171         while (<$fh>) {
1172                 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1173                 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1174         }
1175         close $fh or die "git log failed: \$?=$?";
1176         $self->git->cat_async_wait;
1177
1178         return unless $sync->{-opt}->{prune};
1179         my $after = scalar keys %$unindexed;
1180         return if $before == $after;
1181
1182         # ensure any blob can not longer be accessed via dumb HTTP
1183         run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1184                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1185 }
1186
1187 sub sync_ranges ($$) {
1188         my ($self, $sync) = @_;
1189         my $reindex = $sync->{reindex};
1190         return $self->last_commits($sync) unless $reindex;
1191         return [] if ref($reindex) ne 'HASH';
1192
1193         my $ranges = $reindex->{from}; # arrayref;
1194         if (ref($ranges) ne 'ARRAY') {
1195                 die 'BUG: $reindex->{from} not an ARRAY';
1196         }
1197         $ranges;
1198 }
1199
1200 sub index_xap_only { # git->cat_async callback
1201         my ($bref, $oid, $type, $size, $smsg) = @_;
1202         my $self = delete $smsg->{self};
1203         my $idx = idx_shard($self, $smsg->{num});
1204         $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1205         $self->{transact_bytes} += $smsg->{bytes};
1206 }
1207
1208 sub index_xap_step ($$$;$) {
1209         my ($self, $sync, $beg, $step) = @_;
1210         my $end = $sync->{art_end};
1211         return if $beg > $end; # nothing to do
1212
1213         $step //= $self->{shards};
1214         my $ibx = $self->{ibx};
1215         if (my $pr = $sync->{-opt}->{-progress}) {
1216                 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1217                         "$beg..$end (% $step)\n");
1218         }
1219         for (my $num = $beg; $num <= $end; $num += $step) {
1220                 last if $sync->{quit};
1221                 my $smsg = $ibx->over->get_art($num) or next;
1222                 $smsg->{self} = $self;
1223                 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1224                 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1225                         ${$sync->{nr}} = $num;
1226                         reindex_checkpoint($self, $sync);
1227                 }
1228         }
1229 }
1230
1231 sub index_todo ($$$) {
1232         my ($self, $sync, $unit) = @_;
1233         return if $sync->{quit};
1234         unindex_todo($self, $sync, $unit);
1235         my $stk = delete($unit->{stack}) or return;
1236         my $all = $self->git;
1237         my $index_oid = $self->can('index_oid');
1238         my $unindex_oid = $self->can('unindex_oid');
1239         my $pfx;
1240         if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1241                 $pfx = "$1 $2"; # v2
1242         } else { # v1
1243                 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1244                 $pfx //= $unit->{git}->{git_dir};
1245         }
1246         local $self->{current_info} = "$pfx ";
1247         local $sync->{latest_cmt} = \(my $latest_cmt);
1248         local $sync->{unit} = $unit;
1249         while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1250                 if ($sync->{quit}) {
1251                         warn "waiting to quit...\n";
1252                         $all->async_wait_all;
1253                         $self->update_last_commit($sync);
1254                         return;
1255                 }
1256                 my $req = {
1257                         %$sync,
1258                         autime => $at,
1259                         cotime => $ct,
1260                         oid => $oid,
1261                         cur_cmt => $cmt
1262                 };
1263                 if ($f eq 'm') {
1264                         if ($sync->{max_size}) {
1265                                 $all->check_async($oid, \&check_size, $req);
1266                         } else {
1267                                 $all->cat_async($oid, $index_oid, $req);
1268                         }
1269                 } elsif ($f eq 'd') {
1270                         $all->cat_async($oid, $unindex_oid, $req);
1271                 }
1272                 if (${$sync->{need_checkpoint}}) {
1273                         reindex_checkpoint($self, $sync);
1274                 }
1275         }
1276         $all->async_wait_all;
1277         $self->update_last_commit($sync, $stk);
1278 }
1279
1280 sub xapian_only {
1281         my ($self, $opt, $sync, $art_beg) = @_;
1282         my $seq = $opt->{'sequential-shard'};
1283         $art_beg //= 0;
1284         local $self->{parallel} = 0 if $seq;
1285         $self->idx_init($opt); # acquire lock
1286         if (my $art_end = $self->{ibx}->mm->max) {
1287                 $sync //= {
1288                         need_checkpoint => \(my $bool = 0),
1289                         -opt => $opt,
1290                         self => $self,
1291                         nr => \(my $nr = 0),
1292                         -regen_fmt => "%u/?\n",
1293                 };
1294                 $sync->{art_end} = $art_end;
1295                 if ($seq || !$self->{parallel}) {
1296                         my $shard_end = $self->{shards} - 1;
1297                         for my $i (0..$shard_end) {
1298                                 last if $sync->{quit};
1299                                 index_xap_step($self, $sync, $art_beg + $i);
1300                                 if ($i != $shard_end) {
1301                                         reindex_checkpoint($self, $sync);
1302                                 }
1303                         }
1304                 } else { # parallel (maybe)
1305                         index_xap_step($self, $sync, $art_beg, 1);
1306                 }
1307         }
1308         $self->git->cat_async_wait;
1309         $self->{ibx}->cleanup;
1310         $self->done;
1311 }
1312
1313 # public, called by public-inbox-index
1314 sub index_sync {
1315         my ($self, $opt) = @_;
1316         $opt //= {};
1317         return xapian_only($self, $opt) if $opt->{xapian_only};
1318
1319         my $epoch_max;
1320         my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1321         if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1322                 use Time::HiRes qw(stat);
1323                 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1324                         my $c = $mm[10]; # 10 = ctime (nsec NV)
1325                         my @hd = stat("$latest/refs/heads");
1326                         my @pr = stat("$latest/packed-refs");
1327                         return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1328                 }
1329         }
1330
1331         my $pr = $opt->{-progress};
1332         my $seq = $opt->{'sequential-shard'};
1333         my $art_beg; # the NNTP article number we start xapian_only at
1334         my $idxlevel = $self->{ibx}->{indexlevel};
1335         local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1336
1337         $self->idx_init($opt); # acquire lock
1338         fill_alternates($self, $epoch_max);
1339         $self->{oidx}->rethread_prepare($opt);
1340         my $sync = {
1341                 need_checkpoint => \(my $bool = 0),
1342                 reindex => $opt->{reindex},
1343                 -opt => $opt,
1344                 self => $self,
1345                 ibx => $self->{ibx},
1346                 epoch_max => $epoch_max,
1347         };
1348         my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1349         local $SIG{QUIT} = $quit;
1350         local $SIG{INT} = $quit;
1351         local $SIG{TERM} = $quit;
1352
1353         if (sync_prepare($self, $sync)) {
1354                 # tmp_clone seems to fail if inside a transaction, so
1355                 # we rollback here (because we opened {mm} for reading)
1356                 # Note: we do NOT rely on DBI transactions for atomicity;
1357                 # only for batch performance.
1358                 $self->{mm}->{dbh}->rollback;
1359                 $self->{mm}->{dbh}->begin_work;
1360                 $sync->{mm_tmp} =
1361                         $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1362
1363                 # xapian_only works incrementally w/o --reindex
1364                 if ($seq && !$opt->{reindex}) {
1365                         $art_beg = $sync->{mm_tmp}->max || -1;
1366                         $art_beg++;
1367                 }
1368         }
1369         # work forwards through history
1370         index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1371         $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1372         $self->done;
1373
1374         if (my $nr = $sync->{nr}) {
1375                 my $pr = $sync->{-opt}->{-progress};
1376                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1377         }
1378
1379         my $quit_warn;
1380         # deal with Xapian shards sequentially
1381         if ($seq && delete($sync->{mm_tmp})) {
1382                 if ($sync->{quit}) {
1383                         $quit_warn = 1;
1384                 } else {
1385                         $self->{ibx}->{indexlevel} = $idxlevel;
1386                         xapian_only($self, $opt, $sync, $art_beg);
1387                         $quit_warn = 1 if $sync->{quit};
1388                 }
1389         }
1390
1391         # --reindex on the command-line
1392         if (!$sync->{quit} && $opt->{reindex} &&
1393                         !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1394                 $self->lock_acquire;
1395                 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1396                 if (my $xdb = $s0->idx_acquire) {
1397                         my $n = $xdb->get_metadata('has_threadid');
1398                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1399                 }
1400                 $s0->idx_release;
1401                 $self->lock_release;
1402         }
1403
1404         # reindex does not pick up new changes, so we rerun w/o it:
1405         if ($opt->{reindex} && !$sync->{quit}) {
1406                 my %again = %$opt;
1407                 $sync = undef;
1408                 delete @again{qw(rethread reindex -skip_lock)};
1409                 index_sync($self, \%again);
1410                 $opt->{quit} = $again{quit}; # propagate to caller
1411         }
1412         warn <<EOF if $quit_warn;
1413 W: interrupted, --xapian-only --reindex required upon restart
1414 EOF
1415 }
1416
1417 sub ipc_atfork_child {
1418         my ($self) = @_;
1419         if (my $lei = delete $self->{lei}) {
1420                 $lei->_lei_atfork_child;
1421                 my $pkt_op_p = delete $lei->{pkt_op_p};
1422                 close($pkt_op_p->{op_p});
1423         }
1424         $self->SUPER::ipc_atfork_child;
1425 }
1426
1427 1;