]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
Merge remote-tracking branch 'origin/edit' into next
[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 references);
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!/[0-9]+\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 # indexes a message, returns true if checkpointing is needed
120 sub do_idx ($$$$$$$) {
121         my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
122         $self->{over}->add_overview($mime, $len, $num, $oid, $mid0);
123         my $npart = $self->{partitions};
124         my $part = $num % $npart;
125         my $idx = idx_part($self, $part);
126         $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
127         my $n = $self->{transact_bytes} += $len;
128         $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $npart);
129 }
130
131 sub _add {
132         my ($self, $mime, $check_cb) = @_;
133
134         # spam check:
135         if ($check_cb) {
136                 $mime = $check_cb->($mime) or return;
137         }
138
139         # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
140         # as does SQLite 3.4.1+ (released in 2007-07-20), and
141         # Xapian 1.3.2+ (released 2015-03-15).
142         # For the most part, we can spawn git-fast-import without
143         # leaking FDs to it...
144         $self->idx_init;
145
146         my $mid0;
147         my $num = num_for($self, $mime, \$mid0);
148         defined $num or return; # duplicate
149         defined $mid0 or die "BUG: $mid0 undefined\n";
150         my $im = $self->importer;
151         my $cmt = $im->add($mime);
152         $cmt = $im->get_mark($cmt);
153         $self->{last_commit}->[$self->{epoch_max}] = $cmt;
154
155         my ($oid, $len, $msgref) = @{$im->{last_object}};
156         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
157                 $self->checkpoint;
158         }
159
160         $cmt;
161 }
162
163 sub num_for {
164         my ($self, $mime, $mid0) = @_;
165         my $mids = mids($mime->header_obj);
166         if (@$mids) {
167                 my $mid = $mids->[0];
168                 my $num = $self->{mm}->mid_insert($mid);
169                 if (defined $num) { # common case
170                         $$mid0 = $mid;
171                         return $num;
172                 };
173
174                 # crap, Message-ID is already known, hope somebody just resent:
175                 foreach my $m (@$mids) {
176                         # read-only lookup now safe to do after above barrier
177                         my $existing = lookup_content($self, $mime, $m);
178                         # easy, don't store duplicates
179                         # note: do not add more diagnostic info here since
180                         # it gets noisy on public-inbox-watch restarts
181                         return if $existing;
182                 }
183
184                 # AltId may pre-populate article numbers (e.g. X-Mail-Count
185                 # or NNTP article number), use that article number if it's
186                 # not in Over.
187                 my $altid = $self->{-inbox}->{altid};
188                 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
189                         my $num = $self->{mm}->num_for($mid);
190
191                         if (defined $num && !$self->{over}->get_art($num)) {
192                                 $$mid0 = $mid;
193                                 return $num;
194                         }
195                 }
196
197                 # very unlikely:
198                 warn "<$mid> reused for mismatched content\n";
199
200                 # try the rest of the mids
201                 for(my $i = $#$mids; $i >= 1; $i--) {
202                         my $m = $mids->[$i];
203                         $num = $self->{mm}->mid_insert($m);
204                         if (defined $num) {
205                                 warn "alternative <$m> for <$mid> found\n";
206                                 $$mid0 = $m;
207                                 return $num;
208                         }
209                 }
210         }
211         # none of the existing Message-IDs are good, generate a new one:
212         num_for_harder($self, $mime, $mid0);
213 }
214
215 sub num_for_harder {
216         my ($self, $mime, $mid0) = @_;
217
218         my $hdr = $mime->header_obj;
219         my $dig = content_digest($mime);
220         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
221         my $num = $self->{mm}->mid_insert($$mid0);
222         unless (defined $num) {
223                 # it's hard to spoof the last Received: header
224                 my @recvd = $hdr->header_raw('Received');
225                 $dig->add("Received: $_") foreach (@recvd);
226                 $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
227                 $num = $self->{mm}->mid_insert($$mid0);
228
229                 # fall back to a random Message-ID and give up determinism:
230                 until (defined($num)) {
231                         $dig->add(rand);
232                         $$mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
233                         warn "using random Message-ID <$$mid0> as fallback\n";
234                         $num = $self->{mm}->mid_insert($$mid0);
235                 }
236         }
237         PublicInbox::Import::append_mid($hdr, $$mid0);
238         $num;
239 }
240
241 sub idx_part {
242         my ($self, $part) = @_;
243         $self->{idx_parts}->[$part];
244 }
245
246 # idempotent
247 sub idx_init {
248         my ($self, $opt) = @_;
249         return if $self->{idx_parts};
250         my $ibx = $self->{-inbox};
251
252         # do not leak read-only FDs to child processes, we only have these
253         # FDs for duplicate detection so they should not be
254         # frequently activated.
255         delete $ibx->{$_} foreach (qw(git mm search));
256
257         my $indexlevel = $ibx->{indexlevel};
258         if ($indexlevel && $indexlevel eq 'basic') {
259                 $self->{parallel} = 0;
260         }
261
262         if ($self->{parallel}) {
263                 pipe(my ($r, $w)) or die "pipe failed: $!";
264                 # pipe for barrier notifications doesn't need to be big,
265                 # 1031: F_SETPIPE_SZ
266                 fcntl($w, 1031, 4096) if $^O eq 'linux';
267                 $self->{bnote} = [ $r, $w ];
268                 $w->autoflush(1);
269         }
270
271         my $over = $self->{over};
272         $ibx->umask_prepare;
273         $ibx->with_umask(sub {
274                 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
275                 $over->create;
276
277                 # -compact can change partition count while -watch is idle
278                 my $nparts = count_partitions($self);
279                 if ($nparts && $nparts != $self->{partitions}) {
280                         $self->{partitions} = $nparts;
281                 }
282
283                 # need to create all parts before initializing msgmap FD
284                 my $max = $self->{partitions} - 1;
285
286                 # idx_parts must be visible to all forked processes
287                 my $idx = $self->{idx_parts} = [];
288                 for my $i (0..$max) {
289                         push @$idx, PublicInbox::SearchIdxPart->new($self, $i);
290                 }
291
292                 # Now that all subprocesses are up, we can open the FDs
293                 # for SQLite:
294                 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
295                         "$self->{-inbox}->{mainrepo}/msgmap.sqlite3", 1);
296                 $mm->{dbh}->begin_work;
297         });
298 }
299
300 # returns an array mapping [ epoch => latest_commit ]
301 # latest_commit may be undef if nothing was done to that epoch
302 # $replace_map = { $object_id => $strref, ... }
303 sub _replace_oids ($$$) {
304         my ($self, $mime, $replace_map) = @_;
305         $self->done;
306         my $pfx = "$self->{-inbox}->{mainrepo}/git";
307         my $rewrites = []; # epoch => commit
308         my $max = $self->{epoch_max};
309
310         unless (defined($max)) {
311                 defined(my $latest = git_dir_latest($self, \$max)) or return;
312                 $self->{epoch_max} = $max;
313         }
314
315         foreach my $i (0..$max) {
316                 my $git_dir = "$pfx/$i.git";
317                 -d $git_dir or next;
318                 my $git = PublicInbox::Git->new($git_dir);
319                 my $im = $self->import_init($git, 0, 1);
320                 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
321                 $im->done;
322         }
323         $rewrites;
324 }
325
326 sub content_ids ($) {
327         my ($mime) = @_;
328         my @cids = ( content_id($mime) );
329
330         # Email::MIME->as_string doesn't always round-trip, so we may
331         # use a second content_id
332         my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
333         push @cids, $rt if $cids[0] ne $rt;
334         \@cids;
335 }
336
337 sub content_matches ($$) {
338         my ($cids, $existing) = @_;
339         my $cid = content_id($existing);
340         foreach (@$cids) {
341                 return 1 if $_ eq $cid
342         }
343         0
344 }
345
346 # used for removing or replacing (purging)
347 sub rewrite_internal ($$;$$$) {
348         my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
349         $self->idx_init;
350         my ($im, $need_reindex, $replace_map);
351         if ($sref) {
352                 $replace_map = {}; # oid => sref
353                 $need_reindex = [] if $new_mime;
354         } else {
355                 $im = $self->importer;
356         }
357         my $over = $self->{over};
358         my $cids = content_ids($old_mime);
359         my $parts = $self->{idx_parts};
360         my $removed;
361         my $mids = mids($old_mime->header_obj);
362
363         # We avoid introducing new blobs into git since the raw content
364         # can be slightly different, so we do not need the user-supplied
365         # message now that we have the mids and content_id
366         $old_mime = undef;
367         my $mark;
368
369         foreach my $mid (@$mids) {
370                 my %gone; # num => [ smsg, raw ]
371                 my ($id, $prev);
372                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
373                         my $msg = get_blob($self, $smsg);
374                         if (!defined($msg)) {
375                                 warn "broken smsg for $mid\n";
376                                 next; # continue
377                         }
378                         my $orig = $$msg;
379                         my $cur = PublicInbox::MIME->new($msg);
380                         if (content_matches($cids, $cur)) {
381                                 $smsg->{mime} = $cur;
382                                 $gone{$smsg->{num}} = [ $smsg, \$orig ];
383                         }
384                 }
385                 my $n = scalar keys %gone;
386                 next unless $n;
387                 if ($n > 1) {
388                         warn "BUG: multiple articles linked to <$mid>\n",
389                                 join(',', sort keys %gone), "\n";
390                 }
391                 foreach my $num (keys %gone) {
392                         my ($smsg, $orig) = @{$gone{$num}};
393                         # $removed should only be set once assuming
394                         # no bugs in our deduplication code:
395                         $removed = $smsg;
396                         my $oid = $smsg->{blob};
397                         if ($replace_map) {
398                                 $replace_map->{$oid} = $sref;
399                         } else {
400                                 ($mark, undef) = $im->remove($orig, $cmt_msg);
401                         }
402                         $orig = undef;
403                         if ($need_reindex) { # ->replace
404                                 push @$need_reindex, $smsg;
405                         } else { # ->purge or ->remove
406                                 $self->{mm}->num_delete($num);
407                         }
408                         unindex_oid_remote($self, $oid, $mid);
409                 }
410         }
411
412         if (defined $mark) {
413                 my $cmt = $im->get_mark($mark);
414                 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
415         }
416         if ($replace_map && scalar keys %$replace_map) {
417                 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
418                 return { rewrites => $rewrites, need_reindex => $need_reindex };
419         }
420         $removed;
421 }
422
423 # public
424 sub remove {
425         my ($self, $mime, $cmt_msg) = @_;
426         $self->{-inbox}->with_umask(sub {
427                 rewrite_internal($self, $mime, $cmt_msg);
428         });
429 }
430
431 sub _replace ($$;$$) {
432         my ($self, $old_mime, $new_mime, $sref) = @_;
433         my $rewritten = $self->{-inbox}->with_umask(sub {
434                 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
435         }) or return;
436
437         my $rewrites = $rewritten->{rewrites};
438         # ->done is called if there are rewrites since we gc+prune from git
439         $self->idx_init if @$rewrites;
440
441         for my $i (0..$#$rewrites) {
442                 defined(my $cmt = $rewrites->[$i]) or next;
443                 $self->{last_commit}->[$i] = $cmt;
444         }
445         $rewritten;
446 }
447
448 # public
449 sub purge {
450         my ($self, $mime) = @_;
451         my $rewritten = _replace($self, $mime, undef, \'') or return;
452         $rewritten->{rewrites}
453 }
454
455 # returns the git object_id of $fh, does not write the object to FS
456 sub git_hash_raw ($$) {
457         my ($self, $raw) = @_;
458         # grab the expected OID we have to reindex:
459         open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
460         $tmp_fh->autoflush(1);
461         print $tmp_fh $$raw or die "print \$tmp_fh: $!";
462         sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
463
464         my ($r, $w);
465         pipe($r, $w) or die "failed to create pipe: $!";
466         my $rdr = { 0 => fileno($tmp_fh), 1 => fileno($w) };
467         my $git_dir = $self->{-inbox}->git->{git_dir};
468         my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
469         my $pid = spawn($cmd, undef, $rdr);
470         close $w;
471         local $/ = "\n";
472         chomp(my $oid = <$r>);
473         waitpid($pid, 0) == $pid or die "git hash-object did not finish";
474         die "git hash-object failed: $?" if $?;
475         $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
476         $oid;
477 }
478
479 sub _check_mids_match ($$$) {
480         my ($old_list, $new_list, $hdrs) = @_;
481         my %old_mids = map { $_ => 1 } @$old_list;
482         my %new_mids = map { $_ => 1 } @$new_list;
483         my @old = keys %old_mids;
484         my @new = keys %new_mids;
485         my $err = "$hdrs may not be changed when replacing\n";
486         die $err if scalar(@old) != scalar(@new);
487         delete @new_mids{@old};
488         delete @old_mids{@new};
489         die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
490 }
491
492 # Changing Message-IDs or References with ->replace isn't supported.
493 # The rules for dealing with messages with multiple or conflicting
494 # Message-IDs are pretty complex and rethreading hasn't been fully
495 # implemented, yet.
496 sub check_mids_match ($$) {
497         my ($old_mime, $new_mime) = @_;
498         my $old = $old_mime->header_obj;
499         my $new = $new_mime->header_obj;
500         _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
501         _check_mids_match(references($old), references($new),
502                         'References/In-Reply-To');
503 }
504
505 # public
506 sub replace ($$$) {
507         my ($self, $old_mime, $new_mime) = @_;
508
509         check_mids_match($old_mime, $new_mime);
510
511         # mutt will always add Content-Length:, Status:, Lines: when editing
512         PublicInbox::Import::drop_unwanted_headers($new_mime);
513
514         my $raw = $new_mime->as_string;
515         my $expect_oid = git_hash_raw($self, \$raw);
516         my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
517         my $need_reindex = $rewritten->{need_reindex};
518
519         # just in case we have bugs in deduplication code:
520         my $n = scalar(@$need_reindex);
521         if ($n > 1) {
522                 my $list = join(', ', map {
523                                         "$_->{num}: <$_->{mid}>"
524                                 } @$need_reindex);
525                 warn <<"";
526 W: rewritten $n messages matching content of original message (expected: 1).
527 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
528 W: $list
529
530         }
531
532         # make sure we really got the OID:
533         my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
534         $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
535
536         # don't leak FDs to Xapian:
537         $self->{-inbox}->git->cleanup;
538
539         # reindex modified messages:
540         for my $smsg (@$need_reindex) {
541                 my $num = $smsg->{num};
542                 my $mid0 = $smsg->{mid};
543                 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
544         }
545         $rewritten->{rewrites};
546 }
547
548 sub last_commit_part ($$;$) {
549         my ($self, $i, $cmt) = @_;
550         my $v = PublicInbox::Search::SCHEMA_VERSION();
551         $self->{mm}->last_commit_xap($v, $i, $cmt);
552 }
553
554 sub set_last_commits ($) {
555         my ($self) = @_;
556         defined(my $epoch_max = $self->{epoch_max}) or return;
557         my $last_commit = $self->{last_commit};
558         foreach my $i (0..$epoch_max) {
559                 defined(my $cmt = $last_commit->[$i]) or next;
560                 $last_commit->[$i] = undef;
561                 last_commit_part($self, $i, $cmt);
562         }
563 }
564
565 sub barrier_init {
566         my ($self, $n) = @_;
567         $self->{bnote} or return;
568         --$n;
569         my $barrier = { map { $_ => 1 } (0..$n) };
570 }
571
572 sub barrier_wait {
573         my ($self, $barrier) = @_;
574         my $bnote = $self->{bnote} or return;
575         my $r = $bnote->[0];
576         while (scalar keys %$barrier) {
577                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
578                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
579                 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
580         }
581 }
582
583 # public
584 sub checkpoint ($;$) {
585         my ($self, $wait) = @_;
586
587         if (my $im = $self->{im}) {
588                 if ($wait) {
589                         $im->barrier;
590                 } else {
591                         $im->checkpoint;
592                 }
593         }
594         my $parts = $self->{idx_parts};
595         if ($parts) {
596                 my $dbh = $self->{mm}->{dbh};
597
598                 # SQLite msgmap data is second in importance
599                 $dbh->commit;
600
601                 # SQLite overview is third
602                 $self->{over}->commit_lazy;
603
604                 # Now deal with Xapian
605                 if ($wait) {
606                         my $barrier = $self->barrier_init(scalar @$parts);
607
608                         # each partition needs to issue a barrier command
609                         $_->remote_barrier for @$parts;
610
611                         # wait for each Xapian partition
612                         $self->barrier_wait($barrier);
613                 } else {
614                         $_->remote_commit for @$parts;
615                 }
616
617                 # last_commit is special, don't commit these until
618                 # remote partitions are done:
619                 $dbh->begin_work;
620                 set_last_commits($self);
621                 $dbh->commit;
622
623                 $dbh->begin_work;
624         }
625         $self->{transact_bytes} = 0;
626 }
627
628 # issue a write barrier to ensure all data is visible to other processes
629 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
630 # public
631 sub barrier { checkpoint($_[0], 1) };
632
633 # public
634 sub done {
635         my ($self) = @_;
636         my $im = delete $self->{im};
637         $im->done if $im; # PublicInbox::Import::done
638         checkpoint($self);
639         my $mm = delete $self->{mm};
640         $mm->{dbh}->commit if $mm;
641         my $parts = delete $self->{idx_parts};
642         if ($parts) {
643                 $_->remote_close for @$parts;
644         }
645         $self->{over}->disconnect;
646         delete $self->{bnote};
647         $self->{transact_bytes} = 0;
648         $self->lock_release if $parts;
649         $self->{-inbox}->git->cleanup;
650 }
651
652 sub fill_alternates ($$) {
653         my ($self, $epoch) = @_;
654
655         my $pfx = "$self->{-inbox}->{mainrepo}/git";
656         my $all = "$self->{-inbox}->{mainrepo}/all.git";
657         my @cmd;
658         unless (-d $all) {
659                 PublicInbox::Import::init_bare($all);
660         }
661         @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
662                         'include.path', '../../all.git/config');
663         PublicInbox::Import::run_die(\@cmd);
664
665         my $alt = "$all/objects/info/alternates";
666         my %alts;
667         my @add;
668         if (-e $alt) {
669                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
670                 %alts = map { chomp; $_ => 1 } (<$fh>);
671         }
672         foreach my $i (0..$epoch) {
673                 my $dir = "../../git/$i.git/objects";
674                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
675         }
676         return unless @add;
677         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
678         foreach my $dir (@add) {
679                 print $fh "$dir\n" or die "print >> $alt: $!\n";
680         }
681         close $fh or die "close $alt: $!\n";
682 }
683
684 sub git_init {
685         my ($self, $epoch) = @_;
686         my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
687         my @cmd = (qw(git init --bare -q), $git_dir);
688         PublicInbox::Import::run_die(\@cmd);
689         fill_alternates($self, $epoch);
690         $git_dir
691 }
692
693 sub git_dir_latest {
694         my ($self, $max) = @_;
695         $$max = -1;
696         my $pfx = "$self->{-inbox}->{mainrepo}/git";
697         return unless -d $pfx;
698         my $latest;
699         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
700         while (defined(my $git_dir = readdir($dh))) {
701                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
702                 if ($1 > $$max) {
703                         $$max = $1;
704                         $latest = "$pfx/$git_dir";
705                 }
706         }
707         $latest;
708 }
709
710 sub importer {
711         my ($self) = @_;
712         my $im = $self->{im};
713         if ($im) {
714                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
715                         return $im;
716                 } else {
717                         $self->{im} = undef;
718                         $im->done;
719                         $im = undef;
720                         $self->checkpoint;
721                         my $git_dir = $self->git_init(++$self->{epoch_max});
722                         my $git = PublicInbox::Git->new($git_dir);
723                         return $self->import_init($git, 0);
724                 }
725         }
726         my $epoch = 0;
727         my $max;
728         my $latest = git_dir_latest($self, \$max);
729         if (defined $latest) {
730                 my $git = PublicInbox::Git->new($latest);
731                 my $packed_bytes = $git->packed_bytes;
732                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
733
734                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
735                         $epoch = $max + 1;
736                 } else {
737                         $self->{epoch_max} = $max;
738                         return $self->import_init($git, $packed_bytes);
739                 }
740         }
741         $self->{epoch_max} = $epoch;
742         $latest = $self->git_init($epoch);
743         $self->import_init(PublicInbox::Git->new($latest), 0);
744 }
745
746 sub import_init {
747         my ($self, $git, $packed_bytes, $tmp) = @_;
748         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
749         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
750         $im->{want_object_info} = 1;
751         $im->{lock_path} = undef;
752         $im->{path_type} = 'v2';
753         $self->{im} = $im unless $tmp;
754         $im;
755 }
756
757 # XXX experimental
758 sub diff ($$$) {
759         my ($mid, $cur, $new) = @_;
760         use File::Temp qw(tempfile);
761
762         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
763         print $ah $cur->as_string or die "print: $!";
764         close $ah or die "close: $!";
765         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
766         PublicInbox::Import::drop_unwanted_headers($new);
767         print $bh $new->as_string or die "print: $!";
768         close $bh or die "close: $!";
769         my $cmd = [ qw(diff -u), $an, $bn ];
770         print STDERR "# MID conflict <$mid>\n";
771         my $pid = spawn($cmd, undef, { 1 => 2 });
772         defined $pid or die "diff failed to spawn $!";
773         waitpid($pid, 0) == $pid or die "diff did not finish";
774         unlink($an, $bn);
775 }
776
777 sub get_blob ($$) {
778         my ($self, $smsg) = @_;
779         if (my $im = $self->{im}) {
780                 my $msg = $im->cat_blob($smsg->{blob});
781                 return $msg if $msg;
782         }
783         # older message, should be in alternates
784         my $ibx = $self->{-inbox};
785         $ibx->msg_by_smsg($smsg);
786 }
787
788 sub lookup_content ($$$) {
789         my ($self, $mime, $mid) = @_;
790         my $over = $self->{over};
791         my $cids = content_ids($mime);
792         my ($id, $prev);
793         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
794                 my $msg = get_blob($self, $smsg);
795                 if (!defined($msg)) {
796                         warn "broken smsg for $mid\n";
797                         next;
798                 }
799                 my $cur = PublicInbox::MIME->new($msg);
800                 if (content_matches($cids, $cur)) {
801                         $smsg->{mime} = $cur;
802                         return $smsg;
803                 }
804
805
806                 # XXX DEBUG_DIFF is experimental and may be removed
807                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
808         }
809         undef;
810 }
811
812 sub atfork_child {
813         my ($self) = @_;
814         my $fh = delete $self->{reindex_pipe};
815         close $fh if $fh;
816         if (my $parts = $self->{idx_parts}) {
817                 $_->atfork_child foreach @$parts;
818         }
819         if (my $im = $self->{im}) {
820                 $im->atfork_child;
821         }
822         die "unexpected mm" if $self->{mm};
823         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
824         $self->{bnote}->[1];
825 }
826
827 sub mark_deleted ($$$$) {
828         my ($self, $sync, $git, $oid) = @_;
829         my $msgref = $git->cat_file($oid);
830         my $mime = PublicInbox::MIME->new($$msgref);
831         my $mids = mids($mime->header_obj);
832         my $cid = content_id($mime);
833         foreach my $mid (@$mids) {
834                 $sync->{D}->{"$mid\0$cid"} = $oid;
835         }
836 }
837
838 sub reindex_oid ($$$$) {
839         my ($self, $sync, $git, $oid) = @_;
840         my $len;
841         my $msgref = $git->cat_file($oid, \$len);
842         my $mime = PublicInbox::MIME->new($$msgref);
843         my $mids = mids($mime->header_obj);
844         my $cid = content_id($mime);
845
846         # get the NNTP article number we used before, highest number wins
847         # and gets deleted from sync->{mm_tmp};
848         my $mid0;
849         my $num = -1;
850         my $del = 0;
851         foreach my $mid (@$mids) {
852                 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
853                 my $n = $sync->{mm_tmp}->num_for($mid);
854                 if (defined $n && $n > $num) {
855                         $mid0 = $mid;
856                         $num = $n;
857                         $self->{mm}->mid_set($num, $mid0);
858                 }
859         }
860         if (!defined($mid0) && !$del) {
861                 $num = $sync->{regen}--;
862                 die "BUG: ran out of article numbers\n" if $num <= 0;
863                 my $mm = $self->{mm};
864                 foreach my $mid (reverse @$mids) {
865                         if ($mm->mid_set($num, $mid) == 1) {
866                                 $mid0 = $mid;
867                                 last;
868                         }
869                 }
870                 if (!defined($mid0)) {
871                         my $id = '<' . join('> <', @$mids) . '>';
872                         warn "Message-ID $id unusable for $num\n";
873                         foreach my $mid (@$mids) {
874                                 defined(my $n = $mm->num_for($mid)) or next;
875                                 warn "#$n previously mapped for <$mid>\n";
876                         }
877                 }
878         }
879
880         if (!defined($mid0) || $del) {
881                 if (!defined($mid0) && $del) { # expected for deletes
882                         $num = $sync->{regen}--;
883                         $self->{mm}->num_highwater($num) if !$sync->{reindex};
884                         return
885                 }
886
887                 my $id = '<' . join('> <', @$mids) . '>';
888                 defined($mid0) or
889                         warn "Skipping $id, no article number found\n";
890                 if ($del && defined($mid0)) {
891                         warn "$id was deleted $del " .
892                                 "time(s) but mapped to article #$num\n";
893                 }
894                 return;
895
896         }
897         $sync->{mm_tmp}->mid_delete($mid0) or
898                 die "failed to delete <$mid0> for article #$num\n";
899         $sync->{nr}++;
900         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
901                 $git->cleanup;
902                 $sync->{mm_tmp}->atfork_prepare;
903                 $self->done; # release lock
904
905                 if (my $pr = $sync->{-opt}->{-progress}) {
906                         my ($bn) = (split('/', $git->{git_dir}))[-1];
907                         $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
908                 }
909
910                 # allow -watch or -mda to write...
911                 $self->idx_init; # reacquire lock
912                 $sync->{mm_tmp}->atfork_parent;
913         }
914 }
915
916 # only update last_commit for $i on reindex iff newer than current
917 sub update_last_commit ($$$$) {
918         my ($self, $git, $i, $cmt) = @_;
919         my $last = last_commit_part($self, $i);
920         if (defined $last && is_ancestor($git, $last, $cmt)) {
921                 my @cmd = (qw(rev-list --count), "$last..$cmt");
922                 chomp(my $n = $git->qx(@cmd));
923                 return if $n ne '' && $n == 0;
924         }
925         last_commit_part($self, $i, $cmt);
926 }
927
928 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
929
930 sub last_commits ($$) {
931         my ($self, $epoch_max) = @_;
932         my $heads = [];
933         for (my $i = $epoch_max; $i >= 0; $i--) {
934                 $heads->[$i] = last_commit_part($self, $i);
935         }
936         $heads;
937 }
938
939 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
940
941 # returns a revision range for git-log(1)
942 sub log_range ($$$$$) {
943         my ($self, $sync, $git, $i, $tip) = @_;
944         my $opt = $sync->{-opt};
945         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
946         my $cur = $sync->{ranges}->[$i] or do {
947                 $pr->("$i.git indexing all of $tip") if $pr;
948                 return $tip; # all of it
949         };
950
951         # fast equality check to avoid (v)fork+execve overhead
952         if ($cur eq $tip) {
953                 $sync->{ranges}->[$i] = undef;
954                 return;
955         }
956
957         my $range = "$cur..$tip";
958         $pr->("$i.git checking contiguity... ") if $pr;
959         if (is_ancestor($git, $cur, $tip)) { # common case
960                 $pr->("OK\n") if $pr;
961                 my $n = $git->qx(qw(rev-list --count), $range);
962                 chomp($n);
963                 if ($n == 0) {
964                         $sync->{ranges}->[$i] = undef;
965                         $pr->("$i.git has nothing new\n") if $pr;
966                         return; # nothing to do
967                 }
968                 $pr->("$i.git has $n changes since $cur\n") if $pr;
969         } else {
970                 $pr->("FAIL\n") if $pr;
971                 warn <<"";
972 discontiguous range: $range
973 Rewritten history? (in $git->{git_dir})
974
975                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
976                 if ($base) {
977                         $range = "$base..$tip";
978                         warn "found merge-base: $base\n"
979                 } else {
980                         $range = $tip;
981                         warn "discarding history at $cur\n";
982                 }
983                 warn <<"";
984 reindexing $git->{git_dir} starting at
985 $range
986
987                 $sync->{unindex_range}->{$i} = "$base..$cur";
988         }
989         $range;
990 }
991
992 sub sync_prepare ($$$) {
993         my ($self, $sync, $epoch_max) = @_;
994         my $pr = $sync->{-opt}->{-progress};
995         my $regen_max = 0;
996         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
997
998         # reindex stops at the current heads and we later rerun index_sync
999         # without {reindex}
1000         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1001
1002         for (my $i = $epoch_max; $i >= 0; $i--) {
1003                 die 'BUG: already indexing!' if $self->{reindex_pipe};
1004                 my $git_dir = git_dir_n($self, $i);
1005                 -d $git_dir or next; # missing parts are fine
1006                 my $git = PublicInbox::Git->new($git_dir);
1007                 if ($reindex_heads) {
1008                         $head = $reindex_heads->[$i] or next;
1009                 }
1010                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1011
1012                 next if $?; # new repo
1013                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1014                 $sync->{ranges}->[$i] = $range;
1015
1016                 # can't use 'rev-list --count' if we use --diff-filter
1017                 $pr->("$i.git counting $range ... ") if $pr;
1018                 my $n = 0;
1019                 my $fh = $git->popen(qw(log --pretty=tformat:%H
1020                                 --no-notes --no-color --no-renames
1021                                 --diff-filter=AM), $range, '--', 'm');
1022                 ++$n while <$fh>;
1023                 $pr->("$n\n") if $pr;
1024                 $regen_max += $n;
1025         }
1026
1027         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1028
1029         # reindex should NOT see new commits anymore, if we do,
1030         # it's a problem and we need to notice it via die()
1031         my $pad = length($regen_max) + 1;
1032         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1033         $sync->{nr} = 0;
1034         return -1 if $sync->{reindex};
1035         $regen_max + $self->{mm}->num_highwater() || 0;
1036 }
1037
1038 sub unindex_oid_remote ($$$) {
1039         my ($self, $oid, $mid) = @_;
1040         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
1041         $self->{over}->remove_oid($oid, $mid);
1042 }
1043
1044 sub unindex_oid ($$$) {
1045         my ($self, $git, $oid) = @_;
1046         my $msgref = $git->cat_file($oid);
1047         my $mime = PublicInbox::MIME->new($msgref);
1048         my $mids = mids($mime->header_obj);
1049         $mime = $msgref = undef;
1050         my $over = $self->{over};
1051         foreach my $mid (@$mids) {
1052                 my %gone;
1053                 my ($id, $prev);
1054                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1055                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1056                         1; # continue
1057                 }
1058                 my $n = scalar keys %gone;
1059                 next unless $n;
1060                 if ($n > 1) {
1061                         warn "BUG: multiple articles linked to $oid\n",
1062                                 join(',',sort keys %gone), "\n";
1063                 }
1064                 foreach my $num (keys %gone) {
1065                         $self->{unindexed}->{$_}++;
1066                         $self->{mm}->num_delete($num);
1067                 }
1068                 unindex_oid_remote($self, $oid, $mid);
1069         }
1070 }
1071
1072 my $x40 = qr/[a-f0-9]{40}/;
1073 sub unindex ($$$$) {
1074         my ($self, $sync, $git, $unindex_range) = @_;
1075         my $un = $self->{unindexed} ||= {}; # num => removal count
1076         my $before = scalar keys %$un;
1077         my @cmd = qw(log --raw -r
1078                         --no-notes --no-color --no-abbrev --no-renames);
1079         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1080         while (<$fh>) {
1081                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1082                 unindex_oid($self, $git, $1);
1083         }
1084         delete $self->{reindex_pipe};
1085         $fh = undef;
1086
1087         return unless $sync->{-opt}->{prune};
1088         my $after = scalar keys %$un;
1089         return if $before == $after;
1090
1091         # ensure any blob can not longer be accessed via dumb HTTP
1092         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1093                 qw(-c gc.reflogExpire=now gc --prune=all)]);
1094 }
1095
1096 sub sync_ranges ($$$) {
1097         my ($self, $sync, $epoch_max) = @_;
1098         my $reindex = $sync->{reindex};
1099
1100         return last_commits($self, $epoch_max) unless $reindex;
1101         return [] if ref($reindex) ne 'HASH';
1102
1103         my $ranges = $reindex->{from}; # arrayref;
1104         if (ref($ranges) ne 'ARRAY') {
1105                 die 'BUG: $reindex->{from} not an ARRAY';
1106         }
1107         $ranges;
1108 }
1109
1110 sub index_epoch ($$$) {
1111         my ($self, $sync, $i) = @_;
1112
1113         my $git_dir = git_dir_n($self, $i);
1114         die 'BUG: already reindexing!' if $self->{reindex_pipe};
1115         -d $git_dir or return; # missing parts are fine
1116         fill_alternates($self, $i);
1117         my $git = PublicInbox::Git->new($git_dir);
1118         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1119                 unindex($self, $sync, $git, $unindex_range);
1120         }
1121         defined(my $range = $sync->{ranges}->[$i]) or return;
1122         if (my $pr = $sync->{-opt}->{-progress}) {
1123                 $pr->("$i.git indexing $range\n");
1124         }
1125
1126         my @cmd = qw(log --raw -r --pretty=tformat:%H
1127                         --no-notes --no-color --no-abbrev --no-renames);
1128         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1129         my $cmt;
1130         while (<$fh>) {
1131                 chomp;
1132                 $self->{current_info} = "$i.git $_";
1133                 if (/\A$x40$/o && !defined($cmt)) {
1134                         $cmt = $_;
1135                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1136                         reindex_oid($self, $sync, $git, $1);
1137                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1138                         mark_deleted($self, $sync, $git, $1);
1139                 }
1140         }
1141         $fh = undef;
1142         delete $self->{reindex_pipe};
1143         update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1144 }
1145
1146 # public, called by public-inbox-index
1147 sub index_sync {
1148         my ($self, $opt) = @_;
1149         $opt ||= {};
1150         my $pr = $opt->{-progress};
1151         my $epoch_max;
1152         my $latest = git_dir_latest($self, \$epoch_max);
1153         return unless defined $latest;
1154         $self->idx_init($opt); # acquire lock
1155         my $sync = {
1156                 D => {}, # "$mid\0$cid" => $oid
1157                 unindex_range => {}, # EPOCH => oid_old..oid_new
1158                 reindex => $opt->{reindex},
1159                 -opt => $opt
1160         };
1161         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1162         $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1163
1164         if ($sync->{regen}) {
1165                 # tmp_clone seems to fail if inside a transaction, so
1166                 # we rollback here (because we opened {mm} for reading)
1167                 # Note: we do NOT rely on DBI transactions for atomicity;
1168                 # only for batch performance.
1169                 $self->{mm}->{dbh}->rollback;
1170                 $self->{mm}->{dbh}->begin_work;
1171                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1172         }
1173
1174         # work backwards through history
1175         for (my $i = $epoch_max; $i >= 0; $i--) {
1176                 index_epoch($self, $sync, $i);
1177         }
1178
1179         # unindex is required for leftovers if "deletes" affect messages
1180         # in a previous fetch+index window:
1181         if (my @leftovers = values %{delete $sync->{D}}) {
1182                 my $git = $self->{-inbox}->git;
1183                 unindex_oid($self, $git, $_) for @leftovers;
1184                 $git->cleanup;
1185         }
1186         $self->done;
1187
1188         if (my $nr = $sync->{nr}) {
1189                 my $pr = $sync->{-opt}->{-progress};
1190                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1191         }
1192
1193         # reindex does not pick up new changes, so we rerun w/o it:
1194         if ($opt->{reindex}) {
1195                 my %again = %$opt;
1196                 $sync = undef;
1197                 delete @again{qw(reindex -skip_lock)};
1198                 index_sync($self, \%again);
1199         }
1200 }
1201
1202 1;