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