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