]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
0dcdedae54c914675559733b5364255c34206c41
[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 remove_internal {
263         my ($self, $mime, $cmt_msg, $purge) = @_;
264         $self->idx_init;
265         my $im = $self->importer unless $purge;
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 = get_blob($self, $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         }
317
318         if (defined $mark) {
319                 my $cmt = $im->get_mark($mark);
320                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
321         }
322         if ($purge && scalar keys %$purge) {
323                 return purge_oids($self, $purge);
324         }
325         $removed;
326 }
327
328 sub remove {
329         my ($self, $mime, $cmt_msg) = @_;
330         remove_internal($self, $mime, $cmt_msg);
331 }
332
333 sub purge {
334         my ($self, $mime) = @_;
335         my $purges = remove_internal($self, $mime, undef, {});
336         $self->idx_init if @$purges; # ->done is called on purges
337         for my $i (0..$#$purges) {
338                 defined(my $cmt = $purges->[$i]) or next;
339                 $self->{last_commit}->[$i] = $cmt;
340         }
341         $purges;
342 }
343
344 sub last_commit_part ($$;$) {
345         my ($self, $i, $cmt) = @_;
346         my $v = PublicInbox::Search::SCHEMA_VERSION();
347         $self->{mm}->last_commit_xap($v, $i, $cmt);
348 }
349
350 sub set_last_commits ($) {
351         my ($self) = @_;
352         defined(my $epoch_max = $self->{epoch_max}) or return;
353         my $last_commit = $self->{last_commit};
354         foreach my $i (0..$epoch_max) {
355                 defined(my $cmt = $last_commit->[$i]) or next;
356                 $last_commit->[$i] = undef;
357                 last_commit_part($self, $i, $cmt);
358         }
359 }
360
361 sub barrier_init {
362         my ($self, $n) = @_;
363         $self->{bnote} or return;
364         --$n;
365         my $barrier = { map { $_ => 1 } (0..$n) };
366 }
367
368 sub barrier_wait {
369         my ($self, $barrier) = @_;
370         my $bnote = $self->{bnote} or return;
371         my $r = $bnote->[0];
372         while (scalar keys %$barrier) {
373                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
374                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
375                 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
376         }
377 }
378
379 sub checkpoint ($;$) {
380         my ($self, $wait) = @_;
381
382         if (my $im = $self->{im}) {
383                 if ($wait) {
384                         $im->barrier;
385                 } else {
386                         $im->checkpoint;
387                 }
388         }
389         my $parts = $self->{idx_parts};
390         if ($parts) {
391                 my $dbh = $self->{mm}->{dbh};
392
393                 # SQLite msgmap data is second in importance
394                 $dbh->commit;
395
396                 # SQLite overview is third
397                 $self->{over}->commit_lazy;
398
399                 # Now deal with Xapian
400                 if ($wait) {
401                         my $barrier = $self->barrier_init(scalar @$parts);
402
403                         # each partition needs to issue a barrier command
404                         $_->remote_barrier for @$parts;
405
406                         # wait for each Xapian partition
407                         $self->barrier_wait($barrier);
408                 } else {
409                         $_->remote_commit for @$parts;
410                 }
411
412                 # last_commit is special, don't commit these until
413                 # remote partitions are done:
414                 $dbh->begin_work;
415                 set_last_commits($self);
416                 $dbh->commit;
417
418                 $dbh->begin_work;
419         }
420         $self->{transact_bytes} = 0;
421 }
422
423 # issue a write barrier to ensure all data is visible to other processes
424 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
425 sub barrier { checkpoint($_[0], 1) };
426
427 sub done {
428         my ($self) = @_;
429         my $im = delete $self->{im};
430         $im->done if $im; # PublicInbox::Import::done
431         checkpoint($self);
432         my $mm = delete $self->{mm};
433         $mm->{dbh}->commit if $mm;
434         my $parts = delete $self->{idx_parts};
435         if ($parts) {
436                 $_->remote_close for @$parts;
437         }
438         $self->{over}->disconnect;
439         delete $self->{bnote};
440         $self->{transact_bytes} = 0;
441         $self->lock_release if $parts;
442 }
443
444 sub git_init {
445         my ($self, $epoch) = @_;
446         my $pfx = "$self->{-inbox}->{mainrepo}/git";
447         my $git_dir = "$pfx/$epoch.git";
448         my @cmd = (qw(git init --bare -q), $git_dir);
449         PublicInbox::Import::run_die(\@cmd);
450
451         my $all = "$self->{-inbox}->{mainrepo}/all.git";
452         unless (-d $all) {
453                 @cmd = (qw(git init --bare -q), $all);
454                 PublicInbox::Import::run_die(\@cmd);
455                 @cmd = (qw/git config/, "--file=$all/config",
456                                 'repack.writeBitmaps', 'true');
457                 PublicInbox::Import::run_die(\@cmd);
458         }
459
460         @cmd = (qw/git config/, "--file=$git_dir/config",
461                         'include.path', '../../all.git/config');
462         PublicInbox::Import::run_die(\@cmd);
463
464         my $alt = "$all/objects/info/alternates";
465         my $new_obj_dir = "../../git/$epoch.git/objects";
466         my %alts;
467         if (-e $alt) {
468                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
469                 %alts = map { chomp; $_ => 1 } (<$fh>);
470         }
471         return $git_dir if $alts{$new_obj_dir};
472         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
473         print $fh "$new_obj_dir\n" or die "print >> $alt: $!\n";
474         close $fh or die "close $alt: $!\n";
475         $git_dir
476 }
477
478 sub git_dir_latest {
479         my ($self, $max) = @_;
480         $$max = -1;
481         my $pfx = "$self->{-inbox}->{mainrepo}/git";
482         return unless -d $pfx;
483         my $latest;
484         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
485         while (defined(my $git_dir = readdir($dh))) {
486                 $git_dir =~ m!\A(\d+)\.git\z! or next;
487                 if ($1 > $$max) {
488                         $$max = $1;
489                         $latest = "$pfx/$git_dir";
490                 }
491         }
492         $latest;
493 }
494
495 sub importer {
496         my ($self) = @_;
497         my $im = $self->{im};
498         if ($im) {
499                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
500                         return $im;
501                 } else {
502                         $self->{im} = undef;
503                         $im->done;
504                         $im = undef;
505                         $self->checkpoint;
506                         my $git_dir = $self->git_init(++$self->{epoch_max});
507                         my $git = PublicInbox::Git->new($git_dir);
508                         return $self->import_init($git, 0);
509                 }
510         }
511         my $epoch = 0;
512         my $max;
513         my $latest = git_dir_latest($self, \$max);
514         if (defined $latest) {
515                 my $git = PublicInbox::Git->new($latest);
516                 my $packed_bytes = $git->packed_bytes;
517                 if ($packed_bytes >= $self->{rotate_bytes}) {
518                         $epoch = $max + 1;
519                 } else {
520                         $self->{epoch_max} = $max;
521                         return $self->import_init($git, $packed_bytes);
522                 }
523         }
524         $self->{epoch_max} = $epoch;
525         $latest = $self->git_init($epoch);
526         $self->import_init(PublicInbox::Git->new($latest), 0);
527 }
528
529 sub import_init {
530         my ($self, $git, $packed_bytes, $tmp) = @_;
531         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
532         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
533         $im->{want_object_info} = 1;
534         $im->{lock_path} = undef;
535         $im->{path_type} = 'v2';
536         $self->{im} = $im unless $tmp;
537         $im;
538 }
539
540 # XXX experimental
541 sub diff ($$$) {
542         my ($mid, $cur, $new) = @_;
543         use File::Temp qw(tempfile);
544         use PublicInbox::Spawn qw(spawn);
545
546         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
547         print $ah $cur->as_string or die "print: $!";
548         close $ah or die "close: $!";
549         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
550         PublicInbox::Import::drop_unwanted_headers($new);
551         print $bh $new->as_string or die "print: $!";
552         close $bh or die "close: $!";
553         my $cmd = [ qw(diff -u), $an, $bn ];
554         print STDERR "# MID conflict <$mid>\n";
555         my $pid = spawn($cmd, undef, { 1 => 2 });
556         defined $pid or die "diff failed to spawn $!";
557         waitpid($pid, 0) == $pid or die "diff did not finish";
558         unlink($an, $bn);
559 }
560
561 sub get_blob ($$) {
562         my ($self, $smsg) = @_;
563         if (my $im = $self->{im}) {
564                 my $msg = $im->cat_blob($smsg->{blob});
565                 return $msg if $msg;
566         }
567         # older message, should be in alternates
568         my $ibx = $self->{-inbox};
569         $ibx->msg_by_smsg($smsg);
570 }
571
572 sub lookup_content {
573         my ($self, $mime, $mid) = @_;
574         my $over = $self->{over};
575         my $cid = content_id($mime);
576         my $found;
577         my ($id, $prev);
578         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
579                 my $msg = get_blob($self, $smsg);
580                 if (!defined($msg)) {
581                         warn "broken smsg for $mid\n";
582                         next;
583                 }
584                 my $cur = PublicInbox::MIME->new($msg);
585                 if (content_id($cur) eq $cid) {
586                         $smsg->{mime} = $cur;
587                         $found = $smsg;
588                         last;
589                 }
590
591                 # XXX DEBUG_DIFF is experimental and may be removed
592                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
593         }
594         $found;
595 }
596
597 sub atfork_child {
598         my ($self) = @_;
599         my $fh = delete $self->{reindex_pipe};
600         close $fh if $fh;
601         if (my $parts = $self->{idx_parts}) {
602                 $_->atfork_child foreach @$parts;
603         }
604         if (my $im = $self->{im}) {
605                 $im->atfork_child;
606         }
607         die "unexpected mm" if $self->{mm};
608         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
609         $self->{bnote}->[1];
610 }
611
612 sub mark_deleted {
613         my ($self, $D, $git, $oid) = @_;
614         my $msgref = $git->cat_file($oid);
615         my $mime = PublicInbox::MIME->new($$msgref);
616         my $mids = mids($mime->header_obj);
617         my $cid = content_id($mime);
618         foreach my $mid (@$mids) {
619                 $D->{"$mid\0$cid"} = 1;
620         }
621 }
622
623 sub reindex_oid {
624         my ($self, $mm_tmp, $D, $git, $oid, $regen) = @_;
625         my $len;
626         my $msgref = $git->cat_file($oid, \$len);
627         my $mime = PublicInbox::MIME->new($$msgref);
628         my $mids = mids($mime->header_obj);
629         my $cid = content_id($mime);
630
631         # get the NNTP article number we used before, highest number wins
632         # and gets deleted from mm_tmp;
633         my $mid0;
634         my $num = -1;
635         my $del = 0;
636         foreach my $mid (@$mids) {
637                 $del += (delete $D->{"$mid\0$cid"} || 0);
638                 my $n = $mm_tmp->num_for($mid);
639                 if (defined $n && $n > $num) {
640                         $mid0 = $mid;
641                         $num = $n;
642                 }
643         }
644         if (!defined($mid0) && $regen && !$del) {
645                 $num = $$regen--;
646                 die "BUG: ran out of article numbers\n" if $num <= 0;
647                 my $mm = $self->{mm};
648                 foreach my $mid (reverse @$mids) {
649                         if ($mm->mid_set($num, $mid) == 1) {
650                                 $mid0 = $mid;
651                                 last;
652                         }
653                 }
654                 if (!defined($mid0)) {
655                         my $id = '<' . join('> <', @$mids) . '>';
656                         warn "Message-ID $id unusable for $num\n";
657                         foreach my $mid (@$mids) {
658                                 defined(my $n = $mm->num_for($mid)) or next;
659                                 warn "#$n previously mapped for <$mid>\n";
660                         }
661                 }
662         }
663
664         if (!defined($mid0) || $del) {
665                 if (!defined($mid0) && $del) { # expected for deletes
666                         $$regen--;
667                         return
668                 }
669
670                 my $id = '<' . join('> <', @$mids) . '>';
671                 defined($mid0) or
672                         warn "Skipping $id, no article number found\n";
673                 if ($del && defined($mid0)) {
674                         warn "$id was deleted $del " .
675                                 "time(s) but mapped to article #$num\n";
676                 }
677                 return;
678
679         }
680         $mm_tmp->mid_delete($mid0) or
681                 die "failed to delete <$mid0> for article #$num\n";
682
683         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
684         my $nparts = $self->{partitions};
685         my $part = $num % $nparts;
686         my $idx = $self->idx_part($part);
687         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
688         my $n = $self->{transact_bytes} += $len;
689         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
690                 $git->cleanup;
691                 $mm_tmp->atfork_prepare;
692                 $self->done; # release lock
693                 # allow -watch or -mda to write...
694                 $self->idx_init; # reacquire lock
695                 $mm_tmp->atfork_parent;
696         }
697 }
698
699 # only update last_commit for $i on reindex iff newer than current
700 sub update_last_commit {
701         my ($self, $git, $i, $cmt) = @_;
702         my $last = last_commit_part($self, $i);
703         if (defined $last && is_ancestor($git, $last, $cmt)) {
704                 my @cmd = (qw(rev-list --count), "$last..$cmt");
705                 chomp(my $n = $git->qx(@cmd));
706                 return if $n ne '' && $n == 0;
707         }
708         last_commit_part($self, $i, $cmt);
709 }
710
711 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
712
713 sub last_commits {
714         my ($self, $epoch_max) = @_;
715         my $heads = [];
716         for (my $i = $epoch_max; $i >= 0; $i--) {
717                 $heads->[$i] = last_commit_part($self, $i);
718         }
719         $heads;
720 }
721
722 sub is_ancestor ($$$) {
723         my ($git, $cur, $tip) = @_;
724         return 0 unless $git->check($cur);
725         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
726                 qw(merge-base --is-ancestor), $cur, $tip ];
727         my $pid = spawn($cmd);
728         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
729         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
730         $? == 0;
731 }
732
733 sub index_prepare {
734         my ($self, $opts, $epoch_max, $ranges) = @_;
735         my $regen_max = 0;
736         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
737         for (my $i = $epoch_max; $i >= 0; $i--) {
738                 die "already indexing!\n" if $self->{index_pipe};
739                 my $git_dir = git_dir_n($self, $i);
740                 -d $git_dir or next; # missing parts are fine
741                 my $git = PublicInbox::Git->new($git_dir);
742                 chomp(my $tip = $git->qx('rev-parse', $head));
743                 my $range;
744                 if (defined(my $cur = $ranges->[$i])) {
745                         $range = "$cur..$tip";
746                         if (is_ancestor($git, $cur, $tip)) { # common case
747                                 my $n = $git->qx(qw(rev-list --count), $range);
748                                 chomp($n);
749                                 if ($n == 0) {
750                                         $ranges->[$i] = undef;
751                                         next;
752                                 }
753                         } else {
754                                 warn <<"";
755 discontiguous range: $range
756 Rewritten history? (in $git_dir)
757
758                                 my $base = $git->qx('merge-base', $tip, $cur);
759                                 chomp $base;
760                                 if ($base) {
761                                         $range = "$base..$tip";
762                                         warn "found merge-base: $base\n"
763                                 } else {
764                                         $range = $tip;
765                                         warn <<"";
766 discarding history at $cur
767
768                                 }
769                                 warn <<"";
770 reindexing $git_dir starting at
771 $range
772
773                                 $self->{"unindex-range.$i"} = "$base..$cur";
774                         }
775                 } else {
776                         $range = $tip; # all of it
777                 }
778                 $ranges->[$i] = $range;
779
780                 # can't use 'rev-list --count' if we use --diff-filter
781                 my $fh = $git->popen(qw(log --pretty=tformat:%h
782                                 --no-notes --no-color --no-renames
783                                 --diff-filter=AM), $range, '--', 'm');
784                 ++$regen_max while <$fh>;
785         }
786         \$regen_max;
787 }
788
789 sub unindex_oid_remote {
790         my ($self, $oid, $mid) = @_;
791         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
792         $self->{over}->remove_oid($oid, $mid);
793 }
794
795 sub unindex_oid {
796         my ($self, $git, $oid) = @_;
797         my $msgref = $git->cat_file($oid);
798         my $mime = PublicInbox::MIME->new($msgref);
799         my $mids = mids($mime->header_obj);
800         $mime = $msgref = undef;
801         my $over = $self->{over};
802         foreach my $mid (@$mids) {
803                 my %gone;
804                 my ($id, $prev);
805                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
806                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
807                         1; # continue
808                 }
809                 my $n = scalar keys %gone;
810                 next unless $n;
811                 if ($n > 1) {
812                         warn "BUG: multiple articles linked to $oid\n",
813                                 join(',',sort keys %gone), "\n";
814                 }
815                 $self->{unindexed}->{$_}++ foreach keys %gone;
816                 $self->unindex_oid_remote($oid, $mid);
817         }
818 }
819
820 my $x40 = qr/[a-f0-9]{40}/;
821 sub unindex {
822         my ($self, $opts, $git, $unindex_range) = @_;
823         my $un = $self->{unindexed} ||= {}; # num => removal count
824         my $before = scalar keys %$un;
825         my @cmd = qw(log --raw -r
826                         --no-notes --no-color --no-abbrev --no-renames);
827         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
828         while (<$fh>) {
829                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
830                 $self->unindex_oid($git, $1);
831         }
832         delete $self->{reindex_pipe};
833         $fh = undef;
834
835         return unless $opts->{prune};
836         my $after = scalar keys %$un;
837         return if $before == $after;
838
839         # ensure any blob can not longer be accessed via dumb HTTP
840         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
841                 qw(-c gc.reflogExpire=now gc --prune=all)]);
842 }
843
844 sub index_sync {
845         my ($self, $opts) = @_;
846         $opts ||= {};
847         my $epoch_max;
848         my $latest = git_dir_latest($self, \$epoch_max);
849         return unless defined $latest;
850         $self->idx_init; # acquire lock
851         my $mm_tmp = $self->{mm}->tmp_clone;
852         my $ranges = $opts->{reindex} ? [] : $self->last_commits($epoch_max);
853
854         my ($min, $max) = $mm_tmp->minmax;
855         my $regen = $self->index_prepare($opts, $epoch_max, $ranges);
856         $$regen += $max if $max;
857         my $D = {};
858         my @cmd = qw(log --raw -r --pretty=tformat:%h
859                         --no-notes --no-color --no-abbrev --no-renames);
860
861         # work backwards through history
862         my $last_commit = [];
863         for (my $i = $epoch_max; $i >= 0; $i--) {
864                 my $git_dir = git_dir_n($self, $i);
865                 die "already reindexing!\n" if delete $self->{reindex_pipe};
866                 -d $git_dir or next; # missing parts are fine
867                 my $git = PublicInbox::Git->new($git_dir);
868                 my $unindex = delete $self->{"unindex-range.$i"};
869                 $self->unindex($opts, $git, $unindex) if $unindex;
870                 defined(my $range = $ranges->[$i]) or next;
871                 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
872                 my $cmt;
873                 while (<$fh>) {
874                         if (/\A$x40$/o && !defined($cmt)) {
875                                 chomp($cmt = $_);
876                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
877                                 $self->reindex_oid($mm_tmp, $D, $git, $1,
878                                                 $regen);
879                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
880                                 $self->mark_deleted($D, $git, $1);
881                         }
882                 }
883                 $fh = undef;
884                 delete $self->{reindex_pipe};
885                 $self->update_last_commit($git, $i, $cmt) if defined $cmt;
886         }
887         my @d = sort keys %$D;
888         if (@d) {
889                 warn "BUG: ", scalar(@d)," unseen deleted messages marked\n";
890                 foreach (@d) {
891                         my ($mid, undef) = split(/\0/, $_, 2);
892                         warn "<$mid>\n";
893                 }
894         }
895         $self->done;
896 }
897
898 1;