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