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;
12 use PublicInbox::MIME;
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);
128 my ($self, $shards, $skip_epoch) = @_;
129 if (defined $shards) {
130 $self->{parallel} = 0 if $shards == 0;
131 $self->{shards} = $shards if $shards > 0;
135 git_dir_latest($self, \$epoch_max);
136 if (defined $skip_epoch && $epoch_max == -1) {
137 $epoch_max = $skip_epoch;
139 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
143 # returns undef on duplicate or spam
144 # mimics Import::add and wraps it for v2
146 my ($self, $mime, $check_cb) = @_;
147 $self->{-inbox}->with_umask(sub {
148 _add($self, $mime, $check_cb)
152 # indexes a message, returns true if checkpointing is needed
154 my ($self, $msgref, $mime, $smsg) = @_;
155 $smsg->{ds} //= msg_datestamp($mime->header_obj, $self->{autime});
156 $smsg->{ts} //= msg_timestamp($mime->header_obj, $self->{cotime});
157 $self->{over}->add_overview($mime, $smsg);
158 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
159 $idx->index_raw($msgref, $mime, $smsg);
160 my $n = $self->{transact_bytes} += $smsg->{bytes};
161 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
165 my ($self, $mime, $check_cb) = @_;
169 $mime = $check_cb->($mime) or return;
172 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
173 # as does SQLite 3.4.1+ (released in 2007-07-20), and
174 # Xapian 1.3.2+ (released 2015-03-15).
175 # For the most part, we can spawn git-fast-import without
176 # leaking FDs to it...
179 my ($num, $mid0) = v2_num_for($self, $mime);
180 defined $num or return; # duplicate
181 defined $mid0 or die "BUG: $mid0 undefined\n";
182 my $im = $self->importer;
183 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
184 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
185 $cmt = $im->get_mark($cmt);
186 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
188 my $msgref = delete $smsg->{-raw_email};
189 if (do_idx($self, $msgref, $mime, $smsg)) {
197 my ($self, $mime) = @_;
198 my $mids = mids($mime->header_obj);
200 my $mid = $mids->[0];
201 my $num = $self->{mm}->mid_insert($mid);
202 if (defined $num) { # common case
206 # crap, Message-ID is already known, hope somebody just resent:
207 foreach my $m (@$mids) {
208 # read-only lookup now safe to do after above barrier
209 # easy, don't store duplicates
210 # note: do not add more diagnostic info here since
211 # it gets noisy on public-inbox-watch restarts
212 return () if content_exists($self, $mime, $m);
215 # AltId may pre-populate article numbers (e.g. X-Mail-Count
216 # or NNTP article number), use that article number if it's
218 my $altid = $self->{-inbox}->{altid};
219 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
220 my $num = $self->{mm}->num_for($mid);
222 if (defined $num && !$self->{over}->get_art($num)) {
228 warn "<$mid> reused for mismatched content\n";
230 # try the rest of the mids
231 for(my $i = $#$mids; $i >= 1; $i--) {
233 $num = $self->{mm}->mid_insert($m);
235 warn "alternative <$m> for <$mid> found\n";
240 # none of the existing Message-IDs are good, generate a new one:
241 v2_num_for_harder($self, $mime);
244 sub v2_num_for_harder {
245 my ($self, $mime) = @_;
247 my $hdr = $mime->header_obj;
248 my $dig = content_digest($mime);
249 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
250 my $num = $self->{mm}->mid_insert($mid0);
251 unless (defined $num) {
252 # it's hard to spoof the last Received: header
253 my @recvd = $hdr->header_raw('Received');
254 $dig->add("Received: $_") foreach (@recvd);
255 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
256 $num = $self->{mm}->mid_insert($mid0);
258 # fall back to a random Message-ID and give up determinism:
259 until (defined($num)) {
261 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
262 warn "using random Message-ID <$mid0> as fallback\n";
263 $num = $self->{mm}->mid_insert($mid0);
266 PublicInbox::Import::append_mid($hdr, $mid0);
271 my ($self, $shard_i) = @_;
272 $self->{idx_shards}->[$shard_i];
277 my ($self, $opt) = @_;
278 return if $self->{idx_shards};
279 my $ibx = $self->{-inbox};
281 # do not leak read-only FDs to child processes, we only have these
282 # FDs for duplicate detection so they should not be
283 # frequently activated.
284 delete $ibx->{$_} foreach (qw(git mm search));
286 my $indexlevel = $ibx->{indexlevel};
287 if ($indexlevel && $indexlevel eq 'basic') {
288 $self->{parallel} = 0;
291 if ($self->{parallel}) {
292 pipe(my ($r, $w)) or die "pipe failed: $!";
293 # pipe for barrier notifications doesn't need to be big,
295 fcntl($w, 1031, 4096) if $^O eq 'linux';
296 $self->{bnote} = [ $r, $w ];
300 my $over = $self->{over};
302 $ibx->with_umask(sub {
303 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
306 # xcpdb can change shard count while -watch is idle
307 my $nshards = count_shards($self);
308 if ($nshards && $nshards != $self->{shards}) {
309 $self->{shards} = $nshards;
312 # need to create all shards before initializing msgmap FD
313 my $max = $self->{shards} - 1;
315 # idx_shards must be visible to all forked processes
316 my $idx = $self->{idx_shards} = [];
317 for my $i (0..$max) {
318 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
321 # Now that all subprocesses are up, we can open the FDs
323 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
324 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
325 $mm->{dbh}->begin_work;
329 # returns an array mapping [ epoch => latest_commit ]
330 # latest_commit may be undef if nothing was done to that epoch
331 # $replace_map = { $object_id => $strref, ... }
332 sub _replace_oids ($$$) {
333 my ($self, $mime, $replace_map) = @_;
335 my $pfx = "$self->{-inbox}->{inboxdir}/git";
336 my $rewrites = []; # epoch => commit
337 my $max = $self->{epoch_max};
339 unless (defined($max)) {
340 defined(my $latest = git_dir_latest($self, \$max)) or return;
341 $self->{epoch_max} = $max;
344 foreach my $i (0..$max) {
345 my $git_dir = "$pfx/$i.git";
347 my $git = PublicInbox::Git->new($git_dir);
348 my $im = $self->import_init($git, 0, 1);
349 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
355 sub content_ids ($) {
357 my @cids = ( content_id($mime) );
359 # Email::MIME->as_string doesn't always round-trip, so we may
360 # use a second content_id
361 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
362 push @cids, $rt if $cids[0] ne $rt;
366 sub content_matches ($$) {
367 my ($cids, $existing) = @_;
368 my $cid = content_id($existing);
370 return 1 if $_ eq $cid
375 # used for removing or replacing (purging)
376 sub rewrite_internal ($$;$$$) {
377 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
379 my ($im, $need_reindex, $replace_map);
381 $replace_map = {}; # oid => sref
382 $need_reindex = [] if $new_mime;
384 $im = $self->importer;
386 my $over = $self->{over};
387 my $cids = content_ids($old_mime);
389 my $mids = mids($old_mime->header_obj);
391 # We avoid introducing new blobs into git since the raw content
392 # can be slightly different, so we do not need the user-supplied
393 # message now that we have the mids and content_id
397 foreach my $mid (@$mids) {
398 my %gone; # num => [ smsg, $mime, raw ]
400 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
401 my $msg = get_blob($self, $smsg);
402 if (!defined($msg)) {
403 warn "broken smsg for $mid\n";
407 my $cur = PublicInbox::MIME->new($msg);
408 if (content_matches($cids, $cur)) {
409 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
412 my $n = scalar keys %gone;
415 warn "BUG: multiple articles linked to <$mid>\n",
416 join(',', sort keys %gone), "\n";
418 foreach my $num (keys %gone) {
419 my ($smsg, $mime, $orig) = @{$gone{$num}};
420 # @removed should only be set once assuming
421 # no bugs in our deduplication code:
422 @removed = (undef, $mime, $smsg);
423 my $oid = $smsg->{blob};
425 $replace_map->{$oid} = $sref;
427 ($mark, undef) = $im->remove($orig, $cmt_msg);
431 if ($need_reindex) { # ->replace
432 push @$need_reindex, $smsg;
433 } else { # ->purge or ->remove
434 $self->{mm}->num_delete($num);
436 unindex_oid_remote($self, $oid, $mid);
441 my $cmt = $im->get_mark($mark);
442 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
444 if ($replace_map && scalar keys %$replace_map) {
445 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
446 return { rewrites => $rewrites, need_reindex => $need_reindex };
448 defined($mark) ? @removed : undef;
451 # public (see PublicInbox::Import->remove), but note the 3rd element
452 # (retval[2]) is not part of the stable API shared with Import->remove
454 my ($self, $mime, $cmt_msg) = @_;
456 $self->{-inbox}->with_umask(sub {
457 @ret = rewrite_internal($self, $mime, $cmt_msg);
459 defined($ret[0]) ? @ret : undef;
462 sub _replace ($$;$$) {
463 my ($self, $old_mime, $new_mime, $sref) = @_;
464 my $rewritten = $self->{-inbox}->with_umask(sub {
465 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
468 my $rewrites = $rewritten->{rewrites};
469 # ->done is called if there are rewrites since we gc+prune from git
470 $self->idx_init if @$rewrites;
472 for my $i (0..$#$rewrites) {
473 defined(my $cmt = $rewrites->[$i]) or next;
474 $self->{last_commit}->[$i] = $cmt;
481 my ($self, $mime) = @_;
482 my $rewritten = _replace($self, $mime, undef, \'') or return;
483 $rewritten->{rewrites}
486 # returns the git object_id of $fh, does not write the object to FS
487 sub git_hash_raw ($$) {
488 my ($self, $raw) = @_;
489 # grab the expected OID we have to reindex:
490 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
491 $tmp_fh->autoflush(1);
492 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
493 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
495 my $git_dir = $self->{-inbox}->git->{git_dir};
496 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
497 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
499 chomp(my $oid = <$r>);
500 close $r or die "git hash-object failed: $?";
501 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
505 sub _check_mids_match ($$$) {
506 my ($old_list, $new_list, $hdrs) = @_;
507 my %old_mids = map { $_ => 1 } @$old_list;
508 my %new_mids = map { $_ => 1 } @$new_list;
509 my @old = keys %old_mids;
510 my @new = keys %new_mids;
511 my $err = "$hdrs may not be changed when replacing\n";
512 die $err if scalar(@old) != scalar(@new);
513 delete @new_mids{@old};
514 delete @old_mids{@new};
515 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
518 # Changing Message-IDs or References with ->replace isn't supported.
519 # The rules for dealing with messages with multiple or conflicting
520 # Message-IDs are pretty complex and rethreading hasn't been fully
522 sub check_mids_match ($$) {
523 my ($old_mime, $new_mime) = @_;
524 my $old = $old_mime->header_obj;
525 my $new = $new_mime->header_obj;
526 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
527 _check_mids_match(references($old), references($new),
528 'References/In-Reply-To');
533 my ($self, $old_mime, $new_mime) = @_;
535 check_mids_match($old_mime, $new_mime);
537 # mutt will always add Content-Length:, Status:, Lines: when editing
538 PublicInbox::Import::drop_unwanted_headers($new_mime);
540 my $raw = $new_mime->as_string;
541 my $expect_oid = git_hash_raw($self, \$raw);
542 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
543 my $need_reindex = $rewritten->{need_reindex};
545 # just in case we have bugs in deduplication code:
546 my $n = scalar(@$need_reindex);
548 my $list = join(', ', map {
549 "$_->{num}: <$_->{mid}>"
552 W: rewritten $n messages matching content of original message (expected: 1).
553 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
558 # make sure we really got the OID:
559 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
560 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
562 # don't leak FDs to Xapian:
563 $self->{-inbox}->git->cleanup;
565 # reindex modified messages:
566 for my $smsg (@$need_reindex) {
567 my $new_smsg = bless {
572 }, 'PublicInbox::Smsg';
573 do_idx($self, \$raw, $new_mime, $new_smsg);
575 $rewritten->{rewrites};
578 sub last_epoch_commit ($$;$) {
579 my ($self, $i, $cmt) = @_;
580 my $v = PublicInbox::Search::SCHEMA_VERSION();
581 $self->{mm}->last_commit_xap($v, $i, $cmt);
584 sub set_last_commits ($) {
586 defined(my $epoch_max = $self->{epoch_max}) or return;
587 my $last_commit = $self->{last_commit};
588 foreach my $i (0..$epoch_max) {
589 defined(my $cmt = $last_commit->[$i]) or next;
590 $last_commit->[$i] = undef;
591 last_epoch_commit($self, $i, $cmt);
597 $self->{bnote} or return;
599 my $barrier = { map { $_ => 1 } (0..$n) };
603 my ($self, $barrier) = @_;
604 my $bnote = $self->{bnote} or return;
606 while (scalar keys %$barrier) {
607 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
608 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
609 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
614 sub checkpoint ($;$) {
615 my ($self, $wait) = @_;
617 if (my $im = $self->{im}) {
624 my $shards = $self->{idx_shards};
626 my $dbh = $self->{mm}->{dbh};
628 # SQLite msgmap data is second in importance
631 # SQLite overview is third
632 $self->{over}->commit_lazy;
634 # Now deal with Xapian
636 my $barrier = $self->barrier_init(scalar @$shards);
638 # each shard needs to issue a barrier command
639 $_->remote_barrier for @$shards;
641 # wait for each Xapian shard
642 $self->barrier_wait($barrier);
644 $_->remote_commit for @$shards;
647 # last_commit is special, don't commit these until
648 # remote shards are done:
650 set_last_commits($self);
655 $self->{transact_bytes} = 0;
658 # issue a write barrier to ensure all data is visible to other processes
659 # and read-only ops. Order of data importance is: git > SQLite > Xapian
661 sub barrier { checkpoint($_[0], 1) };
666 my $im = delete $self->{im};
667 $im->done if $im; # PublicInbox::Import::done
669 my $mm = delete $self->{mm};
670 $mm->{dbh}->commit if $mm;
671 my $shards = delete $self->{idx_shards};
673 $_->remote_close for @$shards;
675 $self->{over}->disconnect;
676 delete $self->{bnote};
677 $self->{transact_bytes} = 0;
678 $self->lock_release if $shards;
679 $self->{-inbox}->git->cleanup;
682 sub fill_alternates ($$) {
683 my ($self, $epoch) = @_;
685 my $pfx = "$self->{-inbox}->{inboxdir}/git";
686 my $all = "$self->{-inbox}->{inboxdir}/all.git";
689 PublicInbox::Import::init_bare($all);
691 my $info_dir = "$all/objects/info";
692 my $alt = "$info_dir/alternates";
696 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
697 $mode = (stat($fh))[2] & 07777;
699 # we assign a sort score to every alternate and favor
700 # the newest (highest numbered) one when we
702 my $other = 0; # in case admin adds non-epoch repos
704 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
710 } split(/\n+/, do { local $/; <$fh> });
713 foreach my $i (0..$epoch) {
714 my $dir = "../../git/$i.git/objects";
715 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
722 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
723 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
724 or die "print $tmp: $!\n";
725 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
726 close $fh or die "close $tmp $!\n";
727 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
731 my ($self, $epoch) = @_;
732 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
733 my @cmd = (qw(git init --bare -q), $git_dir);
734 PublicInbox::Import::run_die(\@cmd);
735 @cmd = (qw/git config/, "--file=$git_dir/config",
736 'include.path', '../../all.git/config');
737 PublicInbox::Import::run_die(\@cmd);
738 fill_alternates($self, $epoch);
743 my ($self, $max) = @_;
745 my $pfx = "$self->{-inbox}->{inboxdir}/git";
746 return unless -d $pfx;
748 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
749 while (defined(my $git_dir = readdir($dh))) {
750 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
753 $latest = "$pfx/$git_dir";
761 my $im = $self->{im};
763 if ($im->{bytes_added} < $self->{rotate_bytes}) {
770 my $git_dir = $self->git_init(++$self->{epoch_max});
771 my $git = PublicInbox::Git->new($git_dir);
772 return $self->import_init($git, 0);
777 my $latest = git_dir_latest($self, \$max);
778 if (defined $latest) {
779 my $git = PublicInbox::Git->new($latest);
780 my $packed_bytes = $git->packed_bytes;
781 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
783 if ($unpacked_bytes >= $self->{rotate_bytes}) {
786 $self->{epoch_max} = $max;
787 return $self->import_init($git, $packed_bytes);
790 $self->{epoch_max} = $epoch;
791 $latest = $self->git_init($epoch);
792 $self->import_init(PublicInbox::Git->new($latest), 0);
796 my ($self, $git, $packed_bytes, $tmp) = @_;
797 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
798 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
799 $im->{lock_path} = undef;
800 $im->{path_type} = 'v2';
801 $self->{im} = $im unless $tmp;
807 my ($mid, $cur, $new) = @_;
809 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
810 print $ah $cur->as_string or die "print: $!";
811 close $ah or die "close: $!";
812 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
813 PublicInbox::Import::drop_unwanted_headers($new);
814 print $bh $new->as_string or die "print: $!";
815 close $bh or die "close: $!";
816 my $cmd = [ qw(diff -u), $an, $bn ];
817 print STDERR "# MID conflict <$mid>\n";
818 my $pid = spawn($cmd, undef, { 1 => 2 });
819 waitpid($pid, 0) == $pid or die "diff did not finish";
824 my ($self, $smsg) = @_;
825 if (my $im = $self->{im}) {
826 my $msg = $im->cat_blob($smsg->{blob});
829 # older message, should be in alternates
830 my $ibx = $self->{-inbox};
831 $ibx->msg_by_smsg($smsg);
834 sub content_exists ($$$) {
835 my ($self, $mime, $mid) = @_;
836 my $over = $self->{over};
837 my $cids = content_ids($mime);
839 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
840 my $msg = get_blob($self, $smsg);
841 if (!defined($msg)) {
842 warn "broken smsg for $mid\n";
845 my $cur = PublicInbox::MIME->new($msg);
846 return 1 if content_matches($cids, $cur);
848 # XXX DEBUG_DIFF is experimental and may be removed
849 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
856 my $fh = delete $self->{reindex_pipe};
858 if (my $shards = $self->{idx_shards}) {
859 $_->atfork_child foreach @$shards;
861 if (my $im = $self->{im}) {
864 die "unexpected mm" if $self->{mm};
865 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
869 sub mark_deleted ($$$$) {
870 my ($self, $sync, $git, $oid) = @_;
871 my $msgref = $git->cat_file($oid);
872 my $mime = PublicInbox::MIME->new($$msgref);
873 my $mids = mids($mime->header_obj);
874 my $cid = content_id($mime);
875 foreach my $mid (@$mids) {
876 $sync->{D}->{"$mid\0$cid"} = $oid;
880 sub reindex_checkpoint ($$$) {
881 my ($self, $sync, $git) = @_;
884 $sync->{mm_tmp}->atfork_prepare;
885 $self->done; # release lock
887 if (my $pr = $sync->{-opt}->{-progress}) {
888 my ($bn) = (split('/', $git->{git_dir}))[-1];
889 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
892 # allow -watch or -mda to write...
893 $self->idx_init; # reacquire lock
894 $sync->{mm_tmp}->atfork_parent;
897 # only for a few odd messages with multiple Message-IDs
898 sub reindex_oid_m ($$$$;$) {
899 my ($self, $sync, $git, $oid, $regen_num) = @_;
900 $self->{current_info} = "multi_mid $oid";
901 my ($num, $mid0, $len);
902 my $msgref = $git->cat_file($oid, \$len);
903 my $mime = PublicInbox::MIME->new($$msgref);
904 my $mids = mids($mime->header_obj);
905 my $cid = content_id($mime);
906 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
908 for my $mid (reverse @$mids) {
909 delete($sync->{D}->{"$mid\0$cid"}) and
910 die "BUG: reindex_oid should handle <$mid> delete";
912 my $over = $self->{over};
913 for my $mid (reverse @$mids) {
914 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
915 next unless defined $num;
916 if (defined($regen_num) && $regen_num != $num) {
917 die "BUG: regen(#$regen_num) != over(#$num)";
920 unless (defined($num)) {
921 for my $mid (reverse @$mids) {
922 # is this a number we got before?
923 my $n = $sync->{mm_tmp}->num_for($mid);
924 next unless defined $n;
925 next if defined($regen_num) && $regen_num != $n;
926 ($num, $mid0) = ($n, $mid);
931 $sync->{mm_tmp}->num_delete($num);
932 } elsif (defined $regen_num) {
934 for my $mid (reverse @$mids) {
935 $self->{mm}->mid_set($num, $mid) == 1 or next;
939 unless (defined $mid0) {
940 warn "E: cannot regen #$num\n";
943 } else { # fixup bugs in old mirrors on reindex
944 for my $mid (reverse @$mids) {
945 $num = $self->{mm}->mid_insert($mid);
946 next unless defined $num;
951 if ($sync->{reindex}) {
952 warn "reindex added #$num <$mid0>\n";
955 warn "E: cannot find article #\n";
965 }, 'PublicInbox::Smsg';
966 if (do_idx($self, $msgref, $mime, $smsg)) {
967 reindex_checkpoint($self, $sync, $git);
971 sub check_unindexed ($$$) {
972 my ($self, $num, $mid0) = @_;
973 my $unindexed = $self->{unindexed} // {};
974 my $n = delete($unindexed->{$mid0});
975 defined $n or return;
977 die "BUG: unindexed $n != $num <$mid0>\n";
979 $self->{mm}->mid_set($num, $mid0);
983 # reuse Msgmap to store num => oid mapping (rather than num => mid)
984 sub multi_mid_q_new () {
985 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
986 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
987 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
988 # for Msgmap->DESTROY:
989 $multi_mid->{tmp_name} = $fn;
990 $multi_mid->{pid} = $$;
991 close $fh or die "failed to close $fn: $!";
995 sub multi_mid_q_push ($$$) {
996 my ($self, $sync, $oid) = @_;
997 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
998 if ($sync->{reindex}) { # no regen on reindex
999 $multi_mid->push_oid($oid, $self);
1001 my $num = $sync->{regen}--;
1002 die "BUG: ran out of article numbers" if $num <= 0;
1003 $multi_mid->set_oid($num, $oid, $self);
1007 sub reindex_oid ($$$$) {
1008 my ($self, $sync, $git, $oid) = @_;
1009 my ($num, $mid0, $len);
1010 my $msgref = $git->cat_file($oid, \$len);
1011 return if $len == 0; # purged
1012 my $mime = PublicInbox::MIME->new($$msgref);
1013 my $mids = mids($mime->header_obj);
1014 my $cid = content_id($mime);
1016 if (scalar(@$mids) == 0) {
1017 warn "E: $oid has no Message-ID, skipping\n";
1019 } elsif (scalar(@$mids) == 1) {
1020 my $mid = $mids->[0];
1022 # was the file previously marked as deleted?, skip if so
1023 if (delete($sync->{D}->{"$mid\0$cid"})) {
1024 if (!$sync->{reindex}) {
1025 $num = $sync->{regen}--;
1026 $self->{mm}->num_highwater($num);
1031 # is this a number we got before?
1032 $num = $sync->{mm_tmp}->num_for($mid);
1035 check_unindexed($self, $num, $mid0);
1037 $num = $sync->{regen}--;
1038 die "BUG: ran out of article numbers" if $num <= 0;
1039 if ($self->{mm}->mid_set($num, $mid) != 1) {
1040 warn "E: unable to assign $num => <$mid>\n";
1045 } else { # multiple MIDs are a weird case:
1048 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1051 unindex_oid_remote($self, $oid, $_) for @$mids;
1052 # do not delete from {mm_tmp}, since another
1053 # single-MID message may use it.
1054 } else { # handle them at the end:
1055 multi_mid_q_push($self, $sync, $oid);
1059 $sync->{mm_tmp}->mid_delete($mid0) or
1060 die "failed to delete <$mid0> for article #$num\n";
1067 }, 'PublicInbox::Smsg';
1068 if (do_idx($self, $msgref, $mime, $smsg)) {
1069 reindex_checkpoint($self, $sync, $git);
1073 # only update last_commit for $i on reindex iff newer than current
1074 sub update_last_commit ($$$$) {
1075 my ($self, $git, $i, $cmt) = @_;
1076 my $last = last_epoch_commit($self, $i);
1077 if (defined $last && is_ancestor($git, $last, $cmt)) {
1078 my @cmd = (qw(rev-list --count), "$last..$cmt");
1079 chomp(my $n = $git->qx(@cmd));
1080 return if $n ne '' && $n == 0;
1082 last_epoch_commit($self, $i, $cmt);
1085 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1087 sub last_commits ($$) {
1088 my ($self, $epoch_max) = @_;
1090 for (my $i = $epoch_max; $i >= 0; $i--) {
1091 $heads->[$i] = last_epoch_commit($self, $i);
1096 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1098 # returns a revision range for git-log(1)
1099 sub log_range ($$$$$) {
1100 my ($self, $sync, $git, $i, $tip) = @_;
1101 my $opt = $sync->{-opt};
1102 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1103 my $cur = $sync->{ranges}->[$i] or do {
1104 $pr->("$i.git indexing all of $tip") if $pr;
1105 return $tip; # all of it
1108 # fast equality check to avoid (v)fork+execve overhead
1110 $sync->{ranges}->[$i] = undef;
1114 my $range = "$cur..$tip";
1115 $pr->("$i.git checking contiguity... ") if $pr;
1116 if (is_ancestor($git, $cur, $tip)) { # common case
1117 $pr->("OK\n") if $pr;
1118 my $n = $git->qx(qw(rev-list --count), $range);
1121 $sync->{ranges}->[$i] = undef;
1122 $pr->("$i.git has nothing new\n") if $pr;
1123 return; # nothing to do
1125 $pr->("$i.git has $n changes since $cur\n") if $pr;
1127 $pr->("FAIL\n") if $pr;
1129 discontiguous range: $range
1130 Rewritten history? (in $git->{git_dir})
1132 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1134 $range = "$base..$tip";
1135 warn "found merge-base: $base\n"
1138 warn "discarding history at $cur\n";
1141 reindexing $git->{git_dir} starting at
1144 $sync->{unindex_range}->{$i} = "$base..$cur";
1149 sub sync_prepare ($$$) {
1150 my ($self, $sync, $epoch_max) = @_;
1151 my $pr = $sync->{-opt}->{-progress};
1153 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1155 # reindex stops at the current heads and we later rerun index_sync
1157 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1159 for (my $i = $epoch_max; $i >= 0; $i--) {
1160 die 'BUG: already indexing!' if $self->{reindex_pipe};
1161 my $git_dir = git_dir_n($self, $i);
1162 -d $git_dir or next; # missing epochs are fine
1163 my $git = PublicInbox::Git->new($git_dir);
1164 if ($reindex_heads) {
1165 $head = $reindex_heads->[$i] or next;
1167 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1169 next if $?; # new repo
1170 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1171 $sync->{ranges}->[$i] = $range;
1173 # can't use 'rev-list --count' if we use --diff-filter
1174 $pr->("$i.git counting $range ... ") if $pr;
1176 my $fh = $git->popen(qw(log --pretty=tformat:%H
1177 --no-notes --no-color --no-renames
1178 --diff-filter=AM), $range, '--', 'm');
1180 close $fh or die "git log failed: \$?=$?";
1181 $pr->("$n\n") if $pr;
1185 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1187 # reindex should NOT see new commits anymore, if we do,
1188 # it's a problem and we need to notice it via die()
1189 my $pad = length($regen_max) + 1;
1190 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1192 return -1 if $sync->{reindex};
1193 $regen_max + $self->{mm}->num_highwater() || 0;
1196 sub unindex_oid_remote ($$$) {
1197 my ($self, $oid, $mid) = @_;
1198 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1199 $self->{over}->remove_oid($oid, $mid);
1202 sub unindex_oid ($$$;$) {
1203 my ($self, $git, $oid, $unindexed) = @_;
1204 my $mm = $self->{mm};
1205 my $msgref = $git->cat_file($oid);
1206 my $mime = PublicInbox::MIME->new($msgref);
1207 my $mids = mids($mime->header_obj);
1208 $mime = $msgref = undef;
1209 my $over = $self->{over};
1210 foreach my $mid (@$mids) {
1213 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1214 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1217 my $n = scalar keys %gone;
1220 warn "BUG: multiple articles linked to $oid\n",
1221 join(',',sort keys %gone), "\n";
1223 foreach my $num (keys %gone) {
1225 my $mid0 = $mm->mid_for($num);
1226 $unindexed->{$mid0} = $num;
1228 $mm->num_delete($num);
1230 unindex_oid_remote($self, $oid, $mid);
1234 my $x40 = qr/[a-f0-9]{40}/;
1235 sub unindex ($$$$) {
1236 my ($self, $sync, $git, $unindex_range) = @_;
1237 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1238 my $before = scalar keys %$unindexed;
1239 # order does not matter, here:
1240 my @cmd = qw(log --raw -r
1241 --no-notes --no-color --no-abbrev --no-renames);
1242 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1244 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1245 unindex_oid($self, $git, $1, $unindexed);
1247 delete $self->{reindex_pipe};
1248 close $fh or die "git log failed: \$?=$?";
1250 return unless $sync->{-opt}->{prune};
1251 my $after = scalar keys %$unindexed;
1252 return if $before == $after;
1254 # ensure any blob can not longer be accessed via dumb HTTP
1255 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1256 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1259 sub sync_ranges ($$$) {
1260 my ($self, $sync, $epoch_max) = @_;
1261 my $reindex = $sync->{reindex};
1263 return last_commits($self, $epoch_max) unless $reindex;
1264 return [] if ref($reindex) ne 'HASH';
1266 my $ranges = $reindex->{from}; # arrayref;
1267 if (ref($ranges) ne 'ARRAY') {
1268 die 'BUG: $reindex->{from} not an ARRAY';
1273 sub index_epoch ($$$) {
1274 my ($self, $sync, $i) = @_;
1276 my $git_dir = git_dir_n($self, $i);
1277 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1278 -d $git_dir or return; # missing epochs are fine
1279 fill_alternates($self, $i);
1280 my $git = PublicInbox::Git->new($git_dir);
1281 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1282 unindex($self, $sync, $git, $unindex_range);
1284 defined(my $range = $sync->{ranges}->[$i]) or return;
1285 if (my $pr = $sync->{-opt}->{-progress}) {
1286 $pr->("$i.git indexing $range\n");
1289 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1290 --no-notes --no-color --no-abbrev --no-renames);
1291 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1295 $self->{current_info} = "$i.git $_";
1296 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1298 $self->{autime} = $2;
1299 $self->{cotime} = $3;
1300 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1301 reindex_oid($self, $sync, $git, $1);
1302 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1303 mark_deleted($self, $sync, $git, $1);
1306 close $fh or die "git log failed: \$?=$?";
1307 delete $self->{reindex_pipe};
1308 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1311 # public, called by public-inbox-index
1313 my ($self, $opt) = @_;
1315 my $pr = $opt->{-progress};
1317 my $latest = git_dir_latest($self, \$epoch_max);
1318 return unless defined $latest;
1319 $self->idx_init($opt); # acquire lock
1321 D => {}, # "$mid\0$cid" => $oid
1322 unindex_range => {}, # EPOCH => oid_old..oid_new
1323 reindex => $opt->{reindex},
1326 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1327 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1329 if ($sync->{regen}) {
1330 # tmp_clone seems to fail if inside a transaction, so
1331 # we rollback here (because we opened {mm} for reading)
1332 # Note: we do NOT rely on DBI transactions for atomicity;
1333 # only for batch performance.
1334 $self->{mm}->{dbh}->rollback;
1335 $self->{mm}->{dbh}->begin_work;
1336 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1339 # work backwards through history
1340 for (my $i = $epoch_max; $i >= 0; $i--) {
1341 index_epoch($self, $sync, $i);
1344 # unindex is required for leftovers if "deletes" affect messages
1345 # in a previous fetch+index window:
1347 if (my @leftovers = values %{delete $sync->{D}}) {
1348 $git = $self->{-inbox}->git;
1349 for my $oid (@leftovers) {
1350 $self->{current_info} = "leftover $oid";
1351 unindex_oid($self, $git, $oid);
1354 if (my $multi_mid = delete $sync->{multi_mid}) {
1355 $git //= $self->{-inbox}->git;
1356 my $min = $multi_mid->{min};
1357 my $max = $multi_mid->{max};
1358 if ($sync->{reindex}) {
1359 # we may need to create new Message-IDs if mirrors
1360 # were initially indexed with old versions
1361 for (my $i = $max; $i >= $min; $i--) {
1363 $oid = $multi_mid->get_oid($i, $self) or next;
1364 next unless defined $oid;
1365 reindex_oid_m($self, $sync, $git, $oid);
1367 } else { # regen on initial index
1368 for my $num ($min..$max) {
1370 $oid = $multi_mid->get_oid($num, $self) or next;
1371 reindex_oid_m($self, $sync, $git, $oid, $num);
1375 $git->cleanup if $git;
1378 if (my $nr = $sync->{nr}) {
1379 my $pr = $sync->{-opt}->{-progress};
1380 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1383 # reindex does not pick up new changes, so we rerun w/o it:
1384 if ($opt->{reindex}) {
1387 delete @again{qw(reindex -skip_lock)};
1388 index_sync($self, \%again);