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