+ die "unexpected mm" if $self->{mm};
+ close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
+ $self->{bnote}->[1];
+}
+
+sub mark_deleted ($$$$) {
+ my ($self, $sync, $git, $oid) = @_;
+ my $msgref = $git->cat_file($oid);
+ my $mime = PublicInbox::MIME->new($$msgref);
+ my $mids = mids($mime->header_obj);
+ my $cid = content_id($mime);
+ foreach my $mid (@$mids) {
+ $sync->{D}->{"$mid\0$cid"} = $oid;
+ }
+}
+
+sub reindex_checkpoint ($$$) {
+ my ($self, $sync, $git) = @_;
+
+ $git->cleanup;
+ $sync->{mm_tmp}->atfork_prepare;
+ $self->done; # release lock
+
+ if (my $pr = $sync->{-opt}->{-progress}) {
+ my ($bn) = (split('/', $git->{git_dir}))[-1];
+ $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
+ }
+
+ # allow -watch or -mda to write...
+ $self->idx_init; # reacquire lock
+ $sync->{mm_tmp}->atfork_parent;
+}
+
+# only for a few odd messages with multiple Message-IDs
+sub reindex_oid_m ($$$$;$) {
+ my ($self, $sync, $git, $oid, $regen_num) = @_;
+ $self->{current_info} = "multi_mid $oid";
+ my ($num, $mid0, $len);
+ my $msgref = $git->cat_file($oid, \$len);
+ my $mime = PublicInbox::MIME->new($$msgref);
+ my $mids = mids($mime->header_obj);
+ my $cid = content_id($mime);
+ die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
+
+ for my $mid (reverse @$mids) {
+ delete($sync->{D}->{"$mid\0$cid"}) and
+ die "BUG: reindex_oid should handle <$mid> delete";
+ }
+ my $over = $self->{over};
+ for my $mid (reverse @$mids) {
+ ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
+ next unless defined $num;
+ if (defined($regen_num) && $regen_num != $num) {
+ die "BUG: regen(#$regen_num) != over(#$num)";
+ }
+ }
+ unless (defined($num)) {
+ for my $mid (reverse @$mids) {
+ # is this a number we got before?
+ my $n = $sync->{mm_tmp}->num_for($mid);
+ next unless defined $n;
+ next if defined($regen_num) && $regen_num != $n;
+ ($num, $mid0) = ($n, $mid);
+ last;
+ }
+ }
+ if (defined($num)) {
+ $sync->{mm_tmp}->num_delete($num);
+ } elsif (defined $regen_num) {
+ $num = $regen_num;
+ for my $mid (reverse @$mids) {
+ $self->{mm}->mid_set($num, $mid) == 1 or next;
+ $mid0 = $mid;
+ last;
+ }
+ unless (defined $mid0) {
+ warn "E: cannot regen #$num\n";
+ return;
+ }
+ } else { # fixup bugs in old mirrors on reindex
+ for my $mid (reverse @$mids) {
+ $num = $self->{mm}->mid_insert($mid);
+ next unless defined $num;
+ $mid0 = $mid;
+ last;
+ }
+ if (defined $mid0) {
+ if ($sync->{reindex}) {
+ warn "reindex added #$num <$mid0>\n";
+ }
+ } else {
+ warn "E: cannot find article #\n";
+ return;
+ }
+ }
+ $sync->{nr}++;
+ if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
+ reindex_checkpoint($self, $sync, $git);
+ }
+}
+
+sub check_unindexed ($$$) {
+ my ($self, $num, $mid0) = @_;
+ my $unindexed = $self->{unindexed} // {};
+ my $n = delete($unindexed->{$mid0});
+ defined $n or return;
+ if ($n != $num) {
+ die "BUG: unindexed $n != $num <$mid0>\n";
+ } else {
+ $self->{mm}->mid_set($num, $mid0);
+ }
+}
+
+# reuse Msgmap to store num => oid mapping (rather than num => mid)
+sub multi_mid_q_new () {
+ my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
+ my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
+ $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
+ # for Msgmap->DESTROY:
+ $multi_mid->{tmp_name} = $fn;
+ $multi_mid->{pid} = $$;
+ close $fh or die "failed to close $fn: $!";
+ $multi_mid
+}
+
+sub multi_mid_q_push ($$) {
+ my ($sync, $oid) = @_;
+ my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
+ if ($sync->{reindex}) { # no regen on reindex
+ $multi_mid->mid_insert($oid);
+ } else {
+ my $num = $sync->{regen}--;
+ die "BUG: ran out of article numbers" if $num <= 0;
+ $multi_mid->mid_set($num, $oid);
+ }
+}
+
+sub reindex_oid ($$$$) {
+ my ($self, $sync, $git, $oid) = @_;
+ my ($num, $mid0, $len);
+ my $msgref = $git->cat_file($oid, \$len);
+ return if $len == 0; # purged
+ my $mime = PublicInbox::MIME->new($$msgref);
+ my $mids = mids($mime->header_obj);
+ my $cid = content_id($mime);
+
+ if (scalar(@$mids) == 0) {
+ warn "E: $oid has no Message-ID, skipping\n";
+ return;
+ } elsif (scalar(@$mids) == 1) {
+ my $mid = $mids->[0];
+
+ # was the file previously marked as deleted?, skip if so
+ if (delete($sync->{D}->{"$mid\0$cid"})) {
+ if (!$sync->{reindex}) {
+ $num = $sync->{regen}--;
+ $self->{mm}->num_highwater($num);
+ }
+ return;
+ }
+
+ # is this a number we got before?
+ $num = $sync->{mm_tmp}->num_for($mid);
+ if (defined $num) {
+ $mid0 = $mid;
+ check_unindexed($self, $num, $mid0);
+ } else {
+ $num = $sync->{regen}--;
+ die "BUG: ran out of article numbers" if $num <= 0;
+ if ($self->{mm}->mid_set($num, $mid) != 1) {
+ warn "E: unable to assign $num => <$mid>\n";
+ return;
+ }
+ $mid0 = $mid;
+ }
+ } else { # multiple MIDs are a weird case:
+ my $del = 0;
+ for (@$mids) {
+ $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
+ }
+ if ($del) {
+ unindex_oid_remote($self, $oid, $_) for @$mids;
+ # do not delete from {mm_tmp}, since another
+ # single-MID message may use it.
+ } else { # handle them at the end:
+ multi_mid_q_push($sync, $oid);
+ }
+ return;
+ }
+ $sync->{mm_tmp}->mid_delete($mid0) or
+ die "failed to delete <$mid0> for article #$num\n";
+ $sync->{nr}++;
+ if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
+ reindex_checkpoint($self, $sync, $git);
+ }
+}
+
+# only update last_commit for $i on reindex iff newer than current
+sub update_last_commit ($$$$) {
+ my ($self, $git, $i, $cmt) = @_;
+ my $last = last_epoch_commit($self, $i);
+ if (defined $last && is_ancestor($git, $last, $cmt)) {
+ my @cmd = (qw(rev-list --count), "$last..$cmt");
+ chomp(my $n = $git->qx(@cmd));
+ return if $n ne '' && $n == 0;
+ }
+ last_epoch_commit($self, $i, $cmt);
+}
+
+sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
+
+sub last_commits ($$) {
+ my ($self, $epoch_max) = @_;
+ my $heads = [];
+ for (my $i = $epoch_max; $i >= 0; $i--) {
+ $heads->[$i] = last_epoch_commit($self, $i);
+ }
+ $heads;
+}
+
+*is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
+
+# returns a revision range for git-log(1)
+sub log_range ($$$$$) {
+ my ($self, $sync, $git, $i, $tip) = @_;
+ my $opt = $sync->{-opt};
+ my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
+ my $cur = $sync->{ranges}->[$i] or do {
+ $pr->("$i.git indexing all of $tip") if $pr;
+ return $tip; # all of it
+ };
+
+ # fast equality check to avoid (v)fork+execve overhead
+ if ($cur eq $tip) {
+ $sync->{ranges}->[$i] = undef;
+ return;
+ }
+
+ my $range = "$cur..$tip";
+ $pr->("$i.git checking contiguity... ") if $pr;
+ if (is_ancestor($git, $cur, $tip)) { # common case
+ $pr->("OK\n") if $pr;
+ my $n = $git->qx(qw(rev-list --count), $range);
+ chomp($n);
+ if ($n == 0) {
+ $sync->{ranges}->[$i] = undef;
+ $pr->("$i.git has nothing new\n") if $pr;
+ return; # nothing to do
+ }
+ $pr->("$i.git has $n changes since $cur\n") if $pr;
+ } else {
+ $pr->("FAIL\n") if $pr;
+ warn <<"";
+discontiguous range: $range
+Rewritten history? (in $git->{git_dir})
+
+ chomp(my $base = $git->qx('merge-base', $tip, $cur));
+ if ($base) {
+ $range = "$base..$tip";
+ warn "found merge-base: $base\n"
+ } else {
+ $range = $tip;
+ warn "discarding history at $cur\n";
+ }
+ warn <<"";
+reindexing $git->{git_dir} starting at
+$range
+
+ $sync->{unindex_range}->{$i} = "$base..$cur";
+ }
+ $range;
+}
+
+sub sync_prepare ($$$) {
+ my ($self, $sync, $epoch_max) = @_;
+ my $pr = $sync->{-opt}->{-progress};
+ my $regen_max = 0;
+ my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
+
+ # reindex stops at the current heads and we later rerun index_sync
+ # without {reindex}
+ my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
+
+ for (my $i = $epoch_max; $i >= 0; $i--) {
+ die 'BUG: already indexing!' if $self->{reindex_pipe};
+ my $git_dir = git_dir_n($self, $i);
+ -d $git_dir or next; # missing epochs are fine
+ my $git = PublicInbox::Git->new($git_dir);
+ if ($reindex_heads) {
+ $head = $reindex_heads->[$i] or next;
+ }
+ chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
+
+ next if $?; # new repo
+ my $range = log_range($self, $sync, $git, $i, $tip) or next;
+ $sync->{ranges}->[$i] = $range;
+
+ # can't use 'rev-list --count' if we use --diff-filter
+ $pr->("$i.git counting $range ... ") if $pr;
+ my $n = 0;
+ my $fh = $git->popen(qw(log --pretty=tformat:%H
+ --no-notes --no-color --no-renames
+ --diff-filter=AM), $range, '--', 'm');
+ ++$n while <$fh>;
+ close $fh or die "git log failed: \$?=$?";
+ $pr->("$n\n") if $pr;
+ $regen_max += $n;
+ }
+
+ return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
+
+ # reindex should NOT see new commits anymore, if we do,
+ # it's a problem and we need to notice it via die()
+ my $pad = length($regen_max) + 1;
+ $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
+ $sync->{nr} = 0;
+ return -1 if $sync->{reindex};
+ $regen_max + $self->{mm}->num_highwater() || 0;
+}
+
+sub unindex_oid_remote ($$$) {
+ my ($self, $oid, $mid) = @_;
+ $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
+ $self->{over}->remove_oid($oid, $mid);
+}
+
+sub unindex_oid ($$$;$) {
+ my ($self, $git, $oid, $unindexed) = @_;
+ my $mm = $self->{mm};
+ my $msgref = $git->cat_file($oid);
+ my $mime = PublicInbox::MIME->new($msgref);
+ my $mids = mids($mime->header_obj);
+ $mime = $msgref = undef;
+ my $over = $self->{over};
+ foreach my $mid (@$mids) {
+ my %gone;
+ my ($id, $prev);
+ while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
+ $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
+ 1; # continue
+ }
+ my $n = scalar keys %gone;
+ next unless $n;
+ if ($n > 1) {
+ warn "BUG: multiple articles linked to $oid\n",
+ join(',',sort keys %gone), "\n";
+ }
+ foreach my $num (keys %gone) {
+ if ($unindexed) {
+ my $mid0 = $mm->mid_for($num);
+ $unindexed->{$mid0} = $num;
+ }
+ $mm->num_delete($num);
+ }
+ unindex_oid_remote($self, $oid, $mid);
+ }
+}
+
+my $x40 = qr/[a-f0-9]{40}/;
+sub unindex ($$$$) {
+ my ($self, $sync, $git, $unindex_range) = @_;
+ my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
+ my $before = scalar keys %$unindexed;
+ # order does not matter, here:
+ my @cmd = qw(log --raw -r
+ --no-notes --no-color --no-abbrev --no-renames);
+ my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
+ while (<$fh>) {
+ /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
+ unindex_oid($self, $git, $1, $unindexed);
+ }
+ delete $self->{reindex_pipe};
+ close $fh or die "git log failed: \$?=$?";
+
+ return unless $sync->{-opt}->{prune};
+ my $after = scalar keys %$unindexed;
+ return if $before == $after;
+
+ # ensure any blob can not longer be accessed via dumb HTTP
+ PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
+ qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
+}
+
+sub sync_ranges ($$$) {
+ my ($self, $sync, $epoch_max) = @_;
+ my $reindex = $sync->{reindex};
+
+ return last_commits($self, $epoch_max) unless $reindex;
+ return [] if ref($reindex) ne 'HASH';
+
+ my $ranges = $reindex->{from}; # arrayref;
+ if (ref($ranges) ne 'ARRAY') {
+ die 'BUG: $reindex->{from} not an ARRAY';
+ }
+ $ranges;
+}
+
+sub index_epoch ($$$) {
+ my ($self, $sync, $i) = @_;
+
+ my $git_dir = git_dir_n($self, $i);
+ die 'BUG: already reindexing!' if $self->{reindex_pipe};
+ -d $git_dir or return; # missing epochs are fine
+ fill_alternates($self, $i);
+ my $git = PublicInbox::Git->new($git_dir);
+ if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
+ unindex($self, $sync, $git, $unindex_range);
+ }
+ defined(my $range = $sync->{ranges}->[$i]) or return;
+ if (my $pr = $sync->{-opt}->{-progress}) {
+ $pr->("$i.git indexing $range\n");
+ }
+
+ my @cmd = qw(log --raw -r --pretty=tformat:%H
+ --no-notes --no-color --no-abbrev --no-renames);
+ my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
+ my $cmt;
+ while (<$fh>) {
+ chomp;
+ $self->{current_info} = "$i.git $_";
+ if (/\A$x40$/o && !defined($cmt)) {
+ $cmt = $_;
+ } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
+ reindex_oid($self, $sync, $git, $1);
+ } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
+ mark_deleted($self, $sync, $git, $1);
+ }
+ }
+ close $fh or die "git log failed: \$?=$?";
+ delete $self->{reindex_pipe};
+ update_last_commit($self, $git, $i, $cmt) if defined $cmt;
+}
+
+# public, called by public-inbox-index
+sub index_sync {
+ my ($self, $opt) = @_;
+ $opt ||= {};
+ my $pr = $opt->{-progress};
+ my $epoch_max;
+ my $latest = git_dir_latest($self, \$epoch_max);
+ return unless defined $latest;
+ $self->idx_init($opt); # acquire lock
+ my $sync = {
+ D => {}, # "$mid\0$cid" => $oid
+ unindex_range => {}, # EPOCH => oid_old..oid_new
+ reindex => $opt->{reindex},
+ -opt => $opt
+ };
+ $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
+ $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
+
+ if ($sync->{regen}) {
+ # tmp_clone seems to fail if inside a transaction, so
+ # we rollback here (because we opened {mm} for reading)
+ # Note: we do NOT rely on DBI transactions for atomicity;
+ # only for batch performance.
+ $self->{mm}->{dbh}->rollback;
+ $self->{mm}->{dbh}->begin_work;
+ $sync->{mm_tmp} = $self->{mm}->tmp_clone;
+ }
+
+ # work backwards through history
+ for (my $i = $epoch_max; $i >= 0; $i--) {
+ index_epoch($self, $sync, $i);
+ }
+
+ # unindex is required for leftovers if "deletes" affect messages
+ # in a previous fetch+index window:
+ my $git;
+ if (my @leftovers = values %{delete $sync->{D}}) {
+ $git = $self->{-inbox}->git;
+ for my $oid (@leftovers) {
+ $self->{current_info} = "leftover $oid";
+ unindex_oid($self, $git, $oid);
+ }
+ }
+ if (my $multi_mid = delete $sync->{multi_mid}) {
+ $git //= $self->{-inbox}->git;
+ my ($min, $max) = $multi_mid->minmax;
+ if ($sync->{reindex}) {
+ # we may need to create new Message-IDs if mirrors
+ # were initially indexed with old versions
+ for (my $i = $max; $i >= $min; $i--) {
+ my $oid = $multi_mid->mid_for($i);
+ next unless defined $oid;
+ reindex_oid_m($self, $sync, $git, $oid);
+ }
+ } else { # regen on initial index
+ for my $num ($min..$max) {
+ my $oid = $multi_mid->mid_for($num);
+ next unless defined $oid;
+ reindex_oid_m($self, $sync, $git, $oid, $num);
+ }
+ }
+ }
+ $git->cleanup if $git;
+ $self->done;
+
+ if (my $nr = $sync->{nr}) {
+ my $pr = $sync->{-opt}->{-progress};
+ $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
+ }
+
+ # reindex does not pick up new changes, so we rerun w/o it:
+ if ($opt->{reindex}) {
+ my %again = %$opt;
+ $sync = undef;
+ delete @again{qw(reindex -skip_lock)};
+ index_sync($self, \%again);
+ }