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