]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
7ece6b014ff0f24f2f527da3a43565307c8faa4e
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018-2019 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3
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;
7 use strict;
8 use warnings;
9 use base qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
11 use PublicInbox::MIME;
12 use PublicInbox::Git;
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;
21 use IO::Handle;
22
23 # an estimate of the post-packed size to the raw uncompressed size
24 my $PACKING_FACTOR = 0.4;
25
26 # SATA storage lags behind what CPUs are capable of, so relying on
27 # nproc(1) can be misleading and having extra Xapian shards 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 shards
32 our $NPROC_MAX_DEFAULT = 4;
33
34 sub nproc_shards ($) {
35         my ($creat_opt) = @_;
36         if (ref($creat_opt) eq 'HASH') {
37                 if (defined(my $n = $creat_opt->{nproc})) {
38                         return $n
39                 }
40         }
41
42         my $n = $ENV{NPROC};
43         if (!$n) {
44                 chomp($n = `nproc 2>/dev/null`);
45                 # assume 2 cores if GNU nproc(1) is not available
46                 $n = 2 if !$n;
47                 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
48         }
49
50         # subtract for the main process and git-fast-import
51         $n -= 1;
52         $n < 1 ? 1 : $n;
53 }
54
55 sub count_shards ($) {
56         my ($self) = @_;
57         my $n = 0;
58         my $xpfx = $self->{xpfx};
59
60         # always load existing shards in case core count changes:
61         # Also, shard count may change while -watch is running
62         # due to "xcpdb --reshard"
63         if (-d $xpfx) {
64                 foreach my $shard (<$xpfx/*>) {
65                         -d $shard && $shard =~ m!/[0-9]+\z! or next;
66                         eval {
67                                 Search::Xapian::Database->new($shard)->close;
68                                 $n++;
69                         };
70                 }
71         }
72         $n;
73 }
74
75 sub new {
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->{inboxdir} or die "no inboxdir in inbox\n";
80         unless (-d $dir) {
81                 if ($creat) {
82                         require File::Path;
83                         File::Path::mkpath($dir);
84                 } else {
85                         die "$dir does not exist\n";
86                 }
87         }
88
89         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
90         $v2ibx->umask_prepare;
91
92         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
93         my $self = {
94                 -inbox => $v2ibx,
95                 im => undef, #  PublicInbox::Import
96                 parallel => 1,
97                 transact_bytes => 0,
98                 current_info => '',
99                 xpfx => $xpfx,
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
105         };
106         $self->{shards} = count_shards($self) || nproc_shards($creat);
107         bless $self, $class;
108 }
109
110 # public (for now?)
111 sub init_inbox {
112         my ($self, $parallel, $skip_epoch) = @_;
113         $self->{parallel} = $parallel;
114         $self->idx_init;
115         my $epoch_max = -1;
116         git_dir_latest($self, \$epoch_max);
117         if (defined $skip_epoch && $epoch_max == -1) {
118                 $epoch_max = $skip_epoch;
119         }
120         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
121         $self->done;
122 }
123
124 # returns undef on duplicate or spam
125 # mimics Import::add and wraps it for v2
126 sub add {
127         my ($self, $mime, $check_cb) = @_;
128         $self->{-inbox}->with_umask(sub {
129                 _add($self, $mime, $check_cb)
130         });
131 }
132
133 # indexes a message, returns true if checkpointing is needed
134 sub do_idx ($$$$$$$) {
135         my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
136         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
137         my $idx = idx_shard($self, $num % $self->{shards});
138         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
139         my $n = $self->{transact_bytes} += $len;
140         $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
141 }
142
143 sub _add {
144         my ($self, $mime, $check_cb) = @_;
145
146         # spam check:
147         if ($check_cb) {
148                 $mime = $check_cb->($mime) or return;
149         }
150
151         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
152         # as does SQLite 3.4.1+ (released in 2007-07-20), and
153         # Xapian 1.3.2+ (released 2015-03-15).
154         # For the most part, we can spawn git-fast-import without
155         # leaking FDs to it...
156         $self->idx_init;
157
158         my ($num, $mid0) = v2_num_for($self, $mime);
159         defined $num or return; # duplicate
160         defined $mid0 or die "BUG: $mid0 undefined\n";
161         my $im = $self->importer;
162         my $cmt = $im->add($mime);
163         $cmt = $im->get_mark($cmt);
164         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
165
166         my ($oid, $len, $msgref) = @{$im->{last_object}};
167         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
168                 $self->checkpoint;
169         }
170
171         $cmt;
172 }
173
174 sub v2_num_for {
175         my ($self, $mime) = @_;
176         my $mids = mids($mime->header_obj);
177         if (@$mids) {
178                 my $mid = $mids->[0];
179                 my $num = $self->{mm}->mid_insert($mid);
180                 if (defined $num) { # common case
181                         return ($num, $mid);
182                 }
183
184                 # crap, Message-ID is already known, hope somebody just resent:
185                 foreach my $m (@$mids) {
186                         # read-only lookup now safe to do after above barrier
187                         my $existing = lookup_content($self, $mime, $m);
188                         # easy, don't store duplicates
189                         # note: do not add more diagnostic info here since
190                         # it gets noisy on public-inbox-watch restarts
191                         return () if $existing;
192                 }
193
194                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
195                 # or NNTP article number), use that article number if it's
196                 # not in Over.
197                 my $altid = $self->{-inbox}->{altid};
198                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
199                         my $num = $self->{mm}->num_for($mid);
200
201                         if (defined $num && !$self->{over}->get_art($num)) {
202                                 return ($num, $mid);
203                         }
204                 }
205
206                 # very unlikely:
207                 warn "<$mid> reused for mismatched content\n";
208
209                 # try the rest of the mids
210                 for(my $i = $#$mids; $i >= 1; $i--) {
211                         my $m = $mids->[$i];
212                         $num = $self->{mm}->mid_insert($m);
213                         if (defined $num) {
214                                 warn "alternative <$m> for <$mid> found\n";
215                                 return ($num, $m);
216                         }
217                 }
218         }
219         # none of the existing Message-IDs are good, generate a new one:
220         v2_num_for_harder($self, $mime);
221 }
222
223 sub v2_num_for_harder {
224         my ($self, $mime) = @_;
225
226         my $hdr = $mime->header_obj;
227         my $dig = content_digest($mime);
228         my $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);
236
237                 # fall back to a random Message-ID and give up determinism:
238                 until (defined($num)) {
239                         $dig->add(rand);
240                         $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
241                         warn "using random Message-ID <$mid0> as fallback\n";
242                         $num = $self->{mm}->mid_insert($mid0);
243                 }
244         }
245         PublicInbox::Import::append_mid($hdr, $mid0);
246         ($num, $mid0);
247 }
248
249 sub idx_shard {
250         my ($self, $shard_i) = @_;
251         $self->{idx_shards}->[$shard_i];
252 }
253
254 # idempotent
255 sub idx_init {
256         my ($self, $opt) = @_;
257         return if $self->{idx_shards};
258         my $ibx = $self->{-inbox};
259
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));
264
265         my $indexlevel = $ibx->{indexlevel};
266         if ($indexlevel && $indexlevel eq 'basic') {
267                 $self->{parallel} = 0;
268         }
269
270         if ($self->{parallel}) {
271                 pipe(my ($r, $w)) or die "pipe failed: $!";
272                 # pipe for barrier notifications doesn't need to be big,
273                 # 1031: F_SETPIPE_SZ
274                 fcntl($w, 1031, 4096) if $^O eq 'linux';
275                 $self->{bnote} = [ $r, $w ];
276                 $w->autoflush(1);
277         }
278
279         my $over = $self->{over};
280         $ibx->umask_prepare;
281         $ibx->with_umask(sub {
282                 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
283                 $over->create;
284
285                 # xcpdb can change shard count while -watch is idle
286                 my $nshards = count_shards($self);
287                 if ($nshards && $nshards != $self->{shards}) {
288                         $self->{shards} = $nshards;
289                 }
290
291                 # need to create all shards before initializing msgmap FD
292                 my $max = $self->{shards} - 1;
293
294                 # idx_shards must be visible to all forked processes
295                 my $idx = $self->{idx_shards} = [];
296                 for my $i (0..$max) {
297                         push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
298                 }
299
300                 # Now that all subprocesses are up, we can open the FDs
301                 # for SQLite:
302                 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
303                         "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
304                 $mm->{dbh}->begin_work;
305         });
306 }
307
308 # returns an array mapping [ epoch => latest_commit ]
309 # latest_commit may be undef if nothing was done to that epoch
310 # $replace_map = { $object_id => $strref, ... }
311 sub _replace_oids ($$$) {
312         my ($self, $mime, $replace_map) = @_;
313         $self->done;
314         my $pfx = "$self->{-inbox}->{inboxdir}/git";
315         my $rewrites = []; # epoch => commit
316         my $max = $self->{epoch_max};
317
318         unless (defined($max)) {
319                 defined(my $latest = git_dir_latest($self, \$max)) or return;
320                 $self->{epoch_max} = $max;
321         }
322
323         foreach my $i (0..$max) {
324                 my $git_dir = "$pfx/$i.git";
325                 -d $git_dir or next;
326                 my $git = PublicInbox::Git->new($git_dir);
327                 my $im = $self->import_init($git, 0, 1);
328                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
329                 $im->done;
330         }
331         $rewrites;
332 }
333
334 sub content_ids ($) {
335         my ($mime) = @_;
336         my @cids = ( content_id($mime) );
337
338         # Email::MIME->as_string doesn't always round-trip, so we may
339         # use a second content_id
340         my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
341         push @cids, $rt if $cids[0] ne $rt;
342         \@cids;
343 }
344
345 sub content_matches ($$) {
346         my ($cids, $existing) = @_;
347         my $cid = content_id($existing);
348         foreach (@$cids) {
349                 return 1 if $_ eq $cid
350         }
351         0
352 }
353
354 # used for removing or replacing (purging)
355 sub rewrite_internal ($$;$$$) {
356         my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
357         $self->idx_init;
358         my ($im, $need_reindex, $replace_map);
359         if ($sref) {
360                 $replace_map = {}; # oid => sref
361                 $need_reindex = [] if $new_mime;
362         } else {
363                 $im = $self->importer;
364         }
365         my $over = $self->{over};
366         my $cids = content_ids($old_mime);
367         my $removed;
368         my $mids = mids($old_mime->header_obj);
369
370         # We avoid introducing new blobs into git since the raw content
371         # can be slightly different, so we do not need the user-supplied
372         # message now that we have the mids and content_id
373         $old_mime = undef;
374         my $mark;
375
376         foreach my $mid (@$mids) {
377                 my %gone; # num => [ smsg, raw ]
378                 my ($id, $prev);
379                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
380                         my $msg = get_blob($self, $smsg);
381                         if (!defined($msg)) {
382                                 warn "broken smsg for $mid\n";
383                                 next; # continue
384                         }
385                         my $orig = $$msg;
386                         my $cur = PublicInbox::MIME->new($msg);
387                         if (content_matches($cids, $cur)) {
388                                 $smsg->{mime} = $cur;
389                                 $gone{$smsg->{num}} = [ $smsg, \$orig ];
390                         }
391                 }
392                 my $n = scalar keys %gone;
393                 next unless $n;
394                 if ($n > 1) {
395                         warn "BUG: multiple articles linked to <$mid>\n",
396                                 join(',', sort keys %gone), "\n";
397                 }
398                 foreach my $num (keys %gone) {
399                         my ($smsg, $orig) = @{$gone{$num}};
400                         # $removed should only be set once assuming
401                         # no bugs in our deduplication code:
402                         $removed = $smsg;
403                         my $oid = $smsg->{blob};
404                         if ($replace_map) {
405                                 $replace_map->{$oid} = $sref;
406                         } else {
407                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
408                         }
409                         $orig = undef;
410                         if ($need_reindex) { # ->replace
411                                 push @$need_reindex, $smsg;
412                         } else { # ->purge or ->remove
413                                 $self->{mm}->num_delete($num);
414                         }
415                         unindex_oid_remote($self, $oid, $mid);
416                 }
417         }
418
419         if (defined $mark) {
420                 my $cmt = $im->get_mark($mark);
421                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
422         }
423         if ($replace_map && scalar keys %$replace_map) {
424                 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
425                 return { rewrites => $rewrites, need_reindex => $need_reindex };
426         }
427         $removed;
428 }
429
430 # public
431 sub remove {
432         my ($self, $mime, $cmt_msg) = @_;
433         $self->{-inbox}->with_umask(sub {
434                 rewrite_internal($self, $mime, $cmt_msg);
435         });
436 }
437
438 sub _replace ($$;$$) {
439         my ($self, $old_mime, $new_mime, $sref) = @_;
440         my $rewritten = $self->{-inbox}->with_umask(sub {
441                 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
442         }) or return;
443
444         my $rewrites = $rewritten->{rewrites};
445         # ->done is called if there are rewrites since we gc+prune from git
446         $self->idx_init if @$rewrites;
447
448         for my $i (0..$#$rewrites) {
449                 defined(my $cmt = $rewrites->[$i]) or next;
450                 $self->{last_commit}->[$i] = $cmt;
451         }
452         $rewritten;
453 }
454
455 # public
456 sub purge {
457         my ($self, $mime) = @_;
458         my $rewritten = _replace($self, $mime, undef, \'') or return;
459         $rewritten->{rewrites}
460 }
461
462 # returns the git object_id of $fh, does not write the object to FS
463 sub git_hash_raw ($$) {
464         my ($self, $raw) = @_;
465         # grab the expected OID we have to reindex:
466         open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
467         $tmp_fh->autoflush(1);
468         print $tmp_fh $$raw or die "print \$tmp_fh: $!";
469         sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
470
471         my ($r, $w);
472         pipe($r, $w) or die "failed to create pipe: $!";
473         my $rdr = { 0 => fileno($tmp_fh), 1 => fileno($w) };
474         my $git_dir = $self->{-inbox}->git->{git_dir};
475         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
476         my $pid = spawn($cmd, undef, $rdr);
477         close $w;
478         local $/ = "\n";
479         chomp(my $oid = <$r>);
480         waitpid($pid, 0) == $pid or die "git hash-object did not finish";
481         die "git hash-object failed: $?" if $?;
482         $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
483         $oid;
484 }
485
486 sub _check_mids_match ($$$) {
487         my ($old_list, $new_list, $hdrs) = @_;
488         my %old_mids = map { $_ => 1 } @$old_list;
489         my %new_mids = map { $_ => 1 } @$new_list;
490         my @old = keys %old_mids;
491         my @new = keys %new_mids;
492         my $err = "$hdrs may not be changed when replacing\n";
493         die $err if scalar(@old) != scalar(@new);
494         delete @new_mids{@old};
495         delete @old_mids{@new};
496         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
497 }
498
499 # Changing Message-IDs or References with ->replace isn't supported.
500 # The rules for dealing with messages with multiple or conflicting
501 # Message-IDs are pretty complex and rethreading hasn't been fully
502 # implemented, yet.
503 sub check_mids_match ($$) {
504         my ($old_mime, $new_mime) = @_;
505         my $old = $old_mime->header_obj;
506         my $new = $new_mime->header_obj;
507         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
508         _check_mids_match(references($old), references($new),
509                         'References/In-Reply-To');
510 }
511
512 # public
513 sub replace ($$$) {
514         my ($self, $old_mime, $new_mime) = @_;
515
516         check_mids_match($old_mime, $new_mime);
517
518         # mutt will always add Content-Length:, Status:, Lines: when editing
519         PublicInbox::Import::drop_unwanted_headers($new_mime);
520
521         my $raw = $new_mime->as_string;
522         my $expect_oid = git_hash_raw($self, \$raw);
523         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
524         my $need_reindex = $rewritten->{need_reindex};
525
526         # just in case we have bugs in deduplication code:
527         my $n = scalar(@$need_reindex);
528         if ($n > 1) {
529                 my $list = join(', ', map {
530                                         "$_->{num}: <$_->{mid}>"
531                                 } @$need_reindex);
532                 warn <<"";
533 W: rewritten $n messages matching content of original message (expected: 1).
534 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
535 W: $list
536
537         }
538
539         # make sure we really got the OID:
540         my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
541         $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
542
543         # don't leak FDs to Xapian:
544         $self->{-inbox}->git->cleanup;
545
546         # reindex modified messages:
547         for my $smsg (@$need_reindex) {
548                 my $num = $smsg->{num};
549                 my $mid0 = $smsg->{mid};
550                 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
551         }
552         $rewritten->{rewrites};
553 }
554
555 sub last_epoch_commit ($$;$) {
556         my ($self, $i, $cmt) = @_;
557         my $v = PublicInbox::Search::SCHEMA_VERSION();
558         $self->{mm}->last_commit_xap($v, $i, $cmt);
559 }
560
561 sub set_last_commits ($) {
562         my ($self) = @_;
563         defined(my $epoch_max = $self->{epoch_max}) or return;
564         my $last_commit = $self->{last_commit};
565         foreach my $i (0..$epoch_max) {
566                 defined(my $cmt = $last_commit->[$i]) or next;
567                 $last_commit->[$i] = undef;
568                 last_epoch_commit($self, $i, $cmt);
569         }
570 }
571
572 sub barrier_init {
573         my ($self, $n) = @_;
574         $self->{bnote} or return;
575         --$n;
576         my $barrier = { map { $_ => 1 } (0..$n) };
577 }
578
579 sub barrier_wait {
580         my ($self, $barrier) = @_;
581         my $bnote = $self->{bnote} or return;
582         my $r = $bnote->[0];
583         while (scalar keys %$barrier) {
584                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
585                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
586                 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
587         }
588 }
589
590 # public
591 sub checkpoint ($;$) {
592         my ($self, $wait) = @_;
593
594         if (my $im = $self->{im}) {
595                 if ($wait) {
596                         $im->barrier;
597                 } else {
598                         $im->checkpoint;
599                 }
600         }
601         my $shards = $self->{idx_shards};
602         if ($shards) {
603                 my $dbh = $self->{mm}->{dbh};
604
605                 # SQLite msgmap data is second in importance
606                 $dbh->commit;
607
608                 # SQLite overview is third
609                 $self->{over}->commit_lazy;
610
611                 # Now deal with Xapian
612                 if ($wait) {
613                         my $barrier = $self->barrier_init(scalar @$shards);
614
615                         # each shard needs to issue a barrier command
616                         $_->remote_barrier for @$shards;
617
618                         # wait for each Xapian shard
619                         $self->barrier_wait($barrier);
620                 } else {
621                         $_->remote_commit for @$shards;
622                 }
623
624                 # last_commit is special, don't commit these until
625                 # remote shards are done:
626                 $dbh->begin_work;
627                 set_last_commits($self);
628                 $dbh->commit;
629
630                 $dbh->begin_work;
631         }
632         $self->{transact_bytes} = 0;
633 }
634
635 # issue a write barrier to ensure all data is visible to other processes
636 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
637 # public
638 sub barrier { checkpoint($_[0], 1) };
639
640 # public
641 sub done {
642         my ($self) = @_;
643         my $im = delete $self->{im};
644         $im->done if $im; # PublicInbox::Import::done
645         checkpoint($self);
646         my $mm = delete $self->{mm};
647         $mm->{dbh}->commit if $mm;
648         my $shards = delete $self->{idx_shards};
649         if ($shards) {
650                 $_->remote_close for @$shards;
651         }
652         $self->{over}->disconnect;
653         delete $self->{bnote};
654         $self->{transact_bytes} = 0;
655         $self->lock_release if $shards;
656         $self->{-inbox}->git->cleanup;
657 }
658
659 sub fill_alternates ($$) {
660         my ($self, $epoch) = @_;
661
662         my $pfx = "$self->{-inbox}->{inboxdir}/git";
663         my $all = "$self->{-inbox}->{inboxdir}/all.git";
664
665         unless (-d $all) {
666                 PublicInbox::Import::init_bare($all);
667         }
668         my $alt = "$all/objects/info/alternates";
669         my %alts;
670         my @add;
671         if (-e $alt) {
672                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
673                 %alts = map { chomp; $_ => 1 } (<$fh>);
674         }
675         foreach my $i (0..$epoch) {
676                 my $dir = "../../git/$i.git/objects";
677                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
678         }
679         return unless @add;
680         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
681         foreach my $dir (@add) {
682                 print $fh "$dir\n" or die "print >> $alt: $!\n";
683         }
684         close $fh or die "close $alt: $!\n";
685 }
686
687 sub git_init {
688         my ($self, $epoch) = @_;
689         my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
690         my @cmd = (qw(git init --bare -q), $git_dir);
691         PublicInbox::Import::run_die(\@cmd);
692         @cmd = (qw/git config/, "--file=$git_dir/config",
693                         'include.path', '../../all.git/config');
694         PublicInbox::Import::run_die(\@cmd);
695         fill_alternates($self, $epoch);
696         $git_dir
697 }
698
699 sub git_dir_latest {
700         my ($self, $max) = @_;
701         $$max = -1;
702         my $pfx = "$self->{-inbox}->{inboxdir}/git";
703         return unless -d $pfx;
704         my $latest;
705         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
706         while (defined(my $git_dir = readdir($dh))) {
707                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
708                 if ($1 > $$max) {
709                         $$max = $1;
710                         $latest = "$pfx/$git_dir";
711                 }
712         }
713         $latest;
714 }
715
716 sub importer {
717         my ($self) = @_;
718         my $im = $self->{im};
719         if ($im) {
720                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
721                         return $im;
722                 } else {
723                         $self->{im} = undef;
724                         $im->done;
725                         $im = undef;
726                         $self->checkpoint;
727                         my $git_dir = $self->git_init(++$self->{epoch_max});
728                         my $git = PublicInbox::Git->new($git_dir);
729                         return $self->import_init($git, 0);
730                 }
731         }
732         my $epoch = 0;
733         my $max;
734         my $latest = git_dir_latest($self, \$max);
735         if (defined $latest) {
736                 my $git = PublicInbox::Git->new($latest);
737                 my $packed_bytes = $git->packed_bytes;
738                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
739
740                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
741                         $epoch = $max + 1;
742                 } else {
743                         $self->{epoch_max} = $max;
744                         return $self->import_init($git, $packed_bytes);
745                 }
746         }
747         $self->{epoch_max} = $epoch;
748         $latest = $self->git_init($epoch);
749         $self->import_init(PublicInbox::Git->new($latest), 0);
750 }
751
752 sub import_init {
753         my ($self, $git, $packed_bytes, $tmp) = @_;
754         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
755         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
756         $im->{want_object_info} = 1;
757         $im->{lock_path} = undef;
758         $im->{path_type} = 'v2';
759         $self->{im} = $im unless $tmp;
760         $im;
761 }
762
763 # XXX experimental
764 sub diff ($$$) {
765         my ($mid, $cur, $new) = @_;
766         use File::Temp qw(tempfile);
767
768         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
769         print $ah $cur->as_string or die "print: $!";
770         close $ah or die "close: $!";
771         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
772         PublicInbox::Import::drop_unwanted_headers($new);
773         print $bh $new->as_string or die "print: $!";
774         close $bh or die "close: $!";
775         my $cmd = [ qw(diff -u), $an, $bn ];
776         print STDERR "# MID conflict <$mid>\n";
777         my $pid = spawn($cmd, undef, { 1 => 2 });
778         defined $pid or die "diff failed to spawn $!";
779         waitpid($pid, 0) == $pid or die "diff did not finish";
780         unlink($an, $bn);
781 }
782
783 sub get_blob ($$) {
784         my ($self, $smsg) = @_;
785         if (my $im = $self->{im}) {
786                 my $msg = $im->cat_blob($smsg->{blob});
787                 return $msg if $msg;
788         }
789         # older message, should be in alternates
790         my $ibx = $self->{-inbox};
791         $ibx->msg_by_smsg($smsg);
792 }
793
794 sub lookup_content ($$$) {
795         my ($self, $mime, $mid) = @_;
796         my $over = $self->{over};
797         my $cids = content_ids($mime);
798         my ($id, $prev);
799         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
800                 my $msg = get_blob($self, $smsg);
801                 if (!defined($msg)) {
802                         warn "broken smsg for $mid\n";
803                         next;
804                 }
805                 my $cur = PublicInbox::MIME->new($msg);
806                 if (content_matches($cids, $cur)) {
807                         $smsg->{mime} = $cur;
808                         return $smsg;
809                 }
810
811
812                 # XXX DEBUG_DIFF is experimental and may be removed
813                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
814         }
815         undef;
816 }
817
818 sub atfork_child {
819         my ($self) = @_;
820         my $fh = delete $self->{reindex_pipe};
821         close $fh if $fh;
822         if (my $shards = $self->{idx_shards}) {
823                 $_->atfork_child foreach @$shards;
824         }
825         if (my $im = $self->{im}) {
826                 $im->atfork_child;
827         }
828         die "unexpected mm" if $self->{mm};
829         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
830         $self->{bnote}->[1];
831 }
832
833 sub mark_deleted ($$$$) {
834         my ($self, $sync, $git, $oid) = @_;
835         my $msgref = $git->cat_file($oid);
836         my $mime = PublicInbox::MIME->new($$msgref);
837         my $mids = mids($mime->header_obj);
838         my $cid = content_id($mime);
839         foreach my $mid (@$mids) {
840                 $sync->{D}->{"$mid\0$cid"} = $oid;
841         }
842 }
843
844 sub reindex_checkpoint ($$$) {
845         my ($self, $sync, $git) = @_;
846
847         $git->cleanup;
848         $sync->{mm_tmp}->atfork_prepare;
849         $self->done; # release lock
850
851         if (my $pr = $sync->{-opt}->{-progress}) {
852                 my ($bn) = (split('/', $git->{git_dir}))[-1];
853                 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
854         }
855
856         # allow -watch or -mda to write...
857         $self->idx_init; # reacquire lock
858         $sync->{mm_tmp}->atfork_parent;
859 }
860
861 # only for a few odd messages with multiple Message-IDs
862 sub reindex_oid_m ($$$$) {
863         my ($self, $sync, $git, $oid) = @_;
864         my ($num, $mid0, $len);
865         my $msgref = $git->cat_file($oid, \$len);
866         my $mime = PublicInbox::MIME->new($$msgref);
867         my $mids = mids($mime->header_obj);
868         my $cid = content_id($mime);
869         die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
870
871         for my $mid (reverse @$mids) {
872                 delete($sync->{D}->{"$mid\0$cid"}) and
873                         die "BUG: reindex_oid should handle <$mid> delete";
874         }
875         for my $mid (reverse @$mids) {
876                 ($num, $mid0) = $self->{over}->num_mid0_for_oid($oid, $mid);
877                 last if defined $num;
878         }
879         unless (defined($num)) {
880                 for my $mid (reverse @$mids) {
881                         # is this a number we got before?
882                         $num = $sync->{mm_tmp}->num_for($mid);
883                         next unless defined $num;
884                         $mid0 = $mid;
885                         last;
886                 }
887         }
888         if (defined($num)) {
889                 $sync->{mm_tmp}->num_delete($num);
890         } else {
891                 $num = $sync->{regen}--;
892                 if ($num <= 0) {
893                         # fixup bugs in old mirrors on reindex
894                         for my $mid (reverse @$mids) {
895                                 $num = $self->{mm}->mid_insert($mid);
896                                 next unless defined $num;
897                                 $mid0 = $mid;
898                                 last;
899                         }
900                         if (defined $mid0) {
901                                 if ($sync->{reindex}) {
902                                         warn "reindex added #$num <$mid0>\n";
903                                 }
904                         } else {
905                                 warn "E: cannot find article #\n";
906                                 return;
907                         }
908                 } else { # $num > 0, use the new article number
909                         for my $mid (reverse @$mids) {
910                                 $self->{mm}->mid_set($num, $mid) == 1 or next;
911                                 $mid0 = $mid;
912                                 last;
913                         }
914                         unless (defined $mid0) {
915                                 warn "E: cannot regen #$num\n";
916                                 return;
917                         }
918                 }
919         }
920         $sync->{nr}++;
921         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
922                 reindex_checkpoint($self, $sync, $git);
923         }
924 }
925
926 sub check_unindexed ($$$) {
927         my ($self, $num, $mid0) = @_;
928         my $unindexed = $self->{unindexed} // {};
929         my $n = delete($unindexed->{$mid0});
930         defined $n or return;
931         if ($n != $num) {
932                 die "BUG: unindexed $n != $num <$mid0>\n";
933         } else {
934                 $self->{mm}->mid_set($num, $mid0);
935         }
936 }
937
938 sub reindex_oid ($$$$) {
939         my ($self, $sync, $git, $oid) = @_;
940         my ($num, $mid0, $len);
941         my $msgref = $git->cat_file($oid, \$len);
942         return if $len == 0; # purged
943         my $mime = PublicInbox::MIME->new($$msgref);
944         my $mids = mids($mime->header_obj);
945         my $cid = content_id($mime);
946
947         if (scalar(@$mids) == 0) {
948                 warn "E: $oid has no Message-ID, skipping\n";
949                 return;
950         } elsif (scalar(@$mids) == 1) {
951                 my $mid = $mids->[0];
952
953                 # was the file previously marked as deleted?, skip if so
954                 if (delete($sync->{D}->{"$mid\0$cid"})) {
955                         if (!$sync->{reindex}) {
956                                 $num = $sync->{regen}--;
957                                 $self->{mm}->num_highwater($num);
958                         }
959                         return;
960                 }
961
962                 # is this a number we got before?
963                 $num = $sync->{mm_tmp}->num_for($mid);
964                 if (defined $num) {
965                         $mid0 = $mid;
966                         check_unindexed($self, $num, $mid0);
967                 } else {
968                         $num = $sync->{regen}--;
969                         die "BUG: ran out of article numbers\n" if $num <= 0;
970                         if ($self->{mm}->mid_set($num, $mid) != 1) {
971                                 warn "E: unable to assign $num => <$mid>\n";
972                                 return;
973                         }
974                         $mid0 = $mid;
975                 }
976         } else { # multiple MIDs are a weird case:
977                 my $del = 0;
978                 for (@$mids) {
979                         $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
980                 }
981                 if ($del) {
982                         unindex_oid_remote($self, $oid, $_) for @$mids;
983                         # do not delete from {mm_tmp}, since another
984                         # single-MID message may use it.
985                 } else { # handle them at the end:
986                         push @{$sync->{multi_mid} //= []}, $oid;
987                 }
988                 return;
989         }
990         $sync->{mm_tmp}->mid_delete($mid0) or
991                 die "failed to delete <$mid0> for article #$num\n";
992         $sync->{nr}++;
993         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
994                 reindex_checkpoint($self, $sync, $git);
995         }
996 }
997
998 # only update last_commit for $i on reindex iff newer than current
999 sub update_last_commit ($$$$) {
1000         my ($self, $git, $i, $cmt) = @_;
1001         my $last = last_epoch_commit($self, $i);
1002         if (defined $last && is_ancestor($git, $last, $cmt)) {
1003                 my @cmd = (qw(rev-list --count), "$last..$cmt");
1004                 chomp(my $n = $git->qx(@cmd));
1005                 return if $n ne '' && $n == 0;
1006         }
1007         last_epoch_commit($self, $i, $cmt);
1008 }
1009
1010 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1011
1012 sub last_commits ($$) {
1013         my ($self, $epoch_max) = @_;
1014         my $heads = [];
1015         for (my $i = $epoch_max; $i >= 0; $i--) {
1016                 $heads->[$i] = last_epoch_commit($self, $i);
1017         }
1018         $heads;
1019 }
1020
1021 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1022
1023 # returns a revision range for git-log(1)
1024 sub log_range ($$$$$) {
1025         my ($self, $sync, $git, $i, $tip) = @_;
1026         my $opt = $sync->{-opt};
1027         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1028         my $cur = $sync->{ranges}->[$i] or do {
1029                 $pr->("$i.git indexing all of $tip") if $pr;
1030                 return $tip; # all of it
1031         };
1032
1033         # fast equality check to avoid (v)fork+execve overhead
1034         if ($cur eq $tip) {
1035                 $sync->{ranges}->[$i] = undef;
1036                 return;
1037         }
1038
1039         my $range = "$cur..$tip";
1040         $pr->("$i.git checking contiguity... ") if $pr;
1041         if (is_ancestor($git, $cur, $tip)) { # common case
1042                 $pr->("OK\n") if $pr;
1043                 my $n = $git->qx(qw(rev-list --count), $range);
1044                 chomp($n);
1045                 if ($n == 0) {
1046                         $sync->{ranges}->[$i] = undef;
1047                         $pr->("$i.git has nothing new\n") if $pr;
1048                         return; # nothing to do
1049                 }
1050                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1051         } else {
1052                 $pr->("FAIL\n") if $pr;
1053                 warn <<"";
1054 discontiguous range: $range
1055 Rewritten history? (in $git->{git_dir})
1056
1057                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1058                 if ($base) {
1059                         $range = "$base..$tip";
1060                         warn "found merge-base: $base\n"
1061                 } else {
1062                         $range = $tip;
1063                         warn "discarding history at $cur\n";
1064                 }
1065                 warn <<"";
1066 reindexing $git->{git_dir} starting at
1067 $range
1068
1069                 $sync->{unindex_range}->{$i} = "$base..$cur";
1070         }
1071         $range;
1072 }
1073
1074 sub sync_prepare ($$$) {
1075         my ($self, $sync, $epoch_max) = @_;
1076         my $pr = $sync->{-opt}->{-progress};
1077         my $regen_max = 0;
1078         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1079
1080         # reindex stops at the current heads and we later rerun index_sync
1081         # without {reindex}
1082         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1083
1084         for (my $i = $epoch_max; $i >= 0; $i--) {
1085                 die 'BUG: already indexing!' if $self->{reindex_pipe};
1086                 my $git_dir = git_dir_n($self, $i);
1087                 -d $git_dir or next; # missing epochs are fine
1088                 my $git = PublicInbox::Git->new($git_dir);
1089                 if ($reindex_heads) {
1090                         $head = $reindex_heads->[$i] or next;
1091                 }
1092                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1093
1094                 next if $?; # new repo
1095                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1096                 $sync->{ranges}->[$i] = $range;
1097
1098                 # can't use 'rev-list --count' if we use --diff-filter
1099                 $pr->("$i.git counting $range ... ") if $pr;
1100                 my $n = 0;
1101                 my $fh = $git->popen(qw(log --pretty=tformat:%H
1102                                 --no-notes --no-color --no-renames
1103                                 --diff-filter=AM), $range, '--', 'm');
1104                 ++$n while <$fh>;
1105                 $pr->("$n\n") if $pr;
1106                 $regen_max += $n;
1107         }
1108
1109         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1110
1111         # reindex should NOT see new commits anymore, if we do,
1112         # it's a problem and we need to notice it via die()
1113         my $pad = length($regen_max) + 1;
1114         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1115         $sync->{nr} = 0;
1116         return -1 if $sync->{reindex};
1117         $regen_max + $self->{mm}->num_highwater() || 0;
1118 }
1119
1120 sub unindex_oid_remote ($$$) {
1121         my ($self, $oid, $mid) = @_;
1122         $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1123         $self->{over}->remove_oid($oid, $mid);
1124 }
1125
1126 sub unindex_oid ($$$;$) {
1127         my ($self, $git, $oid, $unindexed) = @_;
1128         my $mm = $self->{mm};
1129         my $msgref = $git->cat_file($oid);
1130         my $mime = PublicInbox::MIME->new($msgref);
1131         my $mids = mids($mime->header_obj);
1132         $mime = $msgref = undef;
1133         my $over = $self->{over};
1134         foreach my $mid (@$mids) {
1135                 my %gone;
1136                 my ($id, $prev);
1137                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1138                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1139                         1; # continue
1140                 }
1141                 my $n = scalar keys %gone;
1142                 next unless $n;
1143                 if ($n > 1) {
1144                         warn "BUG: multiple articles linked to $oid\n",
1145                                 join(',',sort keys %gone), "\n";
1146                 }
1147                 foreach my $num (keys %gone) {
1148                         if ($unindexed) {
1149                                 my $mid0 = $mm->mid_for($num);
1150                                 $unindexed->{$mid0} = $num;
1151                         }
1152                         $mm->num_delete($num);
1153                 }
1154                 unindex_oid_remote($self, $oid, $mid);
1155         }
1156 }
1157
1158 my $x40 = qr/[a-f0-9]{40}/;
1159 sub unindex ($$$$) {
1160         my ($self, $sync, $git, $unindex_range) = @_;
1161         my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1162         my $before = scalar keys %$unindexed;
1163         # order does not matter, here:
1164         my @cmd = qw(log --raw -r
1165                         --no-notes --no-color --no-abbrev --no-renames);
1166         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1167         while (<$fh>) {
1168                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1169                 unindex_oid($self, $git, $1, $unindexed);
1170         }
1171         delete $self->{reindex_pipe};
1172         $fh = undef;
1173
1174         return unless $sync->{-opt}->{prune};
1175         my $after = scalar keys %$unindexed;
1176         return if $before == $after;
1177
1178         # ensure any blob can not longer be accessed via dumb HTTP
1179         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1180                 qw(-c gc.reflogExpire=now gc --prune=all)]);
1181 }
1182
1183 sub sync_ranges ($$$) {
1184         my ($self, $sync, $epoch_max) = @_;
1185         my $reindex = $sync->{reindex};
1186
1187         return last_commits($self, $epoch_max) unless $reindex;
1188         return [] if ref($reindex) ne 'HASH';
1189
1190         my $ranges = $reindex->{from}; # arrayref;
1191         if (ref($ranges) ne 'ARRAY') {
1192                 die 'BUG: $reindex->{from} not an ARRAY';
1193         }
1194         $ranges;
1195 }
1196
1197 sub index_epoch ($$$) {
1198         my ($self, $sync, $i) = @_;
1199
1200         my $git_dir = git_dir_n($self, $i);
1201         die 'BUG: already reindexing!' if $self->{reindex_pipe};
1202         -d $git_dir or return; # missing epochs are fine
1203         fill_alternates($self, $i);
1204         my $git = PublicInbox::Git->new($git_dir);
1205         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1206                 unindex($self, $sync, $git, $unindex_range);
1207         }
1208         defined(my $range = $sync->{ranges}->[$i]) or return;
1209         if (my $pr = $sync->{-opt}->{-progress}) {
1210                 $pr->("$i.git indexing $range\n");
1211         }
1212
1213         my @cmd = qw(log --raw -r --pretty=tformat:%H
1214                         --no-notes --no-color --no-abbrev --no-renames);
1215         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1216         my $cmt;
1217         while (<$fh>) {
1218                 chomp;
1219                 $self->{current_info} = "$i.git $_";
1220                 if (/\A$x40$/o && !defined($cmt)) {
1221                         $cmt = $_;
1222                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1223                         reindex_oid($self, $sync, $git, $1);
1224                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1225                         mark_deleted($self, $sync, $git, $1);
1226                 }
1227         }
1228         $fh = undef;
1229         delete $self->{reindex_pipe};
1230         update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1231 }
1232
1233 # public, called by public-inbox-index
1234 sub index_sync {
1235         my ($self, $opt) = @_;
1236         $opt ||= {};
1237         my $pr = $opt->{-progress};
1238         my $epoch_max;
1239         my $latest = git_dir_latest($self, \$epoch_max);
1240         return unless defined $latest;
1241         $self->idx_init($opt); # acquire lock
1242         my $sync = {
1243                 D => {}, # "$mid\0$cid" => $oid
1244                 unindex_range => {}, # EPOCH => oid_old..oid_new
1245                 reindex => $opt->{reindex},
1246                 -opt => $opt
1247         };
1248         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1249         $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1250
1251         if ($sync->{regen}) {
1252                 # tmp_clone seems to fail if inside a transaction, so
1253                 # we rollback here (because we opened {mm} for reading)
1254                 # Note: we do NOT rely on DBI transactions for atomicity;
1255                 # only for batch performance.
1256                 $self->{mm}->{dbh}->rollback;
1257                 $self->{mm}->{dbh}->begin_work;
1258                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1259         }
1260
1261         # work backwards through history
1262         for (my $i = $epoch_max; $i >= 0; $i--) {
1263                 index_epoch($self, $sync, $i);
1264         }
1265
1266         # unindex is required for leftovers if "deletes" affect messages
1267         # in a previous fetch+index window:
1268         my $git;
1269         if (my @leftovers = values %{delete $sync->{D}}) {
1270                 $git = $self->{-inbox}->git;
1271                 for my $oid (@leftovers) {
1272                         $self->{current_info} = "leftover $oid";
1273                         unindex_oid($self, $git, $oid);
1274                 }
1275         }
1276         if (my $multi_mid = delete $sync->{multi_mid}) {
1277                 $git //= $self->{-inbox}->git;
1278
1279                 while (defined(my $oid = pop(@$multi_mid))) {
1280                         $self->{current_info} = "multi_mid $oid";
1281                         reindex_oid_m($self, $sync, $git, $oid);
1282                 }
1283                 $git->cleanup if $git;
1284         }
1285         $self->done;
1286
1287         if (my $nr = $sync->{nr}) {
1288                 my $pr = $sync->{-opt}->{-progress};
1289                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1290         }
1291
1292         # reindex does not pick up new changes, so we rerun w/o it:
1293         if ($opt->{reindex}) {
1294                 my %again = %$opt;
1295                 $sync = undef;
1296                 delete @again{qw(reindex -skip_lock)};
1297                 index_sync($self, \%again);
1298         }
1299 }
1300
1301 1;