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