1 # Copyright (C) 2018-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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;
9 use parent qw(PublicInbox::Lock PublicInbox::IPC);
10 use PublicInbox::SearchIdxShard;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentHash qw(content_hash content_digest git_sha);
17 use PublicInbox::InboxWritable;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd run_die);
21 use PublicInbox::Search;
22 use PublicInbox::SearchIdx qw(log2stack is_ancestor check_size is_bad_blob);
23 use IO::Handle; # ->autoflush
27 my $OID = qr/[a-f0-9]{40,}/;
28 # an estimate of the post-packed size to the raw uncompressed size
29 our $PACKING_FACTOR = 0.4;
31 # SATA storage lags behind what CPUs are capable of, so relying on
32 # nproc(1) can be misleading and having extra Xapian shards is a
33 # waste of FDs and space. It can also lead to excessive IO latency
34 # and slow things down. Users on NVME or other fast storage can
35 # use the NPROC env or switches in our script/public-inbox-* programs
36 # to increase Xapian shards
37 our $NPROC_MAX_DEFAULT = 4;
39 sub nproc_shards ($) {
41 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
44 # assume 2 cores if not detectable or zero
45 state $NPROC_DETECTED = PublicInbox::IPC::detect_nproc() || 2;
47 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
50 # subtract for the main process and git-fast-import
55 sub count_shards ($) {
57 if (my $ibx = $self->{ibx}) {
58 # always load existing shards in case core count changes:
59 # Also, shard count may change while -watch is running
60 my $srch = $ibx->search or return 0;
61 delete $ibx->{search};
63 } else { # ExtSearchIdx
64 $self->{nshard} ||= scalar($self->xdb_shards_flat);
69 # $creat may be any true value, or 0/undef. A hashref is true,
70 # and $creat->{nproc} may be set to an integer
71 my ($class, $v2ibx, $creat) = @_;
72 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
73 my $dir = $v2ibx->assert_usable_dir;
77 File::Path::mkpath($dir);
79 die "$dir does not exist\n";
82 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
85 im => undef, # PublicInbox::Import
91 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
92 lock_path => "$dir/inbox.lock",
93 # limit each git repo (epoch) to 1GB or so
94 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
95 last_commit => [], # git epoch -> commit
97 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
98 $self->{shards} = count_shards($self) || nproc_shards($creat);
104 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
105 if (defined $shards) {
106 $self->{parallel} = 0 if $shards == 0;
107 $self->{shards} = $shards if $shards > 0;
110 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
111 my $max = $self->{ibx}->max_git_epoch;
112 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
113 $self->git_init($max // 0);
117 # returns undef on duplicate or spam
118 # mimics Import::add and wraps it for v2
120 my ($self, $eml, $check_cb) = @_;
121 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
125 my ($self, $num) = @_;
126 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
129 # indexes a message, returns true if checkpointing is needed
131 my ($self, $eml, $smsg) = @_;
132 $self->{oidx}->add_overview($eml, $smsg);
133 if ($self->{-need_xapian}) {
134 my $idx = idx_shard($self, $smsg->{num});
135 $idx->index_eml($eml, $smsg);
137 my $n = $self->{transact_bytes} += $smsg->{bytes};
138 $n >= $self->{batch_bytes};
142 my ($self, $mime, $check_cb) = @_;
146 $mime = $check_cb->($mime, $self->{ibx}) or return;
149 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
150 # as does SQLite 3.4.1+ (released in 2007-07-20), and
151 # Xapian 1.3.2+ (released 2015-03-15).
152 # For the most part, we can spawn git-fast-import without
153 # leaking FDs to it...
156 my ($num, $mid0) = v2_num_for($self, $mime);
157 defined $num or return; # duplicate
158 defined $mid0 or die "BUG: \$mid0 undefined\n";
159 my $im = $self->importer;
160 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
161 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
162 $cmt = $im->get_mark($cmt);
163 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
165 if (do_idx($self, $mime, $smsg)) {
173 my ($self, $mime) = @_;
174 my $mids = mids($mime);
176 my $mid = $mids->[0];
177 my $num = $self->{mm}->mid_insert($mid);
178 if (defined $num) { # common case
182 # crap, Message-ID is already known, hope somebody just resent:
183 foreach my $m (@$mids) {
184 # read-only lookup now safe to do after above barrier
185 # easy, don't store duplicates
186 # note: do not add more diagnostic info here since
187 # it gets noisy on public-inbox-watch restarts
188 return () if content_exists($self, $mime, $m);
191 # AltId may pre-populate article numbers (e.g. X-Mail-Count
192 # or NNTP article number), use that article number if it's
194 my $altid = $self->{ibx}->{altid};
195 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
196 my $num = $self->{mm}->num_for($mid);
198 if (defined $num && !$self->{oidx}->get_art($num)) {
204 warn "<$mid> reused for mismatched content\n";
206 # try the rest of the mids
207 for(my $i = $#$mids; $i >= 1; $i--) {
209 $num = $self->{mm}->mid_insert($m);
211 warn "alternative <$m> for <$mid> found\n";
216 # none of the existing Message-IDs are good, generate a new one:
217 v2_num_for_harder($self, $mime);
220 sub v2_num_for_harder {
221 my ($self, $eml) = @_;
223 my $dig = content_digest($eml);
224 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
225 my $num = $self->{mm}->mid_insert($mid0);
226 unless (defined $num) {
227 # it's hard to spoof the last Received: header
228 my @recvd = $eml->header_raw('Received');
229 $dig->add("Received: $_") foreach (@recvd);
230 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
231 $num = $self->{mm}->mid_insert($mid0);
233 # fall back to a random Message-ID and give up determinism:
234 until (defined($num)) {
236 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
237 warn "using random Message-ID <$mid0> as fallback\n";
238 $num = $self->{mm}->mid_insert($mid0);
241 PublicInbox::Import::append_mid($eml, $mid0);
245 sub _idx_init { # with_umask callback
246 my ($self, $opt) = @_;
247 $self->lock_acquire unless $opt && $opt->{-skip_lock};
248 $self->{oidx}->create;
250 # xcpdb can change shard count while -watch is idle
251 my $nshards = count_shards($self);
252 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
253 $self->{batch_bytes} = $opt->{batch_size} //
254 $PublicInbox::SearchIdx::BATCH_BYTES;
256 # need to create all shards before initializing msgmap FD
257 # idx_shards must be visible to all forked processes
258 my $max = $self->{shards} - 1;
259 my $idx = $self->{idx_shards} = [];
260 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
261 $self->{-need_xapian} = $idx->[0]->need_xapian;
263 # SearchIdxShard may do their own flushing, so don't scale
264 # until after forking
265 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
267 my $ibx = $self->{ibx} or return; # ExtIdxSearch
269 # Now that all subprocesses are up, we can open the FDs
271 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
272 "$ibx->{inboxdir}/msgmap.sqlite3",
273 $ibx->{-no_fsync} ? 2 : 1);
274 $mm->{dbh}->begin_work;
277 sub parallel_init ($$) {
278 my ($self, $indexlevel) = @_;
279 $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
284 my ($self, $opt) = @_;
285 return if $self->{idx_shards};
286 my $ibx = $self->{ibx};
288 # do not leak read-only FDs to child processes, we only have these
289 # FDs for duplicate detection so they should not be
290 # frequently activated.
291 delete @$ibx{qw(mm search)};
294 parallel_init($self, $ibx->{indexlevel});
295 $ibx->with_umask(\&_idx_init, $self, $opt);
298 # returns an array mapping [ epoch => latest_commit ]
299 # latest_commit may be undef if nothing was done to that epoch
300 # $replace_map = { $object_id => $strref, ... }
301 sub _replace_oids ($$$) {
302 my ($self, $mime, $replace_map) = @_;
304 my $ibx = $self->{ibx};
305 my $pfx = "$ibx->{inboxdir}/git";
306 my $rewrites = []; # epoch => commit
307 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
309 foreach my $i (0..$max) {
310 my $git_dir = "$pfx/$i.git";
312 my $git = PublicInbox::Git->new($git_dir);
313 my $im = $self->import_init($git, 0, 1);
314 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
320 sub content_hashes ($) {
322 my @chashes = ( content_hash($mime) );
324 # We still support Email::MIME, here, and
325 # Email::MIME->as_string doesn't always round-trip, so we may
326 # use a second content_hash
327 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
328 push @chashes, $rt if $chashes[0] ne $rt;
332 sub content_matches ($$) {
333 my ($chashes, $existing) = @_;
334 my $chash = content_hash($existing);
335 foreach (@$chashes) {
336 return 1 if $_ eq $chash
341 # used for removing or replacing (purging)
342 sub rewrite_internal ($$;$$$) {
343 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
345 my ($im, $need_reindex, $replace_map);
347 $replace_map = {}; # oid => sref
348 $need_reindex = [] if $new_eml;
350 $im = $self->importer;
352 my $oidx = $self->{oidx};
353 my $chashes = content_hashes($old_eml);
355 my $mids = mids($old_eml);
357 # We avoid introducing new blobs into git since the raw content
358 # can be slightly different, so we do not need the user-supplied
359 # message now that we have the mids and content_hash
363 foreach my $mid (@$mids) {
364 my %gone; # num => [ smsg, $mime, raw ]
366 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
367 my $msg = get_blob($self, $smsg);
368 if (!defined($msg)) {
369 warn "broken smsg for $mid\n";
373 my $cur = PublicInbox::Eml->new($msg);
374 if (content_matches($chashes, $cur)) {
375 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
378 my $n = scalar keys %gone;
381 warn "BUG: multiple articles linked to <$mid>\n",
382 join(',', sort keys %gone), "\n";
384 foreach my $num (keys %gone) {
385 my ($smsg, $mime, $orig) = @{$gone{$num}};
386 # $removed should only be set once assuming
387 # no bugs in our deduplication code:
388 $removed = [ undef, $mime, $smsg ];
389 my $oid = $smsg->{blob};
391 $replace_map->{$oid} = $sref;
393 ($mark, undef) = $im->remove($orig, $cmt_msg);
394 $removed->[0] = $mark;
397 if ($need_reindex) { # ->replace
398 push @$need_reindex, $smsg;
399 } else { # ->purge or ->remove
400 $self->{mm}->num_delete($num);
402 unindex_oid_aux($self, $oid, $mid);
407 my $cmt = $im->get_mark($mark);
408 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
410 if ($replace_map && scalar keys %$replace_map) {
411 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
412 return { rewrites => $rewrites, need_reindex => $need_reindex };
414 defined($mark) ? $removed : undef;
417 # public (see PublicInbox::Import->remove), but note the 3rd element
418 # (retval[2]) is not part of the stable API shared with Import->remove
420 my ($self, $eml, $cmt_msg) = @_;
421 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
422 $self, $eml, $cmt_msg);
423 defined($r) && defined($r->[0]) ? @$r: undef;
426 sub _replace ($$;$$) {
427 my ($self, $old_eml, $new_eml, $sref) = @_;
428 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
429 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
430 $self, $old_eml, undef, $new_eml, $sref) or return;
432 my $rewrites = $rewritten->{rewrites};
433 # ->done is called if there are rewrites since we gc+prune from git
434 $self->idx_init if @$rewrites;
436 for my $i (0..$#$rewrites) {
437 defined(my $cmt = $rewrites->[$i]) or next;
438 $self->{last_commit}->[$i] = $cmt;
445 my ($self, $mime) = @_;
446 my $rewritten = _replace($self, $mime, undef, \'') or return;
447 $rewritten->{rewrites}
450 sub _check_mids_match ($$$) {
451 my ($old_list, $new_list, $hdrs) = @_;
452 my %old_mids = map { $_ => 1 } @$old_list;
453 my %new_mids = map { $_ => 1 } @$new_list;
454 my @old = keys %old_mids;
455 my @new = keys %new_mids;
456 my $err = "$hdrs may not be changed when replacing\n";
457 die $err if scalar(@old) != scalar(@new);
458 delete @new_mids{@old};
459 delete @old_mids{@new};
460 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
463 # Changing Message-IDs or References with ->replace isn't supported.
464 # The rules for dealing with messages with multiple or conflicting
465 # Message-IDs are pretty complex and rethreading hasn't been fully
467 sub check_mids_match ($$) {
468 my ($old, $new) = @_;
469 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
470 _check_mids_match(references($old), references($new),
471 'References/In-Reply-To');
476 my ($self, $old_mime, $new_mime) = @_;
478 check_mids_match($old_mime, $new_mime);
480 # mutt will always add Content-Length:, Status:, Lines: when editing
481 PublicInbox::Import::drop_unwanted_headers($new_mime);
483 my $raw = $new_mime->as_string;
484 my $expect_oid = git_sha(1, \$raw)->hexdigest;
485 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
486 my $need_reindex = $rewritten->{need_reindex};
488 # just in case we have bugs in deduplication code:
489 my $n = scalar(@$need_reindex);
491 my $list = join(', ', map {
492 "$_->{num}: <$_->{mid}>"
495 W: rewritten $n messages matching content of original message (expected: 1).
496 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
501 # make sure we really got the OID:
502 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
503 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
505 # don't leak FDs to Xapian:
508 # reindex modified messages:
509 for my $smsg (@$need_reindex) {
510 my $new_smsg = bless {
514 }, 'PublicInbox::Smsg';
515 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
516 $new_smsg->populate($new_mime, $sync);
517 $new_smsg->set_bytes($raw, $bytes);
518 do_idx($self, $new_mime, $new_smsg);
520 $rewritten->{rewrites};
523 sub last_epoch_commit ($$;$) {
524 my ($self, $i, $cmt) = @_;
525 my $v = PublicInbox::Search::SCHEMA_VERSION();
526 $self->{mm}->last_commit_xap($v, $i, $cmt);
529 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
531 defined(my $epoch_max = $self->{epoch_max}) or return;
532 my $last_commit = $self->{last_commit};
533 foreach my $i (0..$epoch_max) {
534 defined(my $cmt = $last_commit->[$i]) or next;
535 $last_commit->[$i] = undef;
536 last_epoch_commit($self, $i, $cmt);
541 sub checkpoint ($;$) {
542 my ($self, $wait) = @_;
544 if (my $im = $self->{im}) {
551 my $shards = $self->{idx_shards};
553 my $mm = $self->{mm};
554 my $dbh = $mm->{dbh} if $mm;
556 # SQLite msgmap data is second in importance
557 $dbh->commit if $dbh;
559 # SQLite overview is third
560 $self->{oidx}->commit_lazy;
562 # Now deal with Xapian
564 # start commit_txn_lazy asynchronously on all parallel shards
565 # (non-parallel waits here)
566 $_->ipc_do('commit_txn_lazy') for @$shards;
568 # transactions started on parallel shards,
569 # wait for them by issuing an echo command (echo can only
570 # run after commit_txn_lazy is done)
571 if ($wait && $self->{parallel}) {
573 for my $shard (@$shards) {
574 my $echo = $shard->ipc_do('echo', $i);
575 $echo == $i or die <<"";
576 shard[$i] bad echo:$echo != $i waiting for txn commit
582 my $midx = $self->{midx}; # misc index
585 $PublicInbox::Search::X{CLOEXEC_UNSET} and
589 # last_commit is special, don't commit these until
590 # Xapian shards are done:
591 $dbh->begin_work if $dbh;
592 set_last_commits($self);
598 $self->{total_bytes} += $self->{transact_bytes};
599 $self->{transact_bytes} = 0;
602 # issue a write barrier to ensure all data is visible to other processes
603 # and read-only ops. Order of data importance is: git > SQLite > Xapian
605 sub barrier { checkpoint($_[0], 1) };
607 # true if locked and active
608 sub active { !!$_[0]->{im} }
614 if (my $im = delete $self->{im}) {
615 eval { $im->done }; # PublicInbox::Import::done
616 $err .= "import done: $@\n" if $@;
619 eval { checkpoint($self) };
620 $err .= "checkpoint: $@\n" if $@;
622 if (my $mm = delete $self->{mm}) {
623 my $m = $err ? 'rollback' : 'commit';
624 eval { $mm->{dbh}->$m };
625 $err .= "msgmap $m: $@\n" if $@;
627 my $shards = delete $self->{idx_shards};
630 eval { $_->shard_close };
631 $err .= "shard close: $@\n" if $@;
634 eval { $self->{oidx}->dbh_close };
635 $err .= "over close: $@\n" if $@;
636 delete $self->{midx};
637 my $nbytes = $self->{total_bytes};
638 $self->{total_bytes} = 0;
639 $self->lock_release(!!$nbytes) if $shards;
644 sub write_alternates ($$$) {
645 my ($info_dir, $mode, $out) = @_;
646 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXX', DIR => $info_dir);
647 my $tmp = $fh->filename;
648 print $fh @$out or die "print $tmp: $!\n";
649 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
650 close $fh or die "close $tmp $!\n";
651 my $alt = "$info_dir/alternates";
652 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
653 $fh->unlink_on_destroy(0);
656 sub fill_alternates ($$) {
657 my ($self, $epoch) = @_;
659 my $pfx = "$self->{ibx}->{inboxdir}/git";
660 my $all = "$self->{ibx}->{inboxdir}/all.git";
661 PublicInbox::Import::init_bare($all) unless -d $all;
662 my $info_dir = "$all/objects/info";
663 my $alt = "$info_dir/alternates";
667 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
668 $mode = (stat($fh))[2] & 07777;
670 # we assign a sort score to every alternate and favor
671 # the newest (highest numbered) one because loose objects
672 # require scanning epochs and only the latest epoch is
673 # expected to see loose objects
675 my $other = 0; # in case admin adds non-epoch repos
677 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
683 } split(/\n+/, do { local $/; <$fh> });
686 foreach my $i (0..$epoch) {
687 my $dir = "../../git/$i.git/objects";
688 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
694 write_alternates($info_dir, $mode,
695 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
699 my ($self, $epoch) = @_;
700 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
701 PublicInbox::Import::init_bare($git_dir);
702 run_die([qw(git config), "--file=$git_dir/config",
703 qw(include.path ../../all.git/config)]);
704 fill_alternates($self, $epoch);
710 my $im = $self->{im};
712 if ($im->{bytes_added} < $self->{rotate_bytes}) {
719 my $git_dir = $self->git_init(++$self->{epoch_max});
720 my $git = PublicInbox::Git->new($git_dir);
721 return $self->import_init($git, 0);
726 my $latest = $self->{ibx}->git_dir_latest(\$max);
727 if (defined $latest) {
728 my $git = PublicInbox::Git->new($latest);
729 my $packed_bytes = $git->packed_bytes;
730 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
732 if ($unpacked_bytes >= $self->{rotate_bytes}) {
735 $self->{epoch_max} = $max;
736 return $self->import_init($git, $packed_bytes);
739 $self->{epoch_max} = $epoch;
740 $latest = $self->git_init($epoch);
741 $self->import_init(PublicInbox::Git->new($latest), 0);
745 my ($self, $git, $packed_bytes, $tmp) = @_;
746 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
747 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
748 $im->{lock_path} = undef;
749 $im->{path_type} = 'v2';
750 $self->{im} = $im unless $tmp;
756 my ($mid, $cur, $new) = @_;
758 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXX', TMPDIR => 1);
759 print $ah $cur->as_string or die "print: $!";
760 $ah->flush or die "flush: $!";
761 PublicInbox::Import::drop_unwanted_headers($new);
762 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXX', TMPDIR => 1);
763 print $bh $new->as_string or die "print: $!";
764 $bh->flush or die "flush: $!";
765 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
766 print STDERR "# MID conflict <$mid>\n";
767 my $pid = spawn($cmd, undef, { 1 => 2 });
768 waitpid($pid, 0) == $pid or die "diff did not finish";
772 my ($self, $smsg) = @_;
773 if (my $im = $self->{im}) {
774 my $msg = $im->cat_blob($smsg->{blob});
777 # older message, should be in alternates
778 $self->{ibx}->msg_by_smsg($smsg);
781 sub content_exists ($$$) {
782 my ($self, $mime, $mid) = @_;
783 my $oidx = $self->{oidx};
784 my $chashes = content_hashes($mime);
786 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
787 my $msg = get_blob($self, $smsg);
788 if (!defined($msg)) {
789 warn "broken smsg for $mid\n";
792 my $cur = PublicInbox::Eml->new($msg);
793 return 1 if content_matches($chashes, $cur);
795 # XXX DEBUG_DIFF is experimental and may be removed
796 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
803 if (my $older_siblings = $self->{idx_shards}) {
804 $_->ipc_sibling_atfork_child for @$older_siblings;
806 if (my $im = $self->{im}) {
809 die "BUG: unexpected mm" if $self->{mm};
812 sub reindex_checkpoint ($$) {
813 my ($self, $sync) = @_;
815 $self->git->async_wait_all;
816 $self->update_last_commit($sync);
817 ${$sync->{need_checkpoint}} = 0;
818 my $mm_tmp = $sync->{mm_tmp};
819 $mm_tmp->atfork_prepare if $mm_tmp;
820 die 'BUG: {im} during reindex' if $self->{im};
821 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
822 checkpoint($self, 1); # no need to release lock on pure index
824 $self->done; # release lock
827 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
828 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
831 # allow -watch or -mda to write...
832 $self->idx_init($sync->{-opt}); # reacquire lock
833 if (my $intvl = $sync->{check_intvl}) { # eidx
834 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
836 $mm_tmp->atfork_parent if $mm_tmp;
839 sub index_finalize ($$) {
840 my ($arg, $index) = @_;
841 ++$arg->{self}->{nidx};
842 if (defined(my $cur = $arg->{cur_cmt})) {
843 ${$arg->{latest_cmt}} = $cur;
845 die 'BUG: {cur_cmt} missing';
846 } # else { unindexing @leftovers doesn't set {cur_cmt}
849 sub index_oid { # cat_async callback
850 my ($bref, $oid, $type, $size, $arg) = @_;
851 is_bad_blob($oid, $type, $size, $arg->{oid}) and
852 return index_finalize($arg, 1); # size == 0 purged returns here
853 my $self = $arg->{self};
854 local $self->{current_info} = "$self->{current_info} $oid";
856 my $eml = PublicInbox::Eml->new($$bref);
857 my $mids = mids($eml);
858 my $chash = content_hash($eml);
860 if (scalar(@$mids) == 0) {
861 warn "E: $oid has no Message-ID, skipping\n";
865 # {unindexed} is unlikely
866 if (my $unindexed = $arg->{unindexed}) {
867 my $oidbin = pack('H*', $oid);
868 my $u = $unindexed->{$oidbin};
869 ($num, $mid0) = splice(@$u, 0, 2) if $u;
871 $self->{mm}->mid_set($num, $mid0);
872 if (scalar(@$u) == 0) { # done with current OID
873 delete $unindexed->{$oidbin};
874 delete($arg->{unindexed}) if !keys(%$unindexed);
878 if (!defined($num)) { # reuse if reindexing (or duplicates)
879 my $oidx = $self->{oidx};
880 for my $mid (@$mids) {
881 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
882 last if defined $num;
885 $mid0 //= do { # is this a number we got before?
886 $num = $arg->{mm_tmp}->num_for($mids->[0]);
887 defined($num) ? $mids->[0] : undef;
889 if (!defined($num)) {
890 for (my $i = $#$mids; $i >= 1; $i--) {
891 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
899 $arg->{mm_tmp}->num_delete($num);
900 } else { # never seen
901 $num = $self->{mm}->mid_insert($mids->[0]);
904 } else { # rare, try the rest of them, backwards
905 for (my $i = $#$mids; $i >= 1; $i--) {
906 $num = $self->{mm}->mid_insert($mids->[$i]);
914 if (!defined($num)) {
915 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
923 }, 'PublicInbox::Smsg';
924 $smsg->populate($eml, $arg);
925 $smsg->set_bytes($$bref, $size);
926 if (do_idx($self, $eml, $smsg)) {
927 ${$arg->{need_checkpoint}} = 1;
929 index_finalize($arg, 1);
932 # only update last_commit for $i on reindex iff newer than current
933 sub update_last_commit {
934 my ($self, $sync, $stk) = @_;
935 my $unit = $sync->{unit} // return;
936 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
937 defined($latest_cmt) or return;
938 my $last = last_epoch_commit($self, $unit->{epoch});
939 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
940 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
941 chomp(my $n = $unit->{git}->qx(@cmd));
942 return if $n ne '' && $n == 0;
944 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
948 my ($self, $sync) = @_;
950 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
951 $heads->[$i] = last_epoch_commit($self, $i);
956 # returns a revision range for git-log(1)
957 sub log_range ($$$) {
958 my ($sync, $unit, $tip) = @_;
959 my $opt = $sync->{-opt};
960 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
961 my $i = $unit->{epoch};
962 my $cur = $sync->{ranges}->[$i] or do {
963 $pr->("$i.git indexing all of $tip\n") if $pr;
964 return $tip; # all of it
967 # fast equality check to avoid (v)fork+execve overhead
969 $sync->{ranges}->[$i] = undef;
973 my $range = "$cur..$tip";
974 $pr->("$i.git checking contiguity... ") if $pr;
975 my $git = $unit->{git};
976 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
977 $pr->("OK\n") if $pr;
978 my $n = $git->qx(qw(rev-list --count), $range);
981 $sync->{ranges}->[$i] = undef;
982 $pr->("$i.git has nothing new\n") if $pr;
983 return; # nothing to do
985 $pr->("$i.git has $n changes since $cur\n") if $pr;
987 $pr->("FAIL\n") if $pr;
989 discontiguous range: $range
990 Rewritten history? (in $git->{git_dir})
992 chomp(my $base = $git->qx('merge-base', $tip, $cur));
994 $range = "$base..$tip";
995 warn "found merge-base: $base\n"
998 warn "discarding history at $cur\n";
1001 reindexing $git->{git_dir}
1004 # $cur^0 may no longer exist if pruned by git
1005 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1006 $unit->{unindex_range} = "$base..$cur";
1007 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1008 $unit->{unindex_range} = "$base..";
1010 warn "W: unable to unindex before $range\n";
1016 # overridden by ExtSearchIdx
1017 sub artnum_max { $_[0]->{mm}->num_highwater }
1019 sub sync_prepare ($$) {
1020 my ($self, $sync) = @_;
1021 $sync->{ranges} = sync_ranges($self, $sync);
1022 my $pr = $sync->{-opt}->{-progress};
1024 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1027 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1028 $pfx //= $sync->{ibx}->{inboxdir};
1032 if ($self->{ibx_map}) {
1033 # ExtSearchIdx won't index messages unless they're in
1034 # over.sqlite3 for a given inbox, so don't read beyond
1035 # what's in the per-inbox index.
1036 $reindex_heads = [];
1037 my $v = PublicInbox::Search::SCHEMA_VERSION;
1038 my $mm = $sync->{ibx}->mm;
1039 for my $i (0..$sync->{epoch_max}) {
1040 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1042 } elsif ($sync->{reindex}) { # V2 inbox
1043 # reindex stops at the current heads and we later
1044 # rerun index_sync without {reindex}
1045 $reindex_heads = $self->last_commits($sync);
1047 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1048 $sync->{index_oid} = $self->can('index_oid');
1050 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1051 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1052 my $git_dir = "$git_pfx/$i.git";
1053 -d $git_dir or next; # missing epochs are fine
1054 my $git = PublicInbox::Git->new($git_dir);
1055 my $unit = { git => $git, epoch => $i };
1057 if ($reindex_heads) {
1058 $tip = $head = $reindex_heads->[$i] or next;
1060 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1061 next if $?; # new repo
1064 my $range = log_range($sync, $unit, $tip) or next;
1065 # can't use 'rev-list --count' if we use --diff-filter
1066 $pr->("$pfx $i.git counting $range ... ") if $pr;
1067 # Don't bump num_highwater on --reindex by using {D}.
1068 # We intentionally do NOT use {D} in the non-reindex case
1069 # because we want NNTP article number gaps from unindexed
1070 # messages to show up in mirrors, too.
1071 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1072 my $stk = log2stack($sync, $git, $range);
1073 return 0 if $sync->{quit};
1074 my $nr = $stk ? $stk->num_records : 0;
1075 $pr->("$nr\n") if $pr;
1076 $unit->{stack} = $stk; # may be undef
1077 unshift @{$sync->{todo}}, $unit;
1080 return 0 if $sync->{quit};
1082 # XXX this should not happen unless somebody bypasses checks in
1083 # our code and blindly injects "d" file history into git repos
1084 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1085 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1086 local $self->{current_info} = 'leftover ';
1087 my $unindex_oid = $self->can('unindex_oid');
1088 for my $oid (@leftovers) {
1089 last if $sync->{quit};
1090 $oid = unpack('H*', $oid);
1091 my $req = { %$sync, oid => $oid };
1092 $self->git->cat_async($oid, $unindex_oid, $req);
1094 $self->git->cat_async_wait;
1096 return 0 if $sync->{quit};
1098 $sync->{-regen_fmt} = "%u/?\n";
1102 # reindex should NOT see new commits anymore, if we do,
1103 # it's a problem and we need to notice it via die()
1104 my $pad = length($regen_max) + 1;
1105 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1106 $sync->{nr} = \(my $nr = 0);
1107 return -1 if $sync->{reindex};
1108 $regen_max + $self->artnum_max || 0;
1111 sub unindex_oid_aux ($$$) {
1112 my ($self, $oid, $mid) = @_;
1113 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1114 return unless $self->{-need_xapian};
1115 for my $num (@removed) {
1116 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1120 sub unindex_oid ($$;$) { # git->cat_async callback
1121 my ($bref, $oid, $type, $size, $arg) = @_;
1122 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1123 return index_finalize($arg, 0);
1124 my $self = $arg->{self};
1125 local $self->{current_info} = "$self->{current_info} $oid";
1126 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1127 my $mm = $self->{mm};
1128 my $mids = mids(PublicInbox::Eml->new($bref));
1130 my $oidx = $self->{oidx};
1131 foreach my $mid (@$mids) {
1134 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1135 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1137 my $n = scalar(keys(%gone)) or next;
1139 warn "BUG: multiple articles linked to $oid\n",
1140 join(',',sort keys %gone), "\n";
1142 # reuse (num => mid) mapping in ascending numeric order
1143 for my $num (sort { $a <=> $b } keys %gone) {
1146 my $mid0 = $mm->mid_for($num);
1147 my $oidbin = pack('H*', $oid);
1148 push @{$unindexed->{$oidbin}}, $num, $mid0;
1150 $mm->num_delete($num);
1152 unindex_oid_aux($self, $oid, $mid);
1154 index_finalize($arg, 0);
1157 sub git { $_[0]->{ibx}->git }
1159 # this is rare, it only happens when we get discontiguous history in
1160 # a mirror because the source used -purge or -edit
1161 sub unindex_todo ($$$) {
1162 my ($self, $sync, $unit) = @_;
1163 my $unindex_range = delete($unit->{unindex_range}) // return;
1164 my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1165 my $before = scalar keys %$unindexed;
1166 # order does not matter, here:
1167 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1168 --no-abbrev --no-renames), $unindex_range);
1169 local $sync->{in_unindex} = 1;
1170 my $unindex_oid = $self->can('unindex_oid');
1172 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1173 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1175 close $fh or die "git log failed: \$?=$?";
1176 $self->git->cat_async_wait;
1178 return unless $sync->{-opt}->{prune};
1179 my $after = scalar keys %$unindexed;
1180 return if $before == $after;
1182 # ensure any blob can not longer be accessed via dumb HTTP
1183 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1184 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1187 sub sync_ranges ($$) {
1188 my ($self, $sync) = @_;
1189 my $reindex = $sync->{reindex};
1190 return $self->last_commits($sync) unless $reindex;
1191 return [] if ref($reindex) ne 'HASH';
1193 my $ranges = $reindex->{from}; # arrayref;
1194 if (ref($ranges) ne 'ARRAY') {
1195 die 'BUG: $reindex->{from} not an ARRAY';
1200 sub index_xap_only { # git->cat_async callback
1201 my ($bref, $oid, $type, $size, $smsg) = @_;
1202 my $self = delete $smsg->{self};
1203 my $idx = idx_shard($self, $smsg->{num});
1204 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1205 $self->{transact_bytes} += $smsg->{bytes};
1208 sub index_xap_step ($$$;$) {
1209 my ($self, $sync, $beg, $step) = @_;
1210 my $end = $sync->{art_end};
1211 return if $beg > $end; # nothing to do
1213 $step //= $self->{shards};
1214 my $ibx = $self->{ibx};
1215 if (my $pr = $sync->{-opt}->{-progress}) {
1216 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1217 "$beg..$end (% $step)\n");
1219 for (my $num = $beg; $num <= $end; $num += $step) {
1220 last if $sync->{quit};
1221 my $smsg = $ibx->over->get_art($num) or next;
1222 $smsg->{self} = $self;
1223 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1224 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1225 ${$sync->{nr}} = $num;
1226 reindex_checkpoint($self, $sync);
1231 sub index_todo ($$$) {
1232 my ($self, $sync, $unit) = @_;
1233 return if $sync->{quit};
1234 unindex_todo($self, $sync, $unit);
1235 my $stk = delete($unit->{stack}) or return;
1236 my $all = $self->git;
1237 my $index_oid = $self->can('index_oid');
1238 my $unindex_oid = $self->can('unindex_oid');
1240 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1241 $pfx = "$1 $2"; # v2
1243 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1244 $pfx //= $unit->{git}->{git_dir};
1246 local $self->{current_info} = "$pfx ";
1247 local $sync->{latest_cmt} = \(my $latest_cmt);
1248 local $sync->{unit} = $unit;
1249 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1250 if ($sync->{quit}) {
1251 warn "waiting to quit...\n";
1252 $all->async_wait_all;
1253 $self->update_last_commit($sync);
1264 if ($sync->{max_size}) {
1265 $all->check_async($oid, \&check_size, $req);
1267 $all->cat_async($oid, $index_oid, $req);
1269 } elsif ($f eq 'd') {
1270 $all->cat_async($oid, $unindex_oid, $req);
1272 if (${$sync->{need_checkpoint}}) {
1273 reindex_checkpoint($self, $sync);
1276 $all->async_wait_all;
1277 $self->update_last_commit($sync, $stk);
1281 my ($self, $opt, $sync, $art_beg) = @_;
1282 my $seq = $opt->{sequential_shard};
1284 local $self->{parallel} = 0 if $seq;
1285 $self->idx_init($opt); # acquire lock
1286 if (my $art_end = $self->{ibx}->mm->max) {
1288 need_checkpoint => \(my $bool = 0),
1291 nr => \(my $nr = 0),
1292 -regen_fmt => "%u/?\n",
1294 $sync->{art_end} = $art_end;
1295 if ($seq || !$self->{parallel}) {
1296 my $shard_end = $self->{shards} - 1;
1297 for my $i (0..$shard_end) {
1298 last if $sync->{quit};
1299 index_xap_step($self, $sync, $art_beg + $i);
1300 if ($i != $shard_end) {
1301 reindex_checkpoint($self, $sync);
1304 } else { # parallel (maybe)
1305 index_xap_step($self, $sync, $art_beg, 1);
1308 $self->git->cat_async_wait;
1309 $self->{ibx}->cleanup;
1313 # public, called by public-inbox-index
1315 my ($self, $opt) = @_;
1317 return xapian_only($self, $opt) if $opt->{xapian_only};
1320 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1321 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1322 use Time::HiRes qw(stat);
1323 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1324 my $c = $mm[10]; # 10 = ctime (nsec NV)
1325 my @hd = stat("$latest/refs/heads");
1326 my @pr = stat("$latest/packed-refs");
1327 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1331 my $pr = $opt->{-progress};
1332 my $seq = $opt->{sequential_shard};
1333 my $art_beg; # the NNTP article number we start xapian_only at
1334 my $idxlevel = $self->{ibx}->{indexlevel};
1335 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1337 $self->idx_init($opt); # acquire lock
1338 fill_alternates($self, $epoch_max);
1339 $self->{oidx}->rethread_prepare($opt);
1341 need_checkpoint => \(my $bool = 0),
1342 reindex => $opt->{reindex},
1345 ibx => $self->{ibx},
1346 epoch_max => $epoch_max,
1348 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1349 local $SIG{QUIT} = $quit;
1350 local $SIG{INT} = $quit;
1351 local $SIG{TERM} = $quit;
1353 if (sync_prepare($self, $sync)) {
1354 # tmp_clone seems to fail if inside a transaction, so
1355 # we rollback here (because we opened {mm} for reading)
1356 # Note: we do NOT rely on DBI transactions for atomicity;
1357 # only for batch performance.
1358 $self->{mm}->{dbh}->rollback;
1359 $self->{mm}->{dbh}->begin_work;
1361 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1363 # xapian_only works incrementally w/o --reindex
1364 if ($seq && !$opt->{reindex}) {
1365 $art_beg = $sync->{mm_tmp}->max || -1;
1369 # work forwards through history
1370 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1371 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1374 if (my $nr = $sync->{nr}) {
1375 my $pr = $sync->{-opt}->{-progress};
1376 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1380 # deal with Xapian shards sequentially
1381 if ($seq && delete($sync->{mm_tmp})) {
1382 if ($sync->{quit}) {
1385 $self->{ibx}->{indexlevel} = $idxlevel;
1386 xapian_only($self, $opt, $sync, $art_beg);
1387 $quit_warn = 1 if $sync->{quit};
1391 # --reindex on the command-line
1392 if (!$sync->{quit} && $opt->{reindex} &&
1393 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1394 $self->lock_acquire;
1395 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1396 if (my $xdb = $s0->idx_acquire) {
1397 my $n = $xdb->get_metadata('has_threadid');
1398 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1401 $self->lock_release;
1404 # reindex does not pick up new changes, so we rerun w/o it:
1405 if ($opt->{reindex} && !$sync->{quit}) {
1408 delete @again{qw(rethread reindex -skip_lock)};
1409 index_sync($self, \%again);
1410 $opt->{quit} = $again{quit}; # propagate to caller
1412 warn <<EOF if $quit_warn;
1413 W: interrupted, --xapian-only --reindex required upon restart
1417 sub ipc_atfork_child {
1419 if (my $lei = delete $self->{lei}) {
1420 $lei->_lei_atfork_child;
1421 my $pkt_op_p = delete $lei->{pkt_op_p};
1422 close($pkt_op_p->{op_p});
1424 $self->SUPER::ipc_atfork_child;