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