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