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