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>
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 base qw(PublicInbox::Lock);
11 use PublicInbox::SearchIdxShard;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentId qw(content_id content_digest);
17 use PublicInbox::Inbox;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd);
21 use PublicInbox::SearchIdx;
22 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
23 use PublicInbox::MultiMidQueue;
24 use IO::Handle; # ->autoflush
25 use File::Temp qw(tempfile);
27 # an estimate of the post-packed size to the raw uncompressed size
28 my $PACKING_FACTOR = 0.4;
30 # SATA storage lags behind what CPUs are capable of, so relying on
31 # nproc(1) can be misleading and having extra Xapian shards is a
32 # waste of FDs and space. It can also lead to excessive IO latency
33 # and slow things down. Users on NVME or other fast storage can
34 # use the NPROC env or switches in our script/public-inbox-* programs
35 # to increase Xapian shards
36 our $NPROC_MAX_DEFAULT = 4;
39 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
40 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
43 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
44 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
45 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
48 # should we bother with `sysctl hw.ncpu`? Those only give
49 # us total processor count, not online processor count.
53 sub nproc_shards ($) {
55 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
58 # assume 2 cores if not detectable or zero
59 state $NPROC_DETECTED = detect_nproc() || 2;
61 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
64 # subtract for the main process and git-fast-import
69 sub count_shards ($) {
72 my $xpfx = $self->{xpfx};
74 # always load existing shards in case core count changes:
75 # Also, shard count may change while -watch is running
76 # due to "xcpdb --reshard"
78 require PublicInbox::Search;
79 PublicInbox::Search::load_xapian();
80 my $XapianDatabase = $PublicInbox::Search::X{Database};
81 foreach my $shard (<$xpfx/*>) {
82 -d $shard && $shard =~ m!/[0-9]+\z! or next;
84 $XapianDatabase->new($shard)->close;
93 # $creat may be any true value, or 0/undef. A hashref is true,
94 # and $creat->{nproc} may be set to an integer
95 my ($class, $v2ibx, $creat) = @_;
96 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
97 my $dir = $v2ibx->assert_usable_dir;
101 File::Path::mkpath($dir);
103 die "$dir does not exist\n";
106 $v2ibx->umask_prepare;
108 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
111 im => undef, # PublicInbox::Import
116 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
117 lock_path => "$dir/inbox.lock",
118 # limit each git repo (epoch) to 1GB or so
119 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
120 last_commit => [], # git repo -> commit
122 $self->{shards} = count_shards($self) || nproc_shards($creat);
123 $self->{index_max_size} = $v2ibx->{index_max_size};
129 my ($self, $shards, $skip_epoch) = @_;
130 if (defined $shards) {
131 $self->{parallel} = 0 if $shards == 0;
132 $self->{shards} = $shards if $shards > 0;
136 git_dir_latest($self, \$epoch_max);
137 if (defined $skip_epoch && $epoch_max == -1) {
138 $epoch_max = $skip_epoch;
140 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
144 # returns undef on duplicate or spam
145 # mimics Import::add and wraps it for v2
147 my ($self, $mime, $check_cb) = @_;
148 $self->{-inbox}->with_umask(sub {
149 _add($self, $mime, $check_cb)
153 # indexes a message, returns true if checkpointing is needed
155 my ($self, $msgref, $mime, $smsg) = @_;
156 $smsg->{ds} //= msg_datestamp($mime->header_obj, $self->{autime});
157 $smsg->{ts} //= msg_timestamp($mime->header_obj, $self->{cotime});
158 $self->{over}->add_overview($mime, $smsg);
159 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
160 $idx->index_raw($msgref, $mime, $smsg);
161 my $n = $self->{transact_bytes} += $smsg->{bytes};
162 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
166 my ($self, $mime, $check_cb) = @_;
170 $mime = $check_cb->($mime) or return;
173 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
174 # as does SQLite 3.4.1+ (released in 2007-07-20), and
175 # Xapian 1.3.2+ (released 2015-03-15).
176 # For the most part, we can spawn git-fast-import without
177 # leaking FDs to it...
180 my ($num, $mid0) = v2_num_for($self, $mime);
181 defined $num or return; # duplicate
182 defined $mid0 or die "BUG: $mid0 undefined\n";
183 my $im = $self->importer;
184 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
185 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
186 $cmt = $im->get_mark($cmt);
187 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
189 my $msgref = delete $smsg->{-raw_email};
190 if (do_idx($self, $msgref, $mime, $smsg)) {
198 my ($self, $mime) = @_;
199 my $mids = mids($mime->header_obj);
201 my $mid = $mids->[0];
202 my $num = $self->{mm}->mid_insert($mid);
203 if (defined $num) { # common case
207 # crap, Message-ID is already known, hope somebody just resent:
208 foreach my $m (@$mids) {
209 # read-only lookup now safe to do after above barrier
210 # easy, don't store duplicates
211 # note: do not add more diagnostic info here since
212 # it gets noisy on public-inbox-watch restarts
213 return () if content_exists($self, $mime, $m);
216 # AltId may pre-populate article numbers (e.g. X-Mail-Count
217 # or NNTP article number), use that article number if it's
219 my $altid = $self->{-inbox}->{altid};
220 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
221 my $num = $self->{mm}->num_for($mid);
223 if (defined $num && !$self->{over}->get_art($num)) {
229 warn "<$mid> reused for mismatched content\n";
231 # try the rest of the mids
232 for(my $i = $#$mids; $i >= 1; $i--) {
234 $num = $self->{mm}->mid_insert($m);
236 warn "alternative <$m> for <$mid> found\n";
241 # none of the existing Message-IDs are good, generate a new one:
242 v2_num_for_harder($self, $mime);
245 sub v2_num_for_harder {
246 my ($self, $mime) = @_;
248 my $hdr = $mime->header_obj;
249 my $dig = content_digest($mime);
250 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
251 my $num = $self->{mm}->mid_insert($mid0);
252 unless (defined $num) {
253 # it's hard to spoof the last Received: header
254 my @recvd = $hdr->header_raw('Received');
255 $dig->add("Received: $_") foreach (@recvd);
256 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
257 $num = $self->{mm}->mid_insert($mid0);
259 # fall back to a random Message-ID and give up determinism:
260 until (defined($num)) {
262 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
263 warn "using random Message-ID <$mid0> as fallback\n";
264 $num = $self->{mm}->mid_insert($mid0);
267 PublicInbox::Import::append_mid($hdr, $mid0);
272 my ($self, $shard_i) = @_;
273 $self->{idx_shards}->[$shard_i];
278 my ($self, $opt) = @_;
279 return if $self->{idx_shards};
280 my $ibx = $self->{-inbox};
282 # do not leak read-only FDs to child processes, we only have these
283 # FDs for duplicate detection so they should not be
284 # frequently activated.
285 delete $ibx->{$_} foreach (qw(git mm search));
287 my $indexlevel = $ibx->{indexlevel};
288 if ($indexlevel && $indexlevel eq 'basic') {
289 $self->{parallel} = 0;
292 if ($self->{parallel}) {
293 pipe(my ($r, $w)) or die "pipe failed: $!";
294 # pipe for barrier notifications doesn't need to be big,
296 fcntl($w, 1031, 4096) if $^O eq 'linux';
297 $self->{bnote} = [ $r, $w ];
301 my $over = $self->{over};
303 $ibx->with_umask(sub {
304 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
307 # xcpdb can change shard count while -watch is idle
308 my $nshards = count_shards($self);
309 if ($nshards && $nshards != $self->{shards}) {
310 $self->{shards} = $nshards;
313 # need to create all shards before initializing msgmap FD
314 my $max = $self->{shards} - 1;
316 # idx_shards must be visible to all forked processes
317 my $idx = $self->{idx_shards} = [];
318 for my $i (0..$max) {
319 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
322 # Now that all subprocesses are up, we can open the FDs
324 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
325 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
326 $mm->{dbh}->begin_work;
330 # returns an array mapping [ epoch => latest_commit ]
331 # latest_commit may be undef if nothing was done to that epoch
332 # $replace_map = { $object_id => $strref, ... }
333 sub _replace_oids ($$$) {
334 my ($self, $mime, $replace_map) = @_;
336 my $pfx = "$self->{-inbox}->{inboxdir}/git";
337 my $rewrites = []; # epoch => commit
338 my $max = $self->{epoch_max};
340 unless (defined($max)) {
341 defined(my $latest = git_dir_latest($self, \$max)) or return;
342 $self->{epoch_max} = $max;
345 foreach my $i (0..$max) {
346 my $git_dir = "$pfx/$i.git";
348 my $git = PublicInbox::Git->new($git_dir);
349 my $im = $self->import_init($git, 0, 1);
350 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
356 sub content_ids ($) {
358 my @cids = ( content_id($mime) );
360 # We still support Email::MIME, here, and
361 # Email::MIME->as_string doesn't always round-trip, so we may
362 # use a second content_id
363 my $rt = content_id(PublicInbox::Eml->new(\($mime->as_string)));
364 push @cids, $rt if $cids[0] ne $rt;
368 sub content_matches ($$) {
369 my ($cids, $existing) = @_;
370 my $cid = content_id($existing);
372 return 1 if $_ eq $cid
377 # used for removing or replacing (purging)
378 sub rewrite_internal ($$;$$$) {
379 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
381 my ($im, $need_reindex, $replace_map);
383 $replace_map = {}; # oid => sref
384 $need_reindex = [] if $new_mime;
386 $im = $self->importer;
388 my $over = $self->{over};
389 my $cids = content_ids($old_mime);
391 my $mids = mids($old_mime->header_obj);
393 # We avoid introducing new blobs into git since the raw content
394 # can be slightly different, so we do not need the user-supplied
395 # message now that we have the mids and content_id
399 foreach my $mid (@$mids) {
400 my %gone; # num => [ smsg, $mime, raw ]
402 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
403 my $msg = get_blob($self, $smsg);
404 if (!defined($msg)) {
405 warn "broken smsg for $mid\n";
409 my $cur = PublicInbox::Eml->new($msg);
410 if (content_matches($cids, $cur)) {
411 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
414 my $n = scalar keys %gone;
417 warn "BUG: multiple articles linked to <$mid>\n",
418 join(',', sort keys %gone), "\n";
420 foreach my $num (keys %gone) {
421 my ($smsg, $mime, $orig) = @{$gone{$num}};
422 # @removed should only be set once assuming
423 # no bugs in our deduplication code:
424 @removed = (undef, $mime, $smsg);
425 my $oid = $smsg->{blob};
427 $replace_map->{$oid} = $sref;
429 ($mark, undef) = $im->remove($orig, $cmt_msg);
433 if ($need_reindex) { # ->replace
434 push @$need_reindex, $smsg;
435 } else { # ->purge or ->remove
436 $self->{mm}->num_delete($num);
438 unindex_oid_remote($self, $oid, $mid);
443 my $cmt = $im->get_mark($mark);
444 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
446 if ($replace_map && scalar keys %$replace_map) {
447 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
448 return { rewrites => $rewrites, need_reindex => $need_reindex };
450 defined($mark) ? @removed : undef;
453 # public (see PublicInbox::Import->remove), but note the 3rd element
454 # (retval[2]) is not part of the stable API shared with Import->remove
456 my ($self, $mime, $cmt_msg) = @_;
458 $self->{-inbox}->with_umask(sub {
459 @ret = rewrite_internal($self, $mime, $cmt_msg);
461 defined($ret[0]) ? @ret : undef;
464 sub _replace ($$;$$) {
465 my ($self, $old_mime, $new_mime, $sref) = @_;
466 my $rewritten = $self->{-inbox}->with_umask(sub {
467 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
470 my $rewrites = $rewritten->{rewrites};
471 # ->done is called if there are rewrites since we gc+prune from git
472 $self->idx_init if @$rewrites;
474 for my $i (0..$#$rewrites) {
475 defined(my $cmt = $rewrites->[$i]) or next;
476 $self->{last_commit}->[$i] = $cmt;
483 my ($self, $mime) = @_;
484 my $rewritten = _replace($self, $mime, undef, \'') or return;
485 $rewritten->{rewrites}
488 # returns the git object_id of $fh, does not write the object to FS
489 sub git_hash_raw ($$) {
490 my ($self, $raw) = @_;
491 # grab the expected OID we have to reindex:
492 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
493 $tmp_fh->autoflush(1);
494 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
495 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
497 my $git_dir = $self->{-inbox}->git->{git_dir};
498 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
499 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
501 chomp(my $oid = <$r>);
502 close $r or die "git hash-object failed: $?";
503 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
507 sub _check_mids_match ($$$) {
508 my ($old_list, $new_list, $hdrs) = @_;
509 my %old_mids = map { $_ => 1 } @$old_list;
510 my %new_mids = map { $_ => 1 } @$new_list;
511 my @old = keys %old_mids;
512 my @new = keys %new_mids;
513 my $err = "$hdrs may not be changed when replacing\n";
514 die $err if scalar(@old) != scalar(@new);
515 delete @new_mids{@old};
516 delete @old_mids{@new};
517 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
520 # Changing Message-IDs or References with ->replace isn't supported.
521 # The rules for dealing with messages with multiple or conflicting
522 # Message-IDs are pretty complex and rethreading hasn't been fully
524 sub check_mids_match ($$) {
525 my ($old_mime, $new_mime) = @_;
526 my $old = $old_mime->header_obj;
527 my $new = $new_mime->header_obj;
528 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
529 _check_mids_match(references($old), references($new),
530 'References/In-Reply-To');
535 my ($self, $old_mime, $new_mime) = @_;
537 check_mids_match($old_mime, $new_mime);
539 # mutt will always add Content-Length:, Status:, Lines: when editing
540 PublicInbox::Import::drop_unwanted_headers($new_mime);
542 my $raw = $new_mime->as_string;
543 my $expect_oid = git_hash_raw($self, \$raw);
544 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
545 my $need_reindex = $rewritten->{need_reindex};
547 # just in case we have bugs in deduplication code:
548 my $n = scalar(@$need_reindex);
550 my $list = join(', ', map {
551 "$_->{num}: <$_->{mid}>"
554 W: rewritten $n messages matching content of original message (expected: 1).
555 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
560 # make sure we really got the OID:
561 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
562 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
564 # don't leak FDs to Xapian:
565 $self->{-inbox}->git->cleanup;
567 # reindex modified messages:
568 for my $smsg (@$need_reindex) {
569 my $new_smsg = bless {
574 }, 'PublicInbox::Smsg';
575 do_idx($self, \$raw, $new_mime, $new_smsg);
577 $rewritten->{rewrites};
580 sub last_epoch_commit ($$;$) {
581 my ($self, $i, $cmt) = @_;
582 my $v = PublicInbox::Search::SCHEMA_VERSION();
583 $self->{mm}->last_commit_xap($v, $i, $cmt);
586 sub set_last_commits ($) {
588 defined(my $epoch_max = $self->{epoch_max}) or return;
589 my $last_commit = $self->{last_commit};
590 foreach my $i (0..$epoch_max) {
591 defined(my $cmt = $last_commit->[$i]) or next;
592 $last_commit->[$i] = undef;
593 last_epoch_commit($self, $i, $cmt);
599 $self->{bnote} or return;
601 my $barrier = { map { $_ => 1 } (0..$n) };
605 my ($self, $barrier) = @_;
606 my $bnote = $self->{bnote} or return;
608 while (scalar keys %$barrier) {
609 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
610 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
611 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
616 sub checkpoint ($;$) {
617 my ($self, $wait) = @_;
619 if (my $im = $self->{im}) {
626 my $shards = $self->{idx_shards};
628 my $dbh = $self->{mm}->{dbh};
630 # SQLite msgmap data is second in importance
633 # SQLite overview is third
634 $self->{over}->commit_lazy;
636 # Now deal with Xapian
638 my $barrier = $self->barrier_init(scalar @$shards);
640 # each shard needs to issue a barrier command
641 $_->remote_barrier for @$shards;
643 # wait for each Xapian shard
644 $self->barrier_wait($barrier);
646 $_->remote_commit for @$shards;
649 # last_commit is special, don't commit these until
650 # remote shards are done:
652 set_last_commits($self);
657 $self->{transact_bytes} = 0;
660 # issue a write barrier to ensure all data is visible to other processes
661 # and read-only ops. Order of data importance is: git > SQLite > Xapian
663 sub barrier { checkpoint($_[0], 1) };
668 my $im = delete $self->{im};
669 $im->done if $im; # PublicInbox::Import::done
671 my $mm = delete $self->{mm};
672 $mm->{dbh}->commit if $mm;
673 my $shards = delete $self->{idx_shards};
675 $_->remote_close for @$shards;
677 $self->{over}->disconnect;
678 delete $self->{bnote};
679 $self->{transact_bytes} = 0;
680 $self->lock_release if $shards;
681 $self->{-inbox}->git->cleanup;
684 sub fill_alternates ($$) {
685 my ($self, $epoch) = @_;
687 my $pfx = "$self->{-inbox}->{inboxdir}/git";
688 my $all = "$self->{-inbox}->{inboxdir}/all.git";
691 PublicInbox::Import::init_bare($all);
693 my $info_dir = "$all/objects/info";
694 my $alt = "$info_dir/alternates";
698 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
699 $mode = (stat($fh))[2] & 07777;
701 # we assign a sort score to every alternate and favor
702 # the newest (highest numbered) one when we
704 my $other = 0; # in case admin adds non-epoch repos
706 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
712 } split(/\n+/, do { local $/; <$fh> });
715 foreach my $i (0..$epoch) {
716 my $dir = "../../git/$i.git/objects";
717 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
724 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
725 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
726 or die "print $tmp: $!\n";
727 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
728 close $fh or die "close $tmp $!\n";
729 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
733 my ($self, $epoch) = @_;
734 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
735 PublicInbox::Import::init_bare($git_dir);
736 my @cmd = (qw/git config/, "--file=$git_dir/config",
737 'include.path', '../../all.git/config');
738 PublicInbox::Import::run_die(\@cmd);
739 fill_alternates($self, $epoch);
744 my ($self, $max) = @_;
746 my $pfx = "$self->{-inbox}->{inboxdir}/git";
747 return unless -d $pfx;
749 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
750 while (defined(my $git_dir = readdir($dh))) {
751 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
754 $latest = "$pfx/$git_dir";
762 my $im = $self->{im};
764 if ($im->{bytes_added} < $self->{rotate_bytes}) {
771 my $git_dir = $self->git_init(++$self->{epoch_max});
772 my $git = PublicInbox::Git->new($git_dir);
773 return $self->import_init($git, 0);
778 my $latest = git_dir_latest($self, \$max);
779 if (defined $latest) {
780 my $git = PublicInbox::Git->new($latest);
781 my $packed_bytes = $git->packed_bytes;
782 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
784 if ($unpacked_bytes >= $self->{rotate_bytes}) {
787 $self->{epoch_max} = $max;
788 return $self->import_init($git, $packed_bytes);
791 $self->{epoch_max} = $epoch;
792 $latest = $self->git_init($epoch);
793 $self->import_init(PublicInbox::Git->new($latest), 0);
797 my ($self, $git, $packed_bytes, $tmp) = @_;
798 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
799 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
800 $im->{lock_path} = undef;
801 $im->{path_type} = 'v2';
802 $self->{im} = $im unless $tmp;
808 my ($mid, $cur, $new) = @_;
810 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
811 print $ah $cur->as_string or die "print: $!";
812 close $ah or die "close: $!";
813 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
814 PublicInbox::Import::drop_unwanted_headers($new);
815 print $bh $new->as_string or die "print: $!";
816 close $bh or die "close: $!";
817 my $cmd = [ qw(diff -u), $an, $bn ];
818 print STDERR "# MID conflict <$mid>\n";
819 my $pid = spawn($cmd, undef, { 1 => 2 });
820 waitpid($pid, 0) == $pid or die "diff did not finish";
825 my ($self, $smsg) = @_;
826 if (my $im = $self->{im}) {
827 my $msg = $im->cat_blob($smsg->{blob});
830 # older message, should be in alternates
831 my $ibx = $self->{-inbox};
832 $ibx->msg_by_smsg($smsg);
835 sub content_exists ($$$) {
836 my ($self, $mime, $mid) = @_;
837 my $over = $self->{over};
838 my $cids = content_ids($mime);
840 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
841 my $msg = get_blob($self, $smsg);
842 if (!defined($msg)) {
843 warn "broken smsg for $mid\n";
846 my $cur = PublicInbox::Eml->new($msg);
847 return 1 if content_matches($cids, $cur);
849 # XXX DEBUG_DIFF is experimental and may be removed
850 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
857 my $fh = delete $self->{reindex_pipe};
859 if (my $shards = $self->{idx_shards}) {
860 $_->atfork_child foreach @$shards;
862 if (my $im = $self->{im}) {
865 die "unexpected mm" if $self->{mm};
866 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
870 sub mark_deleted ($$$$) {
871 my ($self, $sync, $git, $oid) = @_;
872 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
873 my $msgref = $git->cat_file($oid);
874 my $mime = PublicInbox::Eml->new($$msgref);
875 my $mids = mids($mime->header_obj);
876 my $cid = content_id($mime);
877 foreach my $mid (@$mids) {
878 $sync->{D}->{"$mid\0$cid"} = $oid;
882 sub reindex_checkpoint ($$$) {
883 my ($self, $sync, $git) = @_;
886 $sync->{mm_tmp}->atfork_prepare;
887 $self->done; # release lock
889 if (my $pr = $sync->{-opt}->{-progress}) {
890 my ($bn) = (split('/', $git->{git_dir}))[-1];
891 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
894 # allow -watch or -mda to write...
895 $self->idx_init; # reacquire lock
896 $sync->{mm_tmp}->atfork_parent;
899 # only for a few odd messages with multiple Message-IDs
900 sub reindex_oid_m ($$$$;$) {
901 my ($self, $sync, $git, $oid, $regen_num) = @_;
902 $self->{current_info} = "multi_mid $oid";
903 my ($num, $mid0, $len);
904 my $msgref = $git->cat_file($oid, \$len);
905 my $mime = PublicInbox::Eml->new($$msgref);
906 my $mids = mids($mime->header_obj);
907 my $cid = content_id($mime);
908 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
910 for my $mid (reverse @$mids) {
911 delete($sync->{D}->{"$mid\0$cid"}) and
912 die "BUG: reindex_oid should handle <$mid> delete";
914 my $over = $self->{over};
915 for my $mid (reverse @$mids) {
916 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
917 next unless defined $num;
918 if (defined($regen_num) && $regen_num != $num) {
919 die "BUG: regen(#$regen_num) != over(#$num)";
922 unless (defined($num)) {
923 for my $mid (reverse @$mids) {
924 # is this a number we got before?
925 my $n = $sync->{mm_tmp}->num_for($mid);
926 next unless defined $n;
927 next if defined($regen_num) && $regen_num != $n;
928 ($num, $mid0) = ($n, $mid);
933 $sync->{mm_tmp}->num_delete($num);
934 } elsif (defined $regen_num) {
936 for my $mid (reverse @$mids) {
937 $self->{mm}->mid_set($num, $mid) == 1 or next;
941 unless (defined $mid0) {
942 warn "E: cannot regen #$num\n";
945 } else { # fixup bugs in old mirrors on reindex
946 for my $mid (reverse @$mids) {
947 $num = $self->{mm}->mid_insert($mid);
948 next unless defined $num;
953 if ($sync->{reindex}) {
954 warn "reindex added #$num <$mid0>\n";
957 warn "E: cannot find article #\n";
967 }, 'PublicInbox::Smsg';
968 if (do_idx($self, $msgref, $mime, $smsg)) {
969 reindex_checkpoint($self, $sync, $git);
973 sub check_unindexed ($$$) {
974 my ($self, $num, $mid0) = @_;
975 my $unindexed = $self->{unindexed} // {};
976 my $n = delete($unindexed->{$mid0});
977 defined $n or return;
979 die "BUG: unindexed $n != $num <$mid0>\n";
981 $self->{mm}->mid_set($num, $mid0);
985 sub multi_mid_q_push ($$$) {
986 my ($self, $sync, $oid) = @_;
987 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
988 if ($sync->{reindex}) { # no regen on reindex
989 $multi_mid->push_oid($oid, $self);
991 my $num = $sync->{regen}--;
992 die "BUG: ran out of article numbers" if $num <= 0;
993 $multi_mid->set_oid($num, $oid, $self);
997 sub reindex_oid ($$$$) {
998 my ($self, $sync, $git, $oid) = @_;
999 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
1000 my ($num, $mid0, $len);
1001 my $msgref = $git->cat_file($oid, \$len);
1002 return if $len == 0; # purged
1003 my $mime = PublicInbox::Eml->new($$msgref);
1004 my $mids = mids($mime->header_obj);
1005 my $cid = content_id($mime);
1007 if (scalar(@$mids) == 0) {
1008 warn "E: $oid has no Message-ID, skipping\n";
1010 } elsif (scalar(@$mids) == 1) {
1011 my $mid = $mids->[0];
1013 # was the file previously marked as deleted?, skip if so
1014 if (delete($sync->{D}->{"$mid\0$cid"})) {
1015 if (!$sync->{reindex}) {
1016 $num = $sync->{regen}--;
1017 $self->{mm}->num_highwater($num);
1022 # is this a number we got before?
1023 $num = $sync->{mm_tmp}->num_for($mid);
1026 check_unindexed($self, $num, $mid0);
1028 $num = $sync->{regen}--;
1029 die "BUG: ran out of article numbers" if $num <= 0;
1030 if ($self->{mm}->mid_set($num, $mid) != 1) {
1031 warn "E: unable to assign $num => <$mid>\n";
1036 } else { # multiple MIDs are a weird case:
1039 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1042 unindex_oid_remote($self, $oid, $_) for @$mids;
1043 # do not delete from {mm_tmp}, since another
1044 # single-MID message may use it.
1045 } else { # handle them at the end:
1046 multi_mid_q_push($self, $sync, $oid);
1050 $sync->{mm_tmp}->mid_delete($mid0) or
1051 die "failed to delete <$mid0> for article #$num\n";
1058 }, 'PublicInbox::Smsg';
1059 if (do_idx($self, $msgref, $mime, $smsg)) {
1060 reindex_checkpoint($self, $sync, $git);
1064 # only update last_commit for $i on reindex iff newer than current
1065 sub update_last_commit ($$$$) {
1066 my ($self, $git, $i, $cmt) = @_;
1067 my $last = last_epoch_commit($self, $i);
1068 if (defined $last && is_ancestor($git, $last, $cmt)) {
1069 my @cmd = (qw(rev-list --count), "$last..$cmt");
1070 chomp(my $n = $git->qx(@cmd));
1071 return if $n ne '' && $n == 0;
1073 last_epoch_commit($self, $i, $cmt);
1076 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1078 sub last_commits ($$) {
1079 my ($self, $epoch_max) = @_;
1081 for (my $i = $epoch_max; $i >= 0; $i--) {
1082 $heads->[$i] = last_epoch_commit($self, $i);
1087 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1089 # returns a revision range for git-log(1)
1090 sub log_range ($$$$$) {
1091 my ($self, $sync, $git, $i, $tip) = @_;
1092 my $opt = $sync->{-opt};
1093 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1094 my $cur = $sync->{ranges}->[$i] or do {
1095 $pr->("$i.git indexing all of $tip") if $pr;
1096 return $tip; # all of it
1099 # fast equality check to avoid (v)fork+execve overhead
1101 $sync->{ranges}->[$i] = undef;
1105 my $range = "$cur..$tip";
1106 $pr->("$i.git checking contiguity... ") if $pr;
1107 if (is_ancestor($git, $cur, $tip)) { # common case
1108 $pr->("OK\n") if $pr;
1109 my $n = $git->qx(qw(rev-list --count), $range);
1112 $sync->{ranges}->[$i] = undef;
1113 $pr->("$i.git has nothing new\n") if $pr;
1114 return; # nothing to do
1116 $pr->("$i.git has $n changes since $cur\n") if $pr;
1118 $pr->("FAIL\n") if $pr;
1120 discontiguous range: $range
1121 Rewritten history? (in $git->{git_dir})
1123 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1125 $range = "$base..$tip";
1126 warn "found merge-base: $base\n"
1129 warn "discarding history at $cur\n";
1132 reindexing $git->{git_dir} starting at
1135 $sync->{unindex_range}->{$i} = "$base..$cur";
1140 sub sync_prepare ($$$) {
1141 my ($self, $sync, $epoch_max) = @_;
1142 my $pr = $sync->{-opt}->{-progress};
1144 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1146 # reindex stops at the current heads and we later rerun index_sync
1148 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1150 for (my $i = $epoch_max; $i >= 0; $i--) {
1151 die 'BUG: already indexing!' if $self->{reindex_pipe};
1152 my $git_dir = git_dir_n($self, $i);
1153 -d $git_dir or next; # missing epochs are fine
1154 my $git = PublicInbox::Git->new($git_dir);
1155 if ($reindex_heads) {
1156 $head = $reindex_heads->[$i] or next;
1158 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1160 next if $?; # new repo
1161 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1162 $sync->{ranges}->[$i] = $range;
1164 # can't use 'rev-list --count' if we use --diff-filter
1165 $pr->("$i.git counting $range ... ") if $pr;
1167 my $fh = $git->popen(qw(log --pretty=tformat:%H
1168 --no-notes --no-color --no-renames
1169 --diff-filter=AM), $range, '--', 'm');
1171 close $fh or die "git log failed: \$?=$?";
1172 $pr->("$n\n") if $pr;
1176 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1178 # reindex should NOT see new commits anymore, if we do,
1179 # it's a problem and we need to notice it via die()
1180 my $pad = length($regen_max) + 1;
1181 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1183 return -1 if $sync->{reindex};
1184 $regen_max + $self->{mm}->num_highwater() || 0;
1187 sub unindex_oid_remote ($$$) {
1188 my ($self, $oid, $mid) = @_;
1189 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1190 $self->{over}->remove_oid($oid, $mid);
1193 sub unindex_oid ($$$;$) {
1194 my ($self, $git, $oid, $unindexed) = @_;
1195 my $mm = $self->{mm};
1196 my $msgref = $git->cat_file($oid);
1197 my $mime = PublicInbox::Eml->new($msgref);
1198 my $mids = mids($mime->header_obj);
1199 $mime = $msgref = undef;
1200 my $over = $self->{over};
1201 foreach my $mid (@$mids) {
1204 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1205 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1208 my $n = scalar keys %gone;
1211 warn "BUG: multiple articles linked to $oid\n",
1212 join(',',sort keys %gone), "\n";
1214 foreach my $num (keys %gone) {
1216 my $mid0 = $mm->mid_for($num);
1217 $unindexed->{$mid0} = $num;
1219 $mm->num_delete($num);
1221 unindex_oid_remote($self, $oid, $mid);
1225 my $x40 = qr/[a-f0-9]{40}/;
1226 sub unindex ($$$$) {
1227 my ($self, $sync, $git, $unindex_range) = @_;
1228 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1229 my $before = scalar keys %$unindexed;
1230 # order does not matter, here:
1231 my @cmd = qw(log --raw -r
1232 --no-notes --no-color --no-abbrev --no-renames);
1233 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1235 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1236 unindex_oid($self, $git, $1, $unindexed);
1238 delete $self->{reindex_pipe};
1239 close $fh or die "git log failed: \$?=$?";
1241 return unless $sync->{-opt}->{prune};
1242 my $after = scalar keys %$unindexed;
1243 return if $before == $after;
1245 # ensure any blob can not longer be accessed via dumb HTTP
1246 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1247 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1250 sub sync_ranges ($$$) {
1251 my ($self, $sync, $epoch_max) = @_;
1252 my $reindex = $sync->{reindex};
1254 return last_commits($self, $epoch_max) unless $reindex;
1255 return [] if ref($reindex) ne 'HASH';
1257 my $ranges = $reindex->{from}; # arrayref;
1258 if (ref($ranges) ne 'ARRAY') {
1259 die 'BUG: $reindex->{from} not an ARRAY';
1264 sub index_epoch ($$$) {
1265 my ($self, $sync, $i) = @_;
1267 my $git_dir = git_dir_n($self, $i);
1268 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1269 -d $git_dir or return; # missing epochs are fine
1270 fill_alternates($self, $i);
1271 my $git = PublicInbox::Git->new($git_dir);
1272 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1273 unindex($self, $sync, $git, $unindex_range);
1275 defined(my $range = $sync->{ranges}->[$i]) or return;
1276 if (my $pr = $sync->{-opt}->{-progress}) {
1277 $pr->("$i.git indexing $range\n");
1280 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1281 --no-notes --no-color --no-abbrev --no-renames);
1282 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1286 $self->{current_info} = "$i.git $_";
1287 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1289 $self->{autime} = $2;
1290 $self->{cotime} = $3;
1291 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1292 reindex_oid($self, $sync, $git, $1);
1293 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1294 mark_deleted($self, $sync, $git, $1);
1297 close $fh or die "git log failed: \$?=$?";
1298 delete $self->{reindex_pipe};
1299 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1302 # public, called by public-inbox-index
1304 my ($self, $opt) = @_;
1306 my $pr = $opt->{-progress};
1308 my $latest = git_dir_latest($self, \$epoch_max);
1309 return unless defined $latest;
1310 $self->idx_init($opt); # acquire lock
1312 D => {}, # "$mid\0$cid" => $oid
1313 unindex_range => {}, # EPOCH => oid_old..oid_new
1314 reindex => $opt->{reindex},
1317 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1318 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1320 if ($sync->{regen}) {
1321 # tmp_clone seems to fail if inside a transaction, so
1322 # we rollback here (because we opened {mm} for reading)
1323 # Note: we do NOT rely on DBI transactions for atomicity;
1324 # only for batch performance.
1325 $self->{mm}->{dbh}->rollback;
1326 $self->{mm}->{dbh}->begin_work;
1327 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1330 # work backwards through history
1331 for (my $i = $epoch_max; $i >= 0; $i--) {
1332 index_epoch($self, $sync, $i);
1335 # unindex is required for leftovers if "deletes" affect messages
1336 # in a previous fetch+index window:
1338 if (my @leftovers = values %{delete $sync->{D}}) {
1339 $git = $self->{-inbox}->git;
1340 for my $oid (@leftovers) {
1341 $self->{current_info} = "leftover $oid";
1342 unindex_oid($self, $git, $oid);
1345 if (my $multi_mid = delete $sync->{multi_mid}) {
1346 $git //= $self->{-inbox}->git;
1347 my $min = $multi_mid->{min};
1348 my $max = $multi_mid->{max};
1349 if ($sync->{reindex}) {
1350 # we may need to create new Message-IDs if mirrors
1351 # were initially indexed with old versions
1352 for (my $i = $max; $i >= $min; $i--) {
1354 $oid = $multi_mid->get_oid($i, $self) or next;
1355 next unless defined $oid;
1356 reindex_oid_m($self, $sync, $git, $oid);
1358 } else { # regen on initial index
1359 for my $num ($min..$max) {
1361 $oid = $multi_mid->get_oid($num, $self) or next;
1362 reindex_oid_m($self, $sync, $git, $oid, $num);
1366 $git->cleanup if $git;
1369 if (my $nr = $sync->{nr}) {
1370 my $pr = $sync->{-opt}->{-progress};
1371 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1374 # reindex does not pick up new changes, so we rerun w/o it:
1375 if ($opt->{reindex}) {
1378 delete @again{qw(reindex -skip_lock)};
1379 index_sync($self, \%again);