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 # 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!/\d+\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)
120 my ($self, $mime, $check_cb) = @_;
124 $mime = $check_cb->($mime) or return;
127 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
128 # as does SQLite 3.4.1+ (released in 2007-07-20), and
129 # Xapian 1.3.2+ (released 2015-03-15).
130 # For the most part, we can spawn git-fast-import without
131 # leaking FDs to it...
135 my $num = num_for($self, $mime, \$mid0);
136 defined $num or return; # duplicate
137 defined $mid0 or die "BUG: $mid0 undefined\n";
138 my $im = $self->importer;
139 my $cmt = $im->add($mime);
140 $cmt = $im->get_mark($cmt);
141 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
143 my ($oid, $len, $msgref) = @{$im->{last_object}};
144 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
145 my $nparts = $self->{partitions};
146 my $part = $num % $nparts;
147 my $idx = $self->idx_part($part);
148 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
149 my $n = $self->{transact_bytes} += $len;
150 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
158 my ($self, $mime, $mid0) = @_;
159 my $mids = mids($mime->header_obj);
161 my $mid = $mids->[0];
162 my $num = $self->{mm}->mid_insert($mid);
163 if (defined $num) { # common case
168 # crap, Message-ID is already known, hope somebody just resent:
169 foreach my $m (@$mids) {
170 # read-only lookup now safe to do after above barrier
171 my $existing = lookup_content($self, $mime, $m);
172 # easy, don't store duplicates
173 # note: do not add more diagnostic info here since
174 # it gets noisy on public-inbox-watch restarts
178 # AltId may pre-populate article numbers (e.g. X-Mail-Count
179 # or NNTP article number), use that article number if it's
181 my $altid = $self->{-inbox}->{altid};
182 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
183 my $num = $self->{mm}->num_for($mid);
185 if (defined $num && !$self->{over}->get_art($num)) {
192 warn "<$mid> reused for mismatched content\n";
194 # try the rest of the mids
195 for(my $i = $#$mids; $i >= 1; $i--) {
197 $num = $self->{mm}->mid_insert($m);
199 warn "alternative <$m> for <$mid> found\n";
205 # none of the existing Message-IDs are good, generate a new one:
206 num_for_harder($self, $mime, $mid0);
210 my ($self, $mime, $mid0) = @_;
212 my $hdr = $mime->header_obj;
213 my $dig = content_digest($mime);
214 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
215 my $num = $self->{mm}->mid_insert($$mid0);
216 unless (defined $num) {
217 # it's hard to spoof the last Received: header
218 my @recvd = $hdr->header_raw('Received');
219 $dig->add("Received: $_") foreach (@recvd);
220 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
221 $num = $self->{mm}->mid_insert($$mid0);
223 # fall back to a random Message-ID and give up determinism:
224 until (defined($num)) {
226 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
227 warn "using random Message-ID <$$mid0> as fallback\n";
228 $num = $self->{mm}->mid_insert($$mid0);
231 PublicInbox::Import::append_mid($hdr, $$mid0);
236 my ($self, $part) = @_;
237 $self->{idx_parts}->[$part];
242 my ($self, $opt) = @_;
243 return if $self->{idx_parts};
244 my $ibx = $self->{-inbox};
246 # do not leak read-only FDs to child processes, we only have these
247 # FDs for duplicate detection so they should not be
248 # frequently activated.
249 delete $ibx->{$_} foreach (qw(git mm search));
251 my $indexlevel = $ibx->{indexlevel};
252 if ($indexlevel && $indexlevel eq 'basic') {
253 $self->{parallel} = 0;
256 if ($self->{parallel}) {
257 pipe(my ($r, $w)) or die "pipe failed: $!";
258 # pipe for barrier notifications doesn't need to be big,
260 fcntl($w, 1031, 4096) if $^O eq 'linux';
261 $self->{bnote} = [ $r, $w ];
265 my $over = $self->{over};
267 $ibx->with_umask(sub {
268 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
271 # -compact can change partition count while -watch is idle
272 my $nparts = count_partitions($self);
273 if ($nparts && $nparts != $self->{partitions}) {
274 $self->{partitions} = $nparts;
277 # need to create all parts before initializing msgmap FD
278 my $max = $self->{partitions} - 1;
280 # idx_parts must be visible to all forked processes
281 my $idx = $self->{idx_parts} = [];
282 for my $i (0..$max) {
283 push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
286 # Now that all subprocesses are up, we can open the FDs
288 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
289 "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
290 $mm->{dbh}->begin_work;
294 sub purge_oids ($$) {
295 my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
297 my $pfx = "$self->{-inbox}->{mainrepo}/git";
299 my $max = $self->{epoch_max};
301 unless (defined($max)) {
302 defined(my $latest = git_dir_latest($self, \$max)) or return;
303 $self->{epoch_max} = $max;
305 foreach my $i (0..$max) {
306 my $git_dir = "$pfx/$i.git";
308 my $git = PublicInbox::Git->new($git_dir);
309 my $im = $self->import_init($git, 0, 1);
310 $purges->[$i] = $im->purge_oids($purge);
316 sub content_ids ($) {
318 my @cids = ( content_id($mime) );
320 # Email::MIME->as_string doesn't always round-trip, so we may
321 # use a second content_id
322 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
323 push @cids, $rt if $cids[0] ne $rt;
327 sub content_matches ($$) {
328 my ($cids, $existing) = @_;
329 my $cid = content_id($existing);
331 return 1 if $_ eq $cid
336 sub remove_internal ($$$$) {
337 my ($self, $mime, $cmt_msg, $purge) = @_;
339 my $im = $self->importer unless $purge;
340 my $over = $self->{over};
341 my $cids = content_ids($mime);
342 my $parts = $self->{idx_parts};
343 my $mm = $self->{mm};
345 my $mids = mids($mime->header_obj);
347 # We avoid introducing new blobs into git since the raw content
348 # can be slightly different, so we do not need the user-supplied
349 # message now that we have the mids and content_id
353 foreach my $mid (@$mids) {
356 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
357 my $msg = get_blob($self, $smsg);
358 if (!defined($msg)) {
359 warn "broken smsg for $mid\n";
363 my $cur = PublicInbox::MIME->new($msg);
364 if (content_matches($cids, $cur)) {
365 $smsg->{mime} = $cur;
366 $gone{$smsg->{num}} = [ $smsg, \$orig ];
369 my $n = scalar keys %gone;
372 warn "BUG: multiple articles linked to <$mid>\n",
373 join(',', sort keys %gone), "\n";
375 foreach my $num (keys %gone) {
376 my ($smsg, $orig) = @{$gone{$num}};
377 $mm->num_delete($num);
378 # $removed should only be set once assuming
379 # no bugs in our deduplication code:
381 my $oid = $smsg->{blob};
385 ($mark, undef) = $im->remove($orig, $cmt_msg);
388 unindex_oid_remote($self, $oid, $mid);
393 my $cmt = $im->get_mark($mark);
394 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
396 if ($purge && scalar keys %$purge) {
397 return purge_oids($self, $purge);
404 my ($self, $mime, $cmt_msg) = @_;
405 $self->{-inbox}->with_umask(sub {
406 remove_internal($self, $mime, $cmt_msg, undef);
412 my ($self, $mime) = @_;
413 my $purges = $self->{-inbox}->with_umask(sub {
414 remove_internal($self, $mime, undef, {});
416 $self->idx_init if @$purges; # ->done is called on purges
417 for my $i (0..$#$purges) {
418 defined(my $cmt = $purges->[$i]) or next;
419 $self->{last_commit}->[$i] = $cmt;
424 sub last_commit_part ($$;$) {
425 my ($self, $i, $cmt) = @_;
426 my $v = PublicInbox::Search::SCHEMA_VERSION();
427 $self->{mm}->last_commit_xap($v, $i, $cmt);
430 sub set_last_commits ($) {
432 defined(my $epoch_max = $self->{epoch_max}) or return;
433 my $last_commit = $self->{last_commit};
434 foreach my $i (0..$epoch_max) {
435 defined(my $cmt = $last_commit->[$i]) or next;
436 $last_commit->[$i] = undef;
437 last_commit_part($self, $i, $cmt);
443 $self->{bnote} or return;
445 my $barrier = { map { $_ => 1 } (0..$n) };
449 my ($self, $barrier) = @_;
450 my $bnote = $self->{bnote} or return;
452 while (scalar keys %$barrier) {
453 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
454 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
455 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
460 sub checkpoint ($;$) {
461 my ($self, $wait) = @_;
463 if (my $im = $self->{im}) {
470 my $parts = $self->{idx_parts};
472 my $dbh = $self->{mm}->{dbh};
474 # SQLite msgmap data is second in importance
477 # SQLite overview is third
478 $self->{over}->commit_lazy;
480 # Now deal with Xapian
482 my $barrier = $self->barrier_init(scalar @$parts);
484 # each partition needs to issue a barrier command
485 $_->remote_barrier for @$parts;
487 # wait for each Xapian partition
488 $self->barrier_wait($barrier);
490 $_->remote_commit for @$parts;
493 # last_commit is special, don't commit these until
494 # remote partitions are done:
496 set_last_commits($self);
501 $self->{transact_bytes} = 0;
504 # issue a write barrier to ensure all data is visible to other processes
505 # and read-only ops. Order of data importance is: git > SQLite > Xapian
507 sub barrier { checkpoint($_[0], 1) };
512 my $im = delete $self->{im};
513 $im->done if $im; # PublicInbox::Import::done
515 my $mm = delete $self->{mm};
516 $mm->{dbh}->commit if $mm;
517 my $parts = delete $self->{idx_parts};
519 $_->remote_close for @$parts;
521 $self->{over}->disconnect;
522 delete $self->{bnote};
523 $self->{transact_bytes} = 0;
524 $self->lock_release if $parts;
525 $self->{-inbox}->git->cleanup;
528 sub fill_alternates ($$) {
529 my ($self, $epoch) = @_;
531 my $pfx = "$self->{-inbox}->{mainrepo}/git";
532 my $all = "$self->{-inbox}->{mainrepo}/all.git";
535 PublicInbox::Import::init_bare($all);
537 @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
538 'include.path', '../../all.git/config');
539 PublicInbox::Import::run_die(\@cmd);
541 my $alt = "$all/objects/info/alternates";
545 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
546 %alts = map { chomp; $_ => 1 } (<$fh>);
548 foreach my $i (0..$epoch) {
549 my $dir = "../../git/$i.git/objects";
550 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
553 open my $fh, '>>', $alt or die "open >> $alt: $!\n";
554 foreach my $dir (@add) {
555 print $fh "$dir\n" or die "print >> $alt: $!\n";
557 close $fh or die "close $alt: $!\n";
561 my ($self, $epoch) = @_;
562 my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
563 my @cmd = (qw(git init --bare -q), $git_dir);
564 PublicInbox::Import::run_die(\@cmd);
565 fill_alternates($self, $epoch);
570 my ($self, $max) = @_;
572 my $pfx = "$self->{-inbox}->{mainrepo}/git";
573 return unless -d $pfx;
575 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
576 while (defined(my $git_dir = readdir($dh))) {
577 $git_dir =~ m!\A(\d+)\.git\z! or next;
580 $latest = "$pfx/$git_dir";
588 my $im = $self->{im};
590 if ($im->{bytes_added} < $self->{rotate_bytes}) {
597 my $git_dir = $self->git_init(++$self->{epoch_max});
598 my $git = PublicInbox::Git->new($git_dir);
599 return $self->import_init($git, 0);
604 my $latest = git_dir_latest($self, \$max);
605 if (defined $latest) {
606 my $git = PublicInbox::Git->new($latest);
607 my $packed_bytes = $git->packed_bytes;
608 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
610 if ($unpacked_bytes >= $self->{rotate_bytes}) {
613 $self->{epoch_max} = $max;
614 return $self->import_init($git, $packed_bytes);
617 $self->{epoch_max} = $epoch;
618 $latest = $self->git_init($epoch);
619 $self->import_init(PublicInbox::Git->new($latest), 0);
623 my ($self, $git, $packed_bytes, $tmp) = @_;
624 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
625 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
626 $im->{want_object_info} = 1;
627 $im->{lock_path} = undef;
628 $im->{path_type} = 'v2';
629 $self->{im} = $im unless $tmp;
635 my ($mid, $cur, $new) = @_;
636 use File::Temp qw(tempfile);
638 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
639 print $ah $cur->as_string or die "print: $!";
640 close $ah or die "close: $!";
641 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
642 PublicInbox::Import::drop_unwanted_headers($new);
643 print $bh $new->as_string or die "print: $!";
644 close $bh or die "close: $!";
645 my $cmd = [ qw(diff -u), $an, $bn ];
646 print STDERR "# MID conflict <$mid>\n";
647 my $pid = spawn($cmd, undef, { 1 => 2 });
648 defined $pid or die "diff failed to spawn $!";
649 waitpid($pid, 0) == $pid or die "diff did not finish";
654 my ($self, $smsg) = @_;
655 if (my $im = $self->{im}) {
656 my $msg = $im->cat_blob($smsg->{blob});
659 # older message, should be in alternates
660 my $ibx = $self->{-inbox};
661 $ibx->msg_by_smsg($smsg);
664 sub lookup_content ($$$) {
665 my ($self, $mime, $mid) = @_;
666 my $over = $self->{over};
667 my $cids = content_ids($mime);
669 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
670 my $msg = get_blob($self, $smsg);
671 if (!defined($msg)) {
672 warn "broken smsg for $mid\n";
675 my $cur = PublicInbox::MIME->new($msg);
676 if (content_matches($cids, $cur)) {
677 $smsg->{mime} = $cur;
682 # XXX DEBUG_DIFF is experimental and may be removed
683 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
690 my $fh = delete $self->{reindex_pipe};
692 if (my $parts = $self->{idx_parts}) {
693 $_->atfork_child foreach @$parts;
695 if (my $im = $self->{im}) {
698 die "unexpected mm" if $self->{mm};
699 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
703 sub mark_deleted ($$$$) {
704 my ($self, $sync, $git, $oid) = @_;
705 my $msgref = $git->cat_file($oid);
706 my $mime = PublicInbox::MIME->new($$msgref);
707 my $mids = mids($mime->header_obj);
708 my $cid = content_id($mime);
709 foreach my $mid (@$mids) {
710 $sync->{D}->{"$mid\0$cid"} = $oid;
714 sub reindex_oid ($$$$) {
715 my ($self, $sync, $git, $oid) = @_;
717 my $msgref = $git->cat_file($oid, \$len);
718 my $mime = PublicInbox::MIME->new($$msgref);
719 my $mids = mids($mime->header_obj);
720 my $cid = content_id($mime);
722 # get the NNTP article number we used before, highest number wins
723 # and gets deleted from sync->{mm_tmp};
727 foreach my $mid (@$mids) {
728 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
729 my $n = $sync->{mm_tmp}->num_for($mid);
730 if (defined $n && $n > $num) {
733 $self->{mm}->mid_set($num, $mid0);
736 if (!defined($mid0) && !$del) {
737 $num = $sync->{regen}--;
738 die "BUG: ran out of article numbers\n" if $num <= 0;
739 my $mm = $self->{mm};
740 foreach my $mid (reverse @$mids) {
741 if ($mm->mid_set($num, $mid) == 1) {
746 if (!defined($mid0)) {
747 my $id = '<' . join('> <', @$mids) . '>';
748 warn "Message-ID $id unusable for $num\n";
749 foreach my $mid (@$mids) {
750 defined(my $n = $mm->num_for($mid)) or next;
751 warn "#$n previously mapped for <$mid>\n";
756 if (!defined($mid0) || $del) {
757 if (!defined($mid0) && $del) { # expected for deletes
758 $num = $sync->{regen}--;
759 $self->{mm}->num_highwater($num) if !$sync->{reindex};
763 my $id = '<' . join('> <', @$mids) . '>';
765 warn "Skipping $id, no article number found\n";
766 if ($del && defined($mid0)) {
767 warn "$id was deleted $del " .
768 "time(s) but mapped to article #$num\n";
773 $sync->{mm_tmp}->mid_delete($mid0) or
774 die "failed to delete <$mid0> for article #$num\n";
776 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
777 my $nparts = $self->{partitions};
778 my $part = $num % $nparts;
779 my $idx = $self->idx_part($part);
780 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
781 my $n = $self->{transact_bytes} += $len;
783 if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
785 $sync->{mm_tmp}->atfork_prepare;
786 $self->done; # release lock
788 if (my $pr = $sync->{-opt}->{-progress}) {
789 my ($bn) = (split('/', $git->{git_dir}))[-1];
790 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
793 # allow -watch or -mda to write...
794 $self->idx_init; # reacquire lock
795 $sync->{mm_tmp}->atfork_parent;
799 # only update last_commit for $i on reindex iff newer than current
800 sub update_last_commit ($$$$) {
801 my ($self, $git, $i, $cmt) = @_;
802 my $last = last_commit_part($self, $i);
803 if (defined $last && is_ancestor($git, $last, $cmt)) {
804 my @cmd = (qw(rev-list --count), "$last..$cmt");
805 chomp(my $n = $git->qx(@cmd));
806 return if $n ne '' && $n == 0;
808 last_commit_part($self, $i, $cmt);
811 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
813 sub last_commits ($$) {
814 my ($self, $epoch_max) = @_;
816 for (my $i = $epoch_max; $i >= 0; $i--) {
817 $heads->[$i] = last_commit_part($self, $i);
822 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
824 # returns a revision range for git-log(1)
825 sub log_range ($$$$$) {
826 my ($self, $sync, $git, $i, $tip) = @_;
827 my $opt = $sync->{-opt};
828 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
829 my $cur = $sync->{ranges}->[$i] or do {
830 $pr->("$i.git indexing all of $tip") if $pr;
831 return $tip; # all of it
834 my $range = "$cur..$tip";
835 $pr->("$i.git checking contiguity... ") if $pr;
836 if (is_ancestor($git, $cur, $tip)) { # common case
837 $pr->("OK\n") if $pr;
838 my $n = $git->qx(qw(rev-list --count), $range);
841 $sync->{ranges}->[$i] = undef;
842 $pr->("$i.git has nothing new\n") if $pr;
843 return; # nothing to do
845 $pr->("$i.git has $n changes since $cur\n") if $pr;
847 $pr->("FAIL\n") if $pr;
849 discontiguous range: $range
850 Rewritten history? (in $git->{git_dir})
852 chomp(my $base = $git->qx('merge-base', $tip, $cur));
854 $range = "$base..$tip";
855 warn "found merge-base: $base\n"
858 warn "discarding history at $cur\n";
861 reindexing $git->{git_dir} starting at
864 $sync->{unindex_range}->{$i} = "$base..$cur";
869 sub sync_prepare ($$$) {
870 my ($self, $sync, $epoch_max) = @_;
871 my $pr = $sync->{-opt}->{-progress};
873 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
875 # reindex stops at the current heads and we later rerun index_sync
877 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
879 for (my $i = $epoch_max; $i >= 0; $i--) {
880 die 'BUG: already indexing!' if $self->{reindex_pipe};
881 my $git_dir = git_dir_n($self, $i);
882 -d $git_dir or next; # missing parts are fine
883 my $git = PublicInbox::Git->new($git_dir);
884 if ($reindex_heads) {
885 $head = $reindex_heads->[$i] or next;
887 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
889 next if $?; # new repo
890 my $range = log_range($self, $sync, $git, $i, $tip) or next;
891 $sync->{ranges}->[$i] = $range;
893 # can't use 'rev-list --count' if we use --diff-filter
894 $pr->("$i.git counting $range ... ") if $pr;
896 my $fh = $git->popen(qw(log --pretty=tformat:%H
897 --no-notes --no-color --no-renames
898 --diff-filter=AM), $range, '--', 'm');
900 $pr->("$n\n") if $pr;
903 # reindex should NOT see new commits anymore, if we do,
904 # it's a problem and we need to notice it via die()
905 my $pad = length($regen_max) + 1;
906 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
908 return -1 if $sync->{reindex};
909 $regen_max + $self->{mm}->num_highwater() || 0;
912 sub unindex_oid_remote ($$$) {
913 my ($self, $oid, $mid) = @_;
914 $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
915 $self->{over}->remove_oid($oid, $mid);
918 sub unindex_oid ($$$) {
919 my ($self, $git, $oid) = @_;
920 my $msgref = $git->cat_file($oid);
921 my $mime = PublicInbox::MIME->new($msgref);
922 my $mids = mids($mime->header_obj);
923 $mime = $msgref = undef;
924 my $over = $self->{over};
925 foreach my $mid (@$mids) {
928 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
929 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
932 my $n = scalar keys %gone;
935 warn "BUG: multiple articles linked to $oid\n",
936 join(',',sort keys %gone), "\n";
938 foreach my $num (keys %gone) {
939 $self->{unindexed}->{$_}++;
940 $self->{mm}->num_delete($num);
942 unindex_oid_remote($self, $oid, $mid);
946 my $x40 = qr/[a-f0-9]{40}/;
948 my ($self, $sync, $git, $unindex_range) = @_;
949 my $un = $self->{unindexed} ||= {}; # num => removal count
950 my $before = scalar keys %$un;
951 my @cmd = qw(log --raw -r
952 --no-notes --no-color --no-abbrev --no-renames);
953 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
955 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
956 unindex_oid($self, $git, $1);
958 delete $self->{reindex_pipe};
961 return unless $sync->{-opt}->{prune};
962 my $after = scalar keys %$un;
963 return if $before == $after;
965 # ensure any blob can not longer be accessed via dumb HTTP
966 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
967 qw(-c gc.reflogExpire=now gc --prune=all)]);
970 sub sync_ranges ($$$) {
971 my ($self, $sync, $epoch_max) = @_;
972 my $reindex = $sync->{reindex};
974 return last_commits($self, $epoch_max) unless $reindex;
975 return [] if ref($reindex) ne 'HASH';
977 my $ranges = $reindex->{from}; # arrayref;
978 if (ref($ranges) ne 'ARRAY') {
979 die 'BUG: $reindex->{from} not an ARRAY';
984 sub index_epoch ($$$) {
985 my ($self, $sync, $i) = @_;
987 my $git_dir = git_dir_n($self, $i);
988 die 'BUG: already reindexing!' if $self->{reindex_pipe};
989 -d $git_dir or return; # missing parts are fine
990 fill_alternates($self, $i);
991 my $git = PublicInbox::Git->new($git_dir);
992 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
993 unindex($self, $sync, $git, $unindex_range);
995 defined(my $range = $sync->{ranges}->[$i]) or return;
996 if (my $pr = $sync->{-opt}->{-progress}) {
997 $pr->("$i.git indexing $range\n");
1000 my @cmd = qw(log --raw -r --pretty=tformat:%H
1001 --no-notes --no-color --no-abbrev --no-renames);
1002 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1006 $self->{current_info} = "$i.git $_";
1007 if (/\A$x40$/o && !defined($cmt)) {
1009 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1010 reindex_oid($self, $sync, $git, $1);
1011 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1012 mark_deleted($self, $sync, $git, $1);
1016 delete $self->{reindex_pipe};
1017 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1020 # public, called by public-inbox-index
1022 my ($self, $opt) = @_;
1024 my $pr = $opt->{-progress};
1026 my $latest = git_dir_latest($self, \$epoch_max);
1027 return unless defined $latest;
1028 $self->idx_init($opt); # acquire lock
1030 mm_tmp => $self->{mm}->tmp_clone,
1031 D => {}, # "$mid\0$cid" => $oid
1032 unindex_range => {}, # EPOCH => oid_old..oid_new
1033 reindex => $opt->{reindex},
1036 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1037 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1039 # work backwards through history
1040 for (my $i = $epoch_max; $i >= 0; $i--) {
1041 index_epoch($self, $sync, $i);
1044 # unindex is required for leftovers if "deletes" affect messages
1045 # in a previous fetch+index window:
1046 if (my @leftovers = values %{delete $sync->{D}}) {
1047 my $git = $self->{-inbox}->git;
1048 unindex_oid($self, $git, $_) for @leftovers;
1052 if (my $pr = $sync->{-opt}->{-progress}) {
1053 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $sync->{nr}));
1056 # reindex does not pick up new changes, so we rerun w/o it:
1057 if ($opt->{reindex}) {
1060 delete @again{qw(reindex -skip_lock)};
1061 index_sync($self, \%again);