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