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