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