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