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