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