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