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