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