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