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