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