]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
V2Writeable.pm: Ensure that a found message number is in the msgmap
[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 %alts;
499         my @add;
500         if (-e $alt) {
501                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
502                 %alts = map { chomp; $_ => 1 } (<$fh>);
503         }
504         foreach my $i (0..$epoch) {
505                 my $dir = "../../git/$i.git/objects";
506                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
507         }
508         return $git_dir unless @add;
509         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
510         foreach my $dir (@add) {
511                 print $fh "$dir\n" or die "print >> $alt: $!\n";
512         }
513         close $fh or die "close $alt: $!\n";
514         $git_dir
515 }
516
517 sub git_dir_latest {
518         my ($self, $max) = @_;
519         $$max = -1;
520         my $pfx = "$self->{-inbox}->{mainrepo}/git";
521         return unless -d $pfx;
522         my $latest;
523         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
524         while (defined(my $git_dir = readdir($dh))) {
525                 $git_dir =~ m!\A(\d+)\.git\z! or next;
526                 if ($1 > $$max) {
527                         $$max = $1;
528                         $latest = "$pfx/$git_dir";
529                 }
530         }
531         $latest;
532 }
533
534 sub importer {
535         my ($self) = @_;
536         my $im = $self->{im};
537         if ($im) {
538                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
539                         return $im;
540                 } else {
541                         $self->{im} = undef;
542                         $im->done;
543                         $im = undef;
544                         $self->checkpoint;
545                         my $git_dir = $self->git_init(++$self->{epoch_max});
546                         my $git = PublicInbox::Git->new($git_dir);
547                         return $self->import_init($git, 0);
548                 }
549         }
550         my $epoch = 0;
551         my $max;
552         my $latest = git_dir_latest($self, \$max);
553         if (defined $latest) {
554                 my $git = PublicInbox::Git->new($latest);
555                 my $packed_bytes = $git->packed_bytes;
556                 if ($packed_bytes >= $self->{rotate_bytes}) {
557                         $epoch = $max + 1;
558                 } else {
559                         $self->{epoch_max} = $max;
560                         return $self->import_init($git, $packed_bytes);
561                 }
562         }
563         $self->{epoch_max} = $epoch;
564         $latest = $self->git_init($epoch);
565         $self->import_init(PublicInbox::Git->new($latest), 0);
566 }
567
568 sub import_init {
569         my ($self, $git, $packed_bytes, $tmp) = @_;
570         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
571         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
572         $im->{want_object_info} = 1;
573         $im->{lock_path} = undef;
574         $im->{path_type} = 'v2';
575         $self->{im} = $im unless $tmp;
576         $im;
577 }
578
579 # XXX experimental
580 sub diff ($$$) {
581         my ($mid, $cur, $new) = @_;
582         use File::Temp qw(tempfile);
583
584         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
585         print $ah $cur->as_string or die "print: $!";
586         close $ah or die "close: $!";
587         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
588         PublicInbox::Import::drop_unwanted_headers($new);
589         print $bh $new->as_string or die "print: $!";
590         close $bh or die "close: $!";
591         my $cmd = [ qw(diff -u), $an, $bn ];
592         print STDERR "# MID conflict <$mid>\n";
593         my $pid = spawn($cmd, undef, { 1 => 2 });
594         defined $pid or die "diff failed to spawn $!";
595         waitpid($pid, 0) == $pid or die "diff did not finish";
596         unlink($an, $bn);
597 }
598
599 sub get_blob ($$) {
600         my ($self, $smsg) = @_;
601         if (my $im = $self->{im}) {
602                 my $msg = $im->cat_blob($smsg->{blob});
603                 return $msg if $msg;
604         }
605         # older message, should be in alternates
606         my $ibx = $self->{-inbox};
607         $ibx->msg_by_smsg($smsg);
608 }
609
610 sub lookup_content {
611         my ($self, $mime, $mid) = @_;
612         my $over = $self->{over};
613         my $cids = content_ids($mime);
614         my ($id, $prev);
615         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
616                 my $msg = get_blob($self, $smsg);
617                 if (!defined($msg)) {
618                         warn "broken smsg for $mid\n";
619                         next;
620                 }
621                 my $cur = PublicInbox::MIME->new($msg);
622                 if (content_matches($cids, $cur)) {
623                         $smsg->{mime} = $cur;
624                         return $smsg;
625                 }
626
627
628                 # XXX DEBUG_DIFF is experimental and may be removed
629                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
630         }
631         undef;
632 }
633
634 sub atfork_child {
635         my ($self) = @_;
636         my $fh = delete $self->{reindex_pipe};
637         close $fh if $fh;
638         if (my $parts = $self->{idx_parts}) {
639                 $_->atfork_child foreach @$parts;
640         }
641         if (my $im = $self->{im}) {
642                 $im->atfork_child;
643         }
644         die "unexpected mm" if $self->{mm};
645         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
646         $self->{bnote}->[1];
647 }
648
649 sub mark_deleted {
650         my ($self, $D, $git, $oid) = @_;
651         my $msgref = $git->cat_file($oid);
652         my $mime = PublicInbox::MIME->new($$msgref);
653         my $mids = mids($mime->header_obj);
654         my $cid = content_id($mime);
655         foreach my $mid (@$mids) {
656                 $D->{"$mid\0$cid"} = $oid;
657         }
658 }
659
660 sub reindex_oid {
661         my ($self, $mm_tmp, $D, $git, $oid, $regen, $reindex) = @_;
662         my $len;
663         my $msgref = $git->cat_file($oid, \$len);
664         my $mime = PublicInbox::MIME->new($$msgref);
665         my $mids = mids($mime->header_obj);
666         my $cid = content_id($mime);
667
668         # get the NNTP article number we used before, highest number wins
669         # and gets deleted from mm_tmp;
670         my $mid0;
671         my $num = -1;
672         my $del = 0;
673         foreach my $mid (@$mids) {
674                 $del += delete($D->{"$mid\0$cid"}) ? 1 : 0;
675                 my $n = $mm_tmp->num_for($mid);
676                 if (defined $n && $n > $num) {
677                         $mid0 = $mid;
678                         $num = $n;
679                         $self->{mm}->mid_set($num, $mid0);
680                 }
681         }
682         if (!defined($mid0) && $regen && !$del) {
683                 $num = $$regen--;
684                 die "BUG: ran out of article numbers\n" if $num <= 0;
685                 my $mm = $self->{mm};
686                 foreach my $mid (reverse @$mids) {
687                         if ($mm->mid_set($num, $mid) == 1) {
688                                 $mid0 = $mid;
689                                 last;
690                         }
691                 }
692                 if (!defined($mid0)) {
693                         my $id = '<' . join('> <', @$mids) . '>';
694                         warn "Message-ID $id unusable for $num\n";
695                         foreach my $mid (@$mids) {
696                                 defined(my $n = $mm->num_for($mid)) or next;
697                                 warn "#$n previously mapped for <$mid>\n";
698                         }
699                 }
700         }
701
702         if (!defined($mid0) || $del) {
703                 if (!defined($mid0) && $del) { # expected for deletes
704                         $num = $$regen--;
705                         $self->{mm}->num_highwater($num) unless $reindex;
706                         return
707                 }
708
709                 my $id = '<' . join('> <', @$mids) . '>';
710                 defined($mid0) or
711                         warn "Skipping $id, no article number found\n";
712                 if ($del && defined($mid0)) {
713                         warn "$id was deleted $del " .
714                                 "time(s) but mapped to article #$num\n";
715                 }
716                 return;
717
718         }
719         $mm_tmp->mid_delete($mid0) or
720                 die "failed to delete <$mid0> for article #$num\n";
721
722         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
723         my $nparts = $self->{partitions};
724         my $part = $num % $nparts;
725         my $idx = $self->idx_part($part);
726         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
727         my $n = $self->{transact_bytes} += $len;
728         if ($n > (PublicInbox::SearchIdx::BATCH_BYTES * $nparts)) {
729                 $git->cleanup;
730                 $mm_tmp->atfork_prepare;
731                 $self->done; # release lock
732                 # allow -watch or -mda to write...
733                 $self->idx_init; # reacquire lock
734                 $mm_tmp->atfork_parent;
735         }
736 }
737
738 # only update last_commit for $i on reindex iff newer than current
739 sub update_last_commit {
740         my ($self, $git, $i, $cmt) = @_;
741         my $last = last_commit_part($self, $i);
742         if (defined $last && is_ancestor($git, $last, $cmt)) {
743                 my @cmd = (qw(rev-list --count), "$last..$cmt");
744                 chomp(my $n = $git->qx(@cmd));
745                 return if $n ne '' && $n == 0;
746         }
747         last_commit_part($self, $i, $cmt);
748 }
749
750 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
751
752 sub last_commits {
753         my ($self, $epoch_max) = @_;
754         my $heads = [];
755         for (my $i = $epoch_max; $i >= 0; $i--) {
756                 $heads->[$i] = last_commit_part($self, $i);
757         }
758         $heads;
759 }
760
761 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
762
763 sub index_prepare {
764         my ($self, $opts, $epoch_max, $ranges) = @_;
765         my $regen_max = 0;
766         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
767         for (my $i = $epoch_max; $i >= 0; $i--) {
768                 die "already indexing!\n" if $self->{index_pipe};
769                 my $git_dir = git_dir_n($self, $i);
770                 -d $git_dir or next; # missing parts are fine
771                 my $git = PublicInbox::Git->new($git_dir);
772                 chomp(my $tip = $git->qx('rev-parse', $head));
773                 my $range;
774                 if (defined(my $cur = $ranges->[$i])) {
775                         $range = "$cur..$tip";
776                         if (is_ancestor($git, $cur, $tip)) { # common case
777                                 my $n = $git->qx(qw(rev-list --count), $range);
778                                 chomp($n);
779                                 if ($n == 0) {
780                                         $ranges->[$i] = undef;
781                                         next;
782                                 }
783                         } else {
784                                 warn <<"";
785 discontiguous range: $range
786 Rewritten history? (in $git_dir)
787
788                                 my $base = $git->qx('merge-base', $tip, $cur);
789                                 chomp $base;
790                                 if ($base) {
791                                         $range = "$base..$tip";
792                                         warn "found merge-base: $base\n"
793                                 } else {
794                                         $range = $tip;
795                                         warn <<"";
796 discarding history at $cur
797
798                                 }
799                                 warn <<"";
800 reindexing $git_dir starting at
801 $range
802
803                                 $self->{"unindex-range.$i"} = "$base..$cur";
804                         }
805                 } else {
806                         $range = $tip; # all of it
807                 }
808                 $ranges->[$i] = $range;
809
810                 # can't use 'rev-list --count' if we use --diff-filter
811                 my $fh = $git->popen(qw(log --pretty=tformat:%H
812                                 --no-notes --no-color --no-renames
813                                 --diff-filter=AM), $range, '--', 'm');
814                 ++$regen_max while <$fh>;
815         }
816         \$regen_max;
817 }
818
819 sub unindex_oid_remote {
820         my ($self, $oid, $mid) = @_;
821         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
822         $self->{over}->remove_oid($oid, $mid);
823 }
824
825 sub unindex_oid {
826         my ($self, $git, $oid) = @_;
827         my $msgref = $git->cat_file($oid);
828         my $mime = PublicInbox::MIME->new($msgref);
829         my $mids = mids($mime->header_obj);
830         $mime = $msgref = undef;
831         my $over = $self->{over};
832         foreach my $mid (@$mids) {
833                 my %gone;
834                 my ($id, $prev);
835                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
836                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
837                         1; # continue
838                 }
839                 my $n = scalar keys %gone;
840                 next unless $n;
841                 if ($n > 1) {
842                         warn "BUG: multiple articles linked to $oid\n",
843                                 join(',',sort keys %gone), "\n";
844                 }
845                 $self->{unindexed}->{$_}++ foreach keys %gone;
846                 $self->unindex_oid_remote($oid, $mid);
847         }
848 }
849
850 my $x40 = qr/[a-f0-9]{40}/;
851 sub unindex {
852         my ($self, $opts, $git, $unindex_range) = @_;
853         my $un = $self->{unindexed} ||= {}; # num => removal count
854         my $before = scalar keys %$un;
855         my @cmd = qw(log --raw -r
856                         --no-notes --no-color --no-abbrev --no-renames);
857         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
858         while (<$fh>) {
859                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
860                 $self->unindex_oid($git, $1);
861         }
862         delete $self->{reindex_pipe};
863         $fh = undef;
864
865         return unless $opts->{prune};
866         my $after = scalar keys %$un;
867         return if $before == $after;
868
869         # ensure any blob can not longer be accessed via dumb HTTP
870         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
871                 qw(-c gc.reflogExpire=now gc --prune=all)]);
872 }
873
874 sub index_sync {
875         my ($self, $opts) = @_;
876         $opts ||= {};
877         my $epoch_max;
878         my $latest = git_dir_latest($self, \$epoch_max);
879         return unless defined $latest;
880         $self->idx_init; # acquire lock
881         my $mm_tmp = $self->{mm}->tmp_clone;
882         my $reindex = $opts->{reindex};
883         my $ranges = $reindex ? [] : $self->last_commits($epoch_max);
884
885         my $high = $self->{mm}->num_highwater();
886         my $regen = $self->index_prepare($opts, $epoch_max, $ranges);
887         $$regen += $high if $high;
888         my $D = {}; # "$mid\0$cid" => $oid
889         my @cmd = qw(log --raw -r --pretty=tformat:%H
890                         --no-notes --no-color --no-abbrev --no-renames);
891
892         # work backwards through history
893         my $last_commit = [];
894         for (my $i = $epoch_max; $i >= 0; $i--) {
895                 my $git_dir = git_dir_n($self, $i);
896                 die "already reindexing!\n" if delete $self->{reindex_pipe};
897                 -d $git_dir or next; # missing parts are fine
898                 my $git = PublicInbox::Git->new($git_dir);
899                 my $unindex = delete $self->{"unindex-range.$i"};
900                 $self->unindex($opts, $git, $unindex) if $unindex;
901                 defined(my $range = $ranges->[$i]) or next;
902                 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
903                 my $cmt;
904                 while (<$fh>) {
905                         if (/\A$x40$/o && !defined($cmt)) {
906                                 chomp($cmt = $_);
907                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
908                                 $self->reindex_oid($mm_tmp, $D, $git, $1,
909                                                 $regen, $reindex);
910                         } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
911                                 $self->mark_deleted($D, $git, $1);
912                         }
913                 }
914                 $fh = undef;
915                 delete $self->{reindex_pipe};
916                 $self->update_last_commit($git, $i, $cmt) if defined $cmt;
917         }
918
919         # unindex is required for leftovers if "deletes" affect messages
920         # in a previous fetch+index window:
921         if (scalar keys %$D) {
922                 my $git = $self->{-inbox}->git;
923                 $self->unindex_oid($git, $_) for values %$D;
924                 $git->cleanup;
925         }
926         $self->done;
927 }
928
929 1;