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