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, $shards, $skip_epoch) = @_;
111 if (defined $shards) {
112 $self->{parallel} = 0 if $shards == 0;
113 $self->{shards} = $shards if $shards > 0;
117 git_dir_latest($self, \$epoch_max);
118 if (defined $skip_epoch && $epoch_max == -1) {
119 $epoch_max = $skip_epoch;
121 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
125 # returns undef on duplicate or spam
126 # mimics Import::add and wraps it for v2
128 my ($self, $mime, $check_cb) = @_;
129 $self->{-inbox}->with_umask(sub {
130 _add($self, $mime, $check_cb)
134 # indexes a message, returns true if checkpointing is needed
135 sub do_idx ($$$$$$$) {
136 my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
137 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
138 my $idx = idx_shard($self, $num % $self->{shards});
139 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
140 my $n = $self->{transact_bytes} += $len;
141 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
145 my ($self, $mime, $check_cb) = @_;
149 $mime = $check_cb->($mime) or return;
152 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
153 # as does SQLite 3.4.1+ (released in 2007-07-20), and
154 # Xapian 1.3.2+ (released 2015-03-15).
155 # For the most part, we can spawn git-fast-import without
156 # leaking FDs to it...
159 my ($num, $mid0) = v2_num_for($self, $mime);
160 defined $num or return; # duplicate
161 defined $mid0 or die "BUG: $mid0 undefined\n";
162 my $im = $self->importer;
163 my $cmt = $im->add($mime);
164 $cmt = $im->get_mark($cmt);
165 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
167 my ($oid, $len, $msgref) = @{$im->{last_object}};
168 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
176 my ($self, $mime) = @_;
177 my $mids = mids($mime->header_obj);
179 my $mid = $mids->[0];
180 my $num = $self->{mm}->mid_insert($mid);
181 if (defined $num) { # common case
185 # crap, Message-ID is already known, hope somebody just resent:
186 foreach my $m (@$mids) {
187 # read-only lookup now safe to do after above barrier
188 my $existing = lookup_content($self, $mime, $m);
189 # easy, don't store duplicates
190 # note: do not add more diagnostic info here since
191 # it gets noisy on public-inbox-watch restarts
192 return () if $existing;
195 # AltId may pre-populate article numbers (e.g. X-Mail-Count
196 # or NNTP article number), use that article number if it's
198 my $altid = $self->{-inbox}->{altid};
199 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
200 my $num = $self->{mm}->num_for($mid);
202 if (defined $num && !$self->{over}->get_art($num)) {
208 warn "<$mid> reused for mismatched content\n";
210 # try the rest of the mids
211 for(my $i = $#$mids; $i >= 1; $i--) {
213 $num = $self->{mm}->mid_insert($m);
215 warn "alternative <$m> for <$mid> found\n";
220 # none of the existing Message-IDs are good, generate a new one:
221 v2_num_for_harder($self, $mime);
224 sub v2_num_for_harder {
225 my ($self, $mime) = @_;
227 my $hdr = $mime->header_obj;
228 my $dig = content_digest($mime);
229 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
230 my $num = $self->{mm}->mid_insert($mid0);
231 unless (defined $num) {
232 # it's hard to spoof the last Received: header
233 my @recvd = $hdr->header_raw('Received');
234 $dig->add("Received: $_") foreach (@recvd);
235 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
236 $num = $self->{mm}->mid_insert($mid0);
238 # fall back to a random Message-ID and give up determinism:
239 until (defined($num)) {
241 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
242 warn "using random Message-ID <$mid0> as fallback\n";
243 $num = $self->{mm}->mid_insert($mid0);
246 PublicInbox::Import::append_mid($hdr, $mid0);
251 my ($self, $shard_i) = @_;
252 $self->{idx_shards}->[$shard_i];
257 my ($self, $opt) = @_;
258 return if $self->{idx_shards};
259 my $ibx = $self->{-inbox};
261 # do not leak read-only FDs to child processes, we only have these
262 # FDs for duplicate detection so they should not be
263 # frequently activated.
264 delete $ibx->{$_} foreach (qw(git mm search));
266 my $indexlevel = $ibx->{indexlevel};
267 if ($indexlevel && $indexlevel eq 'basic') {
268 $self->{parallel} = 0;
271 if ($self->{parallel}) {
272 pipe(my ($r, $w)) or die "pipe failed: $!";
273 # pipe for barrier notifications doesn't need to be big,
275 fcntl($w, 1031, 4096) if $^O eq 'linux';
276 $self->{bnote} = [ $r, $w ];
280 my $over = $self->{over};
282 $ibx->with_umask(sub {
283 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
286 # xcpdb can change shard count while -watch is idle
287 my $nshards = count_shards($self);
288 if ($nshards && $nshards != $self->{shards}) {
289 $self->{shards} = $nshards;
292 # need to create all shards before initializing msgmap FD
293 my $max = $self->{shards} - 1;
295 # idx_shards must be visible to all forked processes
296 my $idx = $self->{idx_shards} = [];
297 for my $i (0..$max) {
298 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
301 # Now that all subprocesses are up, we can open the FDs
303 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
304 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
305 $mm->{dbh}->begin_work;
309 # returns an array mapping [ epoch => latest_commit ]
310 # latest_commit may be undef if nothing was done to that epoch
311 # $replace_map = { $object_id => $strref, ... }
312 sub _replace_oids ($$$) {
313 my ($self, $mime, $replace_map) = @_;
315 my $pfx = "$self->{-inbox}->{inboxdir}/git";
316 my $rewrites = []; # epoch => commit
317 my $max = $self->{epoch_max};
319 unless (defined($max)) {
320 defined(my $latest = git_dir_latest($self, \$max)) or return;
321 $self->{epoch_max} = $max;
324 foreach my $i (0..$max) {
325 my $git_dir = "$pfx/$i.git";
327 my $git = PublicInbox::Git->new($git_dir);
328 my $im = $self->import_init($git, 0, 1);
329 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
335 sub content_ids ($) {
337 my @cids = ( content_id($mime) );
339 # Email::MIME->as_string doesn't always round-trip, so we may
340 # use a second content_id
341 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
342 push @cids, $rt if $cids[0] ne $rt;
346 sub content_matches ($$) {
347 my ($cids, $existing) = @_;
348 my $cid = content_id($existing);
350 return 1 if $_ eq $cid
355 # used for removing or replacing (purging)
356 sub rewrite_internal ($$;$$$) {
357 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
359 my ($im, $need_reindex, $replace_map);
361 $replace_map = {}; # oid => sref
362 $need_reindex = [] if $new_mime;
364 $im = $self->importer;
366 my $over = $self->{over};
367 my $cids = content_ids($old_mime);
369 my $mids = mids($old_mime->header_obj);
371 # We avoid introducing new blobs into git since the raw content
372 # can be slightly different, so we do not need the user-supplied
373 # message now that we have the mids and content_id
377 foreach my $mid (@$mids) {
378 my %gone; # num => [ smsg, raw ]
380 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
381 my $msg = get_blob($self, $smsg);
382 if (!defined($msg)) {
383 warn "broken smsg for $mid\n";
387 my $cur = PublicInbox::MIME->new($msg);
388 if (content_matches($cids, $cur)) {
389 $smsg->{mime} = $cur;
390 $gone{$smsg->{num}} = [ $smsg, \$orig ];
393 my $n = scalar keys %gone;
396 warn "BUG: multiple articles linked to <$mid>\n",
397 join(',', sort keys %gone), "\n";
399 foreach my $num (keys %gone) {
400 my ($smsg, $orig) = @{$gone{$num}};
401 # $removed should only be set once assuming
402 # no bugs in our deduplication code:
404 my $oid = $smsg->{blob};
406 $replace_map->{$oid} = $sref;
408 ($mark, undef) = $im->remove($orig, $cmt_msg);
411 if ($need_reindex) { # ->replace
412 push @$need_reindex, $smsg;
413 } else { # ->purge or ->remove
414 $self->{mm}->num_delete($num);
416 unindex_oid_remote($self, $oid, $mid);
421 my $cmt = $im->get_mark($mark);
422 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
424 if ($replace_map && scalar keys %$replace_map) {
425 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
426 return { rewrites => $rewrites, need_reindex => $need_reindex };
433 my ($self, $mime, $cmt_msg) = @_;
434 $self->{-inbox}->with_umask(sub {
435 rewrite_internal($self, $mime, $cmt_msg);
439 sub _replace ($$;$$) {
440 my ($self, $old_mime, $new_mime, $sref) = @_;
441 my $rewritten = $self->{-inbox}->with_umask(sub {
442 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
445 my $rewrites = $rewritten->{rewrites};
446 # ->done is called if there are rewrites since we gc+prune from git
447 $self->idx_init if @$rewrites;
449 for my $i (0..$#$rewrites) {
450 defined(my $cmt = $rewrites->[$i]) or next;
451 $self->{last_commit}->[$i] = $cmt;
458 my ($self, $mime) = @_;
459 my $rewritten = _replace($self, $mime, undef, \'') or return;
460 $rewritten->{rewrites}
463 # returns the git object_id of $fh, does not write the object to FS
464 sub git_hash_raw ($$) {
465 my ($self, $raw) = @_;
466 # grab the expected OID we have to reindex:
467 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
468 $tmp_fh->autoflush(1);
469 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
470 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
472 my $git_dir = $self->{-inbox}->git->{git_dir};
473 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
474 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
476 chomp(my $oid = <$r>);
477 close $r or die "git hash-object failed: $?";
478 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
482 sub _check_mids_match ($$$) {
483 my ($old_list, $new_list, $hdrs) = @_;
484 my %old_mids = map { $_ => 1 } @$old_list;
485 my %new_mids = map { $_ => 1 } @$new_list;
486 my @old = keys %old_mids;
487 my @new = keys %new_mids;
488 my $err = "$hdrs may not be changed when replacing\n";
489 die $err if scalar(@old) != scalar(@new);
490 delete @new_mids{@old};
491 delete @old_mids{@new};
492 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
495 # Changing Message-IDs or References with ->replace isn't supported.
496 # The rules for dealing with messages with multiple or conflicting
497 # Message-IDs are pretty complex and rethreading hasn't been fully
499 sub check_mids_match ($$) {
500 my ($old_mime, $new_mime) = @_;
501 my $old = $old_mime->header_obj;
502 my $new = $new_mime->header_obj;
503 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
504 _check_mids_match(references($old), references($new),
505 'References/In-Reply-To');
510 my ($self, $old_mime, $new_mime) = @_;
512 check_mids_match($old_mime, $new_mime);
514 # mutt will always add Content-Length:, Status:, Lines: when editing
515 PublicInbox::Import::drop_unwanted_headers($new_mime);
517 my $raw = $new_mime->as_string;
518 my $expect_oid = git_hash_raw($self, \$raw);
519 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
520 my $need_reindex = $rewritten->{need_reindex};
522 # just in case we have bugs in deduplication code:
523 my $n = scalar(@$need_reindex);
525 my $list = join(', ', map {
526 "$_->{num}: <$_->{mid}>"
529 W: rewritten $n messages matching content of original message (expected: 1).
530 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
535 # make sure we really got the OID:
536 my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
537 $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
539 # don't leak FDs to Xapian:
540 $self->{-inbox}->git->cleanup;
542 # reindex modified messages:
543 for my $smsg (@$need_reindex) {
544 my $num = $smsg->{num};
545 my $mid0 = $smsg->{mid};
546 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
548 $rewritten->{rewrites};
551 sub last_epoch_commit ($$;$) {
552 my ($self, $i, $cmt) = @_;
553 my $v = PublicInbox::Search::SCHEMA_VERSION();
554 $self->{mm}->last_commit_xap($v, $i, $cmt);
557 sub set_last_commits ($) {
559 defined(my $epoch_max = $self->{epoch_max}) or return;
560 my $last_commit = $self->{last_commit};
561 foreach my $i (0..$epoch_max) {
562 defined(my $cmt = $last_commit->[$i]) or next;
563 $last_commit->[$i] = undef;
564 last_epoch_commit($self, $i, $cmt);
570 $self->{bnote} or return;
572 my $barrier = { map { $_ => 1 } (0..$n) };
576 my ($self, $barrier) = @_;
577 my $bnote = $self->{bnote} or return;
579 while (scalar keys %$barrier) {
580 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
581 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
582 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
587 sub checkpoint ($;$) {
588 my ($self, $wait) = @_;
590 if (my $im = $self->{im}) {
597 my $shards = $self->{idx_shards};
599 my $dbh = $self->{mm}->{dbh};
601 # SQLite msgmap data is second in importance
604 # SQLite overview is third
605 $self->{over}->commit_lazy;
607 # Now deal with Xapian
609 my $barrier = $self->barrier_init(scalar @$shards);
611 # each shard needs to issue a barrier command
612 $_->remote_barrier for @$shards;
614 # wait for each Xapian shard
615 $self->barrier_wait($barrier);
617 $_->remote_commit for @$shards;
620 # last_commit is special, don't commit these until
621 # remote shards are done:
623 set_last_commits($self);
628 $self->{transact_bytes} = 0;
631 # issue a write barrier to ensure all data is visible to other processes
632 # and read-only ops. Order of data importance is: git > SQLite > Xapian
634 sub barrier { checkpoint($_[0], 1) };
639 my $im = delete $self->{im};
640 $im->done if $im; # PublicInbox::Import::done
642 my $mm = delete $self->{mm};
643 $mm->{dbh}->commit if $mm;
644 my $shards = delete $self->{idx_shards};
646 $_->remote_close for @$shards;
648 $self->{over}->disconnect;
649 delete $self->{bnote};
650 $self->{transact_bytes} = 0;
651 $self->lock_release if $shards;
652 $self->{-inbox}->git->cleanup;
655 sub fill_alternates ($$) {
656 my ($self, $epoch) = @_;
658 my $pfx = "$self->{-inbox}->{inboxdir}/git";
659 my $all = "$self->{-inbox}->{inboxdir}/all.git";
662 PublicInbox::Import::init_bare($all);
664 my $info_dir = "$all/objects/info";
665 my $alt = "$info_dir/alternates";
669 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
670 $mode = (stat($fh))[2] & 07777;
672 # we assign a sort score to every alternate and favor
673 # the newest (highest numbered) one when we
675 my $other = 0; # in case admin adds non-epoch repos
677 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
683 } split(/\n+/, do { local $/; <$fh> });
686 foreach my $i (0..$epoch) {
687 my $dir = "../../git/$i.git/objects";
688 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
695 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
696 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
697 or die "print $tmp: $!\n";
698 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
699 close $fh or die "close $tmp $!\n";
700 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
704 my ($self, $epoch) = @_;
705 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
706 my @cmd = (qw(git init --bare -q), $git_dir);
707 PublicInbox::Import::run_die(\@cmd);
708 @cmd = (qw/git config/, "--file=$git_dir/config",
709 'include.path', '../../all.git/config');
710 PublicInbox::Import::run_die(\@cmd);
711 fill_alternates($self, $epoch);
716 my ($self, $max) = @_;
718 my $pfx = "$self->{-inbox}->{inboxdir}/git";
719 return unless -d $pfx;
721 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
722 while (defined(my $git_dir = readdir($dh))) {
723 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
726 $latest = "$pfx/$git_dir";
734 my $im = $self->{im};
736 if ($im->{bytes_added} < $self->{rotate_bytes}) {
743 my $git_dir = $self->git_init(++$self->{epoch_max});
744 my $git = PublicInbox::Git->new($git_dir);
745 return $self->import_init($git, 0);
750 my $latest = git_dir_latest($self, \$max);
751 if (defined $latest) {
752 my $git = PublicInbox::Git->new($latest);
753 my $packed_bytes = $git->packed_bytes;
754 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
756 if ($unpacked_bytes >= $self->{rotate_bytes}) {
759 $self->{epoch_max} = $max;
760 return $self->import_init($git, $packed_bytes);
763 $self->{epoch_max} = $epoch;
764 $latest = $self->git_init($epoch);
765 $self->import_init(PublicInbox::Git->new($latest), 0);
769 my ($self, $git, $packed_bytes, $tmp) = @_;
770 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
771 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
772 $im->{want_object_info} = 1;
773 $im->{lock_path} = undef;
774 $im->{path_type} = 'v2';
775 $self->{im} = $im unless $tmp;
781 my ($mid, $cur, $new) = @_;
783 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
784 print $ah $cur->as_string or die "print: $!";
785 close $ah or die "close: $!";
786 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
787 PublicInbox::Import::drop_unwanted_headers($new);
788 print $bh $new->as_string or die "print: $!";
789 close $bh or die "close: $!";
790 my $cmd = [ qw(diff -u), $an, $bn ];
791 print STDERR "# MID conflict <$mid>\n";
792 my $pid = spawn($cmd, undef, { 1 => 2 });
793 waitpid($pid, 0) == $pid or die "diff did not finish";
798 my ($self, $smsg) = @_;
799 if (my $im = $self->{im}) {
800 my $msg = $im->cat_blob($smsg->{blob});
803 # older message, should be in alternates
804 my $ibx = $self->{-inbox};
805 $ibx->msg_by_smsg($smsg);
808 sub lookup_content ($$$) {
809 my ($self, $mime, $mid) = @_;
810 my $over = $self->{over};
811 my $cids = content_ids($mime);
813 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
814 my $msg = get_blob($self, $smsg);
815 if (!defined($msg)) {
816 warn "broken smsg for $mid\n";
819 my $cur = PublicInbox::MIME->new($msg);
820 if (content_matches($cids, $cur)) {
821 $smsg->{mime} = $cur;
826 # XXX DEBUG_DIFF is experimental and may be removed
827 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
834 my $fh = delete $self->{reindex_pipe};
836 if (my $shards = $self->{idx_shards}) {
837 $_->atfork_child foreach @$shards;
839 if (my $im = $self->{im}) {
842 die "unexpected mm" if $self->{mm};
843 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
847 sub mark_deleted ($$$$) {
848 my ($self, $sync, $git, $oid) = @_;
849 my $msgref = $git->cat_file($oid);
850 my $mime = PublicInbox::MIME->new($$msgref);
851 my $mids = mids($mime->header_obj);
852 my $cid = content_id($mime);
853 foreach my $mid (@$mids) {
854 $sync->{D}->{"$mid\0$cid"} = $oid;
858 sub reindex_checkpoint ($$$) {
859 my ($self, $sync, $git) = @_;
862 $sync->{mm_tmp}->atfork_prepare;
863 $self->done; # release lock
865 if (my $pr = $sync->{-opt}->{-progress}) {
866 my ($bn) = (split('/', $git->{git_dir}))[-1];
867 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
870 # allow -watch or -mda to write...
871 $self->idx_init; # reacquire lock
872 $sync->{mm_tmp}->atfork_parent;
875 # only for a few odd messages with multiple Message-IDs
876 sub reindex_oid_m ($$$$;$) {
877 my ($self, $sync, $git, $oid, $regen_num) = @_;
878 $self->{current_info} = "multi_mid $oid";
879 my ($num, $mid0, $len);
880 my $msgref = $git->cat_file($oid, \$len);
881 my $mime = PublicInbox::MIME->new($$msgref);
882 my $mids = mids($mime->header_obj);
883 my $cid = content_id($mime);
884 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
886 for my $mid (reverse @$mids) {
887 delete($sync->{D}->{"$mid\0$cid"}) and
888 die "BUG: reindex_oid should handle <$mid> delete";
890 my $over = $self->{over};
891 for my $mid (reverse @$mids) {
892 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
893 next unless defined $num;
894 if (defined($regen_num) && $regen_num != $num) {
895 die "BUG: regen(#$regen_num) != over(#$num)";
898 unless (defined($num)) {
899 for my $mid (reverse @$mids) {
900 # is this a number we got before?
901 my $n = $sync->{mm_tmp}->num_for($mid);
902 next unless defined $n;
903 next if defined($regen_num) && $regen_num != $n;
904 ($num, $mid0) = ($n, $mid);
909 $sync->{mm_tmp}->num_delete($num);
910 } elsif (defined $regen_num) {
912 for my $mid (reverse @$mids) {
913 $self->{mm}->mid_set($num, $mid) == 1 or next;
917 unless (defined $mid0) {
918 warn "E: cannot regen #$num\n";
921 } else { # fixup bugs in old mirrors on reindex
922 for my $mid (reverse @$mids) {
923 $num = $self->{mm}->mid_insert($mid);
924 next unless defined $num;
929 if ($sync->{reindex}) {
930 warn "reindex added #$num <$mid0>\n";
933 warn "E: cannot find article #\n";
938 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
939 reindex_checkpoint($self, $sync, $git);
943 sub check_unindexed ($$$) {
944 my ($self, $num, $mid0) = @_;
945 my $unindexed = $self->{unindexed} // {};
946 my $n = delete($unindexed->{$mid0});
947 defined $n or return;
949 die "BUG: unindexed $n != $num <$mid0>\n";
951 $self->{mm}->mid_set($num, $mid0);
955 # reuse Msgmap to store num => oid mapping (rather than num => mid)
956 sub multi_mid_q_new () {
957 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
958 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
959 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
960 # for Msgmap->DESTROY:
961 $multi_mid->{tmp_name} = $fn;
962 $multi_mid->{pid} = $$;
963 close $fh or die "failed to close $fn: $!";
967 sub multi_mid_q_push ($$) {
968 my ($sync, $oid) = @_;
969 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
970 if ($sync->{reindex}) { # no regen on reindex
971 $multi_mid->mid_insert($oid);
973 my $num = $sync->{regen}--;
974 die "BUG: ran out of article numbers" if $num <= 0;
975 $multi_mid->mid_set($num, $oid);
979 sub reindex_oid ($$$$) {
980 my ($self, $sync, $git, $oid) = @_;
981 my ($num, $mid0, $len);
982 my $msgref = $git->cat_file($oid, \$len);
983 return if $len == 0; # purged
984 my $mime = PublicInbox::MIME->new($$msgref);
985 my $mids = mids($mime->header_obj);
986 my $cid = content_id($mime);
988 if (scalar(@$mids) == 0) {
989 warn "E: $oid has no Message-ID, skipping\n";
991 } elsif (scalar(@$mids) == 1) {
992 my $mid = $mids->[0];
994 # was the file previously marked as deleted?, skip if so
995 if (delete($sync->{D}->{"$mid\0$cid"})) {
996 if (!$sync->{reindex}) {
997 $num = $sync->{regen}--;
998 $self->{mm}->num_highwater($num);
1003 # is this a number we got before?
1004 $num = $sync->{mm_tmp}->num_for($mid);
1007 check_unindexed($self, $num, $mid0);
1009 $num = $sync->{regen}--;
1010 die "BUG: ran out of article numbers" if $num <= 0;
1011 if ($self->{mm}->mid_set($num, $mid) != 1) {
1012 warn "E: unable to assign $num => <$mid>\n";
1017 } else { # multiple MIDs are a weird case:
1020 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1023 unindex_oid_remote($self, $oid, $_) for @$mids;
1024 # do not delete from {mm_tmp}, since another
1025 # single-MID message may use it.
1026 } else { # handle them at the end:
1027 multi_mid_q_push($sync, $oid);
1031 $sync->{mm_tmp}->mid_delete($mid0) or
1032 die "failed to delete <$mid0> for article #$num\n";
1034 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1035 reindex_checkpoint($self, $sync, $git);
1039 # only update last_commit for $i on reindex iff newer than current
1040 sub update_last_commit ($$$$) {
1041 my ($self, $git, $i, $cmt) = @_;
1042 my $last = last_epoch_commit($self, $i);
1043 if (defined $last && is_ancestor($git, $last, $cmt)) {
1044 my @cmd = (qw(rev-list --count), "$last..$cmt");
1045 chomp(my $n = $git->qx(@cmd));
1046 return if $n ne '' && $n == 0;
1048 last_epoch_commit($self, $i, $cmt);
1051 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1053 sub last_commits ($$) {
1054 my ($self, $epoch_max) = @_;
1056 for (my $i = $epoch_max; $i >= 0; $i--) {
1057 $heads->[$i] = last_epoch_commit($self, $i);
1062 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1064 # returns a revision range for git-log(1)
1065 sub log_range ($$$$$) {
1066 my ($self, $sync, $git, $i, $tip) = @_;
1067 my $opt = $sync->{-opt};
1068 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1069 my $cur = $sync->{ranges}->[$i] or do {
1070 $pr->("$i.git indexing all of $tip") if $pr;
1071 return $tip; # all of it
1074 # fast equality check to avoid (v)fork+execve overhead
1076 $sync->{ranges}->[$i] = undef;
1080 my $range = "$cur..$tip";
1081 $pr->("$i.git checking contiguity... ") if $pr;
1082 if (is_ancestor($git, $cur, $tip)) { # common case
1083 $pr->("OK\n") if $pr;
1084 my $n = $git->qx(qw(rev-list --count), $range);
1087 $sync->{ranges}->[$i] = undef;
1088 $pr->("$i.git has nothing new\n") if $pr;
1089 return; # nothing to do
1091 $pr->("$i.git has $n changes since $cur\n") if $pr;
1093 $pr->("FAIL\n") if $pr;
1095 discontiguous range: $range
1096 Rewritten history? (in $git->{git_dir})
1098 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1100 $range = "$base..$tip";
1101 warn "found merge-base: $base\n"
1104 warn "discarding history at $cur\n";
1107 reindexing $git->{git_dir} starting at
1110 $sync->{unindex_range}->{$i} = "$base..$cur";
1115 sub sync_prepare ($$$) {
1116 my ($self, $sync, $epoch_max) = @_;
1117 my $pr = $sync->{-opt}->{-progress};
1119 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1121 # reindex stops at the current heads and we later rerun index_sync
1123 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1125 for (my $i = $epoch_max; $i >= 0; $i--) {
1126 die 'BUG: already indexing!' if $self->{reindex_pipe};
1127 my $git_dir = git_dir_n($self, $i);
1128 -d $git_dir or next; # missing epochs are fine
1129 my $git = PublicInbox::Git->new($git_dir);
1130 if ($reindex_heads) {
1131 $head = $reindex_heads->[$i] or next;
1133 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1135 next if $?; # new repo
1136 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1137 $sync->{ranges}->[$i] = $range;
1139 # can't use 'rev-list --count' if we use --diff-filter
1140 $pr->("$i.git counting $range ... ") if $pr;
1142 my $fh = $git->popen(qw(log --pretty=tformat:%H
1143 --no-notes --no-color --no-renames
1144 --diff-filter=AM), $range, '--', 'm');
1146 close $fh or die "git log failed: \$?=$?";
1147 $pr->("$n\n") if $pr;
1151 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1153 # reindex should NOT see new commits anymore, if we do,
1154 # it's a problem and we need to notice it via die()
1155 my $pad = length($regen_max) + 1;
1156 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1158 return -1 if $sync->{reindex};
1159 $regen_max + $self->{mm}->num_highwater() || 0;
1162 sub unindex_oid_remote ($$$) {
1163 my ($self, $oid, $mid) = @_;
1164 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1165 $self->{over}->remove_oid($oid, $mid);
1168 sub unindex_oid ($$$;$) {
1169 my ($self, $git, $oid, $unindexed) = @_;
1170 my $mm = $self->{mm};
1171 my $msgref = $git->cat_file($oid);
1172 my $mime = PublicInbox::MIME->new($msgref);
1173 my $mids = mids($mime->header_obj);
1174 $mime = $msgref = undef;
1175 my $over = $self->{over};
1176 foreach my $mid (@$mids) {
1179 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1180 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1183 my $n = scalar keys %gone;
1186 warn "BUG: multiple articles linked to $oid\n",
1187 join(',',sort keys %gone), "\n";
1189 foreach my $num (keys %gone) {
1191 my $mid0 = $mm->mid_for($num);
1192 $unindexed->{$mid0} = $num;
1194 $mm->num_delete($num);
1196 unindex_oid_remote($self, $oid, $mid);
1200 my $x40 = qr/[a-f0-9]{40}/;
1201 sub unindex ($$$$) {
1202 my ($self, $sync, $git, $unindex_range) = @_;
1203 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1204 my $before = scalar keys %$unindexed;
1205 # order does not matter, here:
1206 my @cmd = qw(log --raw -r
1207 --no-notes --no-color --no-abbrev --no-renames);
1208 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1210 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1211 unindex_oid($self, $git, $1, $unindexed);
1213 delete $self->{reindex_pipe};
1214 close $fh or die "git log failed: \$?=$?";
1216 return unless $sync->{-opt}->{prune};
1217 my $after = scalar keys %$unindexed;
1218 return if $before == $after;
1220 # ensure any blob can not longer be accessed via dumb HTTP
1221 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1222 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1225 sub sync_ranges ($$$) {
1226 my ($self, $sync, $epoch_max) = @_;
1227 my $reindex = $sync->{reindex};
1229 return last_commits($self, $epoch_max) unless $reindex;
1230 return [] if ref($reindex) ne 'HASH';
1232 my $ranges = $reindex->{from}; # arrayref;
1233 if (ref($ranges) ne 'ARRAY') {
1234 die 'BUG: $reindex->{from} not an ARRAY';
1239 sub index_epoch ($$$) {
1240 my ($self, $sync, $i) = @_;
1242 my $git_dir = git_dir_n($self, $i);
1243 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1244 -d $git_dir or return; # missing epochs are fine
1245 fill_alternates($self, $i);
1246 my $git = PublicInbox::Git->new($git_dir);
1247 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1248 unindex($self, $sync, $git, $unindex_range);
1250 defined(my $range = $sync->{ranges}->[$i]) or return;
1251 if (my $pr = $sync->{-opt}->{-progress}) {
1252 $pr->("$i.git indexing $range\n");
1255 my @cmd = qw(log --raw -r --pretty=tformat:%H
1256 --no-notes --no-color --no-abbrev --no-renames);
1257 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1261 $self->{current_info} = "$i.git $_";
1262 if (/\A$x40$/o && !defined($cmt)) {
1264 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1265 reindex_oid($self, $sync, $git, $1);
1266 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1267 mark_deleted($self, $sync, $git, $1);
1270 close $fh or die "git log failed: \$?=$?";
1271 delete $self->{reindex_pipe};
1272 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1275 # public, called by public-inbox-index
1277 my ($self, $opt) = @_;
1279 my $pr = $opt->{-progress};
1281 my $latest = git_dir_latest($self, \$epoch_max);
1282 return unless defined $latest;
1283 $self->idx_init($opt); # acquire lock
1285 D => {}, # "$mid\0$cid" => $oid
1286 unindex_range => {}, # EPOCH => oid_old..oid_new
1287 reindex => $opt->{reindex},
1290 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1291 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1293 if ($sync->{regen}) {
1294 # tmp_clone seems to fail if inside a transaction, so
1295 # we rollback here (because we opened {mm} for reading)
1296 # Note: we do NOT rely on DBI transactions for atomicity;
1297 # only for batch performance.
1298 $self->{mm}->{dbh}->rollback;
1299 $self->{mm}->{dbh}->begin_work;
1300 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1303 # work backwards through history
1304 for (my $i = $epoch_max; $i >= 0; $i--) {
1305 index_epoch($self, $sync, $i);
1308 # unindex is required for leftovers if "deletes" affect messages
1309 # in a previous fetch+index window:
1311 if (my @leftovers = values %{delete $sync->{D}}) {
1312 $git = $self->{-inbox}->git;
1313 for my $oid (@leftovers) {
1314 $self->{current_info} = "leftover $oid";
1315 unindex_oid($self, $git, $oid);
1318 if (my $multi_mid = delete $sync->{multi_mid}) {
1319 $git //= $self->{-inbox}->git;
1320 my ($min, $max) = $multi_mid->minmax;
1321 if ($sync->{reindex}) {
1322 # we may need to create new Message-IDs if mirrors
1323 # were initially indexed with old versions
1324 for (my $i = $max; $i >= $min; $i--) {
1325 my $oid = $multi_mid->mid_for($i);
1326 next unless defined $oid;
1327 reindex_oid_m($self, $sync, $git, $oid);
1329 } else { # regen on initial index
1330 for my $num ($min..$max) {
1331 my $oid = $multi_mid->mid_for($num);
1332 next unless defined $oid;
1333 reindex_oid_m($self, $sync, $git, $oid, $num);
1337 $git->cleanup if $git;
1340 if (my $nr = $sync->{nr}) {
1341 my $pr = $sync->{-opt}->{-progress};
1342 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1345 # reindex does not pick up new changes, so we rerun w/o it:
1346 if ($opt->{reindex}) {
1349 delete @again{qw(reindex -skip_lock)};
1350 index_sync($self, \%again);