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