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