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