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