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