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