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