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);
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 # SATA storage lags behind what CPUs are capable of, so relying on
27 # nproc(1) can be misleading and having extra Xapian partions is a
28 # waste of FDs and space. It can also lead to excessive IO latency
29 # and slow things down. Users on NVME or other fast storage can
30 # use the NPROC env or switches in our script/public-inbox-* programs
31 # to increase Xapian partitions.
32 our $NPROC_MAX_DEFAULT = 4;
36 if (ref($creat_opt) eq 'HASH') {
37 if (defined(my $n = $creat_opt->{nproc})) {
44 chomp($n = `nproc 2>/dev/null`);
45 # assume 2 cores if GNU nproc(1) is not available
47 $n = $NPROC_MAX_DEFAULT if $NPROC_MAX_DEFAULT > 4;
50 # subtract for the main process and git-fast-import
55 sub count_partitions ($) {
58 my $xpfx = $self->{xpfx};
60 # always load existing partitions in case core count changes:
61 # Also, partition count may change while -watch is running
64 foreach my $part (<$xpfx/*>) {
65 -d $part && $part =~ m!/[0-9]+\z! or next;
67 Search::Xapian::Database->new($part)->close;
76 # $creat may be any true value, or 0/undef. A hashref is true,
77 # and $creat->{nproc} may be set to an integer
78 my ($class, $v2ibx, $creat) = @_;
79 my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
83 File::Path::mkpath($dir);
85 die "$dir does not exist\n";
89 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
90 $v2ibx->umask_prepare;
92 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
95 im => undef, # PublicInbox::Import
100 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
101 lock_path => "$dir/inbox.lock",
102 # limit each git repo (epoch) to 1GB or so
103 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
104 last_commit => [], # git repo -> commit
106 $self->{partitions} = count_partitions($self) || nproc_parts($creat);
112 my ($self, $parallel, $skip_epoch) = @_;
113 $self->{parallel} = $parallel;
116 git_dir_latest($self, \$epoch_max);
117 if (defined $skip_epoch && $epoch_max == -1) {
118 $epoch_max = $skip_epoch;
120 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
124 # returns undef on duplicate or spam
125 # mimics Import::add and wraps it for v2
127 my ($self, $mime, $check_cb) = @_;
128 $self->{-inbox}->with_umask(sub {
129 _add($self, $mime, $check_cb)
134 my ($self, $mime, $check_cb) = @_;
138 $mime = $check_cb->($mime) or return;
141 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
142 # as does SQLite 3.4.1+ (released in 2007-07-20), and
143 # Xapian 1.3.2+ (released 2015-03-15).
144 # For the most part, we can spawn git-fast-import without
145 # leaking FDs to it...
149 my $num = num_for($self, $mime, \$mid0);
150 defined $num or return; # duplicate
151 defined $mid0 or die "BUG: $mid0 undefined\n";
152 my $im = $self->importer;
153 my $cmt = $im->add($mime);
154 $cmt = $im->get_mark($cmt);
155 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
157 my ($oid, $len, $msgref) = @{$im->{last_object}};
158 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
159 my $nparts = $self->{partitions};
160 my $part = $num % $nparts;
161 my $idx = $self->idx_part($part);
162 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
163 my $n = $self->{transact_bytes} += $len;
164 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
172 my ($self, $mime, $mid0) = @_;
173 my $mids = mids($mime->header_obj);
175 my $mid = $mids->[0];
176 my $num = $self->{mm}->mid_insert($mid);
177 if (defined $num) { # common case
182 # crap, Message-ID is already known, hope somebody just resent:
183 foreach my $m (@$mids) {
184 # read-only lookup now safe to do after above barrier
185 my $existing = lookup_content($self, $mime, $m);
186 # easy, don't store duplicates
187 # note: do not add more diagnostic info here since
188 # it gets noisy on public-inbox-watch restarts
192 # AltId may pre-populate article numbers (e.g. X-Mail-Count
193 # or NNTP article number), use that article number if it's
195 my $altid = $self->{-inbox}->{altid};
196 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
197 my $num = $self->{mm}->num_for($mid);
199 if (defined $num && !$self->{over}->get_art($num)) {
206 warn "<$mid> reused for mismatched content\n";
208 # try the rest of the mids
209 for(my $i = $#$mids; $i >= 1; $i--) {
211 $num = $self->{mm}->mid_insert($m);
213 warn "alternative <$m> for <$mid> found\n";
219 # none of the existing Message-IDs are good, generate a new one:
220 num_for_harder($self, $mime, $mid0);
224 my ($self, $mime, $mid0) = @_;
226 my $hdr = $mime->header_obj;
227 my $dig = content_digest($mime);
228 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
229 my $num = $self->{mm}->mid_insert($$mid0);
230 unless (defined $num) {
231 # it's hard to spoof the last Received: header
232 my @recvd = $hdr->header_raw('Received');
233 $dig->add("Received: $_") foreach (@recvd);
234 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
235 $num = $self->{mm}->mid_insert($$mid0);
237 # fall back to a random Message-ID and give up determinism:
238 until (defined($num)) {
240 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
241 warn "using random Message-ID <$$mid0> as fallback\n";
242 $num = $self->{mm}->mid_insert($$mid0);
245 PublicInbox::Import::append_mid($hdr, $$mid0);
250 my ($self, $part) = @_;
251 $self->{idx_parts}->[$part];
256 my ($self, $opt) = @_;
257 return if $self->{idx_parts};
258 my $ibx = $self->{-inbox};
260 # do not leak read-only FDs to child processes, we only have these
261 # FDs for duplicate detection so they should not be
262 # frequently activated.
263 delete $ibx->{$_} foreach (qw(git mm search));
265 my $indexlevel = $ibx->{indexlevel};
266 if ($indexlevel && $indexlevel eq 'basic') {
267 $self->{parallel} = 0;
270 if ($self->{parallel}) {
271 pipe(my ($r, $w)) or die "pipe failed: $!";
272 # pipe for barrier notifications doesn't need to be big,
274 fcntl($w, 1031, 4096) if $^O eq 'linux';
275 $self->{bnote} = [ $r, $w ];
279 my $over = $self->{over};
281 $ibx->with_umask(sub {
282 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
285 # -compact can change partition count while -watch is idle
286 my $nparts = count_partitions($self);
287 if ($nparts && $nparts != $self->{partitions}) {
288 $self->{partitions} = $nparts;
291 # need to create all parts before initializing msgmap FD
292 my $max = $self->{partitions} - 1;
294 # idx_parts must be visible to all forked processes
295 my $idx = $self->{idx_parts} = [];
296 for my $i (0..$max) {
297 push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
300 # Now that all subprocesses are up, we can open the FDs
302 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
303 "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
304 $mm->{dbh}->begin_work;
308 sub purge_oids ($$) {
309 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
311 my $pfx = "$self->{-inbox}->{mainrepo}/git";
313 my $max = $self->{epoch_max};
315 unless (defined($max)) {
316 defined(my $latest = git_dir_latest($self, \$max)) or return;
317 $self->{epoch_max} = $max;
319 foreach my $i (0..$max) {
320 my $git_dir = "$pfx/$i.git";
322 my $git = PublicInbox::Git->new($git_dir);
323 my $im = $self->import_init($git, 0, 1);
324 $purges->[$i] = $im->purge_oids($purge);
330 sub content_ids ($) {
332 my @cids = ( content_id($mime) );
334 # Email::MIME->as_string doesn't always round-trip, so we may
335 # use a second content_id
336 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
337 push @cids, $rt if $cids[0] ne $rt;
341 sub content_matches ($$) {
342 my ($cids, $existing) = @_;
343 my $cid = content_id($existing);
345 return 1 if $_ eq $cid
350 sub remove_internal ($$$$) {
351 my ($self, $mime, $cmt_msg, $purge) = @_;
353 my $im = $self->importer unless $purge;
354 my $over = $self->{over};
355 my $cids = content_ids($mime);
356 my $parts = $self->{idx_parts};
357 my $mm = $self->{mm};
359 my $mids = mids($mime->header_obj);
361 # We avoid introducing new blobs into git since the raw content
362 # can be slightly different, so we do not need the user-supplied
363 # message now that we have the mids and content_id
367 foreach my $mid (@$mids) {
370 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
371 my $msg = get_blob($self, $smsg);
372 if (!defined($msg)) {
373 warn "broken smsg for $mid\n";
377 my $cur = PublicInbox::MIME->new($msg);
378 if (content_matches($cids, $cur)) {
379 $smsg->{mime} = $cur;
380 $gone{$smsg->{num}} = [ $smsg, \$orig ];
383 my $n = scalar keys %gone;
386 warn "BUG: multiple articles linked to <$mid>\n",
387 join(',', sort keys %gone), "\n";
389 foreach my $num (keys %gone) {
390 my ($smsg, $orig) = @{$gone{$num}};
391 $mm->num_delete($num);
392 # $removed should only be set once assuming
393 # no bugs in our deduplication code:
395 my $oid = $smsg->{blob};
399 ($mark, undef) = $im->remove($orig, $cmt_msg);
402 unindex_oid_remote($self, $oid, $mid);
407 my $cmt = $im->get_mark($mark);
408 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
410 if ($purge && scalar keys %$purge) {
411 return purge_oids($self, $purge);
418 my ($self, $mime, $cmt_msg) = @_;
419 $self->{-inbox}->with_umask(sub {
420 remove_internal($self, $mime, $cmt_msg, undef);
426 my ($self, $mime) = @_;
427 my $purges = $self->{-inbox}->with_umask(sub {
428 remove_internal($self, $mime, undef, {});
430 $self->idx_init if @$purges; # ->done is called on purges
431 for my $i (0..$#$purges) {
432 defined(my $cmt = $purges->[$i]) or next;
433 $self->{last_commit}->[$i] = $cmt;
438 sub last_commit_part ($$;$) {
439 my ($self, $i, $cmt) = @_;
440 my $v = PublicInbox::Search::SCHEMA_VERSION();
441 $self->{mm}->last_commit_xap($v, $i, $cmt);
444 sub set_last_commits ($) {
446 defined(my $epoch_max = $self->{epoch_max}) or return;
447 my $last_commit = $self->{last_commit};
448 foreach my $i (0..$epoch_max) {
449 defined(my $cmt = $last_commit->[$i]) or next;
450 $last_commit->[$i] = undef;
451 last_commit_part($self, $i, $cmt);
457 $self->{bnote} or return;
459 my $barrier = { map { $_ => 1 } (0..$n) };
463 my ($self, $barrier) = @_;
464 my $bnote = $self->{bnote} or return;
466 while (scalar keys %$barrier) {
467 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
468 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
469 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
474 sub checkpoint ($;$) {
475 my ($self, $wait) = @_;
477 if (my $im = $self->{im}) {
484 my $parts = $self->{idx_parts};
486 my $dbh = $self->{mm}->{dbh};
488 # SQLite msgmap data is second in importance
491 # SQLite overview is third
492 $self->{over}->commit_lazy;
494 # Now deal with Xapian
496 my $barrier = $self->barrier_init(scalar @$parts);
498 # each partition needs to issue a barrier command
499 $_->remote_barrier for @$parts;
501 # wait for each Xapian partition
502 $self->barrier_wait($barrier);
504 $_->remote_commit for @$parts;
507 # last_commit is special, don't commit these until
508 # remote partitions are done:
510 set_last_commits($self);
515 $self->{transact_bytes} = 0;
518 # issue a write barrier to ensure all data is visible to other processes
519 # and read-only ops. Order of data importance is: git > SQLite > Xapian
521 sub barrier { checkpoint($_[0], 1) };
526 my $im = delete $self->{im};
527 $im->done if $im; # PublicInbox::Import::done
529 my $mm = delete $self->{mm};
530 $mm->{dbh}->commit if $mm;
531 my $parts = delete $self->{idx_parts};
533 $_->remote_close for @$parts;
535 $self->{over}->disconnect;
536 delete $self->{bnote};
537 $self->{transact_bytes} = 0;
538 $self->lock_release if $parts;
539 $self->{-inbox}->git->cleanup;
542 sub fill_alternates ($$) {
543 my ($self, $epoch) = @_;
545 my $pfx = "$self->{-inbox}->{mainrepo}/git";
546 my $all = "$self->{-inbox}->{mainrepo}/all.git";
549 PublicInbox::Import::init_bare($all);
551 @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
552 'include.path', '../../all.git/config');
553 PublicInbox::Import::run_die(\@cmd);
555 my $alt = "$all/objects/info/alternates";
559 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
560 %alts = map { chomp; $_ => 1 } (<$fh>);
562 foreach my $i (0..$epoch) {
563 my $dir = "../../git/$i.git/objects";
564 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
567 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
568 foreach my $dir (@add) {
569 print $fh "$dir\n" or die "print >> $alt: $!\n";
571 close $fh or die "close $alt: $!\n";
575 my ($self, $epoch) = @_;
576 my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
577 my @cmd = (qw(git init --bare -q), $git_dir);
578 PublicInbox::Import::run_die(\@cmd);
579 fill_alternates($self, $epoch);
584 my ($self, $max) = @_;
586 my $pfx = "$self->{-inbox}->{mainrepo}/git";
587 return unless -d $pfx;
589 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
590 while (defined(my $git_dir = readdir($dh))) {
591 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
594 $latest = "$pfx/$git_dir";
602 my $im = $self->{im};
604 if ($im->{bytes_added} < $self->{rotate_bytes}) {
611 my $git_dir = $self->git_init(++$self->{epoch_max});
612 my $git = PublicInbox::Git->new($git_dir);
613 return $self->import_init($git, 0);
618 my $latest = git_dir_latest($self, \$max);
619 if (defined $latest) {
620 my $git = PublicInbox::Git->new($latest);
621 my $packed_bytes = $git->packed_bytes;
622 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
624 if ($unpacked_bytes >= $self->{rotate_bytes}) {
627 $self->{epoch_max} = $max;
628 return $self->import_init($git, $packed_bytes);
631 $self->{epoch_max} = $epoch;
632 $latest = $self->git_init($epoch);
633 $self->import_init(PublicInbox::Git->new($latest), 0);
637 my ($self, $git, $packed_bytes, $tmp) = @_;
638 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
639 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
640 $im->{want_object_info} = 1;
641 $im->{lock_path} = undef;
642 $im->{path_type} = 'v2';
643 $self->{im} = $im unless $tmp;
649 my ($mid, $cur, $new) = @_;
650 use File::Temp qw(tempfile);
652 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
653 print $ah $cur->as_string or die "print: $!";
654 close $ah or die "close: $!";
655 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
656 PublicInbox::Import::drop_unwanted_headers($new);
657 print $bh $new->as_string or die "print: $!";
658 close $bh or die "close: $!";
659 my $cmd = [ qw(diff -u), $an, $bn ];
660 print STDERR "# MID conflict <$mid>\n";
661 my $pid = spawn($cmd, undef, { 1 => 2 });
662 defined $pid or die "diff failed to spawn $!";
663 waitpid($pid, 0) == $pid or die "diff did not finish";
668 my ($self, $smsg) = @_;
669 if (my $im = $self->{im}) {
670 my $msg = $im->cat_blob($smsg->{blob});
673 # older message, should be in alternates
674 my $ibx = $self->{-inbox};
675 $ibx->msg_by_smsg($smsg);
678 sub lookup_content ($$$) {
679 my ($self, $mime, $mid) = @_;
680 my $over = $self->{over};
681 my $cids = content_ids($mime);
683 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
684 my $msg = get_blob($self, $smsg);
685 if (!defined($msg)) {
686 warn "broken smsg for $mid\n";
689 my $cur = PublicInbox::MIME->new($msg);
690 if (content_matches($cids, $cur)) {
691 $smsg->{mime} = $cur;
696 # XXX DEBUG_DIFF is experimental and may be removed
697 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
704 my $fh = delete $self->{reindex_pipe};
706 if (my $parts = $self->{idx_parts}) {
707 $_->atfork_child foreach @$parts;
709 if (my $im = $self->{im}) {
712 die "unexpected mm" if $self->{mm};
713 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
717 sub mark_deleted ($$$$) {
718 my ($self, $sync, $git, $oid) = @_;
719 my $msgref = $git->cat_file($oid);
720 my $mime = PublicInbox::MIME->new($$msgref);
721 my $mids = mids($mime->header_obj);
722 my $cid = content_id($mime);
723 foreach my $mid (@$mids) {
724 $sync->{D}->{"$mid\0$cid"} = $oid;
728 sub reindex_oid ($$$$) {
729 my ($self, $sync, $git, $oid) = @_;
731 my $msgref = $git->cat_file($oid, \$len);
732 my $mime = PublicInbox::MIME->new($$msgref);
733 my $mids = mids($mime->header_obj);
734 my $cid = content_id($mime);
736 # get the NNTP article number we used before, highest number wins
737 # and gets deleted from sync->{mm_tmp};
741 foreach my $mid (@$mids) {
742 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
743 my $n = $sync->{mm_tmp}->num_for($mid);
744 if (defined $n && $n > $num) {
747 $self->{mm}->mid_set($num, $mid0);
750 if (!defined($mid0) && !$del) {
751 $num = $sync->{regen}--;
752 die "BUG: ran out of article numbers\n" if $num <= 0;
753 my $mm = $self->{mm};
754 foreach my $mid (reverse @$mids) {
755 if ($mm->mid_set($num, $mid) == 1) {
760 if (!defined($mid0)) {
761 my $id = '<' . join('> <', @$mids) . '>';
762 warn "Message-ID $id unusable for $num\n";
763 foreach my $mid (@$mids) {
764 defined(my $n = $mm->num_for($mid)) or next;
765 warn "#$n previously mapped for <$mid>\n";
770 if (!defined($mid0) || $del) {
771 if (!defined($mid0) && $del) { # expected for deletes
772 $num = $sync->{regen}--;
773 $self->{mm}->num_highwater($num) if !$sync->{reindex};
777 my $id = '<' . join('> <', @$mids) . '>';
779 warn "Skipping $id, no article number found\n";
780 if ($del && defined($mid0)) {
781 warn "$id was deleted $del " .
782 "time(s) but mapped to article #$num\n";
787 $sync->{mm_tmp}->mid_delete($mid0) or
788 die "failed to delete <$mid0> for article #$num\n";
790 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
791 my $nparts = $self->{partitions};
792 my $part = $num % $nparts;
793 my $idx = $self->idx_part($part);
794 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
795 my $n = $self->{transact_bytes} += $len;
797 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
799 $sync->{mm_tmp}->atfork_prepare;
800 $self->done; # release lock
802 if (my $pr = $sync->{-opt}->{-progress}) {
803 my ($bn) = (split('/', $git->{git_dir}))[-1];
804 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
807 # allow -watch or -mda to write...
808 $self->idx_init; # reacquire lock
809 $sync->{mm_tmp}->atfork_parent;
813 # only update last_commit for $i on reindex iff newer than current
814 sub update_last_commit ($$$$) {
815 my ($self, $git, $i, $cmt) = @_;
816 my $last = last_commit_part($self, $i);
817 if (defined $last && is_ancestor($git, $last, $cmt)) {
818 my @cmd = (qw(rev-list --count), "$last..$cmt");
819 chomp(my $n = $git->qx(@cmd));
820 return if $n ne '' && $n == 0;
822 last_commit_part($self, $i, $cmt);
825 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
827 sub last_commits ($$) {
828 my ($self, $epoch_max) = @_;
830 for (my $i = $epoch_max; $i >= 0; $i--) {
831 $heads->[$i] = last_commit_part($self, $i);
836 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
838 # returns a revision range for git-log(1)
839 sub log_range ($$$$$) {
840 my ($self, $sync, $git, $i, $tip) = @_;
841 my $opt = $sync->{-opt};
842 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
843 my $cur = $sync->{ranges}->[$i] or do {
844 $pr->("$i.git indexing all of $tip") if $pr;
845 return $tip; # all of it
848 # fast equality check to avoid (v)fork+execve overhead
850 $sync->{ranges}->[$i] = undef;
854 my $range = "$cur..$tip";
855 $pr->("$i.git checking contiguity... ") if $pr;
856 if (is_ancestor($git, $cur, $tip)) { # common case
857 $pr->("OK\n") if $pr;
858 my $n = $git->qx(qw(rev-list --count), $range);
861 $sync->{ranges}->[$i] = undef;
862 $pr->("$i.git has nothing new\n") if $pr;
863 return; # nothing to do
865 $pr->("$i.git has $n changes since $cur\n") if $pr;
867 $pr->("FAIL\n") if $pr;
869 discontiguous range: $range
870 Rewritten history? (in $git->{git_dir})
872 chomp(my $base = $git->qx('merge-base', $tip, $cur));
874 $range = "$base..$tip";
875 warn "found merge-base: $base\n"
878 warn "discarding history at $cur\n";
881 reindexing $git->{git_dir} starting at
884 $sync->{unindex_range}->{$i} = "$base..$cur";
889 sub sync_prepare ($$$) {
890 my ($self, $sync, $epoch_max) = @_;
891 my $pr = $sync->{-opt}->{-progress};
893 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
895 # reindex stops at the current heads and we later rerun index_sync
897 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
899 for (my $i = $epoch_max; $i >= 0; $i--) {
900 die 'BUG: already indexing!' if $self->{reindex_pipe};
901 my $git_dir = git_dir_n($self, $i);
902 -d $git_dir or next; # missing parts are fine
903 my $git = PublicInbox::Git->new($git_dir);
904 if ($reindex_heads) {
905 $head = $reindex_heads->[$i] or next;
907 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
909 next if $?; # new repo
910 my $range = log_range($self, $sync, $git, $i, $tip) or next;
911 $sync->{ranges}->[$i] = $range;
913 # can't use 'rev-list --count' if we use --diff-filter
914 $pr->("$i.git counting $range ... ") if $pr;
916 my $fh = $git->popen(qw(log --pretty=tformat:%H
917 --no-notes --no-color --no-renames
918 --diff-filter=AM), $range, '--', 'm');
920 $pr->("$n\n") if $pr;
924 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
926 # reindex should NOT see new commits anymore, if we do,
927 # it's a problem and we need to notice it via die()
928 my $pad = length($regen_max) + 1;
929 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
931 return -1 if $sync->{reindex};
932 $regen_max + $self->{mm}->num_highwater() || 0;
935 sub unindex_oid_remote ($$$) {
936 my ($self, $oid, $mid) = @_;
937 $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
938 $self->{over}->remove_oid($oid, $mid);
941 sub unindex_oid ($$$) {
942 my ($self, $git, $oid) = @_;
943 my $msgref = $git->cat_file($oid);
944 my $mime = PublicInbox::MIME->new($msgref);
945 my $mids = mids($mime->header_obj);
946 $mime = $msgref = undef;
947 my $over = $self->{over};
948 foreach my $mid (@$mids) {
951 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
952 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
955 my $n = scalar keys %gone;
958 warn "BUG: multiple articles linked to $oid\n",
959 join(',',sort keys %gone), "\n";
961 foreach my $num (keys %gone) {
962 $self->{unindexed}->{$_}++;
963 $self->{mm}->num_delete($num);
965 unindex_oid_remote($self, $oid, $mid);
969 my $x40 = qr/[a-f0-9]{40}/;
971 my ($self, $sync, $git, $unindex_range) = @_;
972 my $un = $self->{unindexed} ||= {}; # num => removal count
973 my $before = scalar keys %$un;
974 my @cmd = qw(log --raw -r
975 --no-notes --no-color --no-abbrev --no-renames);
976 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
978 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
979 unindex_oid($self, $git, $1);
981 delete $self->{reindex_pipe};
984 return unless $sync->{-opt}->{prune};
985 my $after = scalar keys %$un;
986 return if $before == $after;
988 # ensure any blob can not longer be accessed via dumb HTTP
989 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
990 qw(-c gc.reflogExpire=now gc --prune=all)]);
993 sub sync_ranges ($$$) {
994 my ($self, $sync, $epoch_max) = @_;
995 my $reindex = $sync->{reindex};
997 return last_commits($self, $epoch_max) unless $reindex;
998 return [] if ref($reindex) ne 'HASH';
1000 my $ranges = $reindex->{from}; # arrayref;
1001 if (ref($ranges) ne 'ARRAY') {
1002 die 'BUG: $reindex->{from} not an ARRAY';
1007 sub index_epoch ($$$) {
1008 my ($self, $sync, $i) = @_;
1010 my $git_dir = git_dir_n($self, $i);
1011 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1012 -d $git_dir or return; # missing parts are fine
1013 fill_alternates($self, $i);
1014 my $git = PublicInbox::Git->new($git_dir);
1015 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1016 unindex($self, $sync, $git, $unindex_range);
1018 defined(my $range = $sync->{ranges}->[$i]) or return;
1019 if (my $pr = $sync->{-opt}->{-progress}) {
1020 $pr->("$i.git indexing $range\n");
1023 my @cmd = qw(log --raw -r --pretty=tformat:%H
1024 --no-notes --no-color --no-abbrev --no-renames);
1025 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1029 $self->{current_info} = "$i.git $_";
1030 if (/\A$x40$/o && !defined($cmt)) {
1032 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1033 reindex_oid($self, $sync, $git, $1);
1034 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1035 mark_deleted($self, $sync, $git, $1);
1039 delete $self->{reindex_pipe};
1040 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1043 # public, called by public-inbox-index
1045 my ($self, $opt) = @_;
1047 my $pr = $opt->{-progress};
1049 my $latest = git_dir_latest($self, \$epoch_max);
1050 return unless defined $latest;
1051 $self->idx_init($opt); # acquire lock
1053 D => {}, # "$mid\0$cid" => $oid
1054 unindex_range => {}, # EPOCH => oid_old..oid_new
1055 reindex => $opt->{reindex},
1058 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1059 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1061 if ($sync->{regen}) {
1062 # tmp_clone seems to fail if inside a transaction, so
1063 # we rollback here (because we opened {mm} for reading)
1064 # Note: we do NOT rely on DBI transactions for atomicity;
1065 # only for batch performance.
1066 $self->{mm}->{dbh}->rollback;
1067 $self->{mm}->{dbh}->begin_work;
1068 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1071 # work backwards through history
1072 for (my $i = $epoch_max; $i >= 0; $i--) {
1073 index_epoch($self, $sync, $i);
1076 # unindex is required for leftovers if "deletes" affect messages
1077 # in a previous fetch+index window:
1078 if (my @leftovers = values %{delete $sync->{D}}) {
1079 my $git = $self->{-inbox}->git;
1080 unindex_oid($self, $git, $_) for @leftovers;
1085 if (my $nr = $sync->{nr}) {
1086 my $pr = $sync->{-opt}->{-progress};
1087 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1090 # reindex does not pick up new changes, so we rerun w/o it:
1091 if ($opt->{reindex}) {
1094 delete @again{qw(reindex -skip_lock)};
1095 index_sync($self, \%again);