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