]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
init: allow --skip of old epochs for -V2 repos
[public-inbox.git] / lib / PublicInbox / V2Writable.pm
1 # Copyright (C) 2018 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 package PublicInbox::V2Writable;
6 use strict;
7 use warnings;
8 use base qw(PublicInbox::Lock);
9 use PublicInbox::SearchIdxPart;
10 use PublicInbox::MIME;
11 use PublicInbox::Git;
12 use PublicInbox::Import;
13 use PublicInbox::MID qw(mids);
14 use PublicInbox::ContentId qw(content_id content_digest);
15 use PublicInbox::Inbox;
16 use PublicInbox::OverIdx;
17 use PublicInbox::Msgmap;
18 use PublicInbox::Spawn qw(spawn);
19 use PublicInbox::SearchIdx;
20 use IO::Handle;
21
22 # an estimate of the post-packed size to the raw uncompressed size
23 my $PACKING_FACTOR = 0.4;
24
25 # assume 2 cores if GNU nproc(1) is not available
26 sub nproc_parts () {
27         my $n = int($ENV{NPROC} || `nproc 2>/dev/null` || 2);
28         # subtract for the main process and git-fast-import
29         $n -= 1;
30         $n < 1 ? 1 : $n;
31 }
32
33 sub count_partitions ($) {
34         my ($self) = @_;
35         my $nparts = 0;
36         my $xpfx = $self->{xpfx};
37
38         # always load existing partitions in case core count changes:
39         # Also, partition count may change while -watch is running
40         # due to -compact
41         if (-d $xpfx) {
42                 foreach my $part (<$xpfx/*>) {
43                         -d $part && $part =~ m!/\d+\z! or next;
44                         eval {
45                                 Search::Xapian::Database->new($part)->close;
46                                 $nparts++;
47                         };
48                 }
49         }
50         $nparts;
51 }
52
53 sub new {
54         my ($class, $v2ibx, $creat) = @_;
55         my $dir = $v2ibx->{mainrepo} or die "no mainrepo in inbox\n";
56         unless (-d $dir) {
57                 if ($creat) {
58                         require File::Path;
59                         File::Path::mkpath($dir);
60                 } else {
61                         die "$dir does not exist\n";
62                 }
63         }
64
65         $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
66         $v2ibx->umask_prepare;
67
68         my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
69         my $self = {
70                 -inbox => $v2ibx,
71                 im => undef, #  PublicInbox::Import
72                 parallel => 1,
73                 transact_bytes => 0,
74                 xpfx => $xpfx,
75                 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
76                 lock_path => "$dir/inbox.lock",
77                 # limit each git repo (epoch) to 1GB or so
78                 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
79                 last_commit => [], # git repo -> commit
80         };
81         $self->{partitions} = count_partitions($self) || nproc_parts();
82         bless $self, $class;
83 }
84
85 sub init_inbox {
86         my ($self, $parallel, $skip) = @_;
87         $self->{parallel} = $parallel;
88         $self->idx_init;
89         my $epoch_max = -1;
90         git_dir_latest($self, \$epoch_max);
91         if (defined $skip && $epoch_max == -1) {
92                 $epoch_max = $skip;
93         }
94         $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
95         $self->done;
96 }
97
98 # returns undef on duplicate or spam
99 # mimics Import::add and wraps it for v2
100 sub add {
101         my ($self, $mime, $check_cb) = @_;
102         $self->{-inbox}->with_umask(sub {
103                 _add($self, $mime, $check_cb)
104         });
105 }
106
107 sub _add {
108         my ($self, $mime, $check_cb) = @_;
109
110         # spam check:
111         if ($check_cb) {
112                 $mime = $check_cb->($mime) or return;
113         }
114
115         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
116         # as does SQLite 3.4.1+ (released in 2007-07-20), and
117         # Xapian 1.3.2+ (released 2015-03-15).
118         # For the most part, we can spawn git-fast-import without
119         # leaking FDs to it...
120         $self->idx_init;
121
122         my $mid0;
123         my $num = num_for($self, $mime, \$mid0);
124         defined $num or return; # duplicate
125         defined $mid0 or die "BUG: $mid0 undefined\n";
126         my $im = $self->importer;
127         my $cmt = $im->add($mime);
128         $cmt = $im->get_mark($cmt);
129         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
130
131         my ($oid, $len, $msgref) = @{$im->{last_object}};
132         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
133         my $nparts = $self->{partitions};
134         my $part = $num % $nparts;
135         my $idx = $self->idx_part($part);
136         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
137         my $n = $self->{transact_bytes} += $len;
138         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
139                 $self->checkpoint;
140         }
141
142         $cmt;
143 }
144
145 sub num_for {
146         my ($self, $mime, $mid0) = @_;
147         my $mids = mids($mime->header_obj);
148         if (@$mids) {
149                 my $mid = $mids->[0];
150                 my $num = $self->{mm}->mid_insert($mid);
151                 if (defined $num) { # common case
152                         $$mid0 = $mid;
153                         return $num;
154                 };
155
156                 # crap, Message-ID is already known, hope somebody just resent:
157                 foreach my $m (@$mids) {
158                         # read-only lookup now safe to do after above barrier
159                         my $existing = $self->lookup_content($mime, $m);
160                         # easy, don't store duplicates
161                         # note: do not add more diagnostic info here since
162                         # it gets noisy on public-inbox-watch restarts
163                         return if $existing;
164                 }
165
166                 # very unlikely:
167                 warn "<$mid> reused for mismatched content\n";
168
169                 # try the rest of the mids
170                 for(my $i = $#$mids; $i >= 1; $i--) {
171                         my $m = $mids->[$i];
172                         $num = $self->{mm}->mid_insert($m);
173                         if (defined $num) {
174                                 warn "alternative <$m> for <$mid> found\n";
175                                 $$mid0 = $m;
176                                 return $num;
177                         }
178                 }
179         }
180         # none of the existing Message-IDs are good, generate a new one:
181         num_for_harder($self, $mime, $mid0);
182 }
183
184 sub num_for_harder {
185         my ($self, $mime, $mid0) = @_;
186
187         my $hdr = $mime->header_obj;
188         my $dig = content_digest($mime);
189         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
190         my $num = $self->{mm}->mid_insert($$mid0);
191         unless (defined $num) {
192                 # it's hard to spoof the last Received: header
193                 my @recvd = $hdr->header_raw('Received');
194                 $dig->add("Received: $_") foreach (@recvd);
195                 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
196                 $num = $self->{mm}->mid_insert($$mid0);
197
198                 # fall back to a random Message-ID and give up determinism:
199                 until (defined($num)) {
200                         $dig->add(rand);
201                         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
202                         warn "using random Message-ID <$$mid0> as fallback\n";
203                         $num = $self->{mm}->mid_insert($$mid0);
204                 }
205         }
206         PublicInbox::Import::append_mid($hdr, $$mid0);
207         $num;
208 }
209
210 sub idx_part {
211         my ($self, $part) = @_;
212         $self->{idx_parts}->[$part];
213 }
214
215 # idempotent
216 sub idx_init {
217         my ($self) = @_;
218         return if $self->{idx_parts};
219         my $ibx = $self->{-inbox};
220
221         # do not leak read-only FDs to child processes, we only have these
222         # FDs for duplicate detection so they should not be
223         # frequently activated.
224         delete $ibx->{$_} foreach (qw(git mm search));
225
226        if ($self->{parallel}) {
227                pipe(my ($r, $w)) or die "pipe failed: $!";
228                $self->{bnote} = [ $r, $w ];
229                $w->autoflush(1);
230        }
231
232         my $over = $self->{over};
233         $ibx->umask_prepare;
234         $ibx->with_umask(sub {
235                 $self->lock_acquire;
236                 $over->create;
237
238                 # -compact can change partition count while -watch is idle
239                 my $nparts = count_partitions($self);
240                 if ($nparts && $nparts != $self->{partitions}) {
241                         $self->{partitions} = $nparts;
242                 }
243
244                 # need to create all parts before initializing msgmap FD
245                 my $max = $self->{partitions} - 1;
246
247                 # idx_parts must be visible to all forked processes
248                 my $idx = $self->{idx_parts} = [];
249                 for my $i (0..$max) {
250                         push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
251                 }
252
253                 # Now that all subprocesses are up, we can open the FDs
254                 # for SQLite:
255                 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
256                         "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
257                 $mm->{dbh}->begin_work;
258         });
259 }
260
261 sub purge_oids {
262         my ($self, $purge) = @_; # $purge = { $object_id => 1, ... }
263         $self->done;
264         my $pfx = "$self->{-inbox}->{mainrepo}/git";
265         my $purges = [];
266         foreach my $i (0..$self->{epoch_max}) {
267                 my $git = PublicInbox::Git->new("$pfx/$i.git");
268                 my $im = $self->import_init($git, 0, 1);
269                 $purges->[$i] = $im->purge_oids($purge);
270         }
271         $purges;
272 }
273
274 sub content_ids ($) {
275         my ($mime) = @_;
276         my @cids = ( content_id($mime) );
277
278         # Email::MIME->as_string doesn't always round-trip, so we may
279         # use a second content_id
280         my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
281         push @cids, $rt if $cids[0] ne $rt;
282         \@cids;
283 }
284
285 sub content_matches ($$) {
286         my ($cids, $existing) = @_;
287         my $cid = content_id($existing);
288         foreach (@$cids) {
289                 return 1 if $_ eq $cid
290         }
291         0
292 }
293
294 sub remove_internal {
295         my ($self, $mime, $cmt_msg, $purge) = @_;
296         $self->idx_init;
297         my $im = $self->importer unless $purge;
298         my $over = $self->{over};
299         my $cids = content_ids($mime);
300         my $parts = $self->{idx_parts};
301         my $mm = $self->{mm};
302         my $removed;
303         my $mids = mids($mime->header_obj);
304
305         # We avoid introducing new blobs into git since the raw content
306         # can be slightly different, so we do not need the user-supplied
307         # message now that we have the mids and content_id
308         $mime = undef;
309         my $mark;
310
311         foreach my $mid (@$mids) {
312                 my %gone;
313                 my ($id, $prev);
314                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
315                         my $msg = get_blob($self, $smsg);
316                         if (!defined($msg)) {
317                                 warn "broken smsg for $mid\n";
318                                 next; # continue
319                         }
320                         my $orig = $$msg;
321                         my $cur = PublicInbox::MIME->new($msg);
322                         if (content_matches($cids, $cur)) {
323                                 $smsg->{mime} = $cur;
324                                 $gone{$smsg->{num}} = [ $smsg, \$orig ];
325                         }
326                 }
327                 my $n = scalar keys %gone;
328                 next unless $n;
329                 if ($n > 1) {
330                         warn "BUG: multiple articles linked to <$mid>\n",
331                                 join(',', sort keys %gone), "\n";
332                 }
333                 foreach my $num (keys %gone) {
334                         my ($smsg, $orig) = @{$gone{$num}};
335                         $mm->num_delete($num);
336                         # $removed should only be set once assuming
337                         # no bugs in our deduplication code:
338                         $removed = $smsg;
339                         my $oid = $smsg->{blob};
340                         if ($purge) {
341                                 $purge->{$oid} = 1;
342                         } else {
343                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
344                         }
345                         $orig = undef;
346                         $self->unindex_oid_remote($oid, $mid);
347                 }
348         }
349
350         if (defined $mark) {
351                 my $cmt = $im->get_mark($mark);
352                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
353         }
354         if ($purge && scalar keys %$purge) {
355                 return purge_oids($self, $purge);
356         }
357         $removed;
358 }
359
360 sub remove {
361         my ($self, $mime, $cmt_msg) = @_;
362         $self->{-inbox}->with_umask(sub {
363                 remove_internal($self, $mime, $cmt_msg);
364         });
365 }
366
367 sub purge {
368         my ($self, $mime) = @_;
369         my $purges = $self->{-inbox}->with_umask(sub {
370                 remove_internal($self, $mime, undef, {});
371         });
372         $self->idx_init if @$purges; # ->done is called on purges
373         for my $i (0..$#$purges) {
374                 defined(my $cmt = $purges->[$i]) or next;
375                 $self->{last_commit}->[$i] = $cmt;
376         }
377         $purges;
378 }
379
380 sub last_commit_part ($$;$) {
381         my ($self, $i, $cmt) = @_;
382         my $v = PublicInbox::Search::SCHEMA_VERSION();
383         $self->{mm}->last_commit_xap($v, $i, $cmt);
384 }
385
386 sub set_last_commits ($) {
387         my ($self) = @_;
388         defined(my $epoch_max = $self->{epoch_max}) or return;
389         my $last_commit = $self->{last_commit};
390         foreach my $i (0..$epoch_max) {
391                 defined(my $cmt = $last_commit->[$i]) or next;
392                 $last_commit->[$i] = undef;
393                 last_commit_part($self, $i, $cmt);
394         }
395 }
396
397 sub barrier_init {
398         my ($self, $n) = @_;
399         $self->{bnote} or return;
400         --$n;
401         my $barrier = { map { $_ => 1 } (0..$n) };
402 }
403
404 sub barrier_wait {
405         my ($self, $barrier) = @_;
406         my $bnote = $self->{bnote} or return;
407         my $r = $bnote->[0];
408         while (scalar keys %$barrier) {
409                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
410                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
411                 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
412         }
413 }
414
415 sub checkpoint ($;$) {
416         my ($self, $wait) = @_;
417
418         if (my $im = $self->{im}) {
419                 if ($wait) {
420                         $im->barrier;
421                 } else {
422                         $im->checkpoint;
423                 }
424         }
425         my $parts = $self->{idx_parts};
426         if ($parts) {
427                 my $dbh = $self->{mm}->{dbh};
428
429                 # SQLite msgmap data is second in importance
430                 $dbh->commit;
431
432                 # SQLite overview is third
433                 $self->{over}->commit_lazy;
434
435                 # Now deal with Xapian
436                 if ($wait) {
437                         my $barrier = $self->barrier_init(scalar @$parts);
438
439                         # each partition needs to issue a barrier command
440                         $_->remote_barrier for @$parts;
441
442                         # wait for each Xapian partition
443                         $self->barrier_wait($barrier);
444                 } else {
445                         $_->remote_commit for @$parts;
446                 }
447
448                 # last_commit is special, don't commit these until
449                 # remote partitions are done:
450                 $dbh->begin_work;
451                 set_last_commits($self);
452                 $dbh->commit;
453
454                 $dbh->begin_work;
455         }
456         $self->{transact_bytes} = 0;
457 }
458
459 # issue a write barrier to ensure all data is visible to other processes
460 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
461 sub barrier { checkpoint($_[0], 1) };
462
463 sub done {
464         my ($self) = @_;
465         my $im = delete $self->{im};
466         $im->done if $im; # PublicInbox::Import::done
467         checkpoint($self);
468         my $mm = delete $self->{mm};
469         $mm->{dbh}->commit if $mm;
470         my $parts = delete $self->{idx_parts};
471         if ($parts) {
472                 $_->remote_close for @$parts;
473         }
474         $self->{over}->disconnect;
475         delete $self->{bnote};
476         $self->{transact_bytes} = 0;
477         $self->lock_release if $parts;
478 }
479
480 sub git_init {
481         my ($self, $epoch) = @_;
482         my $pfx = "$self->{-inbox}->{mainrepo}/git";
483         my $git_dir = "$pfx/$epoch.git";
484         my @cmd = (qw(git init --bare -q), $git_dir);
485         PublicInbox::Import::run_die(\@cmd);
486
487         my $all = "$self->{-inbox}->{mainrepo}/all.git";
488         unless (-d $all) {
489                 @cmd = (qw(git init --bare -q), $all);
490                 PublicInbox::Import::run_die(\@cmd);
491                 @cmd = (qw/git config/, "--file=$all/config",
492                                 'repack.writeBitmaps', 'true');
493                 PublicInbox::Import::run_die(\@cmd);
494         }
495
496         @cmd = (qw/git config/, "--file=$git_dir/config",
497                         'include.path', '../../all.git/config');
498         PublicInbox::Import::run_die(\@cmd);
499
500         my $alt = "$all/objects/info/alternates";
501         my %alts;
502         my @add;
503         if (-e $alt) {
504                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
505                 %alts = map { chomp; $_ => 1 } (<$fh>);
506         }
507         foreach my $i (0..$epoch) {
508                 my $dir = "../../git/$i.git/objects";
509                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
510         }
511         return $git_dir unless @add;
512         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
513         foreach my $dir (@add) {
514                 print $fh "$dir\n" or die "print >> $alt: $!\n";
515         }
516         close $fh or die "close $alt: $!\n";
517         $git_dir
518 }
519
520 sub git_dir_latest {
521         my ($self, $max) = @_;
522         $$max = -1;
523         my $pfx = "$self->{-inbox}->{mainrepo}/git";
524         return unless -d $pfx;
525         my $latest;
526         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
527         while (defined(my $git_dir = readdir($dh))) {
528                 $git_dir =~ m!\A(\d+)\.git\z! or next;
529                 if ($1 > $$max) {
530                         $$max = $1;
531                         $latest = "$pfx/$git_dir";
532                 }
533         }
534         $latest;
535 }
536
537 sub importer {
538         my ($self) = @_;
539         my $im = $self->{im};
540         if ($im) {
541                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
542                         return $im;
543                 } else {
544                         $self->{im} = undef;
545                         $im->done;
546                         $im = undef;
547                         $self->checkpoint;
548                         my $git_dir = $self->git_init(++$self->{epoch_max});
549                         my $git = PublicInbox::Git->new($git_dir);
550                         return $self->import_init($git, 0);
551                 }
552         }
553         my $epoch = 0;
554         my $max;
555         my $latest = git_dir_latest($self, \$max);
556         if (defined $latest) {
557                 my $git = PublicInbox::Git->new($latest);
558                 my $packed_bytes = $git->packed_bytes;
559                 if ($packed_bytes >= $self->{rotate_bytes}) {
560                         $epoch = $max + 1;
561                 } else {
562                         $self->{epoch_max} = $max;
563                         return $self->import_init($git, $packed_bytes);
564                 }
565         }
566         $self->{epoch_max} = $epoch;
567         $latest = $self->git_init($epoch);
568         $self->import_init(PublicInbox::Git->new($latest), 0);
569 }
570
571 sub import_init {
572         my ($self, $git, $packed_bytes, $tmp) = @_;
573         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
574         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
575         $im->{want_object_info} = 1;
576         $im->{lock_path} = undef;
577         $im->{path_type} = 'v2';
578         $self->{im} = $im unless $tmp;
579         $im;
580 }
581
582 # XXX experimental
583 sub diff ($$$) {
584         my ($mid, $cur, $new) = @_;
585         use File::Temp qw(tempfile);
586
587         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
588         print $ah $cur->as_string or die "print: $!";
589         close $ah or die "close: $!";
590         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
591         PublicInbox::Import::drop_unwanted_headers($new);
592         print $bh $new->as_string or die "print: $!";
593         close $bh or die "close: $!";
594         my $cmd = [ qw(diff -u), $an, $bn ];
595         print STDERR "# MID conflict <$mid>\n";
596         my $pid = spawn($cmd, undef, { 1 => 2 });
597         defined $pid or die "diff failed to spawn $!";
598         waitpid($pid, 0) == $pid or die "diff did not finish";
599         unlink($an, $bn);
600 }
601
602 sub get_blob ($$) {
603         my ($self, $smsg) = @_;
604         if (my $im = $self->{im}) {
605                 my $msg = $im->cat_blob($smsg->{blob});
606                 return $msg if $msg;
607         }
608         # older message, should be in alternates
609         my $ibx = $self->{-inbox};
610         $ibx->msg_by_smsg($smsg);
611 }
612
613 sub lookup_content {
614         my ($self, $mime, $mid) = @_;
615         my $over = $self->{over};
616         my $cids = content_ids($mime);
617         my ($id, $prev);
618         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
619                 my $msg = get_blob($self, $smsg);
620                 if (!defined($msg)) {
621                         warn "broken smsg for $mid\n";
622                         next;
623                 }
624                 my $cur = PublicInbox::MIME->new($msg);
625                 if (content_matches($cids, $cur)) {
626                         $smsg->{mime} = $cur;
627                         return $smsg;
628                 }
629
630
631                 # XXX DEBUG_DIFF is experimental and may be removed
632                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
633         }
634         undef;
635 }
636
637 sub atfork_child {
638         my ($self) = @_;
639         my $fh = delete $self->{reindex_pipe};
640         close $fh if $fh;
641         if (my $parts = $self->{idx_parts}) {
642                 $_->atfork_child foreach @$parts;
643         }
644         if (my $im = $self->{im}) {
645                 $im->atfork_child;
646         }
647         die "unexpected mm" if $self->{mm};
648         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
649         $self->{bnote}->[1];
650 }
651
652 sub mark_deleted {
653         my ($self, $D, $git, $oid) = @_;
654         my $msgref = $git->cat_file($oid);
655         my $mime = PublicInbox::MIME->new($$msgref);
656         my $mids = mids($mime->header_obj);
657         my $cid = content_id($mime);
658         foreach my $mid (@$mids) {
659                 $D->{"$mid\0$cid"} = $oid;
660         }
661 }
662
663 sub reindex_oid {
664         my ($self, $mm_tmp, $D, $git, $oid, $regen, $reindex) = @_;
665         my $len;
666         my $msgref = $git->cat_file($oid, \$len);
667         my $mime = PublicInbox::MIME->new($$msgref);
668         my $mids = mids($mime->header_obj);
669         my $cid = content_id($mime);
670
671         # get the NNTP article number we used before, highest number wins
672         # and gets deleted from mm_tmp;
673         my $mid0;
674         my $num = -1;
675         my $del = 0;
676         foreach my $mid (@$mids) {
677                 $del += delete($D->{"$mid\0$cid"}) ? 1 : 0;
678                 my $n = $mm_tmp->num_for($mid);
679                 if (defined $n && $n > $num) {
680                         $mid0 = $mid;
681                         $num = $n;
682                         $self->{mm}->mid_set($num, $mid0);
683                 }
684         }
685         if (!defined($mid0) && $regen && !$del) {
686                 $num = $$regen--;
687                 die "BUG: ran out of article numbers\n" if $num <= 0;
688                 my $mm = $self->{mm};
689                 foreach my $mid (reverse @$mids) {
690                         if ($mm->mid_set($num, $mid) == 1) {
691                                 $mid0 = $mid;
692                                 last;
693                         }
694                 }
695                 if (!defined($mid0)) {
696                         my $id = '<' . join('> <', @$mids) . '>';
697                         warn "Message-ID $id unusable for $num\n";
698                         foreach my $mid (@$mids) {
699                                 defined(my $n = $mm->num_for($mid)) or next;
700                                 warn "#$n previously mapped for <$mid>\n";
701                         }
702                 }
703         }
704
705         if (!defined($mid0) || $del) {
706                 if (!defined($mid0) && $del) { # expected for deletes
707                         $num = $$regen--;
708                         $self->{mm}->num_highwater($num) unless $reindex;
709                         return
710                 }
711
712                 my $id = '<' . join('> <', @$mids) . '>';
713                 defined($mid0) or
714                         warn "Skipping $id, no article number found\n";
715                 if ($del && defined($mid0)) {
716                         warn "$id was deleted $del " .
717                                 "time(s) but mapped to article #$num\n";
718                 }
719                 return;
720
721         }
722         $mm_tmp->mid_delete($mid0) or
723                 die "failed to delete <$mid0> for article #$num\n";
724
725         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
726         my $nparts = $self->{partitions};
727         my $part = $num % $nparts;
728         my $idx = $self->idx_part($part);
729         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
730         my $n = $self->{transact_bytes} += $len;
731         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
732                 $git->cleanup;
733                 $mm_tmp->atfork_prepare;
734                 $self->done; # release lock
735                 # allow -watch or -mda to write...
736                 $self->idx_init; # reacquire lock
737                 $mm_tmp->atfork_parent;
738         }
739 }
740
741 # only update last_commit for $i on reindex iff newer than current
742 sub update_last_commit {
743         my ($self, $git, $i, $cmt) = @_;
744         my $last = last_commit_part($self, $i);
745         if (defined $last && is_ancestor($git, $last, $cmt)) {
746                 my @cmd = (qw(rev-list --count), "$last..$cmt");
747                 chomp(my $n = $git->qx(@cmd));
748                 return if $n ne '' && $n == 0;
749         }
750         last_commit_part($self, $i, $cmt);
751 }
752
753 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
754
755 sub last_commits {
756         my ($self, $epoch_max) = @_;
757         my $heads = [];
758         for (my $i = $epoch_max; $i >= 0; $i--) {
759                 $heads->[$i] = last_commit_part($self, $i);
760         }
761         $heads;
762 }
763
764 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
765
766 sub index_prepare {
767         my ($self, $opts, $epoch_max, $ranges) = @_;
768         my $regen_max = 0;
769         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
770         for (my $i = $epoch_max; $i >= 0; $i--) {
771                 die "already indexing!\n" if $self->{index_pipe};
772                 my $git_dir = git_dir_n($self, $i);
773                 -d $git_dir or next; # missing parts are fine
774                 my $git = PublicInbox::Git->new($git_dir);
775                 chomp(my $tip = $git->qx('rev-parse', $head));
776                 my $range;
777                 if (defined(my $cur = $ranges->[$i])) {
778                         $range = "$cur..$tip";
779                         if (is_ancestor($git, $cur, $tip)) { # common case
780                                 my $n = $git->qx(qw(rev-list --count), $range);
781                                 chomp($n);
782                                 if ($n == 0) {
783                                         $ranges->[$i] = undef;
784                                         next;
785                                 }
786                         } else {
787                                 warn <<"";
788 discontiguous range: $range
789 Rewritten history? (in $git_dir)
790
791                                 my $base = $git->qx('merge-base', $tip, $cur);
792                                 chomp $base;
793                                 if ($base) {
794                                         $range = "$base..$tip";
795                                         warn "found merge-base: $base\n"
796                                 } else {
797                                         $range = $tip;
798                                         warn <<"";
799 discarding history at $cur
800
801                                 }
802                                 warn <<"";
803 reindexing $git_dir starting at
804 $range
805
806                                 $self->{"unindex-range.$i"} = "$base..$cur";
807                         }
808                 } else {
809                         $range = $tip; # all of it
810                 }
811                 $ranges->[$i] = $range;
812
813                 # can't use 'rev-list --count' if we use --diff-filter
814                 my $fh = $git->popen(qw(log --pretty=tformat:%H
815                                 --no-notes --no-color --no-renames
816                                 --diff-filter=AM), $range, '--', 'm');
817                 ++$regen_max while <$fh>;
818         }
819         \$regen_max;
820 }
821
822 sub unindex_oid_remote {
823         my ($self, $oid, $mid) = @_;
824         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
825         $self->{over}->remove_oid($oid, $mid);
826 }
827
828 sub unindex_oid {
829         my ($self, $git, $oid) = @_;
830         my $msgref = $git->cat_file($oid);
831         my $mime = PublicInbox::MIME->new($msgref);
832         my $mids = mids($mime->header_obj);
833         $mime = $msgref = undef;
834         my $over = $self->{over};
835         foreach my $mid (@$mids) {
836                 my %gone;
837                 my ($id, $prev);
838                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
839                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
840                         1; # continue
841                 }
842                 my $n = scalar keys %gone;
843                 next unless $n;
844                 if ($n > 1) {
845                         warn "BUG: multiple articles linked to $oid\n",
846                                 join(',',sort keys %gone), "\n";
847                 }
848                 foreach my $num (keys %gone) {
849                         $self->{unindexed}->{$_}++;
850                         $self->{mm}->num_delete($num);
851                 }
852                 $self->unindex_oid_remote($oid, $mid);
853         }
854 }
855
856 my $x40 = qr/[a-f0-9]{40}/;
857 sub unindex {
858         my ($self, $opts, $git, $unindex_range) = @_;
859         my $un = $self->{unindexed} ||= {}; # num => removal count
860         my $before = scalar keys %$un;
861         my @cmd = qw(log --raw -r
862                         --no-notes --no-color --no-abbrev --no-renames);
863         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
864         while (<$fh>) {
865                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
866                 $self->unindex_oid($git, $1);
867         }
868         delete $self->{reindex_pipe};
869         $fh = undef;
870
871         return unless $opts->{prune};
872         my $after = scalar keys %$un;
873         return if $before == $after;
874
875         # ensure any blob can not longer be accessed via dumb HTTP
876         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
877                 qw(-c gc.reflogExpire=now gc --prune=all)]);
878 }
879
880 sub index_sync {
881         my ($self, $opts) = @_;
882         $opts ||= {};
883         my $epoch_max;
884         my $latest = git_dir_latest($self, \$epoch_max);
885         return unless defined $latest;
886         $self->idx_init; # acquire lock
887         my $mm_tmp = $self->{mm}->tmp_clone;
888         my $reindex = $opts->{reindex};
889         my $ranges = $reindex ? [] : $self->last_commits($epoch_max);
890
891         my $high = $self->{mm}->num_highwater();
892         my $regen = $self->index_prepare($opts, $epoch_max, $ranges);
893         $$regen += $high if $high;
894         my $D = {}; # "$mid\0$cid" => $oid
895         my @cmd = qw(log --raw -r --pretty=tformat:%H
896                         --no-notes --no-color --no-abbrev --no-renames);
897
898         # work backwards through history
899         my $last_commit = [];
900         for (my $i = $epoch_max; $i >= 0; $i--) {
901                 my $git_dir = git_dir_n($self, $i);
902                 die "already reindexing!\n" if delete $self->{reindex_pipe};
903                 -d $git_dir or next; # missing parts are fine
904                 my $git = PublicInbox::Git->new($git_dir);
905                 my $unindex = delete $self->{"unindex-range.$i"};
906                 $self->unindex($opts, $git, $unindex) if $unindex;
907                 defined(my $range = $ranges->[$i]) or next;
908                 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
909                 my $cmt;
910                 while (<$fh>) {
911                         if (/\A$x40$/o && !defined($cmt)) {
912                                 chomp($cmt = $_);
913                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
914                                 $self->reindex_oid($mm_tmp, $D, $git, $1,
915                                                 $regen, $reindex);
916                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
917                                 $self->mark_deleted($D, $git, $1);
918                         }
919                 }
920                 $fh = undef;
921                 delete $self->{reindex_pipe};
922                 $self->update_last_commit($git, $i, $cmt) if defined $cmt;
923         }
924
925         # unindex is required for leftovers if "deletes" affect messages
926         # in a previous fetch+index window:
927         if (scalar keys %$D) {
928                 my $git = $self->{-inbox}->git;
929                 $self->unindex_oid($git, $_) for values %$D;
930                 $git->cleanup;
931         }
932         $self->done;
933 }
934
935 1;