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::ContentHash qw(content_hash 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::MultiMidQueue;
23 use IO::Handle; # ->autoflush
24 use File::Temp qw(tempfile);
26 # an estimate of the post-packed size to the raw uncompressed size
27 my $PACKING_FACTOR = 0.4;
29 # SATA storage lags behind what CPUs are capable of, so relying on
30 # nproc(1) can be misleading and having extra Xapian shards is a
31 # waste of FDs and space. It can also lead to excessive IO latency
32 # and slow things down. Users on NVME or other fast storage can
33 # use the NPROC env or switches in our script/public-inbox-* programs
34 # to increase Xapian shards
35 our $NPROC_MAX_DEFAULT = 4;
38 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
39 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
42 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
43 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
44 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
47 # should we bother with `sysctl hw.ncpu`? Those only give
48 # us total processor count, not online processor count.
52 sub nproc_shards ($) {
54 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
57 # assume 2 cores if not detectable or zero
58 state $NPROC_DETECTED = detect_nproc() || 2;
60 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
63 # subtract for the main process and git-fast-import
68 sub count_shards ($) {
71 my $xpfx = $self->{xpfx};
73 # always load existing shards in case core count changes:
74 # Also, shard count may change while -watch is running
75 # due to "xcpdb --reshard"
78 foreach my $shard (<$xpfx/*>) {
79 -d $shard && $shard =~ m!/[0-9]+\z! or next;
80 $XapianDatabase //= do {
81 require PublicInbox::Search;
82 PublicInbox::Search::load_xapian();
83 $PublicInbox::Search::X{Database};
86 $XapianDatabase->new($shard)->close;
95 # $creat may be any true value, or 0/undef. A hashref is true,
96 # and $creat->{nproc} may be set to an integer
97 my ($class, $v2ibx, $creat) = @_;
98 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
99 my $dir = $v2ibx->assert_usable_dir;
103 File::Path::mkpath($dir);
105 die "$dir does not exist\n";
108 $v2ibx->umask_prepare;
110 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
113 im => undef, # PublicInbox::Import
118 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
119 lock_path => "$dir/inbox.lock",
120 # limit each git repo (epoch) to 1GB or so
121 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
122 last_commit => [], # git repo -> commit
124 $self->{shards} = count_shards($self) || nproc_shards($creat);
125 $self->{index_max_size} = $v2ibx->{index_max_size};
131 my ($self, $shards, $skip_epoch) = @_;
132 if (defined $shards) {
133 $self->{parallel} = 0 if $shards == 0;
134 $self->{shards} = $shards if $shards > 0;
138 git_dir_latest($self, \$epoch_max);
139 if (defined $skip_epoch && $epoch_max == -1) {
140 $epoch_max = $skip_epoch;
142 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
146 # returns undef on duplicate or spam
147 # mimics Import::add and wraps it for v2
149 my ($self, $mime, $check_cb) = @_;
150 $self->{-inbox}->with_umask(sub {
151 _add($self, $mime, $check_cb)
155 # indexes a message, returns true if checkpointing is needed
157 my ($self, $msgref, $mime, $smsg) = @_;
158 $smsg->{bytes} = $smsg->{raw_bytes} +
159 PublicInbox::SearchIdx::crlf_adjust($$msgref);
160 $self->{over}->add_overview($mime, $smsg);
161 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
162 $idx->index_raw($msgref, $mime, $smsg);
163 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
164 $n >= ($PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
168 my ($self, $mime, $check_cb) = @_;
172 $mime = $check_cb->($mime) or return;
175 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
176 # as does SQLite 3.4.1+ (released in 2007-07-20), and
177 # Xapian 1.3.2+ (released 2015-03-15).
178 # For the most part, we can spawn git-fast-import without
179 # leaking FDs to it...
182 my ($num, $mid0) = v2_num_for($self, $mime);
183 defined $num or return; # duplicate
184 defined $mid0 or die "BUG: \$mid0 undefined\n";
185 my $im = $self->importer;
186 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
187 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
188 $cmt = $im->get_mark($cmt);
189 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
191 my $msgref = delete $smsg->{-raw_email};
192 if (do_idx($self, $msgref, $mime, $smsg)) {
200 my ($self, $mime) = @_;
201 my $mids = mids($mime->header_obj);
203 my $mid = $mids->[0];
204 my $num = $self->{mm}->mid_insert($mid);
205 if (defined $num) { # common case
209 # crap, Message-ID is already known, hope somebody just resent:
210 foreach my $m (@$mids) {
211 # read-only lookup now safe to do after above barrier
212 # easy, don't store duplicates
213 # note: do not add more diagnostic info here since
214 # it gets noisy on public-inbox-watch restarts
215 return () if content_exists($self, $mime, $m);
218 # AltId may pre-populate article numbers (e.g. X-Mail-Count
219 # or NNTP article number), use that article number if it's
221 my $altid = $self->{-inbox}->{altid};
222 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
223 my $num = $self->{mm}->num_for($mid);
225 if (defined $num && !$self->{over}->get_art($num)) {
231 warn "<$mid> reused for mismatched content\n";
233 # try the rest of the mids
234 for(my $i = $#$mids; $i >= 1; $i--) {
236 $num = $self->{mm}->mid_insert($m);
238 warn "alternative <$m> for <$mid> found\n";
243 # none of the existing Message-IDs are good, generate a new one:
244 v2_num_for_harder($self, $mime);
247 sub v2_num_for_harder {
248 my ($self, $mime) = @_;
250 my $hdr = $mime->header_obj;
251 my $dig = content_digest($mime);
252 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
253 my $num = $self->{mm}->mid_insert($mid0);
254 unless (defined $num) {
255 # it's hard to spoof the last Received: header
256 my @recvd = $hdr->header_raw('Received');
257 $dig->add("Received: $_") foreach (@recvd);
258 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
259 $num = $self->{mm}->mid_insert($mid0);
261 # fall back to a random Message-ID and give up determinism:
262 until (defined($num)) {
264 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
265 warn "using random Message-ID <$mid0> as fallback\n";
266 $num = $self->{mm}->mid_insert($mid0);
269 PublicInbox::Import::append_mid($hdr, $mid0);
274 my ($self, $shard_i) = @_;
275 $self->{idx_shards}->[$shard_i];
280 my ($self, $opt) = @_;
281 return if $self->{idx_shards};
282 my $ibx = $self->{-inbox};
284 # do not leak read-only FDs to child processes, we only have these
285 # FDs for duplicate detection so they should not be
286 # frequently activated.
287 delete $ibx->{$_} foreach (qw(git mm search));
289 my $indexlevel = $ibx->{indexlevel};
290 if ($indexlevel && $indexlevel eq 'basic') {
291 $self->{parallel} = 0;
294 if ($self->{parallel}) {
295 pipe(my ($r, $w)) or die "pipe failed: $!";
296 # pipe for barrier notifications doesn't need to be big,
298 fcntl($w, 1031, 4096) if $^O eq 'linux';
299 $self->{bnote} = [ $r, $w ];
303 my $over = $self->{over};
305 $ibx->with_umask(sub {
306 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
309 # xcpdb can change shard count while -watch is idle
310 my $nshards = count_shards($self);
311 if ($nshards && $nshards != $self->{shards}) {
312 $self->{shards} = $nshards;
315 # need to create all shards before initializing msgmap FD
316 my $max = $self->{shards} - 1;
318 # idx_shards must be visible to all forked processes
319 my $idx = $self->{idx_shards} = [];
320 for my $i (0..$max) {
321 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
324 # Now that all subprocesses are up, we can open the FDs
326 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
327 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
328 $mm->{dbh}->begin_work;
332 # returns an array mapping [ epoch => latest_commit ]
333 # latest_commit may be undef if nothing was done to that epoch
334 # $replace_map = { $object_id => $strref, ... }
335 sub _replace_oids ($$$) {
336 my ($self, $mime, $replace_map) = @_;
338 my $pfx = "$self->{-inbox}->{inboxdir}/git";
339 my $rewrites = []; # epoch => commit
340 my $max = $self->{epoch_max};
342 unless (defined($max)) {
343 defined(my $latest = git_dir_latest($self, \$max)) or return;
344 $self->{epoch_max} = $max;
347 foreach my $i (0..$max) {
348 my $git_dir = "$pfx/$i.git";
350 my $git = PublicInbox::Git->new($git_dir);
351 my $im = $self->import_init($git, 0, 1);
352 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
358 sub content_hashes ($) {
360 my @chashes = ( content_hash($mime) );
362 # We still support Email::MIME, here, and
363 # Email::MIME->as_string doesn't always round-trip, so we may
364 # use a second content_hash
365 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
366 push @chashes, $rt if $chashes[0] ne $rt;
370 sub content_matches ($$) {
371 my ($chashes, $existing) = @_;
372 my $chash = content_hash($existing);
373 foreach (@$chashes) {
374 return 1 if $_ eq $chash
379 # used for removing or replacing (purging)
380 sub rewrite_internal ($$;$$$) {
381 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
383 my ($im, $need_reindex, $replace_map);
385 $replace_map = {}; # oid => sref
386 $need_reindex = [] if $new_mime;
388 $im = $self->importer;
390 my $over = $self->{over};
391 my $chashes = content_hashes($old_mime);
393 my $mids = mids($old_mime->header_obj);
395 # We avoid introducing new blobs into git since the raw content
396 # can be slightly different, so we do not need the user-supplied
397 # message now that we have the mids and content_hash
401 foreach my $mid (@$mids) {
402 my %gone; # num => [ smsg, $mime, raw ]
404 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
405 my $msg = get_blob($self, $smsg);
406 if (!defined($msg)) {
407 warn "broken smsg for $mid\n";
411 my $cur = PublicInbox::Eml->new($msg);
412 if (content_matches($chashes, $cur)) {
413 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
416 my $n = scalar keys %gone;
419 warn "BUG: multiple articles linked to <$mid>\n",
420 join(',', sort keys %gone), "\n";
422 foreach my $num (keys %gone) {
423 my ($smsg, $mime, $orig) = @{$gone{$num}};
424 # @removed should only be set once assuming
425 # no bugs in our deduplication code:
426 @removed = (undef, $mime, $smsg);
427 my $oid = $smsg->{blob};
429 $replace_map->{$oid} = $sref;
431 ($mark, undef) = $im->remove($orig, $cmt_msg);
435 if ($need_reindex) { # ->replace
436 push @$need_reindex, $smsg;
437 } else { # ->purge or ->remove
438 $self->{mm}->num_delete($num);
440 unindex_oid_remote($self, $oid, $mid);
445 my $cmt = $im->get_mark($mark);
446 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
448 if ($replace_map && scalar keys %$replace_map) {
449 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
450 return { rewrites => $rewrites, need_reindex => $need_reindex };
452 defined($mark) ? @removed : undef;
455 # public (see PublicInbox::Import->remove), but note the 3rd element
456 # (retval[2]) is not part of the stable API shared with Import->remove
458 my ($self, $mime, $cmt_msg) = @_;
460 $self->{-inbox}->with_umask(sub {
461 @ret = rewrite_internal($self, $mime, $cmt_msg);
463 defined($ret[0]) ? @ret : undef;
466 sub _replace ($$;$$) {
467 my ($self, $old_mime, $new_mime, $sref) = @_;
468 my $rewritten = $self->{-inbox}->with_umask(sub {
469 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
472 my $rewrites = $rewritten->{rewrites};
473 # ->done is called if there are rewrites since we gc+prune from git
474 $self->idx_init if @$rewrites;
476 for my $i (0..$#$rewrites) {
477 defined(my $cmt = $rewrites->[$i]) or next;
478 $self->{last_commit}->[$i] = $cmt;
485 my ($self, $mime) = @_;
486 my $rewritten = _replace($self, $mime, undef, \'') or return;
487 $rewritten->{rewrites}
490 # returns the git object_id of $fh, does not write the object to FS
491 sub git_hash_raw ($$) {
492 my ($self, $raw) = @_;
493 # grab the expected OID we have to reindex:
494 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
495 $tmp_fh->autoflush(1);
496 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
497 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
499 my $git_dir = $self->{-inbox}->git->{git_dir};
500 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
501 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
503 chomp(my $oid = <$r>);
504 close $r or die "git hash-object failed: $?";
505 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
509 sub _check_mids_match ($$$) {
510 my ($old_list, $new_list, $hdrs) = @_;
511 my %old_mids = map { $_ => 1 } @$old_list;
512 my %new_mids = map { $_ => 1 } @$new_list;
513 my @old = keys %old_mids;
514 my @new = keys %new_mids;
515 my $err = "$hdrs may not be changed when replacing\n";
516 die $err if scalar(@old) != scalar(@new);
517 delete @new_mids{@old};
518 delete @old_mids{@new};
519 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
522 # Changing Message-IDs or References with ->replace isn't supported.
523 # The rules for dealing with messages with multiple or conflicting
524 # Message-IDs are pretty complex and rethreading hasn't been fully
526 sub check_mids_match ($$) {
527 my ($old_mime, $new_mime) = @_;
528 my $old = $old_mime->header_obj;
529 my $new = $new_mime->header_obj;
530 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
531 _check_mids_match(references($old), references($new),
532 'References/In-Reply-To');
537 my ($self, $old_mime, $new_mime) = @_;
539 check_mids_match($old_mime, $new_mime);
541 # mutt will always add Content-Length:, Status:, Lines: when editing
542 PublicInbox::Import::drop_unwanted_headers($new_mime);
544 my $raw = $new_mime->as_string;
545 my $expect_oid = git_hash_raw($self, \$raw);
546 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
547 my $need_reindex = $rewritten->{need_reindex};
549 # just in case we have bugs in deduplication code:
550 my $n = scalar(@$need_reindex);
552 my $list = join(', ', map {
553 "$_->{num}: <$_->{mid}>"
556 W: rewritten $n messages matching content of original message (expected: 1).
557 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
562 # make sure we really got the OID:
563 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
564 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
566 # don't leak FDs to Xapian:
567 $self->{-inbox}->git->cleanup;
569 # reindex modified messages:
570 for my $smsg (@$need_reindex) {
571 my $new_smsg = bless {
576 }, 'PublicInbox::Smsg';
577 my $v2w = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
578 $new_smsg->populate($new_mime, $v2w);
579 do_idx($self, \$raw, $new_mime, $new_smsg);
581 $rewritten->{rewrites};
584 sub last_epoch_commit ($$;$) {
585 my ($self, $i, $cmt) = @_;
586 my $v = PublicInbox::Search::SCHEMA_VERSION();
587 $self->{mm}->last_commit_xap($v, $i, $cmt);
590 sub set_last_commits ($) {
592 defined(my $epoch_max = $self->{epoch_max}) or return;
593 my $last_commit = $self->{last_commit};
594 foreach my $i (0..$epoch_max) {
595 defined(my $cmt = $last_commit->[$i]) or next;
596 $last_commit->[$i] = undef;
597 last_epoch_commit($self, $i, $cmt);
603 $self->{bnote} or return;
605 my $barrier = { map { $_ => 1 } (0..$n) };
609 my ($self, $barrier) = @_;
610 my $bnote = $self->{bnote} or return;
612 while (scalar keys %$barrier) {
613 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
614 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
615 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
620 sub checkpoint ($;$) {
621 my ($self, $wait) = @_;
623 if (my $im = $self->{im}) {
630 my $shards = $self->{idx_shards};
632 my $dbh = $self->{mm}->{dbh};
634 # SQLite msgmap data is second in importance
637 # SQLite overview is third
638 $self->{over}->commit_lazy;
640 # Now deal with Xapian
642 my $barrier = $self->barrier_init(scalar @$shards);
644 # each shard needs to issue a barrier command
645 $_->remote_barrier for @$shards;
647 # wait for each Xapian shard
648 $self->barrier_wait($barrier);
650 $_->remote_commit for @$shards;
653 # last_commit is special, don't commit these until
654 # remote shards are done:
656 set_last_commits($self);
661 $self->{transact_bytes} = 0;
664 # issue a write barrier to ensure all data is visible to other processes
665 # and read-only ops. Order of data importance is: git > SQLite > Xapian
667 sub barrier { checkpoint($_[0], 1) };
672 my $im = delete $self->{im};
673 $im->done if $im; # PublicInbox::Import::done
675 my $mm = delete $self->{mm};
676 $mm->{dbh}->commit if $mm;
677 my $shards = delete $self->{idx_shards};
679 $_->remote_close for @$shards;
681 $self->{over}->disconnect;
682 delete $self->{bnote};
683 $self->{transact_bytes} = 0;
684 $self->lock_release if $shards;
685 $self->{-inbox}->git->cleanup;
688 sub fill_alternates ($$) {
689 my ($self, $epoch) = @_;
691 my $pfx = "$self->{-inbox}->{inboxdir}/git";
692 my $all = "$self->{-inbox}->{inboxdir}/all.git";
695 PublicInbox::Import::init_bare($all);
697 my $info_dir = "$all/objects/info";
698 my $alt = "$info_dir/alternates";
702 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
703 $mode = (stat($fh))[2] & 07777;
705 # we assign a sort score to every alternate and favor
706 # the newest (highest numbered) one when we
708 my $other = 0; # in case admin adds non-epoch repos
710 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
716 } split(/\n+/, do { local $/; <$fh> });
719 foreach my $i (0..$epoch) {
720 my $dir = "../../git/$i.git/objects";
721 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
728 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
729 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
730 or die "print $tmp: $!\n";
731 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
732 close $fh or die "close $tmp $!\n";
733 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
737 my ($self, $epoch) = @_;
738 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
739 PublicInbox::Import::init_bare($git_dir);
740 my @cmd = (qw/git config/, "--file=$git_dir/config",
741 'include.path', '../../all.git/config');
742 PublicInbox::Import::run_die(\@cmd);
743 fill_alternates($self, $epoch);
748 my ($self, $max) = @_;
750 my $pfx = "$self->{-inbox}->{inboxdir}/git";
751 return unless -d $pfx;
753 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
754 while (defined(my $git_dir = readdir($dh))) {
755 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
758 $latest = "$pfx/$git_dir";
766 my $im = $self->{im};
768 if ($im->{bytes_added} < $self->{rotate_bytes}) {
775 my $git_dir = $self->git_init(++$self->{epoch_max});
776 my $git = PublicInbox::Git->new($git_dir);
777 return $self->import_init($git, 0);
782 my $latest = git_dir_latest($self, \$max);
783 if (defined $latest) {
784 my $git = PublicInbox::Git->new($latest);
785 my $packed_bytes = $git->packed_bytes;
786 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
788 if ($unpacked_bytes >= $self->{rotate_bytes}) {
791 $self->{epoch_max} = $max;
792 return $self->import_init($git, $packed_bytes);
795 $self->{epoch_max} = $epoch;
796 $latest = $self->git_init($epoch);
797 $self->import_init(PublicInbox::Git->new($latest), 0);
801 my ($self, $git, $packed_bytes, $tmp) = @_;
802 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
803 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
804 $im->{lock_path} = undef;
805 $im->{path_type} = 'v2';
806 $self->{im} = $im unless $tmp;
812 my ($mid, $cur, $new) = @_;
814 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
815 print $ah $cur->as_string or die "print: $!";
816 close $ah or die "close: $!";
817 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
818 PublicInbox::Import::drop_unwanted_headers($new);
819 print $bh $new->as_string or die "print: $!";
820 close $bh or die "close: $!";
821 my $cmd = [ qw(diff -u), $an, $bn ];
822 print STDERR "# MID conflict <$mid>\n";
823 my $pid = spawn($cmd, undef, { 1 => 2 });
824 waitpid($pid, 0) == $pid or die "diff did not finish";
829 my ($self, $smsg) = @_;
830 if (my $im = $self->{im}) {
831 my $msg = $im->cat_blob($smsg->{blob});
834 # older message, should be in alternates
835 my $ibx = $self->{-inbox};
836 $ibx->msg_by_smsg($smsg);
839 sub content_exists ($$$) {
840 my ($self, $mime, $mid) = @_;
841 my $over = $self->{over};
842 my $chashes = content_hashes($mime);
844 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
845 my $msg = get_blob($self, $smsg);
846 if (!defined($msg)) {
847 warn "broken smsg for $mid\n";
850 my $cur = PublicInbox::Eml->new($msg);
851 return 1 if content_matches($chashes, $cur);
853 # XXX DEBUG_DIFF is experimental and may be removed
854 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
861 my $fh = delete $self->{reindex_pipe};
863 if (my $shards = $self->{idx_shards}) {
864 $_->atfork_child foreach @$shards;
866 if (my $im = $self->{im}) {
869 die "unexpected mm" if $self->{mm};
870 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
874 sub mark_deleted ($$$$) {
875 my ($self, $sync, $git, $oid) = @_;
876 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
877 my $msgref = $git->cat_file($oid);
878 my $mime = PublicInbox::Eml->new($$msgref);
879 my $mids = mids($mime->header_obj);
880 my $chash = content_hash($mime);
881 foreach my $mid (@$mids) {
882 $sync->{D}->{"$mid\0$chash"} = $oid;
886 sub reindex_checkpoint ($$$) {
887 my ($self, $sync, $git) = @_;
890 $sync->{mm_tmp}->atfork_prepare;
891 $self->done; # release lock
893 if (my $pr = $sync->{-opt}->{-progress}) {
894 my ($bn) = (split('/', $git->{git_dir}))[-1];
895 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
898 # allow -watch or -mda to write...
899 $self->idx_init; # reacquire lock
900 $sync->{mm_tmp}->atfork_parent;
903 # only for a few odd messages with multiple Message-IDs
904 sub reindex_oid_m ($$$$;$) {
905 my ($self, $sync, $git, $oid, $regen_num) = @_;
906 $self->{current_info} = "multi_mid $oid";
907 my ($num, $mid0, $len);
908 my $msgref = $git->cat_file($oid, \$len);
909 my $mime = PublicInbox::Eml->new($$msgref);
910 my $mids = mids($mime->header_obj);
911 my $chash = content_hash($mime);
912 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
914 for my $mid (reverse @$mids) {
915 delete($sync->{D}->{"$mid\0$chash"}) and
916 die "BUG: reindex_oid should handle <$mid> delete";
918 my $over = $self->{over};
919 for my $mid (reverse @$mids) {
920 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
921 next unless defined $num;
922 if (defined($regen_num) && $regen_num != $num) {
923 die "BUG: regen(#$regen_num) != over(#$num)";
926 unless (defined($num)) {
927 for my $mid (reverse @$mids) {
928 # is this a number we got before?
929 my $n = $sync->{mm_tmp}->num_for($mid);
930 next unless defined $n;
931 next if defined($regen_num) && $regen_num != $n;
932 ($num, $mid0) = ($n, $mid);
937 $sync->{mm_tmp}->num_delete($num);
938 } elsif (defined $regen_num) {
940 for my $mid (reverse @$mids) {
941 $self->{mm}->mid_set($num, $mid) == 1 or next;
945 unless (defined $mid0) {
946 warn "E: cannot regen #$num\n";
949 } else { # fixup bugs in old mirrors on reindex
950 for my $mid (reverse @$mids) {
951 $num = $self->{mm}->mid_insert($mid);
952 next unless defined $num;
957 if ($sync->{reindex}) {
958 warn "reindex added #$num <$mid0>\n";
961 warn "E: cannot find article #\n";
971 }, 'PublicInbox::Smsg';
972 $smsg->populate($mime, $self);
973 if (do_idx($self, $msgref, $mime, $smsg)) {
974 reindex_checkpoint($self, $sync, $git);
978 sub check_unindexed ($$$) {
979 my ($self, $num, $mid0) = @_;
980 my $unindexed = $self->{unindexed} // {};
981 my $n = delete($unindexed->{$mid0});
982 defined $n or return;
984 die "BUG: unindexed $n != $num <$mid0>\n";
986 $self->{mm}->mid_set($num, $mid0);
990 sub multi_mid_q_push ($$$) {
991 my ($self, $sync, $oid) = @_;
992 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
993 if ($sync->{reindex}) { # no regen on reindex
994 $multi_mid->push_oid($oid, $self);
996 my $num = $sync->{regen}--;
997 die "BUG: ran out of article numbers" if $num <= 0;
998 $multi_mid->set_oid($num, $oid, $self);
1002 sub reindex_oid ($$$$) {
1003 my ($self, $sync, $git, $oid) = @_;
1004 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
1005 my ($num, $mid0, $len);
1006 my $msgref = $git->cat_file($oid, \$len);
1007 return if $len == 0; # purged
1008 my $mime = PublicInbox::Eml->new($$msgref);
1009 my $mids = mids($mime->header_obj);
1010 my $chash = content_hash($mime);
1012 if (scalar(@$mids) == 0) {
1013 warn "E: $oid has no Message-ID, skipping\n";
1015 } elsif (scalar(@$mids) == 1) {
1016 my $mid = $mids->[0];
1018 # was the file previously marked as deleted?, skip if so
1019 if (delete($sync->{D}->{"$mid\0$chash"})) {
1020 if (!$sync->{reindex}) {
1021 $num = $sync->{regen}--;
1022 $self->{mm}->num_highwater($num);
1027 # is this a number we got before?
1028 $num = $sync->{mm_tmp}->num_for($mid);
1031 check_unindexed($self, $num, $mid0);
1033 $num = $sync->{regen}--;
1034 die "BUG: ran out of article numbers" if $num <= 0;
1035 if ($self->{mm}->mid_set($num, $mid) != 1) {
1036 warn "E: unable to assign $num => <$mid>\n";
1041 } else { # multiple MIDs are a weird case:
1044 $del += delete($sync->{D}->{"$_\0$chash"}) // 0;
1047 unindex_oid_remote($self, $oid, $_) for @$mids;
1048 # do not delete from {mm_tmp}, since another
1049 # single-MID message may use it.
1050 } else { # handle them at the end:
1051 multi_mid_q_push($self, $sync, $oid);
1055 $sync->{mm_tmp}->mid_delete($mid0) or
1056 die "failed to delete <$mid0> for article #$num\n";
1063 }, 'PublicInbox::Smsg';
1064 $smsg->populate($mime, $self);
1065 if (do_idx($self, $msgref, $mime, $smsg)) {
1066 reindex_checkpoint($self, $sync, $git);
1070 # only update last_commit for $i on reindex iff newer than current
1071 sub update_last_commit ($$$$) {
1072 my ($self, $git, $i, $cmt) = @_;
1073 my $last = last_epoch_commit($self, $i);
1074 if (defined $last && is_ancestor($git, $last, $cmt)) {
1075 my @cmd = (qw(rev-list --count), "$last..$cmt");
1076 chomp(my $n = $git->qx(@cmd));
1077 return if $n ne '' && $n == 0;
1079 last_epoch_commit($self, $i, $cmt);
1082 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1084 sub last_commits ($$) {
1085 my ($self, $epoch_max) = @_;
1087 for (my $i = $epoch_max; $i >= 0; $i--) {
1088 $heads->[$i] = last_epoch_commit($self, $i);
1093 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1095 # returns a revision range for git-log(1)
1096 sub log_range ($$$$$) {
1097 my ($self, $sync, $git, $i, $tip) = @_;
1098 my $opt = $sync->{-opt};
1099 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1100 my $cur = $sync->{ranges}->[$i] or do {
1101 $pr->("$i.git indexing all of $tip") if $pr;
1102 return $tip; # all of it
1105 # fast equality check to avoid (v)fork+execve overhead
1107 $sync->{ranges}->[$i] = undef;
1111 my $range = "$cur..$tip";
1112 $pr->("$i.git checking contiguity... ") if $pr;
1113 if (is_ancestor($git, $cur, $tip)) { # common case
1114 $pr->("OK\n") if $pr;
1115 my $n = $git->qx(qw(rev-list --count), $range);
1118 $sync->{ranges}->[$i] = undef;
1119 $pr->("$i.git has nothing new\n") if $pr;
1120 return; # nothing to do
1122 $pr->("$i.git has $n changes since $cur\n") if $pr;
1124 $pr->("FAIL\n") if $pr;
1126 discontiguous range: $range
1127 Rewritten history? (in $git->{git_dir})
1129 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1131 $range = "$base..$tip";
1132 warn "found merge-base: $base\n"
1135 warn "discarding history at $cur\n";
1138 reindexing $git->{git_dir} starting at
1141 $sync->{unindex_range}->{$i} = "$base..$cur";
1146 sub sync_prepare ($$$) {
1147 my ($self, $sync, $epoch_max) = @_;
1148 my $pr = $sync->{-opt}->{-progress};
1150 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1152 # reindex stops at the current heads and we later rerun index_sync
1154 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1156 for (my $i = $epoch_max; $i >= 0; $i--) {
1157 die 'BUG: already indexing!' if $self->{reindex_pipe};
1158 my $git_dir = git_dir_n($self, $i);
1159 -d $git_dir or next; # missing epochs are fine
1160 my $git = PublicInbox::Git->new($git_dir);
1161 if ($reindex_heads) {
1162 $head = $reindex_heads->[$i] or next;
1164 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1166 next if $?; # new repo
1167 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1168 $sync->{ranges}->[$i] = $range;
1170 # can't use 'rev-list --count' if we use --diff-filter
1171 $pr->("$i.git counting $range ... ") if $pr;
1173 my $fh = $git->popen(qw(log --pretty=tformat:%H
1174 --no-notes --no-color --no-renames
1175 --diff-filter=AM), $range, '--', 'm');
1177 close $fh or die "git log failed: \$?=$?";
1178 $pr->("$n\n") if $pr;
1182 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1184 # reindex should NOT see new commits anymore, if we do,
1185 # it's a problem and we need to notice it via die()
1186 my $pad = length($regen_max) + 1;
1187 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1189 return -1 if $sync->{reindex};
1190 $regen_max + $self->{mm}->num_highwater() || 0;
1193 sub unindex_oid_remote ($$$) {
1194 my ($self, $oid, $mid) = @_;
1195 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1196 $self->{over}->remove_oid($oid, $mid);
1199 sub unindex_oid ($$$;$) {
1200 my ($self, $git, $oid, $unindexed) = @_;
1201 my $mm = $self->{mm};
1202 my $msgref = $git->cat_file($oid);
1203 my $mime = PublicInbox::Eml->new($msgref);
1204 my $mids = mids($mime->header_obj);
1205 $mime = $msgref = undef;
1206 my $over = $self->{over};
1207 foreach my $mid (@$mids) {
1210 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1211 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1214 my $n = scalar keys %gone;
1217 warn "BUG: multiple articles linked to $oid\n",
1218 join(',',sort keys %gone), "\n";
1220 foreach my $num (keys %gone) {
1222 my $mid0 = $mm->mid_for($num);
1223 $unindexed->{$mid0} = $num;
1225 $mm->num_delete($num);
1227 unindex_oid_remote($self, $oid, $mid);
1231 my $x40 = qr/[a-f0-9]{40}/;
1232 sub unindex ($$$$) {
1233 my ($self, $sync, $git, $unindex_range) = @_;
1234 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1235 my $before = scalar keys %$unindexed;
1236 # order does not matter, here:
1237 my @cmd = qw(log --raw -r
1238 --no-notes --no-color --no-abbrev --no-renames);
1239 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1241 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1242 unindex_oid($self, $git, $1, $unindexed);
1244 delete $self->{reindex_pipe};
1245 close $fh or die "git log failed: \$?=$?";
1247 return unless $sync->{-opt}->{prune};
1248 my $after = scalar keys %$unindexed;
1249 return if $before == $after;
1251 # ensure any blob can not longer be accessed via dumb HTTP
1252 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1253 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1256 sub sync_ranges ($$$) {
1257 my ($self, $sync, $epoch_max) = @_;
1258 my $reindex = $sync->{reindex};
1260 return last_commits($self, $epoch_max) unless $reindex;
1261 return [] if ref($reindex) ne 'HASH';
1263 my $ranges = $reindex->{from}; # arrayref;
1264 if (ref($ranges) ne 'ARRAY') {
1265 die 'BUG: $reindex->{from} not an ARRAY';
1270 sub index_epoch ($$$) {
1271 my ($self, $sync, $i) = @_;
1273 my $git_dir = git_dir_n($self, $i);
1274 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1275 -d $git_dir or return; # missing epochs are fine
1276 fill_alternates($self, $i);
1277 my $git = PublicInbox::Git->new($git_dir);
1278 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1279 unindex($self, $sync, $git, $unindex_range);
1281 defined(my $range = $sync->{ranges}->[$i]) or return;
1282 if (my $pr = $sync->{-opt}->{-progress}) {
1283 $pr->("$i.git indexing $range\n");
1286 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1287 --no-notes --no-color --no-abbrev --no-renames);
1288 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1292 $self->{current_info} = "$i.git $_";
1293 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1295 $self->{autime} = $2;
1296 $self->{cotime} = $3;
1297 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1298 reindex_oid($self, $sync, $git, $1);
1299 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1300 mark_deleted($self, $sync, $git, $1);
1303 close $fh or die "git log failed: \$?=$?";
1304 delete @$self{qw(reindex_pipe autime cotime)};
1305 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1308 # public, called by public-inbox-index
1310 my ($self, $opt) = @_;
1312 my $pr = $opt->{-progress};
1314 my $latest = git_dir_latest($self, \$epoch_max);
1315 return unless defined $latest;
1316 $self->idx_init($opt); # acquire lock
1318 D => {}, # "$mid\0$chash" => $oid
1319 unindex_range => {}, # EPOCH => oid_old..oid_new
1320 reindex => $opt->{reindex},
1323 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1324 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1326 if ($sync->{regen}) {
1327 # tmp_clone seems to fail if inside a transaction, so
1328 # we rollback here (because we opened {mm} for reading)
1329 # Note: we do NOT rely on DBI transactions for atomicity;
1330 # only for batch performance.
1331 $self->{mm}->{dbh}->rollback;
1332 $self->{mm}->{dbh}->begin_work;
1333 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1336 # work backwards through history
1337 for (my $i = $epoch_max; $i >= 0; $i--) {
1338 index_epoch($self, $sync, $i);
1341 # unindex is required for leftovers if "deletes" affect messages
1342 # in a previous fetch+index window:
1344 if (my @leftovers = values %{delete $sync->{D}}) {
1345 $git = $self->{-inbox}->git;
1346 for my $oid (@leftovers) {
1347 $self->{current_info} = "leftover $oid";
1348 unindex_oid($self, $git, $oid);
1351 if (my $multi_mid = delete $sync->{multi_mid}) {
1352 $git //= $self->{-inbox}->git;
1353 my $min = $multi_mid->{min};
1354 my $max = $multi_mid->{max};
1355 if ($sync->{reindex}) {
1356 # we may need to create new Message-IDs if mirrors
1357 # were initially indexed with old versions
1358 for (my $i = $max; $i >= $min; $i--) {
1360 $oid = $multi_mid->get_oid($i, $self) or next;
1361 next unless defined $oid;
1362 reindex_oid_m($self, $sync, $git, $oid);
1364 } else { # regen on initial index
1365 for my $num ($min..$max) {
1367 $oid = $multi_mid->get_oid($num, $self) or next;
1368 reindex_oid_m($self, $sync, $git, $oid, $num);
1372 $git->cleanup if $git;
1375 if (my $nr = $sync->{nr}) {
1376 my $pr = $sync->{-opt}->{-progress};
1377 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1380 # reindex does not pick up new changes, so we rerun w/o it:
1381 if ($opt->{reindex}) {
1384 delete @again{qw(reindex -skip_lock)};
1385 index_sync($self, \%again);