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