1 # Copyright (C) 2018 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::SearchIdxPart;
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;
23 # an estimate of the post-packed size to the raw uncompressed size
24 my $PACKING_FACTOR = 0.4;
26 # assume 2 cores if GNU nproc(1) is not available
29 if (ref($creat_opt) eq 'HASH') {
30 if (defined(my $n = $creat_opt->{nproc})) {
35 my $n = int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
36 # subtract for the main process and git-fast-import
41 sub count_partitions ($) {
44 my $xpfx = $self->{xpfx};
46 # always load existing partitions in case core count changes:
47 # Also, partition count may change while -watch is running
50 foreach my $part (<$xpfx/*>) {
51 -d $part && $part =~ m!/[0-9]+\z! or next;
53 Search::Xapian::Database->new($part)->close;
62 # $creat may be any true value, or 0/undef. A hashref is true,
63 # and $creat->{nproc} may be set to an integer
64 my ($class, $v2ibx, $creat) = @_;
65 my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
69 File::Path::mkpath($dir);
71 die "$dir does not exist\n";
75 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
76 $v2ibx->umask_prepare;
78 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
81 im => undef, # PublicInbox::Import
86 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
87 lock_path => "$dir/inbox.lock",
88 # limit each git repo (epoch) to 1GB or so
89 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
90 last_commit => [], # git repo -> commit
92 $self->{partitions} = count_partitions($self) || nproc_parts($creat);
98 my ($self, $parallel, $skip_epoch) = @_;
99 $self->{parallel} = $parallel;
102 git_dir_latest($self, \$epoch_max);
103 if (defined $skip_epoch && $epoch_max == -1) {
104 $epoch_max = $skip_epoch;
106 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
110 # returns undef on duplicate or spam
111 # mimics Import::add and wraps it for v2
113 my ($self, $mime, $check_cb) = @_;
114 $self->{-inbox}->with_umask(sub {
115 _add($self, $mime, $check_cb)
119 # indexes a message, returns true if checkpointing is needed
120 sub do_idx ($$$$$$$) {
121 my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
122 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
123 my $npart = $self->{partitions};
124 my $part = $num % $npart;
125 my $idx = idx_part($self, $part);
126 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
127 my $n = $self->{transact_bytes} += $len;
128 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $npart);
132 my ($self, $mime, $check_cb) = @_;
136 $mime = $check_cb->($mime) or return;
139 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
140 # as does SQLite 3.4.1+ (released in 2007-07-20), and
141 # Xapian 1.3.2+ (released 2015-03-15).
142 # For the most part, we can spawn git-fast-import without
143 # leaking FDs to it...
147 my $num = num_for($self, $mime, \$mid0);
148 defined $num or return; # duplicate
149 defined $mid0 or die "BUG: $mid0 undefined\n";
150 my $im = $self->importer;
151 my $cmt = $im->add($mime);
152 $cmt = $im->get_mark($cmt);
153 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
155 my ($oid, $len, $msgref) = @{$im->{last_object}};
156 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
164 my ($self, $mime, $mid0) = @_;
165 my $mids = mids($mime->header_obj);
167 my $mid = $mids->[0];
168 my $num = $self->{mm}->mid_insert($mid);
169 if (defined $num) { # common case
174 # crap, Message-ID is already known, hope somebody just resent:
175 foreach my $m (@$mids) {
176 # read-only lookup now safe to do after above barrier
177 my $existing = lookup_content($self, $mime, $m);
178 # easy, don't store duplicates
179 # note: do not add more diagnostic info here since
180 # it gets noisy on public-inbox-watch restarts
184 # AltId may pre-populate article numbers (e.g. X-Mail-Count
185 # or NNTP article number), use that article number if it's
187 my $altid = $self->{-inbox}->{altid};
188 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
189 my $num = $self->{mm}->num_for($mid);
191 if (defined $num && !$self->{over}->get_art($num)) {
198 warn "<$mid> reused for mismatched content\n";
200 # try the rest of the mids
201 for(my $i = $#$mids; $i >= 1; $i--) {
203 $num = $self->{mm}->mid_insert($m);
205 warn "alternative <$m> for <$mid> found\n";
211 # none of the existing Message-IDs are good, generate a new one:
212 num_for_harder($self, $mime, $mid0);
216 my ($self, $mime, $mid0) = @_;
218 my $hdr = $mime->header_obj;
219 my $dig = content_digest($mime);
220 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
221 my $num = $self->{mm}->mid_insert($$mid0);
222 unless (defined $num) {
223 # it's hard to spoof the last Received: header
224 my @recvd = $hdr->header_raw('Received');
225 $dig->add("Received: $_") foreach (@recvd);
226 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
227 $num = $self->{mm}->mid_insert($$mid0);
229 # fall back to a random Message-ID and give up determinism:
230 until (defined($num)) {
232 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
233 warn "using random Message-ID <$$mid0> as fallback\n";
234 $num = $self->{mm}->mid_insert($$mid0);
237 PublicInbox::Import::append_mid($hdr, $$mid0);
242 my ($self, $part) = @_;
243 $self->{idx_parts}->[$part];
248 my ($self, $opt) = @_;
249 return if $self->{idx_parts};
250 my $ibx = $self->{-inbox};
252 # do not leak read-only FDs to child processes, we only have these
253 # FDs for duplicate detection so they should not be
254 # frequently activated.
255 delete $ibx->{$_} foreach (qw(git mm search));
257 my $indexlevel = $ibx->{indexlevel};
258 if ($indexlevel && $indexlevel eq 'basic') {
259 $self->{parallel} = 0;
262 if ($self->{parallel}) {
263 pipe(my ($r, $w)) or die "pipe failed: $!";
264 # pipe for barrier notifications doesn't need to be big,
266 fcntl($w, 1031, 4096) if $^O eq 'linux';
267 $self->{bnote} = [ $r, $w ];
271 my $over = $self->{over};
273 $ibx->with_umask(sub {
274 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
277 # -compact can change partition count while -watch is idle
278 my $nparts = count_partitions($self);
279 if ($nparts && $nparts != $self->{partitions}) {
280 $self->{partitions} = $nparts;
283 # need to create all parts before initializing msgmap FD
284 my $max = $self->{partitions} - 1;
286 # idx_parts must be visible to all forked processes
287 my $idx = $self->{idx_parts} = [];
288 for my $i (0..$max) {
289 push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
292 # Now that all subprocesses are up, we can open the FDs
294 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
295 "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
296 $mm->{dbh}->begin_work;
300 # returns an array mapping [ epoch => latest_commit ]
301 # latest_commit may be undef if nothing was done to that epoch
302 # $replace_map = { $object_id => $strref, ... }
303 sub _replace_oids ($$$) {
304 my ($self, $mime, $replace_map) = @_;
306 my $pfx = "$self->{-inbox}->{mainrepo}/git";
307 my $rewrites = []; # epoch => commit
308 my $max = $self->{epoch_max};
310 unless (defined($max)) {
311 defined(my $latest = git_dir_latest($self, \$max)) or return;
312 $self->{epoch_max} = $max;
315 foreach my $i (0..$max) {
316 my $git_dir = "$pfx/$i.git";
318 my $git = PublicInbox::Git->new($git_dir);
319 my $im = $self->import_init($git, 0, 1);
320 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
326 sub content_ids ($) {
328 my @cids = ( content_id($mime) );
330 # Email::MIME->as_string doesn't always round-trip, so we may
331 # use a second content_id
332 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
333 push @cids, $rt if $cids[0] ne $rt;
337 sub content_matches ($$) {
338 my ($cids, $existing) = @_;
339 my $cid = content_id($existing);
341 return 1 if $_ eq $cid
346 # used for removing or replacing (purging)
347 sub rewrite_internal ($$;$$$) {
348 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
350 my ($im, $need_reindex, $replace_map);
352 $replace_map = {}; # oid => sref
353 $need_reindex = [] if $new_mime;
355 $im = $self->importer;
357 my $over = $self->{over};
358 my $cids = content_ids($old_mime);
359 my $parts = $self->{idx_parts};
361 my $mids = mids($old_mime->header_obj);
363 # We avoid introducing new blobs into git since the raw content
364 # can be slightly different, so we do not need the user-supplied
365 # message now that we have the mids and content_id
369 foreach my $mid (@$mids) {
370 my %gone; # num => [ smsg, raw ]
372 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
373 my $msg = get_blob($self, $smsg);
374 if (!defined($msg)) {
375 warn "broken smsg for $mid\n";
379 my $cur = PublicInbox::MIME->new($msg);
380 if (content_matches($cids, $cur)) {
381 $smsg->{mime} = $cur;
382 $gone{$smsg->{num}} = [ $smsg, \$orig ];
385 my $n = scalar keys %gone;
388 warn "BUG: multiple articles linked to <$mid>\n",
389 join(',', sort keys %gone), "\n";
391 foreach my $num (keys %gone) {
392 my ($smsg, $orig) = @{$gone{$num}};
393 # $removed should only be set once assuming
394 # no bugs in our deduplication code:
396 my $oid = $smsg->{blob};
398 $replace_map->{$oid} = $sref;
400 ($mark, undef) = $im->remove($orig, $cmt_msg);
403 if ($need_reindex) { # ->replace
404 push @$need_reindex, $smsg;
405 } else { # ->purge or ->remove
406 $self->{mm}->num_delete($num);
408 unindex_oid_remote($self, $oid, $mid);
413 my $cmt = $im->get_mark($mark);
414 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
416 if ($replace_map && scalar keys %$replace_map) {
417 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
418 return { rewrites => $rewrites, need_reindex => $need_reindex };
425 my ($self, $mime, $cmt_msg) = @_;
426 $self->{-inbox}->with_umask(sub {
427 rewrite_internal($self, $mime, $cmt_msg);
431 sub _replace ($$;$$) {
432 my ($self, $old_mime, $new_mime, $sref) = @_;
433 my $rewritten = $self->{-inbox}->with_umask(sub {
434 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
437 my $rewrites = $rewritten->{rewrites};
438 # ->done is called if there are rewrites since we gc+prune from git
439 $self->idx_init if @$rewrites;
441 for my $i (0..$#$rewrites) {
442 defined(my $cmt = $rewrites->[$i]) or next;
443 $self->{last_commit}->[$i] = $cmt;
450 my ($self, $mime) = @_;
451 my $rewritten = _replace($self, $mime, undef, \'') or return;
452 $rewritten->{rewrites}
455 # returns the git object_id of $fh, does not write the object to FS
456 sub git_hash_raw ($$) {
457 my ($self, $raw) = @_;
458 # grab the expected OID we have to reindex:
459 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
460 $tmp_fh->autoflush(1);
461 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
462 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
465 pipe($r, $w) or die "failed to create pipe: $!";
466 my $rdr = { 0 => fileno($tmp_fh), 1 => fileno($w) };
467 my $git_dir = $self->{-inbox}->git->{git_dir};
468 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
469 my $pid = spawn($cmd, undef, $rdr);
472 chomp(my $oid = <$r>);
473 waitpid($pid, 0) == $pid or die "git hash-object did not finish";
474 die "git hash-object failed: $?" if $?;
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_commit_part ($$;$) {
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_commit_part($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 part[$1] on barrier wait";
584 sub checkpoint ($;$) {
585 my ($self, $wait) = @_;
587 if (my $im = $self->{im}) {
594 my $parts = $self->{idx_parts};
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 @$parts);
608 # each partition needs to issue a barrier command
609 $_->remote_barrier for @$parts;
611 # wait for each Xapian partition
612 $self->barrier_wait($barrier);
614 $_->remote_commit for @$parts;
617 # last_commit is special, don't commit these until
618 # remote partitions 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 $parts = delete $self->{idx_parts};
643 $_->remote_close for @$parts;
645 $self->{over}->disconnect;
646 delete $self->{bnote};
647 $self->{transact_bytes} = 0;
648 $self->lock_release if $parts;
649 $self->{-inbox}->git->cleanup;
652 sub fill_alternates ($$) {
653 my ($self, $epoch) = @_;
655 my $pfx = "$self->{-inbox}->{mainrepo}/git";
656 my $all = "$self->{-inbox}->{mainrepo}/all.git";
659 PublicInbox::Import::init_bare($all);
661 @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
662 'include.path', '../../all.git/config');
663 PublicInbox::Import::run_die(\@cmd);
665 my $alt = "$all/objects/info/alternates";
669 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
670 %alts = map { chomp; $_ => 1 } (<$fh>);
672 foreach my $i (0..$epoch) {
673 my $dir = "../../git/$i.git/objects";
674 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
677 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
678 foreach my $dir (@add) {
679 print $fh "$dir\n" or die "print >> $alt: $!\n";
681 close $fh or die "close $alt: $!\n";
685 my ($self, $epoch) = @_;
686 my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
687 my @cmd = (qw(git init --bare -q), $git_dir);
688 PublicInbox::Import::run_die(\@cmd);
689 fill_alternates($self, $epoch);
694 my ($self, $max) = @_;
696 my $pfx = "$self->{-inbox}->{mainrepo}/git";
697 return unless -d $pfx;
699 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
700 while (defined(my $git_dir = readdir($dh))) {
701 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
704 $latest = "$pfx/$git_dir";
712 my $im = $self->{im};
714 if ($im->{bytes_added} < $self->{rotate_bytes}) {
721 my $git_dir = $self->git_init(++$self->{epoch_max});
722 my $git = PublicInbox::Git->new($git_dir);
723 return $self->import_init($git, 0);
728 my $latest = git_dir_latest($self, \$max);
729 if (defined $latest) {
730 my $git = PublicInbox::Git->new($latest);
731 my $packed_bytes = $git->packed_bytes;
732 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
734 if ($unpacked_bytes >= $self->{rotate_bytes}) {
737 $self->{epoch_max} = $max;
738 return $self->import_init($git, $packed_bytes);
741 $self->{epoch_max} = $epoch;
742 $latest = $self->git_init($epoch);
743 $self->import_init(PublicInbox::Git->new($latest), 0);
747 my ($self, $git, $packed_bytes, $tmp) = @_;
748 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
749 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
750 $im->{want_object_info} = 1;
751 $im->{lock_path} = undef;
752 $im->{path_type} = 'v2';
753 $self->{im} = $im unless $tmp;
759 my ($mid, $cur, $new) = @_;
760 use File::Temp qw(tempfile);
762 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
763 print $ah $cur->as_string or die "print: $!";
764 close $ah or die "close: $!";
765 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
766 PublicInbox::Import::drop_unwanted_headers($new);
767 print $bh $new->as_string or die "print: $!";
768 close $bh or die "close: $!";
769 my $cmd = [ qw(diff -u), $an, $bn ];
770 print STDERR "# MID conflict <$mid>\n";
771 my $pid = spawn($cmd, undef, { 1 => 2 });
772 defined $pid or die "diff failed to spawn $!";
773 waitpid($pid, 0) == $pid or die "diff did not finish";
778 my ($self, $smsg) = @_;
779 if (my $im = $self->{im}) {
780 my $msg = $im->cat_blob($smsg->{blob});
783 # older message, should be in alternates
784 my $ibx = $self->{-inbox};
785 $ibx->msg_by_smsg($smsg);
788 sub lookup_content ($$$) {
789 my ($self, $mime, $mid) = @_;
790 my $over = $self->{over};
791 my $cids = content_ids($mime);
793 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
794 my $msg = get_blob($self, $smsg);
795 if (!defined($msg)) {
796 warn "broken smsg for $mid\n";
799 my $cur = PublicInbox::MIME->new($msg);
800 if (content_matches($cids, $cur)) {
801 $smsg->{mime} = $cur;
806 # XXX DEBUG_DIFF is experimental and may be removed
807 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
814 my $fh = delete $self->{reindex_pipe};
816 if (my $parts = $self->{idx_parts}) {
817 $_->atfork_child foreach @$parts;
819 if (my $im = $self->{im}) {
822 die "unexpected mm" if $self->{mm};
823 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
827 sub mark_deleted ($$$$) {
828 my ($self, $sync, $git, $oid) = @_;
829 my $msgref = $git->cat_file($oid);
830 my $mime = PublicInbox::MIME->new($$msgref);
831 my $mids = mids($mime->header_obj);
832 my $cid = content_id($mime);
833 foreach my $mid (@$mids) {
834 $sync->{D}->{"$mid\0$cid"} = $oid;
838 sub reindex_oid ($$$$) {
839 my ($self, $sync, $git, $oid) = @_;
841 my $msgref = $git->cat_file($oid, \$len);
842 my $mime = PublicInbox::MIME->new($$msgref);
843 my $mids = mids($mime->header_obj);
844 my $cid = content_id($mime);
846 # get the NNTP article number we used before, highest number wins
847 # and gets deleted from sync->{mm_tmp};
851 foreach my $mid (@$mids) {
852 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
853 my $n = $sync->{mm_tmp}->num_for($mid);
854 if (defined $n && $n > $num) {
857 $self->{mm}->mid_set($num, $mid0);
860 if (!defined($mid0) && !$del) {
861 $num = $sync->{regen}--;
862 die "BUG: ran out of article numbers\n" if $num <= 0;
863 my $mm = $self->{mm};
864 foreach my $mid (reverse @$mids) {
865 if ($mm->mid_set($num, $mid) == 1) {
870 if (!defined($mid0)) {
871 my $id = '<' . join('> <', @$mids) . '>';
872 warn "Message-ID $id unusable for $num\n";
873 foreach my $mid (@$mids) {
874 defined(my $n = $mm->num_for($mid)) or next;
875 warn "#$n previously mapped for <$mid>\n";
880 if (!defined($mid0) || $del) {
881 if (!defined($mid0) && $del) { # expected for deletes
882 $num = $sync->{regen}--;
883 $self->{mm}->num_highwater($num) if !$sync->{reindex};
887 my $id = '<' . join('> <', @$mids) . '>';
889 warn "Skipping $id, no article number found\n";
890 if ($del && defined($mid0)) {
891 warn "$id was deleted $del " .
892 "time(s) but mapped to article #$num\n";
897 $sync->{mm_tmp}->mid_delete($mid0) or
898 die "failed to delete <$mid0> for article #$num\n";
900 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
902 $sync->{mm_tmp}->atfork_prepare;
903 $self->done; # release lock
905 if (my $pr = $sync->{-opt}->{-progress}) {
906 my ($bn) = (split('/', $git->{git_dir}))[-1];
907 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
910 # allow -watch or -mda to write...
911 $self->idx_init; # reacquire lock
912 $sync->{mm_tmp}->atfork_parent;
916 # only update last_commit for $i on reindex iff newer than current
917 sub update_last_commit ($$$$) {
918 my ($self, $git, $i, $cmt) = @_;
919 my $last = last_commit_part($self, $i);
920 if (defined $last && is_ancestor($git, $last, $cmt)) {
921 my @cmd = (qw(rev-list --count), "$last..$cmt");
922 chomp(my $n = $git->qx(@cmd));
923 return if $n ne '' && $n == 0;
925 last_commit_part($self, $i, $cmt);
928 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
930 sub last_commits ($$) {
931 my ($self, $epoch_max) = @_;
933 for (my $i = $epoch_max; $i >= 0; $i--) {
934 $heads->[$i] = last_commit_part($self, $i);
939 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
941 # returns a revision range for git-log(1)
942 sub log_range ($$$$$) {
943 my ($self, $sync, $git, $i, $tip) = @_;
944 my $opt = $sync->{-opt};
945 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
946 my $cur = $sync->{ranges}->[$i] or do {
947 $pr->("$i.git indexing all of $tip") if $pr;
948 return $tip; # all of it
951 # fast equality check to avoid (v)fork+execve overhead
953 $sync->{ranges}->[$i] = undef;
957 my $range = "$cur..$tip";
958 $pr->("$i.git checking contiguity... ") if $pr;
959 if (is_ancestor($git, $cur, $tip)) { # common case
960 $pr->("OK\n") if $pr;
961 my $n = $git->qx(qw(rev-list --count), $range);
964 $sync->{ranges}->[$i] = undef;
965 $pr->("$i.git has nothing new\n") if $pr;
966 return; # nothing to do
968 $pr->("$i.git has $n changes since $cur\n") if $pr;
970 $pr->("FAIL\n") if $pr;
972 discontiguous range: $range
973 Rewritten history? (in $git->{git_dir})
975 chomp(my $base = $git->qx('merge-base', $tip, $cur));
977 $range = "$base..$tip";
978 warn "found merge-base: $base\n"
981 warn "discarding history at $cur\n";
984 reindexing $git->{git_dir} starting at
987 $sync->{unindex_range}->{$i} = "$base..$cur";
992 sub sync_prepare ($$$) {
993 my ($self, $sync, $epoch_max) = @_;
994 my $pr = $sync->{-opt}->{-progress};
996 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
998 # reindex stops at the current heads and we later rerun index_sync
1000 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1002 for (my $i = $epoch_max; $i >= 0; $i--) {
1003 die 'BUG: already indexing!' if $self->{reindex_pipe};
1004 my $git_dir = git_dir_n($self, $i);
1005 -d $git_dir or next; # missing parts are fine
1006 my $git = PublicInbox::Git->new($git_dir);
1007 if ($reindex_heads) {
1008 $head = $reindex_heads->[$i] or next;
1010 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1012 next if $?; # new repo
1013 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1014 $sync->{ranges}->[$i] = $range;
1016 # can't use 'rev-list --count' if we use --diff-filter
1017 $pr->("$i.git counting $range ... ") if $pr;
1019 my $fh = $git->popen(qw(log --pretty=tformat:%H
1020 --no-notes --no-color --no-renames
1021 --diff-filter=AM), $range, '--', 'm');
1023 $pr->("$n\n") if $pr;
1027 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1029 # reindex should NOT see new commits anymore, if we do,
1030 # it's a problem and we need to notice it via die()
1031 my $pad = length($regen_max) + 1;
1032 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1034 return -1 if $sync->{reindex};
1035 $regen_max + $self->{mm}->num_highwater() || 0;
1038 sub unindex_oid_remote ($$$) {
1039 my ($self, $oid, $mid) = @_;
1040 $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
1041 $self->{over}->remove_oid($oid, $mid);
1044 sub unindex_oid ($$$) {
1045 my ($self, $git, $oid) = @_;
1046 my $msgref = $git->cat_file($oid);
1047 my $mime = PublicInbox::MIME->new($msgref);
1048 my $mids = mids($mime->header_obj);
1049 $mime = $msgref = undef;
1050 my $over = $self->{over};
1051 foreach my $mid (@$mids) {
1054 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1055 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1058 my $n = scalar keys %gone;
1061 warn "BUG: multiple articles linked to $oid\n",
1062 join(',',sort keys %gone), "\n";
1064 foreach my $num (keys %gone) {
1065 $self->{unindexed}->{$_}++;
1066 $self->{mm}->num_delete($num);
1068 unindex_oid_remote($self, $oid, $mid);
1072 my $x40 = qr/[a-f0-9]{40}/;
1073 sub unindex ($$$$) {
1074 my ($self, $sync, $git, $unindex_range) = @_;
1075 my $un = $self->{unindexed} ||= {}; # num => removal count
1076 my $before = scalar keys %$un;
1077 my @cmd = qw(log --raw -r
1078 --no-notes --no-color --no-abbrev --no-renames);
1079 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1081 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1082 unindex_oid($self, $git, $1);
1084 delete $self->{reindex_pipe};
1087 return unless $sync->{-opt}->{prune};
1088 my $after = scalar keys %$un;
1089 return if $before == $after;
1091 # ensure any blob can not longer be accessed via dumb HTTP
1092 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1093 qw(-c gc.reflogExpire=now gc --prune=all)]);
1096 sub sync_ranges ($$$) {
1097 my ($self, $sync, $epoch_max) = @_;
1098 my $reindex = $sync->{reindex};
1100 return last_commits($self, $epoch_max) unless $reindex;
1101 return [] if ref($reindex) ne 'HASH';
1103 my $ranges = $reindex->{from}; # arrayref;
1104 if (ref($ranges) ne 'ARRAY') {
1105 die 'BUG: $reindex->{from} not an ARRAY';
1110 sub index_epoch ($$$) {
1111 my ($self, $sync, $i) = @_;
1113 my $git_dir = git_dir_n($self, $i);
1114 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1115 -d $git_dir or return; # missing parts are fine
1116 fill_alternates($self, $i);
1117 my $git = PublicInbox::Git->new($git_dir);
1118 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1119 unindex($self, $sync, $git, $unindex_range);
1121 defined(my $range = $sync->{ranges}->[$i]) or return;
1122 if (my $pr = $sync->{-opt}->{-progress}) {
1123 $pr->("$i.git indexing $range\n");
1126 my @cmd = qw(log --raw -r --pretty=tformat:%H
1127 --no-notes --no-color --no-abbrev --no-renames);
1128 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1132 $self->{current_info} = "$i.git $_";
1133 if (/\A$x40$/o && !defined($cmt)) {
1135 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1136 reindex_oid($self, $sync, $git, $1);
1137 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1138 mark_deleted($self, $sync, $git, $1);
1142 delete $self->{reindex_pipe};
1143 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1146 # public, called by public-inbox-index
1148 my ($self, $opt) = @_;
1150 my $pr = $opt->{-progress};
1152 my $latest = git_dir_latest($self, \$epoch_max);
1153 return unless defined $latest;
1154 $self->idx_init($opt); # acquire lock
1156 D => {}, # "$mid\0$cid" => $oid
1157 unindex_range => {}, # EPOCH => oid_old..oid_new
1158 reindex => $opt->{reindex},
1161 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1162 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1164 if ($sync->{regen}) {
1165 # tmp_clone seems to fail if inside a transaction, so
1166 # we rollback here (because we opened {mm} for reading)
1167 # Note: we do NOT rely on DBI transactions for atomicity;
1168 # only for batch performance.
1169 $self->{mm}->{dbh}->rollback;
1170 $self->{mm}->{dbh}->begin_work;
1171 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1174 # work backwards through history
1175 for (my $i = $epoch_max; $i >= 0; $i--) {
1176 index_epoch($self, $sync, $i);
1179 # unindex is required for leftovers if "deletes" affect messages
1180 # in a previous fetch+index window:
1181 if (my @leftovers = values %{delete $sync->{D}}) {
1182 my $git = $self->{-inbox}->git;
1183 unindex_oid($self, $git, $_) for @leftovers;
1188 if (my $nr = $sync->{nr}) {
1189 my $pr = $sync->{-opt}->{-progress};
1190 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1193 # reindex does not pick up new changes, so we rerun w/o it:
1194 if ($opt->{reindex}) {
1197 delete @again{qw(reindex -skip_lock)};
1198 index_sync($self, \%again);