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