]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: newest epochs go first in alternates
[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 popen_rd);
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 $git_dir = $self->{-inbox}->git->{git_dir};
475         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
476         my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
477         local $/ = "\n";
478         chomp(my $oid = <$r>);
479         close $r or die "git hash-object failed: $?";
480         $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
481         $oid;
482 }
483
484 sub _check_mids_match ($$$) {
485         my ($old_list, $new_list, $hdrs) = @_;
486         my %old_mids = map { $_ => 1 } @$old_list;
487         my %new_mids = map { $_ => 1 } @$new_list;
488         my @old = keys %old_mids;
489         my @new = keys %new_mids;
490         my $err = "$hdrs may not be changed when replacing\n";
491         die $err if scalar(@old) != scalar(@new);
492         delete @new_mids{@old};
493         delete @old_mids{@new};
494         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
495 }
496
497 # Changing Message-IDs or References with ->replace isn't supported.
498 # The rules for dealing with messages with multiple or conflicting
499 # Message-IDs are pretty complex and rethreading hasn't been fully
500 # implemented, yet.
501 sub check_mids_match ($$) {
502         my ($old_mime, $new_mime) = @_;
503         my $old = $old_mime->header_obj;
504         my $new = $new_mime->header_obj;
505         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
506         _check_mids_match(references($old), references($new),
507                         'References/In-Reply-To');
508 }
509
510 # public
511 sub replace ($$$) {
512         my ($self, $old_mime, $new_mime) = @_;
513
514         check_mids_match($old_mime, $new_mime);
515
516         # mutt will always add Content-Length:, Status:, Lines: when editing
517         PublicInbox::Import::drop_unwanted_headers($new_mime);
518
519         my $raw = $new_mime->as_string;
520         my $expect_oid = git_hash_raw($self, \$raw);
521         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
522         my $need_reindex = $rewritten->{need_reindex};
523
524         # just in case we have bugs in deduplication code:
525         my $n = scalar(@$need_reindex);
526         if ($n > 1) {
527                 my $list = join(', ', map {
528                                         "$_->{num}: <$_->{mid}>"
529                                 } @$need_reindex);
530                 warn <<"";
531 W: rewritten $n messages matching content of original message (expected: 1).
532 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
533 W: $list
534
535         }
536
537         # make sure we really got the OID:
538         my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
539         $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
540
541         # don't leak FDs to Xapian:
542         $self->{-inbox}->git->cleanup;
543
544         # reindex modified messages:
545         for my $smsg (@$need_reindex) {
546                 my $num = $smsg->{num};
547                 my $mid0 = $smsg->{mid};
548                 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
549         }
550         $rewritten->{rewrites};
551 }
552
553 sub last_epoch_commit ($$;$) {
554         my ($self, $i, $cmt) = @_;
555         my $v = PublicInbox::Search::SCHEMA_VERSION();
556         $self->{mm}->last_commit_xap($v, $i, $cmt);
557 }
558
559 sub set_last_commits ($) {
560         my ($self) = @_;
561         defined(my $epoch_max = $self->{epoch_max}) or return;
562         my $last_commit = $self->{last_commit};
563         foreach my $i (0..$epoch_max) {
564                 defined(my $cmt = $last_commit->[$i]) or next;
565                 $last_commit->[$i] = undef;
566                 last_epoch_commit($self, $i, $cmt);
567         }
568 }
569
570 sub barrier_init {
571         my ($self, $n) = @_;
572         $self->{bnote} or return;
573         --$n;
574         my $barrier = { map { $_ => 1 } (0..$n) };
575 }
576
577 sub barrier_wait {
578         my ($self, $barrier) = @_;
579         my $bnote = $self->{bnote} or return;
580         my $r = $bnote->[0];
581         while (scalar keys %$barrier) {
582                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
583                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
584                 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
585         }
586 }
587
588 # public
589 sub checkpoint ($;$) {
590         my ($self, $wait) = @_;
591
592         if (my $im = $self->{im}) {
593                 if ($wait) {
594                         $im->barrier;
595                 } else {
596                         $im->checkpoint;
597                 }
598         }
599         my $shards = $self->{idx_shards};
600         if ($shards) {
601                 my $dbh = $self->{mm}->{dbh};
602
603                 # SQLite msgmap data is second in importance
604                 $dbh->commit;
605
606                 # SQLite overview is third
607                 $self->{over}->commit_lazy;
608
609                 # Now deal with Xapian
610                 if ($wait) {
611                         my $barrier = $self->barrier_init(scalar @$shards);
612
613                         # each shard needs to issue a barrier command
614                         $_->remote_barrier for @$shards;
615
616                         # wait for each Xapian shard
617                         $self->barrier_wait($barrier);
618                 } else {
619                         $_->remote_commit for @$shards;
620                 }
621
622                 # last_commit is special, don't commit these until
623                 # remote shards are done:
624                 $dbh->begin_work;
625                 set_last_commits($self);
626                 $dbh->commit;
627
628                 $dbh->begin_work;
629         }
630         $self->{transact_bytes} = 0;
631 }
632
633 # issue a write barrier to ensure all data is visible to other processes
634 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
635 # public
636 sub barrier { checkpoint($_[0], 1) };
637
638 # public
639 sub done {
640         my ($self) = @_;
641         my $im = delete $self->{im};
642         $im->done if $im; # PublicInbox::Import::done
643         checkpoint($self);
644         my $mm = delete $self->{mm};
645         $mm->{dbh}->commit if $mm;
646         my $shards = delete $self->{idx_shards};
647         if ($shards) {
648                 $_->remote_close for @$shards;
649         }
650         $self->{over}->disconnect;
651         delete $self->{bnote};
652         $self->{transact_bytes} = 0;
653         $self->lock_release if $shards;
654         $self->{-inbox}->git->cleanup;
655 }
656
657 sub fill_alternates ($$) {
658         my ($self, $epoch) = @_;
659
660         my $pfx = "$self->{-inbox}->{inboxdir}/git";
661         my $all = "$self->{-inbox}->{inboxdir}/all.git";
662
663         unless (-d $all) {
664                 PublicInbox::Import::init_bare($all);
665         }
666         my $info_dir = "$all/objects/info";
667         my $alt = "$info_dir/alternates";
668         my (%alt, $new);
669         my $mode = 0644;
670         if (-e $alt) {
671                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
672                 $mode = (stat($fh))[2] & 07777;
673
674                 # we assign a sort score to every alternate and favor
675                 # the newest (highest numbered) one when we
676                 my $score;
677                 my $other = 0; # in case admin adds non-epoch repos
678                 %alt = map {;
679                         if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
680                                 $score = $1 + 0;
681                         } else {
682                                 $score = --$other;
683                         }
684                         $_ => $score;
685                 } split(/\n+/, do { local $/; <$fh> });
686         }
687
688         foreach my $i (0..$epoch) {
689                 my $dir = "../../git/$i.git/objects";
690                 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
691                         $alt{$dir} = $i;
692                         $new = 1;
693                 }
694         }
695         return unless $new;
696
697         my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
698         print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
699                 or die "print $tmp: $!\n";
700         chmod($mode, $fh) or die "fchmod $tmp: $!\n";
701         close $fh or die "close $tmp $!\n";
702         rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
703 }
704
705 sub git_init {
706         my ($self, $epoch) = @_;
707         my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
708         my @cmd = (qw(git init --bare -q), $git_dir);
709         PublicInbox::Import::run_die(\@cmd);
710         @cmd = (qw/git config/, "--file=$git_dir/config",
711                         'include.path', '../../all.git/config');
712         PublicInbox::Import::run_die(\@cmd);
713         fill_alternates($self, $epoch);
714         $git_dir
715 }
716
717 sub git_dir_latest {
718         my ($self, $max) = @_;
719         $$max = -1;
720         my $pfx = "$self->{-inbox}->{inboxdir}/git";
721         return unless -d $pfx;
722         my $latest;
723         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
724         while (defined(my $git_dir = readdir($dh))) {
725                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
726                 if ($1 > $$max) {
727                         $$max = $1;
728                         $latest = "$pfx/$git_dir";
729                 }
730         }
731         $latest;
732 }
733
734 sub importer {
735         my ($self) = @_;
736         my $im = $self->{im};
737         if ($im) {
738                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
739                         return $im;
740                 } else {
741                         $self->{im} = undef;
742                         $im->done;
743                         $im = undef;
744                         $self->checkpoint;
745                         my $git_dir = $self->git_init(++$self->{epoch_max});
746                         my $git = PublicInbox::Git->new($git_dir);
747                         return $self->import_init($git, 0);
748                 }
749         }
750         my $epoch = 0;
751         my $max;
752         my $latest = git_dir_latest($self, \$max);
753         if (defined $latest) {
754                 my $git = PublicInbox::Git->new($latest);
755                 my $packed_bytes = $git->packed_bytes;
756                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
757
758                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
759                         $epoch = $max + 1;
760                 } else {
761                         $self->{epoch_max} = $max;
762                         return $self->import_init($git, $packed_bytes);
763                 }
764         }
765         $self->{epoch_max} = $epoch;
766         $latest = $self->git_init($epoch);
767         $self->import_init(PublicInbox::Git->new($latest), 0);
768 }
769
770 sub import_init {
771         my ($self, $git, $packed_bytes, $tmp) = @_;
772         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
773         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
774         $im->{want_object_info} = 1;
775         $im->{lock_path} = undef;
776         $im->{path_type} = 'v2';
777         $self->{im} = $im unless $tmp;
778         $im;
779 }
780
781 # XXX experimental
782 sub diff ($$$) {
783         my ($mid, $cur, $new) = @_;
784
785         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
786         print $ah $cur->as_string or die "print: $!";
787         close $ah or die "close: $!";
788         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
789         PublicInbox::Import::drop_unwanted_headers($new);
790         print $bh $new->as_string or die "print: $!";
791         close $bh or die "close: $!";
792         my $cmd = [ qw(diff -u), $an, $bn ];
793         print STDERR "# MID conflict <$mid>\n";
794         my $pid = spawn($cmd, undef, { 1 => 2 });
795         waitpid($pid, 0) == $pid or die "diff did not finish";
796         unlink($an, $bn);
797 }
798
799 sub get_blob ($$) {
800         my ($self, $smsg) = @_;
801         if (my $im = $self->{im}) {
802                 my $msg = $im->cat_blob($smsg->{blob});
803                 return $msg if $msg;
804         }
805         # older message, should be in alternates
806         my $ibx = $self->{-inbox};
807         $ibx->msg_by_smsg($smsg);
808 }
809
810 sub lookup_content ($$$) {
811         my ($self, $mime, $mid) = @_;
812         my $over = $self->{over};
813         my $cids = content_ids($mime);
814         my ($id, $prev);
815         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
816                 my $msg = get_blob($self, $smsg);
817                 if (!defined($msg)) {
818                         warn "broken smsg for $mid\n";
819                         next;
820                 }
821                 my $cur = PublicInbox::MIME->new($msg);
822                 if (content_matches($cids, $cur)) {
823                         $smsg->{mime} = $cur;
824                         return $smsg;
825                 }
826
827
828                 # XXX DEBUG_DIFF is experimental and may be removed
829                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
830         }
831         undef;
832 }
833
834 sub atfork_child {
835         my ($self) = @_;
836         my $fh = delete $self->{reindex_pipe};
837         close $fh if $fh;
838         if (my $shards = $self->{idx_shards}) {
839                 $_->atfork_child foreach @$shards;
840         }
841         if (my $im = $self->{im}) {
842                 $im->atfork_child;
843         }
844         die "unexpected mm" if $self->{mm};
845         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
846         $self->{bnote}->[1];
847 }
848
849 sub mark_deleted ($$$$) {
850         my ($self, $sync, $git, $oid) = @_;
851         my $msgref = $git->cat_file($oid);
852         my $mime = PublicInbox::MIME->new($$msgref);
853         my $mids = mids($mime->header_obj);
854         my $cid = content_id($mime);
855         foreach my $mid (@$mids) {
856                 $sync->{D}->{"$mid\0$cid"} = $oid;
857         }
858 }
859
860 sub reindex_checkpoint ($$$) {
861         my ($self, $sync, $git) = @_;
862
863         $git->cleanup;
864         $sync->{mm_tmp}->atfork_prepare;
865         $self->done; # release lock
866
867         if (my $pr = $sync->{-opt}->{-progress}) {
868                 my ($bn) = (split('/', $git->{git_dir}))[-1];
869                 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
870         }
871
872         # allow -watch or -mda to write...
873         $self->idx_init; # reacquire lock
874         $sync->{mm_tmp}->atfork_parent;
875 }
876
877 # only for a few odd messages with multiple Message-IDs
878 sub reindex_oid_m ($$$$;$) {
879         my ($self, $sync, $git, $oid, $regen_num) = @_;
880         $self->{current_info} = "multi_mid $oid";
881         my ($num, $mid0, $len);
882         my $msgref = $git->cat_file($oid, \$len);
883         my $mime = PublicInbox::MIME->new($$msgref);
884         my $mids = mids($mime->header_obj);
885         my $cid = content_id($mime);
886         die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
887
888         for my $mid (reverse @$mids) {
889                 delete($sync->{D}->{"$mid\0$cid"}) and
890                         die "BUG: reindex_oid should handle <$mid> delete";
891         }
892         my $over = $self->{over};
893         for my $mid (reverse @$mids) {
894                 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
895                 next unless defined $num;
896                 if (defined($regen_num) && $regen_num != $num) {
897                         die "BUG: regen(#$regen_num) != over(#$num)";
898                 }
899         }
900         unless (defined($num)) {
901                 for my $mid (reverse @$mids) {
902                         # is this a number we got before?
903                         my $n = $sync->{mm_tmp}->num_for($mid);
904                         next unless defined $n;
905                         next if defined($regen_num) && $regen_num != $n;
906                         ($num, $mid0) = ($n, $mid);
907                         last;
908                 }
909         }
910         if (defined($num)) {
911                 $sync->{mm_tmp}->num_delete($num);
912         } elsif (defined $regen_num) {
913                 $num = $regen_num;
914                 for my $mid (reverse @$mids) {
915                         $self->{mm}->mid_set($num, $mid) == 1 or next;
916                         $mid0 = $mid;
917                         last;
918                 }
919                 unless (defined $mid0) {
920                         warn "E: cannot regen #$num\n";
921                         return;
922                 }
923         } else { # fixup bugs in old mirrors on reindex
924                 for my $mid (reverse @$mids) {
925                         $num = $self->{mm}->mid_insert($mid);
926                         next unless defined $num;
927                         $mid0 = $mid;
928                         last;
929                 }
930                 if (defined $mid0) {
931                         if ($sync->{reindex}) {
932                                 warn "reindex added #$num <$mid0>\n";
933                         }
934                 } else {
935                         warn "E: cannot find article #\n";
936                         return;
937                 }
938         }
939         $sync->{nr}++;
940         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
941                 reindex_checkpoint($self, $sync, $git);
942         }
943 }
944
945 sub check_unindexed ($$$) {
946         my ($self, $num, $mid0) = @_;
947         my $unindexed = $self->{unindexed} // {};
948         my $n = delete($unindexed->{$mid0});
949         defined $n or return;
950         if ($n != $num) {
951                 die "BUG: unindexed $n != $num <$mid0>\n";
952         } else {
953                 $self->{mm}->mid_set($num, $mid0);
954         }
955 }
956
957 # reuse Msgmap to store num => oid mapping (rather than num => mid)
958 sub multi_mid_q_new () {
959         my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
960         my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
961         $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
962         # for Msgmap->DESTROY:
963         $multi_mid->{tmp_name} = $fn;
964         $multi_mid->{pid} = $$;
965         close $fh or die "failed to close $fn: $!";
966         $multi_mid
967 }
968
969 sub multi_mid_q_push ($$) {
970         my ($sync, $oid) = @_;
971         my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
972         if ($sync->{reindex}) { # no regen on reindex
973                 $multi_mid->mid_insert($oid);
974         } else {
975                 my $num = $sync->{regen}--;
976                 die "BUG: ran out of article numbers" if $num <= 0;
977                 $multi_mid->mid_set($num, $oid);
978         }
979 }
980
981 sub reindex_oid ($$$$) {
982         my ($self, $sync, $git, $oid) = @_;
983         my ($num, $mid0, $len);
984         my $msgref = $git->cat_file($oid, \$len);
985         return if $len == 0; # purged
986         my $mime = PublicInbox::MIME->new($$msgref);
987         my $mids = mids($mime->header_obj);
988         my $cid = content_id($mime);
989
990         if (scalar(@$mids) == 0) {
991                 warn "E: $oid has no Message-ID, skipping\n";
992                 return;
993         } elsif (scalar(@$mids) == 1) {
994                 my $mid = $mids->[0];
995
996                 # was the file previously marked as deleted?, skip if so
997                 if (delete($sync->{D}->{"$mid\0$cid"})) {
998                         if (!$sync->{reindex}) {
999                                 $num = $sync->{regen}--;
1000                                 $self->{mm}->num_highwater($num);
1001                         }
1002                         return;
1003                 }
1004
1005                 # is this a number we got before?
1006                 $num = $sync->{mm_tmp}->num_for($mid);
1007                 if (defined $num) {
1008                         $mid0 = $mid;
1009                         check_unindexed($self, $num, $mid0);
1010                 } else {
1011                         $num = $sync->{regen}--;
1012                         die "BUG: ran out of article numbers" if $num <= 0;
1013                         if ($self->{mm}->mid_set($num, $mid) != 1) {
1014                                 warn "E: unable to assign $num => <$mid>\n";
1015                                 return;
1016                         }
1017                         $mid0 = $mid;
1018                 }
1019         } else { # multiple MIDs are a weird case:
1020                 my $del = 0;
1021                 for (@$mids) {
1022                         $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1023                 }
1024                 if ($del) {
1025                         unindex_oid_remote($self, $oid, $_) for @$mids;
1026                         # do not delete from {mm_tmp}, since another
1027                         # single-MID message may use it.
1028                 } else { # handle them at the end:
1029                         multi_mid_q_push($sync, $oid);
1030                 }
1031                 return;
1032         }
1033         $sync->{mm_tmp}->mid_delete($mid0) or
1034                 die "failed to delete <$mid0> for article #$num\n";
1035         $sync->{nr}++;
1036         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1037                 reindex_checkpoint($self, $sync, $git);
1038         }
1039 }
1040
1041 # only update last_commit for $i on reindex iff newer than current
1042 sub update_last_commit ($$$$) {
1043         my ($self, $git, $i, $cmt) = @_;
1044         my $last = last_epoch_commit($self, $i);
1045         if (defined $last && is_ancestor($git, $last, $cmt)) {
1046                 my @cmd = (qw(rev-list --count), "$last..$cmt");
1047                 chomp(my $n = $git->qx(@cmd));
1048                 return if $n ne '' && $n == 0;
1049         }
1050         last_epoch_commit($self, $i, $cmt);
1051 }
1052
1053 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1054
1055 sub last_commits ($$) {
1056         my ($self, $epoch_max) = @_;
1057         my $heads = [];
1058         for (my $i = $epoch_max; $i >= 0; $i--) {
1059                 $heads->[$i] = last_epoch_commit($self, $i);
1060         }
1061         $heads;
1062 }
1063
1064 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1065
1066 # returns a revision range for git-log(1)
1067 sub log_range ($$$$$) {
1068         my ($self, $sync, $git, $i, $tip) = @_;
1069         my $opt = $sync->{-opt};
1070         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1071         my $cur = $sync->{ranges}->[$i] or do {
1072                 $pr->("$i.git indexing all of $tip") if $pr;
1073                 return $tip; # all of it
1074         };
1075
1076         # fast equality check to avoid (v)fork+execve overhead
1077         if ($cur eq $tip) {
1078                 $sync->{ranges}->[$i] = undef;
1079                 return;
1080         }
1081
1082         my $range = "$cur..$tip";
1083         $pr->("$i.git checking contiguity... ") if $pr;
1084         if (is_ancestor($git, $cur, $tip)) { # common case
1085                 $pr->("OK\n") if $pr;
1086                 my $n = $git->qx(qw(rev-list --count), $range);
1087                 chomp($n);
1088                 if ($n == 0) {
1089                         $sync->{ranges}->[$i] = undef;
1090                         $pr->("$i.git has nothing new\n") if $pr;
1091                         return; # nothing to do
1092                 }
1093                 $pr->("$i.git has $n changes since $cur\n") if $pr;
1094         } else {
1095                 $pr->("FAIL\n") if $pr;
1096                 warn <<"";
1097 discontiguous range: $range
1098 Rewritten history? (in $git->{git_dir})
1099
1100                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1101                 if ($base) {
1102                         $range = "$base..$tip";
1103                         warn "found merge-base: $base\n"
1104                 } else {
1105                         $range = $tip;
1106                         warn "discarding history at $cur\n";
1107                 }
1108                 warn <<"";
1109 reindexing $git->{git_dir} starting at
1110 $range
1111
1112                 $sync->{unindex_range}->{$i} = "$base..$cur";
1113         }
1114         $range;
1115 }
1116
1117 sub sync_prepare ($$$) {
1118         my ($self, $sync, $epoch_max) = @_;
1119         my $pr = $sync->{-opt}->{-progress};
1120         my $regen_max = 0;
1121         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1122
1123         # reindex stops at the current heads and we later rerun index_sync
1124         # without {reindex}
1125         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1126
1127         for (my $i = $epoch_max; $i >= 0; $i--) {
1128                 die 'BUG: already indexing!' if $self->{reindex_pipe};
1129                 my $git_dir = git_dir_n($self, $i);
1130                 -d $git_dir or next; # missing epochs are fine
1131                 my $git = PublicInbox::Git->new($git_dir);
1132                 if ($reindex_heads) {
1133                         $head = $reindex_heads->[$i] or next;
1134                 }
1135                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1136
1137                 next if $?; # new repo
1138                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1139                 $sync->{ranges}->[$i] = $range;
1140
1141                 # can't use 'rev-list --count' if we use --diff-filter
1142                 $pr->("$i.git counting $range ... ") if $pr;
1143                 my $n = 0;
1144                 my $fh = $git->popen(qw(log --pretty=tformat:%H
1145                                 --no-notes --no-color --no-renames
1146                                 --diff-filter=AM), $range, '--', 'm');
1147                 ++$n while <$fh>;
1148                 close $fh or die "git log failed: \$?=$?";
1149                 $pr->("$n\n") if $pr;
1150                 $regen_max += $n;
1151         }
1152
1153         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1154
1155         # reindex should NOT see new commits anymore, if we do,
1156         # it's a problem and we need to notice it via die()
1157         my $pad = length($regen_max) + 1;
1158         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1159         $sync->{nr} = 0;
1160         return -1 if $sync->{reindex};
1161         $regen_max + $self->{mm}->num_highwater() || 0;
1162 }
1163
1164 sub unindex_oid_remote ($$$) {
1165         my ($self, $oid, $mid) = @_;
1166         $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1167         $self->{over}->remove_oid($oid, $mid);
1168 }
1169
1170 sub unindex_oid ($$$;$) {
1171         my ($self, $git, $oid, $unindexed) = @_;
1172         my $mm = $self->{mm};
1173         my $msgref = $git->cat_file($oid);
1174         my $mime = PublicInbox::MIME->new($msgref);
1175         my $mids = mids($mime->header_obj);
1176         $mime = $msgref = undef;
1177         my $over = $self->{over};
1178         foreach my $mid (@$mids) {
1179                 my %gone;
1180                 my ($id, $prev);
1181                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1182                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1183                         1; # continue
1184                 }
1185                 my $n = scalar keys %gone;
1186                 next unless $n;
1187                 if ($n > 1) {
1188                         warn "BUG: multiple articles linked to $oid\n",
1189                                 join(',',sort keys %gone), "\n";
1190                 }
1191                 foreach my $num (keys %gone) {
1192                         if ($unindexed) {
1193                                 my $mid0 = $mm->mid_for($num);
1194                                 $unindexed->{$mid0} = $num;
1195                         }
1196                         $mm->num_delete($num);
1197                 }
1198                 unindex_oid_remote($self, $oid, $mid);
1199         }
1200 }
1201
1202 my $x40 = qr/[a-f0-9]{40}/;
1203 sub unindex ($$$$) {
1204         my ($self, $sync, $git, $unindex_range) = @_;
1205         my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1206         my $before = scalar keys %$unindexed;
1207         # order does not matter, here:
1208         my @cmd = qw(log --raw -r
1209                         --no-notes --no-color --no-abbrev --no-renames);
1210         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1211         while (<$fh>) {
1212                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1213                 unindex_oid($self, $git, $1, $unindexed);
1214         }
1215         delete $self->{reindex_pipe};
1216         close $fh or die "git log failed: \$?=$?";
1217
1218         return unless $sync->{-opt}->{prune};
1219         my $after = scalar keys %$unindexed;
1220         return if $before == $after;
1221
1222         # ensure any blob can not longer be accessed via dumb HTTP
1223         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1224                 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1225 }
1226
1227 sub sync_ranges ($$$) {
1228         my ($self, $sync, $epoch_max) = @_;
1229         my $reindex = $sync->{reindex};
1230
1231         return last_commits($self, $epoch_max) unless $reindex;
1232         return [] if ref($reindex) ne 'HASH';
1233
1234         my $ranges = $reindex->{from}; # arrayref;
1235         if (ref($ranges) ne 'ARRAY') {
1236                 die 'BUG: $reindex->{from} not an ARRAY';
1237         }
1238         $ranges;
1239 }
1240
1241 sub index_epoch ($$$) {
1242         my ($self, $sync, $i) = @_;
1243
1244         my $git_dir = git_dir_n($self, $i);
1245         die 'BUG: already reindexing!' if $self->{reindex_pipe};
1246         -d $git_dir or return; # missing epochs are fine
1247         fill_alternates($self, $i);
1248         my $git = PublicInbox::Git->new($git_dir);
1249         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1250                 unindex($self, $sync, $git, $unindex_range);
1251         }
1252         defined(my $range = $sync->{ranges}->[$i]) or return;
1253         if (my $pr = $sync->{-opt}->{-progress}) {
1254                 $pr->("$i.git indexing $range\n");
1255         }
1256
1257         my @cmd = qw(log --raw -r --pretty=tformat:%H
1258                         --no-notes --no-color --no-abbrev --no-renames);
1259         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1260         my $cmt;
1261         while (<$fh>) {
1262                 chomp;
1263                 $self->{current_info} = "$i.git $_";
1264                 if (/\A$x40$/o && !defined($cmt)) {
1265                         $cmt = $_;
1266                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1267                         reindex_oid($self, $sync, $git, $1);
1268                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1269                         mark_deleted($self, $sync, $git, $1);
1270                 }
1271         }
1272         close $fh or die "git log failed: \$?=$?";
1273         delete $self->{reindex_pipe};
1274         update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1275 }
1276
1277 # public, called by public-inbox-index
1278 sub index_sync {
1279         my ($self, $opt) = @_;
1280         $opt ||= {};
1281         my $pr = $opt->{-progress};
1282         my $epoch_max;
1283         my $latest = git_dir_latest($self, \$epoch_max);
1284         return unless defined $latest;
1285         $self->idx_init($opt); # acquire lock
1286         my $sync = {
1287                 D => {}, # "$mid\0$cid" => $oid
1288                 unindex_range => {}, # EPOCH => oid_old..oid_new
1289                 reindex => $opt->{reindex},
1290                 -opt => $opt
1291         };
1292         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1293         $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1294
1295         if ($sync->{regen}) {
1296                 # tmp_clone seems to fail if inside a transaction, so
1297                 # we rollback here (because we opened {mm} for reading)
1298                 # Note: we do NOT rely on DBI transactions for atomicity;
1299                 # only for batch performance.
1300                 $self->{mm}->{dbh}->rollback;
1301                 $self->{mm}->{dbh}->begin_work;
1302                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1303         }
1304
1305         # work backwards through history
1306         for (my $i = $epoch_max; $i >= 0; $i--) {
1307                 index_epoch($self, $sync, $i);
1308         }
1309
1310         # unindex is required for leftovers if "deletes" affect messages
1311         # in a previous fetch+index window:
1312         my $git;
1313         if (my @leftovers = values %{delete $sync->{D}}) {
1314                 $git = $self->{-inbox}->git;
1315                 for my $oid (@leftovers) {
1316                         $self->{current_info} = "leftover $oid";
1317                         unindex_oid($self, $git, $oid);
1318                 }
1319         }
1320         if (my $multi_mid = delete $sync->{multi_mid}) {
1321                 $git //= $self->{-inbox}->git;
1322                 my ($min, $max) = $multi_mid->minmax;
1323                 if ($sync->{reindex}) {
1324                         # we may need to create new Message-IDs if mirrors
1325                         # were initially indexed with old versions
1326                         for (my $i = $max; $i >= $min; $i--) {
1327                                 my $oid = $multi_mid->mid_for($i);
1328                                 next unless defined $oid;
1329                                 reindex_oid_m($self, $sync, $git, $oid);
1330                         }
1331                 } else { # regen on initial index
1332                         for my $num ($min..$max) {
1333                                 my $oid = $multi_mid->mid_for($num);
1334                                 next unless defined $oid;
1335                                 reindex_oid_m($self, $sync, $git, $oid, $num);
1336                         }
1337                 }
1338         }
1339         $git->cleanup if $git;
1340         $self->done;
1341
1342         if (my $nr = $sync->{nr}) {
1343                 my $pr = $sync->{-opt}->{-progress};
1344                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1345         }
1346
1347         # reindex does not pick up new changes, so we rerun w/o it:
1348         if ($opt->{reindex}) {
1349                 my %again = %$opt;
1350                 $sync = undef;
1351                 delete @again{qw(reindex -skip_lock)};
1352                 index_sync($self, \%again);
1353         }
1354 }
1355
1356 1;