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