1 # Copyright (C) 2018-2019 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);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::MIME;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentId qw(content_id content_digest);
16 use PublicInbox::Inbox;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx;
21 use IO::Handle; # ->autoflush
22 use File::Temp qw(tempfile);
24 # an estimate of the post-packed size to the raw uncompressed size
25 my $PACKING_FACTOR = 0.4;
27 # SATA storage lags behind what CPUs are capable of, so relying on
28 # nproc(1) can be misleading and having extra Xapian shards is a
29 # waste of FDs and space. It can also lead to excessive IO latency
30 # and slow things down. Users on NVME or other fast storage can
31 # use the NPROC env or switches in our script/public-inbox-* programs
32 # to increase Xapian shards
33 our $NPROC_MAX_DEFAULT = 4;
35 sub nproc_shards ($) {
37 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
40 chomp($n = `nproc 2>/dev/null`);
41 # assume 2 cores if GNU nproc(1) is not available
43 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
46 # subtract for the main process and git-fast-import
51 sub count_shards ($) {
54 my $xpfx = $self->{xpfx};
56 # always load existing shards in case core count changes:
57 # Also, shard count may change while -watch is running
58 # due to "xcpdb --reshard"
60 require PublicInbox::Search;
61 PublicInbox::Search::load_xapian();
62 my $XapianDatabase = $PublicInbox::Search::X{Database};
63 foreach my $shard (<$xpfx/*>) {
64 -d $shard && $shard =~ m!/[0-9]+\z! or next;
66 $XapianDatabase->new($shard)->close;
75 # $creat may be any true value, or 0/undef. A hashref is true,
76 # and $creat->{nproc} may be set to an integer
77 my ($class, $v2ibx, $creat) = @_;
78 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
79 my $dir = $v2ibx->assert_usable_dir;
83 File::Path::mkpath($dir);
85 die "$dir does not exist\n";
88 $v2ibx->umask_prepare;
90 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
93 im => undef, # PublicInbox::Import
98 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
99 lock_path => "$dir/inbox.lock",
100 # limit each git repo (epoch) to 1GB or so
101 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
102 last_commit => [], # git repo -> commit
104 $self->{shards} = count_shards($self) || nproc_shards($creat);
110 my ($self, $parallel, $skip_epoch) = @_;
111 $self->{parallel} = $parallel;
114 git_dir_latest($self, \$epoch_max);
115 if (defined $skip_epoch && $epoch_max == -1) {
116 $epoch_max = $skip_epoch;
118 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
122 # returns undef on duplicate or spam
123 # mimics Import::add and wraps it for v2
125 my ($self, $mime, $check_cb) = @_;
126 $self->{-inbox}->with_umask(sub {
127 _add($self, $mime, $check_cb)
131 # indexes a message, returns true if checkpointing is needed
132 sub do_idx ($$$$$$$) {
133 my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
134 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
135 my $idx = idx_shard($self, $num % $self->{shards});
136 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
137 my $n = $self->{transact_bytes} += $len;
138 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
142 my ($self, $mime, $check_cb) = @_;
146 $mime = $check_cb->($mime) or return;
149 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
150 # as does SQLite 3.4.1+ (released in 2007-07-20), and
151 # Xapian 1.3.2+ (released 2015-03-15).
152 # For the most part, we can spawn git-fast-import without
153 # leaking FDs to it...
156 my ($num, $mid0) = v2_num_for($self, $mime);
157 defined $num or return; # duplicate
158 defined $mid0 or die "BUG: $mid0 undefined\n";
159 my $im = $self->importer;
160 my $cmt = $im->add($mime);
161 $cmt = $im->get_mark($cmt);
162 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
164 my ($oid, $len, $msgref) = @{$im->{last_object}};
165 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
173 my ($self, $mime) = @_;
174 my $mids = mids($mime->header_obj);
176 my $mid = $mids->[0];
177 my $num = $self->{mm}->mid_insert($mid);
178 if (defined $num) { # common case
182 # crap, Message-ID is already known, hope somebody just resent:
183 foreach my $m (@$mids) {
184 # read-only lookup now safe to do after above barrier
185 my $existing = lookup_content($self, $mime, $m);
186 # easy, don't store duplicates
187 # note: do not add more diagnostic info here since
188 # it gets noisy on public-inbox-watch restarts
189 return () if $existing;
192 # AltId may pre-populate article numbers (e.g. X-Mail-Count
193 # or NNTP article number), use that article number if it's
195 my $altid = $self->{-inbox}->{altid};
196 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
197 my $num = $self->{mm}->num_for($mid);
199 if (defined $num && !$self->{over}->get_art($num)) {
205 warn "<$mid> reused for mismatched content\n";
207 # try the rest of the mids
208 for(my $i = $#$mids; $i >= 1; $i--) {
210 $num = $self->{mm}->mid_insert($m);
212 warn "alternative <$m> for <$mid> found\n";
217 # none of the existing Message-IDs are good, generate a new one:
218 v2_num_for_harder($self, $mime);
221 sub v2_num_for_harder {
222 my ($self, $mime) = @_;
224 my $hdr = $mime->header_obj;
225 my $dig = content_digest($mime);
226 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
227 my $num = $self->{mm}->mid_insert($mid0);
228 unless (defined $num) {
229 # it's hard to spoof the last Received: header
230 my @recvd = $hdr->header_raw('Received');
231 $dig->add("Received: $_") foreach (@recvd);
232 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
233 $num = $self->{mm}->mid_insert($mid0);
235 # fall back to a random Message-ID and give up determinism:
236 until (defined($num)) {
238 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
239 warn "using random Message-ID <$mid0> as fallback\n";
240 $num = $self->{mm}->mid_insert($mid0);
243 PublicInbox::Import::append_mid($hdr, $mid0);
248 my ($self, $shard_i) = @_;
249 $self->{idx_shards}->[$shard_i];
254 my ($self, $opt) = @_;
255 return if $self->{idx_shards};
256 my $ibx = $self->{-inbox};
258 # do not leak read-only FDs to child processes, we only have these
259 # FDs for duplicate detection so they should not be
260 # frequently activated.
261 delete $ibx->{$_} foreach (qw(git mm search));
263 my $indexlevel = $ibx->{indexlevel};
264 if ($indexlevel && $indexlevel eq 'basic') {
265 $self->{parallel} = 0;
268 if ($self->{parallel}) {
269 pipe(my ($r, $w)) or die "pipe failed: $!";
270 # pipe for barrier notifications doesn't need to be big,
272 fcntl($w, 1031, 4096) if $^O eq 'linux';
273 $self->{bnote} = [ $r, $w ];
277 my $over = $self->{over};
279 $ibx->with_umask(sub {
280 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
283 # xcpdb can change shard count while -watch is idle
284 my $nshards = count_shards($self);
285 if ($nshards && $nshards != $self->{shards}) {
286 $self->{shards} = $nshards;
289 # need to create all shards before initializing msgmap FD
290 my $max = $self->{shards} - 1;
292 # idx_shards must be visible to all forked processes
293 my $idx = $self->{idx_shards} = [];
294 for my $i (0..$max) {
295 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
298 # Now that all subprocesses are up, we can open the FDs
300 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
301 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
302 $mm->{dbh}->begin_work;
306 # returns an array mapping [ epoch => latest_commit ]
307 # latest_commit may be undef if nothing was done to that epoch
308 # $replace_map = { $object_id => $strref, ... }
309 sub _replace_oids ($$$) {
310 my ($self, $mime, $replace_map) = @_;
312 my $pfx = "$self->{-inbox}->{inboxdir}/git";
313 my $rewrites = []; # epoch => commit
314 my $max = $self->{epoch_max};
316 unless (defined($max)) {
317 defined(my $latest = git_dir_latest($self, \$max)) or return;
318 $self->{epoch_max} = $max;
321 foreach my $i (0..$max) {
322 my $git_dir = "$pfx/$i.git";
324 my $git = PublicInbox::Git->new($git_dir);
325 my $im = $self->import_init($git, 0, 1);
326 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
332 sub content_ids ($) {
334 my @cids = ( content_id($mime) );
336 # Email::MIME->as_string doesn't always round-trip, so we may
337 # use a second content_id
338 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
339 push @cids, $rt if $cids[0] ne $rt;
343 sub content_matches ($$) {
344 my ($cids, $existing) = @_;
345 my $cid = content_id($existing);
347 return 1 if $_ eq $cid
352 # used for removing or replacing (purging)
353 sub rewrite_internal ($$;$$$) {
354 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
356 my ($im, $need_reindex, $replace_map);
358 $replace_map = {}; # oid => sref
359 $need_reindex = [] if $new_mime;
361 $im = $self->importer;
363 my $over = $self->{over};
364 my $cids = content_ids($old_mime);
366 my $mids = mids($old_mime->header_obj);
368 # We avoid introducing new blobs into git since the raw content
369 # can be slightly different, so we do not need the user-supplied
370 # message now that we have the mids and content_id
374 foreach my $mid (@$mids) {
375 my %gone; # num => [ smsg, raw ]
377 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
378 my $msg = get_blob($self, $smsg);
379 if (!defined($msg)) {
380 warn "broken smsg for $mid\n";
384 my $cur = PublicInbox::MIME->new($msg);
385 if (content_matches($cids, $cur)) {
386 $smsg->{mime} = $cur;
387 $gone{$smsg->{num}} = [ $smsg, \$orig ];
390 my $n = scalar keys %gone;
393 warn "BUG: multiple articles linked to <$mid>\n",
394 join(',', sort keys %gone), "\n";
396 foreach my $num (keys %gone) {
397 my ($smsg, $orig) = @{$gone{$num}};
398 # $removed should only be set once assuming
399 # no bugs in our deduplication code:
401 my $oid = $smsg->{blob};
403 $replace_map->{$oid} = $sref;
405 ($mark, undef) = $im->remove($orig, $cmt_msg);
408 if ($need_reindex) { # ->replace
409 push @$need_reindex, $smsg;
410 } else { # ->purge or ->remove
411 $self->{mm}->num_delete($num);
413 unindex_oid_remote($self, $oid, $mid);
418 my $cmt = $im->get_mark($mark);
419 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
421 if ($replace_map && scalar keys %$replace_map) {
422 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
423 return { rewrites => $rewrites, need_reindex => $need_reindex };
430 my ($self, $mime, $cmt_msg) = @_;
431 $self->{-inbox}->with_umask(sub {
432 rewrite_internal($self, $mime, $cmt_msg);
436 sub _replace ($$;$$) {
437 my ($self, $old_mime, $new_mime, $sref) = @_;
438 my $rewritten = $self->{-inbox}->with_umask(sub {
439 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
442 my $rewrites = $rewritten->{rewrites};
443 # ->done is called if there are rewrites since we gc+prune from git
444 $self->idx_init if @$rewrites;
446 for my $i (0..$#$rewrites) {
447 defined(my $cmt = $rewrites->[$i]) or next;
448 $self->{last_commit}->[$i] = $cmt;
455 my ($self, $mime) = @_;
456 my $rewritten = _replace($self, $mime, undef, \'') or return;
457 $rewritten->{rewrites}
460 # returns the git object_id of $fh, does not write the object to FS
461 sub git_hash_raw ($$) {
462 my ($self, $raw) = @_;
463 # grab the expected OID we have to reindex:
464 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
465 $tmp_fh->autoflush(1);
466 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
467 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
469 my $git_dir = $self->{-inbox}->git->{git_dir};
470 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
471 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
473 chomp(my $oid = <$r>);
474 close $r or die "git hash-object failed: $?";
475 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
479 sub _check_mids_match ($$$) {
480 my ($old_list, $new_list, $hdrs) = @_;
481 my %old_mids = map { $_ => 1 } @$old_list;
482 my %new_mids = map { $_ => 1 } @$new_list;
483 my @old = keys %old_mids;
484 my @new = keys %new_mids;
485 my $err = "$hdrs may not be changed when replacing\n";
486 die $err if scalar(@old) != scalar(@new);
487 delete @new_mids{@old};
488 delete @old_mids{@new};
489 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
492 # Changing Message-IDs or References with ->replace isn't supported.
493 # The rules for dealing with messages with multiple or conflicting
494 # Message-IDs are pretty complex and rethreading hasn't been fully
496 sub check_mids_match ($$) {
497 my ($old_mime, $new_mime) = @_;
498 my $old = $old_mime->header_obj;
499 my $new = $new_mime->header_obj;
500 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
501 _check_mids_match(references($old), references($new),
502 'References/In-Reply-To');
507 my ($self, $old_mime, $new_mime) = @_;
509 check_mids_match($old_mime, $new_mime);
511 # mutt will always add Content-Length:, Status:, Lines: when editing
512 PublicInbox::Import::drop_unwanted_headers($new_mime);
514 my $raw = $new_mime->as_string;
515 my $expect_oid = git_hash_raw($self, \$raw);
516 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
517 my $need_reindex = $rewritten->{need_reindex};
519 # just in case we have bugs in deduplication code:
520 my $n = scalar(@$need_reindex);
522 my $list = join(', ', map {
523 "$_->{num}: <$_->{mid}>"
526 W: rewritten $n messages matching content of original message (expected: 1).
527 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
532 # make sure we really got the OID:
533 my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
534 $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
536 # don't leak FDs to Xapian:
537 $self->{-inbox}->git->cleanup;
539 # reindex modified messages:
540 for my $smsg (@$need_reindex) {
541 my $num = $smsg->{num};
542 my $mid0 = $smsg->{mid};
543 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
545 $rewritten->{rewrites};
548 sub last_epoch_commit ($$;$) {
549 my ($self, $i, $cmt) = @_;
550 my $v = PublicInbox::Search::SCHEMA_VERSION();
551 $self->{mm}->last_commit_xap($v, $i, $cmt);
554 sub set_last_commits ($) {
556 defined(my $epoch_max = $self->{epoch_max}) or return;
557 my $last_commit = $self->{last_commit};
558 foreach my $i (0..$epoch_max) {
559 defined(my $cmt = $last_commit->[$i]) or next;
560 $last_commit->[$i] = undef;
561 last_epoch_commit($self, $i, $cmt);
567 $self->{bnote} or return;
569 my $barrier = { map { $_ => 1 } (0..$n) };
573 my ($self, $barrier) = @_;
574 my $bnote = $self->{bnote} or return;
576 while (scalar keys %$barrier) {
577 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
578 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
579 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
584 sub checkpoint ($;$) {
585 my ($self, $wait) = @_;
587 if (my $im = $self->{im}) {
594 my $shards = $self->{idx_shards};
596 my $dbh = $self->{mm}->{dbh};
598 # SQLite msgmap data is second in importance
601 # SQLite overview is third
602 $self->{over}->commit_lazy;
604 # Now deal with Xapian
606 my $barrier = $self->barrier_init(scalar @$shards);
608 # each shard needs to issue a barrier command
609 $_->remote_barrier for @$shards;
611 # wait for each Xapian shard
612 $self->barrier_wait($barrier);
614 $_->remote_commit for @$shards;
617 # last_commit is special, don't commit these until
618 # remote shards are done:
620 set_last_commits($self);
625 $self->{transact_bytes} = 0;
628 # issue a write barrier to ensure all data is visible to other processes
629 # and read-only ops. Order of data importance is: git > SQLite > Xapian
631 sub barrier { checkpoint($_[0], 1) };
636 my $im = delete $self->{im};
637 $im->done if $im; # PublicInbox::Import::done
639 my $mm = delete $self->{mm};
640 $mm->{dbh}->commit if $mm;
641 my $shards = delete $self->{idx_shards};
643 $_->remote_close for @$shards;
645 $self->{over}->disconnect;
646 delete $self->{bnote};
647 $self->{transact_bytes} = 0;
648 $self->lock_release if $shards;
649 $self->{-inbox}->git->cleanup;
652 sub fill_alternates ($$) {
653 my ($self, $epoch) = @_;
655 my $pfx = "$self->{-inbox}->{inboxdir}/git";
656 my $all = "$self->{-inbox}->{inboxdir}/all.git";
659 PublicInbox::Import::init_bare($all);
661 my $info_dir = "$all/objects/info";
662 my $alt = "$info_dir/alternates";
666 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
667 $mode = (stat($fh))[2] & 07777;
669 # we assign a sort score to every alternate and favor
670 # the newest (highest numbered) one when we
672 my $other = 0; # in case admin adds non-epoch repos
674 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
680 } split(/\n+/, do { local $/; <$fh> });
683 foreach my $i (0..$epoch) {
684 my $dir = "../../git/$i.git/objects";
685 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
692 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
693 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
694 or die "print $tmp: $!\n";
695 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
696 close $fh or die "close $tmp $!\n";
697 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
701 my ($self, $epoch) = @_;
702 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
703 my @cmd = (qw(git init --bare -q), $git_dir);
704 PublicInbox::Import::run_die(\@cmd);
705 @cmd = (qw/git config/, "--file=$git_dir/config",
706 'include.path', '../../all.git/config');
707 PublicInbox::Import::run_die(\@cmd);
708 fill_alternates($self, $epoch);
713 my ($self, $max) = @_;
715 my $pfx = "$self->{-inbox}->{inboxdir}/git";
716 return unless -d $pfx;
718 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
719 while (defined(my $git_dir = readdir($dh))) {
720 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
723 $latest = "$pfx/$git_dir";
731 my $im = $self->{im};
733 if ($im->{bytes_added} < $self->{rotate_bytes}) {
740 my $git_dir = $self->git_init(++$self->{epoch_max});
741 my $git = PublicInbox::Git->new($git_dir);
742 return $self->import_init($git, 0);
747 my $latest = git_dir_latest($self, \$max);
748 if (defined $latest) {
749 my $git = PublicInbox::Git->new($latest);
750 my $packed_bytes = $git->packed_bytes;
751 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
753 if ($unpacked_bytes >= $self->{rotate_bytes}) {
756 $self->{epoch_max} = $max;
757 return $self->import_init($git, $packed_bytes);
760 $self->{epoch_max} = $epoch;
761 $latest = $self->git_init($epoch);
762 $self->import_init(PublicInbox::Git->new($latest), 0);
766 my ($self, $git, $packed_bytes, $tmp) = @_;
767 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
768 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
769 $im->{want_object_info} = 1;
770 $im->{lock_path} = undef;
771 $im->{path_type} = 'v2';
772 $self->{im} = $im unless $tmp;
778 my ($mid, $cur, $new) = @_;
780 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
781 print $ah $cur->as_string or die "print: $!";
782 close $ah or die "close: $!";
783 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
784 PublicInbox::Import::drop_unwanted_headers($new);
785 print $bh $new->as_string or die "print: $!";
786 close $bh or die "close: $!";
787 my $cmd = [ qw(diff -u), $an, $bn ];
788 print STDERR "# MID conflict <$mid>\n";
789 my $pid = spawn($cmd, undef, { 1 => 2 });
790 waitpid($pid, 0) == $pid or die "diff did not finish";
795 my ($self, $smsg) = @_;
796 if (my $im = $self->{im}) {
797 my $msg = $im->cat_blob($smsg->{blob});
800 # older message, should be in alternates
801 my $ibx = $self->{-inbox};
802 $ibx->msg_by_smsg($smsg);
805 sub lookup_content ($$$) {
806 my ($self, $mime, $mid) = @_;
807 my $over = $self->{over};
808 my $cids = content_ids($mime);
810 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
811 my $msg = get_blob($self, $smsg);
812 if (!defined($msg)) {
813 warn "broken smsg for $mid\n";
816 my $cur = PublicInbox::MIME->new($msg);
817 if (content_matches($cids, $cur)) {
818 $smsg->{mime} = $cur;
823 # XXX DEBUG_DIFF is experimental and may be removed
824 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
831 my $fh = delete $self->{reindex_pipe};
833 if (my $shards = $self->{idx_shards}) {
834 $_->atfork_child foreach @$shards;
836 if (my $im = $self->{im}) {
839 die "unexpected mm" if $self->{mm};
840 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
844 sub mark_deleted ($$$$) {
845 my ($self, $sync, $git, $oid) = @_;
846 my $msgref = $git->cat_file($oid);
847 my $mime = PublicInbox::MIME->new($$msgref);
848 my $mids = mids($mime->header_obj);
849 my $cid = content_id($mime);
850 foreach my $mid (@$mids) {
851 $sync->{D}->{"$mid\0$cid"} = $oid;
855 sub reindex_checkpoint ($$$) {
856 my ($self, $sync, $git) = @_;
859 $sync->{mm_tmp}->atfork_prepare;
860 $self->done; # release lock
862 if (my $pr = $sync->{-opt}->{-progress}) {
863 my ($bn) = (split('/', $git->{git_dir}))[-1];
864 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
867 # allow -watch or -mda to write...
868 $self->idx_init; # reacquire lock
869 $sync->{mm_tmp}->atfork_parent;
872 # only for a few odd messages with multiple Message-IDs
873 sub reindex_oid_m ($$$$;$) {
874 my ($self, $sync, $git, $oid, $regen_num) = @_;
875 $self->{current_info} = "multi_mid $oid";
876 my ($num, $mid0, $len);
877 my $msgref = $git->cat_file($oid, \$len);
878 my $mime = PublicInbox::MIME->new($$msgref);
879 my $mids = mids($mime->header_obj);
880 my $cid = content_id($mime);
881 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
883 for my $mid (reverse @$mids) {
884 delete($sync->{D}->{"$mid\0$cid"}) and
885 die "BUG: reindex_oid should handle <$mid> delete";
887 my $over = $self->{over};
888 for my $mid (reverse @$mids) {
889 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
890 next unless defined $num;
891 if (defined($regen_num) && $regen_num != $num) {
892 die "BUG: regen(#$regen_num) != over(#$num)";
895 unless (defined($num)) {
896 for my $mid (reverse @$mids) {
897 # is this a number we got before?
898 my $n = $sync->{mm_tmp}->num_for($mid);
899 next unless defined $n;
900 next if defined($regen_num) && $regen_num != $n;
901 ($num, $mid0) = ($n, $mid);
906 $sync->{mm_tmp}->num_delete($num);
907 } elsif (defined $regen_num) {
909 for my $mid (reverse @$mids) {
910 $self->{mm}->mid_set($num, $mid) == 1 or next;
914 unless (defined $mid0) {
915 warn "E: cannot regen #$num\n";
918 } else { # fixup bugs in old mirrors on reindex
919 for my $mid (reverse @$mids) {
920 $num = $self->{mm}->mid_insert($mid);
921 next unless defined $num;
926 if ($sync->{reindex}) {
927 warn "reindex added #$num <$mid0>\n";
930 warn "E: cannot find article #\n";
935 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
936 reindex_checkpoint($self, $sync, $git);
940 sub check_unindexed ($$$) {
941 my ($self, $num, $mid0) = @_;
942 my $unindexed = $self->{unindexed} // {};
943 my $n = delete($unindexed->{$mid0});
944 defined $n or return;
946 die "BUG: unindexed $n != $num <$mid0>\n";
948 $self->{mm}->mid_set($num, $mid0);
952 # reuse Msgmap to store num => oid mapping (rather than num => mid)
953 sub multi_mid_q_new () {
954 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
955 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
956 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
957 # for Msgmap->DESTROY:
958 $multi_mid->{tmp_name} = $fn;
959 $multi_mid->{pid} = $$;
960 close $fh or die "failed to close $fn: $!";
964 sub multi_mid_q_push ($$) {
965 my ($sync, $oid) = @_;
966 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
967 if ($sync->{reindex}) { # no regen on reindex
968 $multi_mid->mid_insert($oid);
970 my $num = $sync->{regen}--;
971 die "BUG: ran out of article numbers" if $num <= 0;
972 $multi_mid->mid_set($num, $oid);
976 sub reindex_oid ($$$$) {
977 my ($self, $sync, $git, $oid) = @_;
978 my ($num, $mid0, $len);
979 my $msgref = $git->cat_file($oid, \$len);
980 return if $len == 0; # purged
981 my $mime = PublicInbox::MIME->new($$msgref);
982 my $mids = mids($mime->header_obj);
983 my $cid = content_id($mime);
985 if (scalar(@$mids) == 0) {
986 warn "E: $oid has no Message-ID, skipping\n";
988 } elsif (scalar(@$mids) == 1) {
989 my $mid = $mids->[0];
991 # was the file previously marked as deleted?, skip if so
992 if (delete($sync->{D}->{"$mid\0$cid"})) {
993 if (!$sync->{reindex}) {
994 $num = $sync->{regen}--;
995 $self->{mm}->num_highwater($num);
1000 # is this a number we got before?
1001 $num = $sync->{mm_tmp}->num_for($mid);
1004 check_unindexed($self, $num, $mid0);
1006 $num = $sync->{regen}--;
1007 die "BUG: ran out of article numbers" if $num <= 0;
1008 if ($self->{mm}->mid_set($num, $mid) != 1) {
1009 warn "E: unable to assign $num => <$mid>\n";
1014 } else { # multiple MIDs are a weird case:
1017 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1020 unindex_oid_remote($self, $oid, $_) for @$mids;
1021 # do not delete from {mm_tmp}, since another
1022 # single-MID message may use it.
1023 } else { # handle them at the end:
1024 multi_mid_q_push($sync, $oid);
1028 $sync->{mm_tmp}->mid_delete($mid0) or
1029 die "failed to delete <$mid0> for article #$num\n";
1031 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1032 reindex_checkpoint($self, $sync, $git);
1036 # only update last_commit for $i on reindex iff newer than current
1037 sub update_last_commit ($$$$) {
1038 my ($self, $git, $i, $cmt) = @_;
1039 my $last = last_epoch_commit($self, $i);
1040 if (defined $last && is_ancestor($git, $last, $cmt)) {
1041 my @cmd = (qw(rev-list --count), "$last..$cmt");
1042 chomp(my $n = $git->qx(@cmd));
1043 return if $n ne '' && $n == 0;
1045 last_epoch_commit($self, $i, $cmt);
1048 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1050 sub last_commits ($$) {
1051 my ($self, $epoch_max) = @_;
1053 for (my $i = $epoch_max; $i >= 0; $i--) {
1054 $heads->[$i] = last_epoch_commit($self, $i);
1059 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1061 # returns a revision range for git-log(1)
1062 sub log_range ($$$$$) {
1063 my ($self, $sync, $git, $i, $tip) = @_;
1064 my $opt = $sync->{-opt};
1065 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1066 my $cur = $sync->{ranges}->[$i] or do {
1067 $pr->("$i.git indexing all of $tip") if $pr;
1068 return $tip; # all of it
1071 # fast equality check to avoid (v)fork+execve overhead
1073 $sync->{ranges}->[$i] = undef;
1077 my $range = "$cur..$tip";
1078 $pr->("$i.git checking contiguity... ") if $pr;
1079 if (is_ancestor($git, $cur, $tip)) { # common case
1080 $pr->("OK\n") if $pr;
1081 my $n = $git->qx(qw(rev-list --count), $range);
1084 $sync->{ranges}->[$i] = undef;
1085 $pr->("$i.git has nothing new\n") if $pr;
1086 return; # nothing to do
1088 $pr->("$i.git has $n changes since $cur\n") if $pr;
1090 $pr->("FAIL\n") if $pr;
1092 discontiguous range: $range
1093 Rewritten history? (in $git->{git_dir})
1095 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1097 $range = "$base..$tip";
1098 warn "found merge-base: $base\n"
1101 warn "discarding history at $cur\n";
1104 reindexing $git->{git_dir} starting at
1107 $sync->{unindex_range}->{$i} = "$base..$cur";
1112 sub sync_prepare ($$$) {
1113 my ($self, $sync, $epoch_max) = @_;
1114 my $pr = $sync->{-opt}->{-progress};
1116 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1118 # reindex stops at the current heads and we later rerun index_sync
1120 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1122 for (my $i = $epoch_max; $i >= 0; $i--) {
1123 die 'BUG: already indexing!' if $self->{reindex_pipe};
1124 my $git_dir = git_dir_n($self, $i);
1125 -d $git_dir or next; # missing epochs are fine
1126 my $git = PublicInbox::Git->new($git_dir);
1127 if ($reindex_heads) {
1128 $head = $reindex_heads->[$i] or next;
1130 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1132 next if $?; # new repo
1133 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1134 $sync->{ranges}->[$i] = $range;
1136 # can't use 'rev-list --count' if we use --diff-filter
1137 $pr->("$i.git counting $range ... ") if $pr;
1139 my $fh = $git->popen(qw(log --pretty=tformat:%H
1140 --no-notes --no-color --no-renames
1141 --diff-filter=AM), $range, '--', 'm');
1143 close $fh or die "git log failed: \$?=$?";
1144 $pr->("$n\n") if $pr;
1148 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1150 # reindex should NOT see new commits anymore, if we do,
1151 # it's a problem and we need to notice it via die()
1152 my $pad = length($regen_max) + 1;
1153 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1155 return -1 if $sync->{reindex};
1156 $regen_max + $self->{mm}->num_highwater() || 0;
1159 sub unindex_oid_remote ($$$) {
1160 my ($self, $oid, $mid) = @_;
1161 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1162 $self->{over}->remove_oid($oid, $mid);
1165 sub unindex_oid ($$$;$) {
1166 my ($self, $git, $oid, $unindexed) = @_;
1167 my $mm = $self->{mm};
1168 my $msgref = $git->cat_file($oid);
1169 my $mime = PublicInbox::MIME->new($msgref);
1170 my $mids = mids($mime->header_obj);
1171 $mime = $msgref = undef;
1172 my $over = $self->{over};
1173 foreach my $mid (@$mids) {
1176 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1177 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1180 my $n = scalar keys %gone;
1183 warn "BUG: multiple articles linked to $oid\n",
1184 join(',',sort keys %gone), "\n";
1186 foreach my $num (keys %gone) {
1188 my $mid0 = $mm->mid_for($num);
1189 $unindexed->{$mid0} = $num;
1191 $mm->num_delete($num);
1193 unindex_oid_remote($self, $oid, $mid);
1197 my $x40 = qr/[a-f0-9]{40}/;
1198 sub unindex ($$$$) {
1199 my ($self, $sync, $git, $unindex_range) = @_;
1200 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1201 my $before = scalar keys %$unindexed;
1202 # order does not matter, here:
1203 my @cmd = qw(log --raw -r
1204 --no-notes --no-color --no-abbrev --no-renames);
1205 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1207 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1208 unindex_oid($self, $git, $1, $unindexed);
1210 delete $self->{reindex_pipe};
1211 close $fh or die "git log failed: \$?=$?";
1213 return unless $sync->{-opt}->{prune};
1214 my $after = scalar keys %$unindexed;
1215 return if $before == $after;
1217 # ensure any blob can not longer be accessed via dumb HTTP
1218 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1219 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1222 sub sync_ranges ($$$) {
1223 my ($self, $sync, $epoch_max) = @_;
1224 my $reindex = $sync->{reindex};
1226 return last_commits($self, $epoch_max) unless $reindex;
1227 return [] if ref($reindex) ne 'HASH';
1229 my $ranges = $reindex->{from}; # arrayref;
1230 if (ref($ranges) ne 'ARRAY') {
1231 die 'BUG: $reindex->{from} not an ARRAY';
1236 sub index_epoch ($$$) {
1237 my ($self, $sync, $i) = @_;
1239 my $git_dir = git_dir_n($self, $i);
1240 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1241 -d $git_dir or return; # missing epochs are fine
1242 fill_alternates($self, $i);
1243 my $git = PublicInbox::Git->new($git_dir);
1244 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1245 unindex($self, $sync, $git, $unindex_range);
1247 defined(my $range = $sync->{ranges}->[$i]) or return;
1248 if (my $pr = $sync->{-opt}->{-progress}) {
1249 $pr->("$i.git indexing $range\n");
1252 my @cmd = qw(log --raw -r --pretty=tformat:%H
1253 --no-notes --no-color --no-abbrev --no-renames);
1254 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1258 $self->{current_info} = "$i.git $_";
1259 if (/\A$x40$/o && !defined($cmt)) {
1261 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1262 reindex_oid($self, $sync, $git, $1);
1263 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1264 mark_deleted($self, $sync, $git, $1);
1267 close $fh or die "git log failed: \$?=$?";
1268 delete $self->{reindex_pipe};
1269 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1272 # public, called by public-inbox-index
1274 my ($self, $opt) = @_;
1276 my $pr = $opt->{-progress};
1278 my $latest = git_dir_latest($self, \$epoch_max);
1279 return unless defined $latest;
1280 $self->idx_init($opt); # acquire lock
1282 D => {}, # "$mid\0$cid" => $oid
1283 unindex_range => {}, # EPOCH => oid_old..oid_new
1284 reindex => $opt->{reindex},
1287 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1288 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1290 if ($sync->{regen}) {
1291 # tmp_clone seems to fail if inside a transaction, so
1292 # we rollback here (because we opened {mm} for reading)
1293 # Note: we do NOT rely on DBI transactions for atomicity;
1294 # only for batch performance.
1295 $self->{mm}->{dbh}->rollback;
1296 $self->{mm}->{dbh}->begin_work;
1297 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1300 # work backwards through history
1301 for (my $i = $epoch_max; $i >= 0; $i--) {
1302 index_epoch($self, $sync, $i);
1305 # unindex is required for leftovers if "deletes" affect messages
1306 # in a previous fetch+index window:
1308 if (my @leftovers = values %{delete $sync->{D}}) {
1309 $git = $self->{-inbox}->git;
1310 for my $oid (@leftovers) {
1311 $self->{current_info} = "leftover $oid";
1312 unindex_oid($self, $git, $oid);
1315 if (my $multi_mid = delete $sync->{multi_mid}) {
1316 $git //= $self->{-inbox}->git;
1317 my ($min, $max) = $multi_mid->minmax;
1318 if ($sync->{reindex}) {
1319 # we may need to create new Message-IDs if mirrors
1320 # were initially indexed with old versions
1321 for (my $i = $max; $i >= $min; $i--) {
1322 my $oid = $multi_mid->mid_for($i);
1323 next unless defined $oid;
1324 reindex_oid_m($self, $sync, $git, $oid);
1326 } else { # regen on initial index
1327 for my $num ($min..$max) {
1328 my $oid = $multi_mid->mid_for($num);
1329 next unless defined $oid;
1330 reindex_oid_m($self, $sync, $git, $oid, $num);
1334 $git->cleanup if $git;
1337 if (my $nr = $sync->{nr}) {
1338 my $pr = $sync->{-opt}->{-progress};
1339 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1342 # reindex does not pick up new changes, so we rerun w/o it:
1343 if ($opt->{reindex}) {
1346 delete @again{qw(reindex -skip_lock)};
1347 index_sync($self, \%again);