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