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