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