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);
20 use PublicInbox::SearchIdx;
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 if (ref($creat_opt) eq 'HASH') {
38 if (defined(my $n = $creat_opt->{nproc})) {
45 chomp($n = `nproc 2>/dev/null`);
46 # assume 2 cores if GNU nproc(1) is not available
48 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
51 # subtract for the main process and git-fast-import
56 sub count_shards ($) {
59 my $xpfx = $self->{xpfx};
61 # always load existing shards in case core count changes:
62 # Also, shard count may change while -watch is running
63 # due to "xcpdb --reshard"
65 require PublicInbox::Search;
66 PublicInbox::Search::load_xapian();
67 my $XapianDatabase = $PublicInbox::Search::X{Database};
68 foreach my $shard (<$xpfx/*>) {
69 -d $shard && $shard =~ m!/[0-9]+\z! or next;
71 $XapianDatabase->new($shard)->close;
80 # $creat may be any true value, or 0/undef. A hashref is true,
81 # and $creat->{nproc} may be set to an integer
82 my ($class, $v2ibx, $creat) = @_;
83 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
84 my $dir = $v2ibx->assert_usable_dir;
88 File::Path::mkpath($dir);
90 die "$dir does not exist\n";
93 $v2ibx->umask_prepare;
95 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
98 im => undef, # PublicInbox::Import
103 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
104 lock_path => "$dir/inbox.lock",
105 # limit each git repo (epoch) to 1GB or so
106 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
107 last_commit => [], # git repo -> commit
109 $self->{shards} = count_shards($self) || nproc_shards($creat);
115 my ($self, $parallel, $skip_epoch) = @_;
116 $self->{parallel} = $parallel;
119 git_dir_latest($self, \$epoch_max);
120 if (defined $skip_epoch && $epoch_max == -1) {
121 $epoch_max = $skip_epoch;
123 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
127 # returns undef on duplicate or spam
128 # mimics Import::add and wraps it for v2
130 my ($self, $mime, $check_cb) = @_;
131 $self->{-inbox}->with_umask(sub {
132 _add($self, $mime, $check_cb)
136 # indexes a message, returns true if checkpointing is needed
137 sub do_idx ($$$$$$$) {
138 my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
139 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
140 my $idx = idx_shard($self, $num % $self->{shards});
141 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
142 my $n = $self->{transact_bytes} += $len;
143 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
147 my ($self, $mime, $check_cb) = @_;
151 $mime = $check_cb->($mime) or return;
154 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
155 # as does SQLite 3.4.1+ (released in 2007-07-20), and
156 # Xapian 1.3.2+ (released 2015-03-15).
157 # For the most part, we can spawn git-fast-import without
158 # leaking FDs to it...
161 my ($num, $mid0) = v2_num_for($self, $mime);
162 defined $num or return; # duplicate
163 defined $mid0 or die "BUG: $mid0 undefined\n";
164 my $im = $self->importer;
165 my $cmt = $im->add($mime);
166 $cmt = $im->get_mark($cmt);
167 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
169 my ($oid, $len, $msgref) = @{$im->{last_object}};
170 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
178 my ($self, $mime) = @_;
179 my $mids = mids($mime->header_obj);
181 my $mid = $mids->[0];
182 my $num = $self->{mm}->mid_insert($mid);
183 if (defined $num) { # common case
187 # crap, Message-ID is already known, hope somebody just resent:
188 foreach my $m (@$mids) {
189 # read-only lookup now safe to do after above barrier
190 my $existing = lookup_content($self, $mime, $m);
191 # easy, don't store duplicates
192 # note: do not add more diagnostic info here since
193 # it gets noisy on public-inbox-watch restarts
194 return () if $existing;
197 # AltId may pre-populate article numbers (e.g. X-Mail-Count
198 # or NNTP article number), use that article number if it's
200 my $altid = $self->{-inbox}->{altid};
201 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
202 my $num = $self->{mm}->num_for($mid);
204 if (defined $num && !$self->{over}->get_art($num)) {
210 warn "<$mid> reused for mismatched content\n";
212 # try the rest of the mids
213 for(my $i = $#$mids; $i >= 1; $i--) {
215 $num = $self->{mm}->mid_insert($m);
217 warn "alternative <$m> for <$mid> found\n";
222 # none of the existing Message-IDs are good, generate a new one:
223 v2_num_for_harder($self, $mime);
226 sub v2_num_for_harder {
227 my ($self, $mime) = @_;
229 my $hdr = $mime->header_obj;
230 my $dig = content_digest($mime);
231 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
232 my $num = $self->{mm}->mid_insert($mid0);
233 unless (defined $num) {
234 # it's hard to spoof the last Received: header
235 my @recvd = $hdr->header_raw('Received');
236 $dig->add("Received: $_") foreach (@recvd);
237 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
238 $num = $self->{mm}->mid_insert($mid0);
240 # fall back to a random Message-ID and give up determinism:
241 until (defined($num)) {
243 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
244 warn "using random Message-ID <$mid0> as fallback\n";
245 $num = $self->{mm}->mid_insert($mid0);
248 PublicInbox::Import::append_mid($hdr, $mid0);
253 my ($self, $shard_i) = @_;
254 $self->{idx_shards}->[$shard_i];
259 my ($self, $opt) = @_;
260 return if $self->{idx_shards};
261 my $ibx = $self->{-inbox};
263 # do not leak read-only FDs to child processes, we only have these
264 # FDs for duplicate detection so they should not be
265 # frequently activated.
266 delete $ibx->{$_} foreach (qw(git mm search));
268 my $indexlevel = $ibx->{indexlevel};
269 if ($indexlevel && $indexlevel eq 'basic') {
270 $self->{parallel} = 0;
273 if ($self->{parallel}) {
274 pipe(my ($r, $w)) or die "pipe failed: $!";
275 # pipe for barrier notifications doesn't need to be big,
277 fcntl($w, 1031, 4096) if $^O eq 'linux';
278 $self->{bnote} = [ $r, $w ];
282 my $over = $self->{over};
284 $ibx->with_umask(sub {
285 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
288 # xcpdb can change shard count while -watch is idle
289 my $nshards = count_shards($self);
290 if ($nshards && $nshards != $self->{shards}) {
291 $self->{shards} = $nshards;
294 # need to create all shards before initializing msgmap FD
295 my $max = $self->{shards} - 1;
297 # idx_shards must be visible to all forked processes
298 my $idx = $self->{idx_shards} = [];
299 for my $i (0..$max) {
300 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
303 # Now that all subprocesses are up, we can open the FDs
305 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
306 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
307 $mm->{dbh}->begin_work;
311 # returns an array mapping [ epoch => latest_commit ]
312 # latest_commit may be undef if nothing was done to that epoch
313 # $replace_map = { $object_id => $strref, ... }
314 sub _replace_oids ($$$) {
315 my ($self, $mime, $replace_map) = @_;
317 my $pfx = "$self->{-inbox}->{inboxdir}/git";
318 my $rewrites = []; # epoch => commit
319 my $max = $self->{epoch_max};
321 unless (defined($max)) {
322 defined(my $latest = git_dir_latest($self, \$max)) or return;
323 $self->{epoch_max} = $max;
326 foreach my $i (0..$max) {
327 my $git_dir = "$pfx/$i.git";
329 my $git = PublicInbox::Git->new($git_dir);
330 my $im = $self->import_init($git, 0, 1);
331 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
337 sub content_ids ($) {
339 my @cids = ( content_id($mime) );
341 # Email::MIME->as_string doesn't always round-trip, so we may
342 # use a second content_id
343 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
344 push @cids, $rt if $cids[0] ne $rt;
348 sub content_matches ($$) {
349 my ($cids, $existing) = @_;
350 my $cid = content_id($existing);
352 return 1 if $_ eq $cid
357 # used for removing or replacing (purging)
358 sub rewrite_internal ($$;$$$) {
359 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
361 my ($im, $need_reindex, $replace_map);
363 $replace_map = {}; # oid => sref
364 $need_reindex = [] if $new_mime;
366 $im = $self->importer;
368 my $over = $self->{over};
369 my $cids = content_ids($old_mime);
371 my $mids = mids($old_mime->header_obj);
373 # We avoid introducing new blobs into git since the raw content
374 # can be slightly different, so we do not need the user-supplied
375 # message now that we have the mids and content_id
379 foreach my $mid (@$mids) {
380 my %gone; # num => [ smsg, raw ]
382 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
383 my $msg = get_blob($self, $smsg);
384 if (!defined($msg)) {
385 warn "broken smsg for $mid\n";
389 my $cur = PublicInbox::MIME->new($msg);
390 if (content_matches($cids, $cur)) {
391 $smsg->{mime} = $cur;
392 $gone{$smsg->{num}} = [ $smsg, \$orig ];
395 my $n = scalar keys %gone;
398 warn "BUG: multiple articles linked to <$mid>\n",
399 join(',', sort keys %gone), "\n";
401 foreach my $num (keys %gone) {
402 my ($smsg, $orig) = @{$gone{$num}};
403 # $removed should only be set once assuming
404 # no bugs in our deduplication code:
406 my $oid = $smsg->{blob};
408 $replace_map->{$oid} = $sref;
410 ($mark, undef) = $im->remove($orig, $cmt_msg);
413 if ($need_reindex) { # ->replace
414 push @$need_reindex, $smsg;
415 } else { # ->purge or ->remove
416 $self->{mm}->num_delete($num);
418 unindex_oid_remote($self, $oid, $mid);
423 my $cmt = $im->get_mark($mark);
424 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
426 if ($replace_map && scalar keys %$replace_map) {
427 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
428 return { rewrites => $rewrites, need_reindex => $need_reindex };
435 my ($self, $mime, $cmt_msg) = @_;
436 $self->{-inbox}->with_umask(sub {
437 rewrite_internal($self, $mime, $cmt_msg);
441 sub _replace ($$;$$) {
442 my ($self, $old_mime, $new_mime, $sref) = @_;
443 my $rewritten = $self->{-inbox}->with_umask(sub {
444 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
447 my $rewrites = $rewritten->{rewrites};
448 # ->done is called if there are rewrites since we gc+prune from git
449 $self->idx_init if @$rewrites;
451 for my $i (0..$#$rewrites) {
452 defined(my $cmt = $rewrites->[$i]) or next;
453 $self->{last_commit}->[$i] = $cmt;
460 my ($self, $mime) = @_;
461 my $rewritten = _replace($self, $mime, undef, \'') or return;
462 $rewritten->{rewrites}
465 # returns the git object_id of $fh, does not write the object to FS
466 sub git_hash_raw ($$) {
467 my ($self, $raw) = @_;
468 # grab the expected OID we have to reindex:
469 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
470 $tmp_fh->autoflush(1);
471 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
472 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
475 pipe($r, $w) or die "failed to create pipe: $!";
476 my $rdr = { 0 => $tmp_fh, 1 => $w };
477 my $git_dir = $self->{-inbox}->git->{git_dir};
478 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
479 my $pid = spawn($cmd, undef, $rdr);
482 chomp(my $oid = <$r>);
483 waitpid($pid, 0) == $pid or die "git hash-object did not finish";
484 die "git hash-object failed: $?" if $?;
485 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
489 sub _check_mids_match ($$$) {
490 my ($old_list, $new_list, $hdrs) = @_;
491 my %old_mids = map { $_ => 1 } @$old_list;
492 my %new_mids = map { $_ => 1 } @$new_list;
493 my @old = keys %old_mids;
494 my @new = keys %new_mids;
495 my $err = "$hdrs may not be changed when replacing\n";
496 die $err if scalar(@old) != scalar(@new);
497 delete @new_mids{@old};
498 delete @old_mids{@new};
499 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
502 # Changing Message-IDs or References with ->replace isn't supported.
503 # The rules for dealing with messages with multiple or conflicting
504 # Message-IDs are pretty complex and rethreading hasn't been fully
506 sub check_mids_match ($$) {
507 my ($old_mime, $new_mime) = @_;
508 my $old = $old_mime->header_obj;
509 my $new = $new_mime->header_obj;
510 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
511 _check_mids_match(references($old), references($new),
512 'References/In-Reply-To');
517 my ($self, $old_mime, $new_mime) = @_;
519 check_mids_match($old_mime, $new_mime);
521 # mutt will always add Content-Length:, Status:, Lines: when editing
522 PublicInbox::Import::drop_unwanted_headers($new_mime);
524 my $raw = $new_mime->as_string;
525 my $expect_oid = git_hash_raw($self, \$raw);
526 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
527 my $need_reindex = $rewritten->{need_reindex};
529 # just in case we have bugs in deduplication code:
530 my $n = scalar(@$need_reindex);
532 my $list = join(', ', map {
533 "$_->{num}: <$_->{mid}>"
536 W: rewritten $n messages matching content of original message (expected: 1).
537 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
542 # make sure we really got the OID:
543 my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
544 $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
546 # don't leak FDs to Xapian:
547 $self->{-inbox}->git->cleanup;
549 # reindex modified messages:
550 for my $smsg (@$need_reindex) {
551 my $num = $smsg->{num};
552 my $mid0 = $smsg->{mid};
553 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
555 $rewritten->{rewrites};
558 sub last_epoch_commit ($$;$) {
559 my ($self, $i, $cmt) = @_;
560 my $v = PublicInbox::Search::SCHEMA_VERSION();
561 $self->{mm}->last_commit_xap($v, $i, $cmt);
564 sub set_last_commits ($) {
566 defined(my $epoch_max = $self->{epoch_max}) or return;
567 my $last_commit = $self->{last_commit};
568 foreach my $i (0..$epoch_max) {
569 defined(my $cmt = $last_commit->[$i]) or next;
570 $last_commit->[$i] = undef;
571 last_epoch_commit($self, $i, $cmt);
577 $self->{bnote} or return;
579 my $barrier = { map { $_ => 1 } (0..$n) };
583 my ($self, $barrier) = @_;
584 my $bnote = $self->{bnote} or return;
586 while (scalar keys %$barrier) {
587 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
588 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
589 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
594 sub checkpoint ($;$) {
595 my ($self, $wait) = @_;
597 if (my $im = $self->{im}) {
604 my $shards = $self->{idx_shards};
606 my $dbh = $self->{mm}->{dbh};
608 # SQLite msgmap data is second in importance
611 # SQLite overview is third
612 $self->{over}->commit_lazy;
614 # Now deal with Xapian
616 my $barrier = $self->barrier_init(scalar @$shards);
618 # each shard needs to issue a barrier command
619 $_->remote_barrier for @$shards;
621 # wait for each Xapian shard
622 $self->barrier_wait($barrier);
624 $_->remote_commit for @$shards;
627 # last_commit is special, don't commit these until
628 # remote shards are done:
630 set_last_commits($self);
635 $self->{transact_bytes} = 0;
638 # issue a write barrier to ensure all data is visible to other processes
639 # and read-only ops. Order of data importance is: git > SQLite > Xapian
641 sub barrier { checkpoint($_[0], 1) };
646 my $im = delete $self->{im};
647 $im->done if $im; # PublicInbox::Import::done
649 my $mm = delete $self->{mm};
650 $mm->{dbh}->commit if $mm;
651 my $shards = delete $self->{idx_shards};
653 $_->remote_close for @$shards;
655 $self->{over}->disconnect;
656 delete $self->{bnote};
657 $self->{transact_bytes} = 0;
658 $self->lock_release if $shards;
659 $self->{-inbox}->git->cleanup;
662 sub fill_alternates ($$) {
663 my ($self, $epoch) = @_;
665 my $pfx = "$self->{-inbox}->{inboxdir}/git";
666 my $all = "$self->{-inbox}->{inboxdir}/all.git";
669 PublicInbox::Import::init_bare($all);
671 my $alt = "$all/objects/info/alternates";
675 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
676 %alts = map { chomp; $_ => 1 } (<$fh>);
678 foreach my $i (0..$epoch) {
679 my $dir = "../../git/$i.git/objects";
680 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
683 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
684 foreach my $dir (@add) {
685 print $fh "$dir\n" or die "print >> $alt: $!\n";
687 close $fh or die "close $alt: $!\n";
691 my ($self, $epoch) = @_;
692 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
693 my @cmd = (qw(git init --bare -q), $git_dir);
694 PublicInbox::Import::run_die(\@cmd);
695 @cmd = (qw/git config/, "--file=$git_dir/config",
696 'include.path', '../../all.git/config');
697 PublicInbox::Import::run_die(\@cmd);
698 fill_alternates($self, $epoch);
703 my ($self, $max) = @_;
705 my $pfx = "$self->{-inbox}->{inboxdir}/git";
706 return unless -d $pfx;
708 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
709 while (defined(my $git_dir = readdir($dh))) {
710 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
713 $latest = "$pfx/$git_dir";
721 my $im = $self->{im};
723 if ($im->{bytes_added} < $self->{rotate_bytes}) {
730 my $git_dir = $self->git_init(++$self->{epoch_max});
731 my $git = PublicInbox::Git->new($git_dir);
732 return $self->import_init($git, 0);
737 my $latest = git_dir_latest($self, \$max);
738 if (defined $latest) {
739 my $git = PublicInbox::Git->new($latest);
740 my $packed_bytes = $git->packed_bytes;
741 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
743 if ($unpacked_bytes >= $self->{rotate_bytes}) {
746 $self->{epoch_max} = $max;
747 return $self->import_init($git, $packed_bytes);
750 $self->{epoch_max} = $epoch;
751 $latest = $self->git_init($epoch);
752 $self->import_init(PublicInbox::Git->new($latest), 0);
756 my ($self, $git, $packed_bytes, $tmp) = @_;
757 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
758 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
759 $im->{want_object_info} = 1;
760 $im->{lock_path} = undef;
761 $im->{path_type} = 'v2';
762 $self->{im} = $im unless $tmp;
768 my ($mid, $cur, $new) = @_;
770 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
771 print $ah $cur->as_string or die "print: $!";
772 close $ah or die "close: $!";
773 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
774 PublicInbox::Import::drop_unwanted_headers($new);
775 print $bh $new->as_string or die "print: $!";
776 close $bh or die "close: $!";
777 my $cmd = [ qw(diff -u), $an, $bn ];
778 print STDERR "# MID conflict <$mid>\n";
779 my $pid = spawn($cmd, undef, { 1 => 2 });
780 defined $pid or die "diff failed to spawn $!";
781 waitpid($pid, 0) == $pid or die "diff did not finish";
786 my ($self, $smsg) = @_;
787 if (my $im = $self->{im}) {
788 my $msg = $im->cat_blob($smsg->{blob});
791 # older message, should be in alternates
792 my $ibx = $self->{-inbox};
793 $ibx->msg_by_smsg($smsg);
796 sub lookup_content ($$$) {
797 my ($self, $mime, $mid) = @_;
798 my $over = $self->{over};
799 my $cids = content_ids($mime);
801 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
802 my $msg = get_blob($self, $smsg);
803 if (!defined($msg)) {
804 warn "broken smsg for $mid\n";
807 my $cur = PublicInbox::MIME->new($msg);
808 if (content_matches($cids, $cur)) {
809 $smsg->{mime} = $cur;
814 # XXX DEBUG_DIFF is experimental and may be removed
815 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
822 my $fh = delete $self->{reindex_pipe};
824 if (my $shards = $self->{idx_shards}) {
825 $_->atfork_child foreach @$shards;
827 if (my $im = $self->{im}) {
830 die "unexpected mm" if $self->{mm};
831 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
835 sub mark_deleted ($$$$) {
836 my ($self, $sync, $git, $oid) = @_;
837 my $msgref = $git->cat_file($oid);
838 my $mime = PublicInbox::MIME->new($$msgref);
839 my $mids = mids($mime->header_obj);
840 my $cid = content_id($mime);
841 foreach my $mid (@$mids) {
842 $sync->{D}->{"$mid\0$cid"} = $oid;
846 sub reindex_checkpoint ($$$) {
847 my ($self, $sync, $git) = @_;
850 $sync->{mm_tmp}->atfork_prepare;
851 $self->done; # release lock
853 if (my $pr = $sync->{-opt}->{-progress}) {
854 my ($bn) = (split('/', $git->{git_dir}))[-1];
855 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
858 # allow -watch or -mda to write...
859 $self->idx_init; # reacquire lock
860 $sync->{mm_tmp}->atfork_parent;
863 # only for a few odd messages with multiple Message-IDs
864 sub reindex_oid_m ($$$$;$) {
865 my ($self, $sync, $git, $oid, $regen_num) = @_;
866 $self->{current_info} = "multi_mid $oid";
867 my ($num, $mid0, $len);
868 my $msgref = $git->cat_file($oid, \$len);
869 my $mime = PublicInbox::MIME->new($$msgref);
870 my $mids = mids($mime->header_obj);
871 my $cid = content_id($mime);
872 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
874 for my $mid (reverse @$mids) {
875 delete($sync->{D}->{"$mid\0$cid"}) and
876 die "BUG: reindex_oid should handle <$mid> delete";
878 my $over = $self->{over};
879 for my $mid (reverse @$mids) {
880 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
881 next unless defined $num;
882 if (defined($regen_num) && $regen_num != $num) {
883 die "BUG: regen(#$regen_num) != over(#$num)";
886 unless (defined($num)) {
887 for my $mid (reverse @$mids) {
888 # is this a number we got before?
889 my $n = $sync->{mm_tmp}->num_for($mid);
890 next unless defined $n;
891 next if defined($regen_num) && $regen_num != $n;
892 ($num, $mid0) = ($n, $mid);
897 $sync->{mm_tmp}->num_delete($num);
898 } elsif (defined $regen_num) {
900 for my $mid (reverse @$mids) {
901 $self->{mm}->mid_set($num, $mid) == 1 or next;
905 unless (defined $mid0) {
906 warn "E: cannot regen #$num\n";
909 } else { # fixup bugs in old mirrors on reindex
910 for my $mid (reverse @$mids) {
911 $num = $self->{mm}->mid_insert($mid);
912 next unless defined $num;
917 if ($sync->{reindex}) {
918 warn "reindex added #$num <$mid0>\n";
921 warn "E: cannot find article #\n";
926 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
927 reindex_checkpoint($self, $sync, $git);
931 sub check_unindexed ($$$) {
932 my ($self, $num, $mid0) = @_;
933 my $unindexed = $self->{unindexed} // {};
934 my $n = delete($unindexed->{$mid0});
935 defined $n or return;
937 die "BUG: unindexed $n != $num <$mid0>\n";
939 $self->{mm}->mid_set($num, $mid0);
943 # reuse Msgmap to store num => oid mapping (rather than num => mid)
944 sub multi_mid_q_new () {
945 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
946 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
947 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
948 # for Msgmap->DESTROY:
949 $multi_mid->{tmp_name} = $fn;
950 $multi_mid->{pid} = $$;
951 close $fh or die "failed to close $fn: $!";
955 sub multi_mid_q_push ($$) {
956 my ($sync, $oid) = @_;
957 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
958 if ($sync->{reindex}) { # no regen on reindex
959 $multi_mid->mid_insert($oid);
961 my $num = $sync->{regen}--;
962 die "BUG: ran out of article numbers" if $num <= 0;
963 $multi_mid->mid_set($num, $oid);
967 sub reindex_oid ($$$$) {
968 my ($self, $sync, $git, $oid) = @_;
969 my ($num, $mid0, $len);
970 my $msgref = $git->cat_file($oid, \$len);
971 return if $len == 0; # purged
972 my $mime = PublicInbox::MIME->new($$msgref);
973 my $mids = mids($mime->header_obj);
974 my $cid = content_id($mime);
976 if (scalar(@$mids) == 0) {
977 warn "E: $oid has no Message-ID, skipping\n";
979 } elsif (scalar(@$mids) == 1) {
980 my $mid = $mids->[0];
982 # was the file previously marked as deleted?, skip if so
983 if (delete($sync->{D}->{"$mid\0$cid"})) {
984 if (!$sync->{reindex}) {
985 $num = $sync->{regen}--;
986 $self->{mm}->num_highwater($num);
991 # is this a number we got before?
992 $num = $sync->{mm_tmp}->num_for($mid);
995 check_unindexed($self, $num, $mid0);
997 $num = $sync->{regen}--;
998 die "BUG: ran out of article numbers" if $num <= 0;
999 if ($self->{mm}->mid_set($num, $mid) != 1) {
1000 warn "E: unable to assign $num => <$mid>\n";
1005 } else { # multiple MIDs are a weird case:
1008 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1011 unindex_oid_remote($self, $oid, $_) for @$mids;
1012 # do not delete from {mm_tmp}, since another
1013 # single-MID message may use it.
1014 } else { # handle them at the end:
1015 multi_mid_q_push($sync, $oid);
1019 $sync->{mm_tmp}->mid_delete($mid0) or
1020 die "failed to delete <$mid0> for article #$num\n";
1022 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1023 reindex_checkpoint($self, $sync, $git);
1027 # only update last_commit for $i on reindex iff newer than current
1028 sub update_last_commit ($$$$) {
1029 my ($self, $git, $i, $cmt) = @_;
1030 my $last = last_epoch_commit($self, $i);
1031 if (defined $last && is_ancestor($git, $last, $cmt)) {
1032 my @cmd = (qw(rev-list --count), "$last..$cmt");
1033 chomp(my $n = $git->qx(@cmd));
1034 return if $n ne '' && $n == 0;
1036 last_epoch_commit($self, $i, $cmt);
1039 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1041 sub last_commits ($$) {
1042 my ($self, $epoch_max) = @_;
1044 for (my $i = $epoch_max; $i >= 0; $i--) {
1045 $heads->[$i] = last_epoch_commit($self, $i);
1050 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1052 # returns a revision range for git-log(1)
1053 sub log_range ($$$$$) {
1054 my ($self, $sync, $git, $i, $tip) = @_;
1055 my $opt = $sync->{-opt};
1056 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1057 my $cur = $sync->{ranges}->[$i] or do {
1058 $pr->("$i.git indexing all of $tip") if $pr;
1059 return $tip; # all of it
1062 # fast equality check to avoid (v)fork+execve overhead
1064 $sync->{ranges}->[$i] = undef;
1068 my $range = "$cur..$tip";
1069 $pr->("$i.git checking contiguity... ") if $pr;
1070 if (is_ancestor($git, $cur, $tip)) { # common case
1071 $pr->("OK\n") if $pr;
1072 my $n = $git->qx(qw(rev-list --count), $range);
1075 $sync->{ranges}->[$i] = undef;
1076 $pr->("$i.git has nothing new\n") if $pr;
1077 return; # nothing to do
1079 $pr->("$i.git has $n changes since $cur\n") if $pr;
1081 $pr->("FAIL\n") if $pr;
1083 discontiguous range: $range
1084 Rewritten history? (in $git->{git_dir})
1086 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1088 $range = "$base..$tip";
1089 warn "found merge-base: $base\n"
1092 warn "discarding history at $cur\n";
1095 reindexing $git->{git_dir} starting at
1098 $sync->{unindex_range}->{$i} = "$base..$cur";
1103 sub sync_prepare ($$$) {
1104 my ($self, $sync, $epoch_max) = @_;
1105 my $pr = $sync->{-opt}->{-progress};
1107 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1109 # reindex stops at the current heads and we later rerun index_sync
1111 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1113 for (my $i = $epoch_max; $i >= 0; $i--) {
1114 die 'BUG: already indexing!' if $self->{reindex_pipe};
1115 my $git_dir = git_dir_n($self, $i);
1116 -d $git_dir or next; # missing epochs are fine
1117 my $git = PublicInbox::Git->new($git_dir);
1118 if ($reindex_heads) {
1119 $head = $reindex_heads->[$i] or next;
1121 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1123 next if $?; # new repo
1124 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1125 $sync->{ranges}->[$i] = $range;
1127 # can't use 'rev-list --count' if we use --diff-filter
1128 $pr->("$i.git counting $range ... ") if $pr;
1130 my $fh = $git->popen(qw(log --pretty=tformat:%H
1131 --no-notes --no-color --no-renames
1132 --diff-filter=AM), $range, '--', 'm');
1134 close $fh or die "git log failed: \$?=$?";
1135 $pr->("$n\n") if $pr;
1139 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1141 # reindex should NOT see new commits anymore, if we do,
1142 # it's a problem and we need to notice it via die()
1143 my $pad = length($regen_max) + 1;
1144 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1146 return -1 if $sync->{reindex};
1147 $regen_max + $self->{mm}->num_highwater() || 0;
1150 sub unindex_oid_remote ($$$) {
1151 my ($self, $oid, $mid) = @_;
1152 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1153 $self->{over}->remove_oid($oid, $mid);
1156 sub unindex_oid ($$$;$) {
1157 my ($self, $git, $oid, $unindexed) = @_;
1158 my $mm = $self->{mm};
1159 my $msgref = $git->cat_file($oid);
1160 my $mime = PublicInbox::MIME->new($msgref);
1161 my $mids = mids($mime->header_obj);
1162 $mime = $msgref = undef;
1163 my $over = $self->{over};
1164 foreach my $mid (@$mids) {
1167 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1168 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1171 my $n = scalar keys %gone;
1174 warn "BUG: multiple articles linked to $oid\n",
1175 join(',',sort keys %gone), "\n";
1177 foreach my $num (keys %gone) {
1179 my $mid0 = $mm->mid_for($num);
1180 $unindexed->{$mid0} = $num;
1182 $mm->num_delete($num);
1184 unindex_oid_remote($self, $oid, $mid);
1188 my $x40 = qr/[a-f0-9]{40}/;
1189 sub unindex ($$$$) {
1190 my ($self, $sync, $git, $unindex_range) = @_;
1191 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1192 my $before = scalar keys %$unindexed;
1193 # order does not matter, here:
1194 my @cmd = qw(log --raw -r
1195 --no-notes --no-color --no-abbrev --no-renames);
1196 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1198 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1199 unindex_oid($self, $git, $1, $unindexed);
1201 delete $self->{reindex_pipe};
1202 close $fh or die "git log failed: \$?=$?";
1204 return unless $sync->{-opt}->{prune};
1205 my $after = scalar keys %$unindexed;
1206 return if $before == $after;
1208 # ensure any blob can not longer be accessed via dumb HTTP
1209 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1210 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1213 sub sync_ranges ($$$) {
1214 my ($self, $sync, $epoch_max) = @_;
1215 my $reindex = $sync->{reindex};
1217 return last_commits($self, $epoch_max) unless $reindex;
1218 return [] if ref($reindex) ne 'HASH';
1220 my $ranges = $reindex->{from}; # arrayref;
1221 if (ref($ranges) ne 'ARRAY') {
1222 die 'BUG: $reindex->{from} not an ARRAY';
1227 sub index_epoch ($$$) {
1228 my ($self, $sync, $i) = @_;
1230 my $git_dir = git_dir_n($self, $i);
1231 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1232 -d $git_dir or return; # missing epochs are fine
1233 fill_alternates($self, $i);
1234 my $git = PublicInbox::Git->new($git_dir);
1235 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1236 unindex($self, $sync, $git, $unindex_range);
1238 defined(my $range = $sync->{ranges}->[$i]) or return;
1239 if (my $pr = $sync->{-opt}->{-progress}) {
1240 $pr->("$i.git indexing $range\n");
1243 my @cmd = qw(log --raw -r --pretty=tformat:%H
1244 --no-notes --no-color --no-abbrev --no-renames);
1245 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1249 $self->{current_info} = "$i.git $_";
1250 if (/\A$x40$/o && !defined($cmt)) {
1252 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1253 reindex_oid($self, $sync, $git, $1);
1254 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1255 mark_deleted($self, $sync, $git, $1);
1258 close $fh or die "git log failed: \$?=$?";
1259 delete $self->{reindex_pipe};
1260 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1263 # public, called by public-inbox-index
1265 my ($self, $opt) = @_;
1267 my $pr = $opt->{-progress};
1269 my $latest = git_dir_latest($self, \$epoch_max);
1270 return unless defined $latest;
1271 $self->idx_init($opt); # acquire lock
1273 D => {}, # "$mid\0$cid" => $oid
1274 unindex_range => {}, # EPOCH => oid_old..oid_new
1275 reindex => $opt->{reindex},
1278 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1279 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1281 if ($sync->{regen}) {
1282 # tmp_clone seems to fail if inside a transaction, so
1283 # we rollback here (because we opened {mm} for reading)
1284 # Note: we do NOT rely on DBI transactions for atomicity;
1285 # only for batch performance.
1286 $self->{mm}->{dbh}->rollback;
1287 $self->{mm}->{dbh}->begin_work;
1288 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1291 # work backwards through history
1292 for (my $i = $epoch_max; $i >= 0; $i--) {
1293 index_epoch($self, $sync, $i);
1296 # unindex is required for leftovers if "deletes" affect messages
1297 # in a previous fetch+index window:
1299 if (my @leftovers = values %{delete $sync->{D}}) {
1300 $git = $self->{-inbox}->git;
1301 for my $oid (@leftovers) {
1302 $self->{current_info} = "leftover $oid";
1303 unindex_oid($self, $git, $oid);
1306 if (my $multi_mid = delete $sync->{multi_mid}) {
1307 $git //= $self->{-inbox}->git;
1308 my ($min, $max) = $multi_mid->minmax;
1309 if ($sync->{reindex}) {
1310 # we may need to create new Message-IDs if mirrors
1311 # were initially indexed with old versions
1312 for (my $i = $max; $i >= $min; $i--) {
1313 my $oid = $multi_mid->mid_for($i);
1314 next unless defined $oid;
1315 reindex_oid_m($self, $sync, $git, $oid);
1317 } else { # regen on initial index
1318 for my $num ($min..$max) {
1319 my $oid = $multi_mid->mid_for($num);
1320 next unless defined $oid;
1321 reindex_oid_m($self, $sync, $git, $oid, $num);
1325 $git->cleanup if $git;
1328 if (my $nr = $sync->{nr}) {
1329 my $pr = $sync->{-opt}->{-progress};
1330 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1333 # reindex does not pick up new changes, so we rerun w/o it:
1334 if ($opt->{reindex}) {
1337 delete @again{qw(reindex -skip_lock)};
1338 index_sync($self, \%again);