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