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);
10 use PublicInbox::SearchIdxShard;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentHash qw(content_hash content_digest);
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 # returns the git object_id of $fh, does not write the object to FS
451 sub git_hash_raw ($$) {
452 my ($self, $raw) = @_;
453 # grab the expected OID we have to reindex:
454 pipe(my($in, $w)) or die "pipe: $!";
455 my $git_dir = $self->git->{git_dir};
456 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
457 my $r = popen_rd($cmd, undef, { 0 => $in });
458 print $w $$raw or die "print \$w: $!";
459 close $w or die "close \$w: $!";
461 chomp(my $oid = <$r>);
462 close $r or die "git hash-object failed: $?";
463 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
467 sub _check_mids_match ($$$) {
468 my ($old_list, $new_list, $hdrs) = @_;
469 my %old_mids = map { $_ => 1 } @$old_list;
470 my %new_mids = map { $_ => 1 } @$new_list;
471 my @old = keys %old_mids;
472 my @new = keys %new_mids;
473 my $err = "$hdrs may not be changed when replacing\n";
474 die $err if scalar(@old) != scalar(@new);
475 delete @new_mids{@old};
476 delete @old_mids{@new};
477 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
480 # Changing Message-IDs or References with ->replace isn't supported.
481 # The rules for dealing with messages with multiple or conflicting
482 # Message-IDs are pretty complex and rethreading hasn't been fully
484 sub check_mids_match ($$) {
485 my ($old, $new) = @_;
486 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
487 _check_mids_match(references($old), references($new),
488 'References/In-Reply-To');
493 my ($self, $old_mime, $new_mime) = @_;
495 check_mids_match($old_mime, $new_mime);
497 # mutt will always add Content-Length:, Status:, Lines: when editing
498 PublicInbox::Import::drop_unwanted_headers($new_mime);
500 my $raw = $new_mime->as_string;
501 my $expect_oid = git_hash_raw($self, \$raw);
502 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
503 my $need_reindex = $rewritten->{need_reindex};
505 # just in case we have bugs in deduplication code:
506 my $n = scalar(@$need_reindex);
508 my $list = join(', ', map {
509 "$_->{num}: <$_->{mid}>"
512 W: rewritten $n messages matching content of original message (expected: 1).
513 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
518 # make sure we really got the OID:
519 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
520 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
522 # don't leak FDs to Xapian:
525 # reindex modified messages:
526 for my $smsg (@$need_reindex) {
527 my $new_smsg = bless {
531 }, 'PublicInbox::Smsg';
532 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
533 $new_smsg->populate($new_mime, $sync);
534 $new_smsg->set_bytes($raw, $bytes);
535 do_idx($self, $new_mime, $new_smsg);
537 $rewritten->{rewrites};
540 sub last_epoch_commit ($$;$) {
541 my ($self, $i, $cmt) = @_;
542 my $v = PublicInbox::Search::SCHEMA_VERSION();
543 $self->{mm}->last_commit_xap($v, $i, $cmt);
546 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
548 defined(my $epoch_max = $self->{epoch_max}) or return;
549 my $last_commit = $self->{last_commit};
550 foreach my $i (0..$epoch_max) {
551 defined(my $cmt = $last_commit->[$i]) or next;
552 $last_commit->[$i] = undef;
553 last_epoch_commit($self, $i, $cmt);
558 sub checkpoint ($;$) {
559 my ($self, $wait) = @_;
561 if (my $im = $self->{im}) {
568 my $shards = $self->{idx_shards};
570 my $mm = $self->{mm};
571 my $dbh = $mm->{dbh} if $mm;
573 # SQLite msgmap data is second in importance
574 $dbh->commit if $dbh;
576 # SQLite overview is third
577 $self->{oidx}->commit_lazy;
579 # Now deal with Xapian
581 # start commit_txn_lazy asynchronously on all parallel shards
582 # (non-parallel waits here)
583 $_->ipc_do('commit_txn_lazy') for @$shards;
585 # transactions started on parallel shards,
586 # wait for them by issuing an echo command (echo can only
587 # run after commit_txn_lazy is done)
588 if ($wait && $self->{parallel}) {
590 for my $shard (@$shards) {
591 my $echo = $shard->ipc_do('echo', $i);
592 $echo == $i or die <<"";
593 shard[$i] bad echo:$echo != $i waiting for txn commit
599 my $midx = $self->{midx}; # misc index
602 $PublicInbox::Search::X{CLOEXEC_UNSET} and
606 # last_commit is special, don't commit these until
607 # Xapian shards are done:
608 $dbh->begin_work if $dbh;
609 set_last_commits($self);
615 $self->{total_bytes} += $self->{transact_bytes};
616 $self->{transact_bytes} = 0;
619 # issue a write barrier to ensure all data is visible to other processes
620 # and read-only ops. Order of data importance is: git > SQLite > Xapian
622 sub barrier { checkpoint($_[0], 1) };
624 # true if locked and active
625 sub active { !!$_[0]->{im} }
631 if (my $im = delete $self->{im}) {
632 eval { $im->done }; # PublicInbox::Import::done
633 $err .= "import done: $@\n" if $@;
636 eval { checkpoint($self) };
637 $err .= "checkpoint: $@\n" if $@;
639 if (my $mm = delete $self->{mm}) {
640 my $m = $err ? 'rollback' : 'commit';
641 eval { $mm->{dbh}->$m };
642 $err .= "msgmap $m: $@\n" if $@;
644 my $shards = delete $self->{idx_shards};
647 eval { $_->shard_close };
648 $err .= "shard close: $@\n" if $@;
651 eval { $self->{oidx}->dbh_close };
652 $err .= "over close: $@\n" if $@;
653 delete $self->{midx};
654 my $nbytes = $self->{total_bytes};
655 $self->{total_bytes} = 0;
656 $self->lock_release(!!$nbytes) if $shards;
661 sub write_alternates ($$$) {
662 my ($info_dir, $mode, $out) = @_;
663 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
664 my $tmp = $fh->filename;
665 print $fh @$out or die "print $tmp: $!\n";
666 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
667 close $fh or die "close $tmp $!\n";
668 my $alt = "$info_dir/alternates";
669 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
670 $fh->unlink_on_destroy(0);
673 sub fill_alternates ($$) {
674 my ($self, $epoch) = @_;
676 my $pfx = "$self->{ibx}->{inboxdir}/git";
677 my $all = "$self->{ibx}->{inboxdir}/all.git";
678 PublicInbox::Import::init_bare($all) unless -d $all;
679 my $info_dir = "$all/objects/info";
680 my $alt = "$info_dir/alternates";
684 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
685 $mode = (stat($fh))[2] & 07777;
687 # we assign a sort score to every alternate and favor
688 # the newest (highest numbered) one because loose objects
689 # require scanning epochs and only the latest epoch is
690 # expected to see loose objects
692 my $other = 0; # in case admin adds non-epoch repos
694 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
700 } split(/\n+/, do { local $/; <$fh> });
703 foreach my $i (0..$epoch) {
704 my $dir = "../../git/$i.git/objects";
705 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
711 write_alternates($info_dir, $mode,
712 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
716 my ($self, $epoch) = @_;
717 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
718 PublicInbox::Import::init_bare($git_dir);
719 run_die([qw(git config), "--file=$git_dir/config",
720 qw(include.path ../../all.git/config)]);
721 fill_alternates($self, $epoch);
727 my $im = $self->{im};
729 if ($im->{bytes_added} < $self->{rotate_bytes}) {
736 my $git_dir = $self->git_init(++$self->{epoch_max});
737 my $git = PublicInbox::Git->new($git_dir);
738 return $self->import_init($git, 0);
743 my $latest = $self->{ibx}->git_dir_latest(\$max);
744 if (defined $latest) {
745 my $git = PublicInbox::Git->new($latest);
746 my $packed_bytes = $git->packed_bytes;
747 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
749 if ($unpacked_bytes >= $self->{rotate_bytes}) {
752 $self->{epoch_max} = $max;
753 return $self->import_init($git, $packed_bytes);
756 $self->{epoch_max} = $epoch;
757 $latest = $self->git_init($epoch);
758 $self->import_init(PublicInbox::Git->new($latest), 0);
762 my ($self, $git, $packed_bytes, $tmp) = @_;
763 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
764 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
765 $im->{lock_path} = undef;
766 $im->{path_type} = 'v2';
767 $self->{im} = $im unless $tmp;
773 my ($mid, $cur, $new) = @_;
775 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
776 print $ah $cur->as_string or die "print: $!";
777 $ah->flush or die "flush: $!";
778 PublicInbox::Import::drop_unwanted_headers($new);
779 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
780 print $bh $new->as_string or die "print: $!";
781 $bh->flush or die "flush: $!";
782 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
783 print STDERR "# MID conflict <$mid>\n";
784 my $pid = spawn($cmd, undef, { 1 => 2 });
785 waitpid($pid, 0) == $pid or die "diff did not finish";
789 my ($self, $smsg) = @_;
790 if (my $im = $self->{im}) {
791 my $msg = $im->cat_blob($smsg->{blob});
794 # older message, should be in alternates
795 $self->{ibx}->msg_by_smsg($smsg);
798 sub content_exists ($$$) {
799 my ($self, $mime, $mid) = @_;
800 my $oidx = $self->{oidx};
801 my $chashes = content_hashes($mime);
803 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
804 my $msg = get_blob($self, $smsg);
805 if (!defined($msg)) {
806 warn "broken smsg for $mid\n";
809 my $cur = PublicInbox::Eml->new($msg);
810 return 1 if content_matches($chashes, $cur);
812 # XXX DEBUG_DIFF is experimental and may be removed
813 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
820 if (my $older_siblings = $self->{idx_shards}) {
821 $_->ipc_sibling_atfork_child for @$older_siblings;
823 if (my $im = $self->{im}) {
826 die "BUG: unexpected mm" if $self->{mm};
829 sub reindex_checkpoint ($$) {
830 my ($self, $sync) = @_;
832 $self->git->async_wait_all;
833 $self->update_last_commit($sync);
834 ${$sync->{need_checkpoint}} = 0;
835 my $mm_tmp = $sync->{mm_tmp};
836 $mm_tmp->atfork_prepare if $mm_tmp;
837 die 'BUG: {im} during reindex' if $self->{im};
838 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
839 checkpoint($self, 1); # no need to release lock on pure index
841 $self->done; # release lock
844 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
845 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
848 # allow -watch or -mda to write...
849 $self->idx_init($sync->{-opt}); # reacquire lock
850 if (my $intvl = $sync->{check_intvl}) { # eidx
851 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
853 $mm_tmp->atfork_parent if $mm_tmp;
856 sub index_finalize ($$) {
857 my ($arg, $index) = @_;
858 ++$arg->{self}->{nidx};
859 if (defined(my $cur = $arg->{cur_cmt})) {
860 ${$arg->{latest_cmt}} = $cur;
862 die 'BUG: {cur_cmt} missing';
863 } # else { unindexing @leftovers doesn't set {cur_cmt}
866 sub index_oid { # cat_async callback
867 my ($bref, $oid, $type, $size, $arg) = @_;
868 is_bad_blob($oid, $type, $size, $arg->{oid}) and
869 return index_finalize($arg, 1); # size == 0 purged returns here
870 my $self = $arg->{self};
871 local $self->{current_info} = "$self->{current_info} $oid";
873 my $eml = PublicInbox::Eml->new($$bref);
874 my $mids = mids($eml);
875 my $chash = content_hash($eml);
877 if (scalar(@$mids) == 0) {
878 warn "E: $oid has no Message-ID, skipping\n";
882 # {unindexed} is unlikely
883 if (my $unindexed = $arg->{unindexed}) {
884 my $oidbin = pack('H*', $oid);
885 my $u = $unindexed->{$oidbin};
886 ($num, $mid0) = splice(@$u, 0, 2) if $u;
888 $self->{mm}->mid_set($num, $mid0);
889 if (scalar(@$u) == 0) { # done with current OID
890 delete $unindexed->{$oidbin};
891 delete($arg->{unindexed}) if !keys(%$unindexed);
895 if (!defined($num)) { # reuse if reindexing (or duplicates)
896 my $oidx = $self->{oidx};
897 for my $mid (@$mids) {
898 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
899 last if defined $num;
902 $mid0 //= do { # is this a number we got before?
903 $num = $arg->{mm_tmp}->num_for($mids->[0]);
904 defined($num) ? $mids->[0] : undef;
906 if (!defined($num)) {
907 for (my $i = $#$mids; $i >= 1; $i--) {
908 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
916 $arg->{mm_tmp}->num_delete($num);
917 } else { # never seen
918 $num = $self->{mm}->mid_insert($mids->[0]);
921 } else { # rare, try the rest of them, backwards
922 for (my $i = $#$mids; $i >= 1; $i--) {
923 $num = $self->{mm}->mid_insert($mids->[$i]);
931 if (!defined($num)) {
932 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
940 }, 'PublicInbox::Smsg';
941 $smsg->populate($eml, $arg);
942 $smsg->set_bytes($$bref, $size);
943 if (do_idx($self, $eml, $smsg)) {
944 ${$arg->{need_checkpoint}} = 1;
946 index_finalize($arg, 1);
949 # only update last_commit for $i on reindex iff newer than current
950 sub update_last_commit {
951 my ($self, $sync, $stk) = @_;
952 my $unit = $sync->{unit} // return;
953 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
954 defined($latest_cmt) or return;
955 my $last = last_epoch_commit($self, $unit->{epoch});
956 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
957 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
958 chomp(my $n = $unit->{git}->qx(@cmd));
959 return if $n ne '' && $n == 0;
961 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
965 my ($self, $sync) = @_;
967 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
968 $heads->[$i] = last_epoch_commit($self, $i);
973 # returns a revision range for git-log(1)
974 sub log_range ($$$) {
975 my ($sync, $unit, $tip) = @_;
976 my $opt = $sync->{-opt};
977 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
978 my $i = $unit->{epoch};
979 my $cur = $sync->{ranges}->[$i] or do {
980 $pr->("$i.git indexing all of $tip\n") if $pr;
981 return $tip; # all of it
984 # fast equality check to avoid (v)fork+execve overhead
986 $sync->{ranges}->[$i] = undef;
990 my $range = "$cur..$tip";
991 $pr->("$i.git checking contiguity... ") if $pr;
992 my $git = $unit->{git};
993 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
994 $pr->("OK\n") if $pr;
995 my $n = $git->qx(qw(rev-list --count), $range);
998 $sync->{ranges}->[$i] = undef;
999 $pr->("$i.git has nothing new\n") if $pr;
1000 return; # nothing to do
1002 $pr->("$i.git has $n changes since $cur\n") if $pr;
1004 $pr->("FAIL\n") if $pr;
1006 discontiguous range: $range
1007 Rewritten history? (in $git->{git_dir})
1009 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1011 $range = "$base..$tip";
1012 warn "found merge-base: $base\n"
1015 warn "discarding history at $cur\n";
1018 reindexing $git->{git_dir}
1021 # $cur^0 may no longer exist if pruned by git
1022 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1023 $unit->{unindex_range} = "$base..$cur";
1024 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1025 $unit->{unindex_range} = "$base..";
1027 warn "W: unable to unindex before $range\n";
1033 # overridden by ExtSearchIdx
1034 sub artnum_max { $_[0]->{mm}->num_highwater }
1036 sub sync_prepare ($$) {
1037 my ($self, $sync) = @_;
1038 $sync->{ranges} = sync_ranges($self, $sync);
1039 my $pr = $sync->{-opt}->{-progress};
1041 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1044 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1045 $pfx //= $sync->{ibx}->{inboxdir};
1049 if ($self->{ibx_map}) {
1050 # ExtSearchIdx won't index messages unless they're in
1051 # over.sqlite3 for a given inbox, so don't read beyond
1052 # what's in the per-inbox index.
1053 $reindex_heads = [];
1054 my $v = PublicInbox::Search::SCHEMA_VERSION;
1055 my $mm = $sync->{ibx}->mm;
1056 for my $i (0..$sync->{epoch_max}) {
1057 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1059 } elsif ($sync->{reindex}) { # V2 inbox
1060 # reindex stops at the current heads and we later
1061 # rerun index_sync without {reindex}
1062 $reindex_heads = $self->last_commits($sync);
1064 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1065 $sync->{index_oid} = $self->can('index_oid');
1067 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1068 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1069 my $git_dir = "$git_pfx/$i.git";
1070 -d $git_dir or next; # missing epochs are fine
1071 my $git = PublicInbox::Git->new($git_dir);
1072 my $unit = { git => $git, epoch => $i };
1074 if ($reindex_heads) {
1075 $tip = $head = $reindex_heads->[$i] or next;
1077 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1078 next if $?; # new repo
1081 my $range = log_range($sync, $unit, $tip) or next;
1082 # can't use 'rev-list --count' if we use --diff-filter
1083 $pr->("$pfx $i.git counting $range ... ") if $pr;
1084 # Don't bump num_highwater on --reindex by using {D}.
1085 # We intentionally do NOT use {D} in the non-reindex case
1086 # because we want NNTP article number gaps from unindexed
1087 # messages to show up in mirrors, too.
1088 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1089 my $stk = log2stack($sync, $git, $range);
1090 return 0 if $sync->{quit};
1091 my $nr = $stk ? $stk->num_records : 0;
1092 $pr->("$nr\n") if $pr;
1093 $unit->{stack} = $stk; # may be undef
1094 unshift @{$sync->{todo}}, $unit;
1097 return 0 if $sync->{quit};
1099 # XXX this should not happen unless somebody bypasses checks in
1100 # our code and blindly injects "d" file history into git repos
1101 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1102 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1103 local $self->{current_info} = 'leftover ';
1104 my $unindex_oid = $self->can('unindex_oid');
1105 for my $oid (@leftovers) {
1106 last if $sync->{quit};
1107 $oid = unpack('H*', $oid);
1108 my $req = { %$sync, oid => $oid };
1109 $self->git->cat_async($oid, $unindex_oid, $req);
1111 $self->git->cat_async_wait;
1113 return 0 if $sync->{quit};
1115 $sync->{-regen_fmt} = "%u/?\n";
1119 # reindex should NOT see new commits anymore, if we do,
1120 # it's a problem and we need to notice it via die()
1121 my $pad = length($regen_max) + 1;
1122 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1123 $sync->{nr} = \(my $nr = 0);
1124 return -1 if $sync->{reindex};
1125 $regen_max + $self->artnum_max || 0;
1128 sub unindex_oid_aux ($$$) {
1129 my ($self, $oid, $mid) = @_;
1130 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1131 return unless $self->{-need_xapian};
1132 for my $num (@removed) {
1133 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1137 sub unindex_oid ($$;$) { # git->cat_async callback
1138 my ($bref, $oid, $type, $size, $arg) = @_;
1139 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1140 return index_finalize($arg, 0);
1141 my $self = $arg->{self};
1142 local $self->{current_info} = "$self->{current_info} $oid";
1143 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1144 my $mm = $self->{mm};
1145 my $mids = mids(PublicInbox::Eml->new($bref));
1147 my $oidx = $self->{oidx};
1148 foreach my $mid (@$mids) {
1151 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1152 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1154 my $n = scalar(keys(%gone)) or next;
1156 warn "BUG: multiple articles linked to $oid\n",
1157 join(',',sort keys %gone), "\n";
1159 # reuse (num => mid) mapping in ascending numeric order
1160 for my $num (sort { $a <=> $b } keys %gone) {
1163 my $mid0 = $mm->mid_for($num);
1164 my $oidbin = pack('H*', $oid);
1165 push @{$unindexed->{$oidbin}}, $num, $mid0;
1167 $mm->num_delete($num);
1169 unindex_oid_aux($self, $oid, $mid);
1171 index_finalize($arg, 0);
1174 sub git { $_[0]->{ibx}->git }
1176 # this is rare, it only happens when we get discontiguous history in
1177 # a mirror because the source used -purge or -edit
1178 sub unindex_todo ($$$) {
1179 my ($self, $sync, $unit) = @_;
1180 my $unindex_range = delete($unit->{unindex_range}) // return;
1181 my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1182 my $before = scalar keys %$unindexed;
1183 # order does not matter, here:
1184 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1185 --no-abbrev --no-renames), $unindex_range);
1186 local $sync->{in_unindex} = 1;
1187 my $unindex_oid = $self->can('unindex_oid');
1189 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1190 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1192 close $fh or die "git log failed: \$?=$?";
1193 $self->git->cat_async_wait;
1195 return unless $sync->{-opt}->{prune};
1196 my $after = scalar keys %$unindexed;
1197 return if $before == $after;
1199 # ensure any blob can not longer be accessed via dumb HTTP
1200 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1201 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1204 sub sync_ranges ($$) {
1205 my ($self, $sync) = @_;
1206 my $reindex = $sync->{reindex};
1207 return $self->last_commits($sync) unless $reindex;
1208 return [] if ref($reindex) ne 'HASH';
1210 my $ranges = $reindex->{from}; # arrayref;
1211 if (ref($ranges) ne 'ARRAY') {
1212 die 'BUG: $reindex->{from} not an ARRAY';
1217 sub index_xap_only { # git->cat_async callback
1218 my ($bref, $oid, $type, $size, $smsg) = @_;
1219 my $self = $smsg->{self};
1220 my $idx = idx_shard($self, $smsg->{num});
1221 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1222 $self->{transact_bytes} += $smsg->{bytes};
1225 sub index_xap_step ($$$;$) {
1226 my ($self, $sync, $beg, $step) = @_;
1227 my $end = $sync->{art_end};
1228 return if $beg > $end; # nothing to do
1230 $step //= $self->{shards};
1231 my $ibx = $self->{ibx};
1232 if (my $pr = $sync->{-opt}->{-progress}) {
1233 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1234 "$beg..$end (% $step)\n");
1236 for (my $num = $beg; $num <= $end; $num += $step) {
1237 last if $sync->{quit};
1238 my $smsg = $ibx->over->get_art($num) or next;
1239 $smsg->{self} = $self;
1240 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1241 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1242 ${$sync->{nr}} = $num;
1243 reindex_checkpoint($self, $sync);
1248 sub index_todo ($$$) {
1249 my ($self, $sync, $unit) = @_;
1250 return if $sync->{quit};
1251 unindex_todo($self, $sync, $unit);
1252 my $stk = delete($unit->{stack}) or return;
1253 my $all = $self->git;
1254 my $index_oid = $self->can('index_oid');
1255 my $unindex_oid = $self->can('unindex_oid');
1257 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1258 $pfx = "$1 $2"; # v2
1260 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1261 $pfx //= $unit->{git}->{git_dir};
1263 local $self->{current_info} = "$pfx ";
1264 local $sync->{latest_cmt} = \(my $latest_cmt);
1265 local $sync->{unit} = $unit;
1266 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1267 if ($sync->{quit}) {
1268 warn "waiting to quit...\n";
1269 $all->async_wait_all;
1270 $self->update_last_commit($sync);
1281 if ($sync->{max_size}) {
1282 $all->check_async($oid, \&check_size, $req);
1284 $all->cat_async($oid, $index_oid, $req);
1286 } elsif ($f eq 'd') {
1287 $all->cat_async($oid, $unindex_oid, $req);
1289 if (${$sync->{need_checkpoint}}) {
1290 reindex_checkpoint($self, $sync);
1293 $all->async_wait_all;
1294 $self->update_last_commit($sync, $stk);
1298 my ($self, $opt, $sync, $art_beg) = @_;
1299 my $seq = $opt->{sequential_shard};
1301 local $self->{parallel} = 0 if $seq;
1302 $self->idx_init($opt); # acquire lock
1303 if (my $art_end = $self->{ibx}->mm->max) {
1305 need_checkpoint => \(my $bool = 0),
1308 nr => \(my $nr = 0),
1309 -regen_fmt => "%u/?\n",
1311 $sync->{art_end} = $art_end;
1312 if ($seq || !$self->{parallel}) {
1313 my $shard_end = $self->{shards} - 1;
1314 for my $i (0..$shard_end) {
1315 last if $sync->{quit};
1316 index_xap_step($self, $sync, $art_beg + $i);
1317 if ($i != $shard_end) {
1318 reindex_checkpoint($self, $sync);
1321 } else { # parallel (maybe)
1322 index_xap_step($self, $sync, $art_beg, 1);
1325 $self->git->cat_async_wait;
1329 # public, called by public-inbox-index
1331 my ($self, $opt) = @_;
1333 return xapian_only($self, $opt) if $opt->{xapian_only};
1336 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1337 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1338 use Time::HiRes qw(stat);
1339 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1340 my $c = $mm[10]; # 10 = ctime (nsec NV)
1341 my @hd = stat("$latest/refs/heads");
1342 my @pr = stat("$latest/packed-refs");
1343 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1347 my $pr = $opt->{-progress};
1348 my $seq = $opt->{sequential_shard};
1349 my $art_beg; # the NNTP article number we start xapian_only at
1350 my $idxlevel = $self->{ibx}->{indexlevel};
1351 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1353 $self->idx_init($opt); # acquire lock
1354 fill_alternates($self, $epoch_max);
1355 $self->{oidx}->rethread_prepare($opt);
1357 need_checkpoint => \(my $bool = 0),
1358 reindex => $opt->{reindex},
1361 ibx => $self->{ibx},
1362 epoch_max => $epoch_max,
1364 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1365 local $SIG{QUIT} = $quit;
1366 local $SIG{INT} = $quit;
1367 local $SIG{TERM} = $quit;
1369 if (sync_prepare($self, $sync)) {
1370 # tmp_clone seems to fail if inside a transaction, so
1371 # we rollback here (because we opened {mm} for reading)
1372 # Note: we do NOT rely on DBI transactions for atomicity;
1373 # only for batch performance.
1374 $self->{mm}->{dbh}->rollback;
1375 $self->{mm}->{dbh}->begin_work;
1377 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1379 # xapian_only works incrementally w/o --reindex
1380 if ($seq && !$opt->{reindex}) {
1381 $art_beg = $sync->{mm_tmp}->max || -1;
1385 # work forwards through history
1386 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1387 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1390 if (my $nr = $sync->{nr}) {
1391 my $pr = $sync->{-opt}->{-progress};
1392 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1396 # deal with Xapian shards sequentially
1397 if ($seq && delete($sync->{mm_tmp})) {
1398 if ($sync->{quit}) {
1401 $self->{ibx}->{indexlevel} = $idxlevel;
1402 xapian_only($self, $opt, $sync, $art_beg);
1403 $quit_warn = 1 if $sync->{quit};
1407 # --reindex on the command-line
1408 if (!$sync->{quit} && $opt->{reindex} &&
1409 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1410 $self->lock_acquire;
1411 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1412 if (my $xdb = $s0->idx_acquire) {
1413 my $n = $xdb->get_metadata('has_threadid');
1414 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1417 $self->lock_release;
1420 # reindex does not pick up new changes, so we rerun w/o it:
1421 if ($opt->{reindex} && !$sync->{quit}) {
1424 delete @again{qw(rethread reindex -skip_lock)};
1425 index_sync($self, \%again);
1426 $opt->{quit} = $again{quit}; # propagate to caller
1428 warn <<EOF if $quit_warn;
1429 W: interrupted, --xapian-only --reindex required upon restart