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