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