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