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