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