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