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