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