]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/V2Writable.pm
v2writable: implement ->replace call
[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         # reindex modified messages:
537         for my $smsg (@$need_reindex) {
538                 my $num = $smsg->{num};
539                 my $mid0 = $smsg->{mid};
540                 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
541         }
542         $rewritten->{rewrites};
543 }
544
545 sub last_commit_part ($$;$) {
546         my ($self, $i, $cmt) = @_;
547         my $v = PublicInbox::Search::SCHEMA_VERSION();
548         $self->{mm}->last_commit_xap($v, $i, $cmt);
549 }
550
551 sub set_last_commits ($) {
552         my ($self) = @_;
553         defined(my $epoch_max = $self->{epoch_max}) or return;
554         my $last_commit = $self->{last_commit};
555         foreach my $i (0..$epoch_max) {
556                 defined(my $cmt = $last_commit->[$i]) or next;
557                 $last_commit->[$i] = undef;
558                 last_commit_part($self, $i, $cmt);
559         }
560 }
561
562 sub barrier_init {
563         my ($self, $n) = @_;
564         $self->{bnote} or return;
565         --$n;
566         my $barrier = { map { $_ => 1 } (0..$n) };
567 }
568
569 sub barrier_wait {
570         my ($self, $barrier) = @_;
571         my $bnote = $self->{bnote} or return;
572         my $r = $bnote->[0];
573         while (scalar keys %$barrier) {
574                 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
575                 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
576                 delete $barrier->{$1} or die "bad part[$1] on barrier wait";
577         }
578 }
579
580 # public
581 sub checkpoint ($;$) {
582         my ($self, $wait) = @_;
583
584         if (my $im = $self->{im}) {
585                 if ($wait) {
586                         $im->barrier;
587                 } else {
588                         $im->checkpoint;
589                 }
590         }
591         my $parts = $self->{idx_parts};
592         if ($parts) {
593                 my $dbh = $self->{mm}->{dbh};
594
595                 # SQLite msgmap data is second in importance
596                 $dbh->commit;
597
598                 # SQLite overview is third
599                 $self->{over}->commit_lazy;
600
601                 # Now deal with Xapian
602                 if ($wait) {
603                         my $barrier = $self->barrier_init(scalar @$parts);
604
605                         # each partition needs to issue a barrier command
606                         $_->remote_barrier for @$parts;
607
608                         # wait for each Xapian partition
609                         $self->barrier_wait($barrier);
610                 } else {
611                         $_->remote_commit for @$parts;
612                 }
613
614                 # last_commit is special, don't commit these until
615                 # remote partitions are done:
616                 $dbh->begin_work;
617                 set_last_commits($self);
618                 $dbh->commit;
619
620                 $dbh->begin_work;
621         }
622         $self->{transact_bytes} = 0;
623 }
624
625 # issue a write barrier to ensure all data is visible to other processes
626 # and read-only ops.  Order of data importance is: git > SQLite > Xapian
627 # public
628 sub barrier { checkpoint($_[0], 1) };
629
630 # public
631 sub done {
632         my ($self) = @_;
633         my $im = delete $self->{im};
634         $im->done if $im; # PublicInbox::Import::done
635         checkpoint($self);
636         my $mm = delete $self->{mm};
637         $mm->{dbh}->commit if $mm;
638         my $parts = delete $self->{idx_parts};
639         if ($parts) {
640                 $_->remote_close for @$parts;
641         }
642         $self->{over}->disconnect;
643         delete $self->{bnote};
644         $self->{transact_bytes} = 0;
645         $self->lock_release if $parts;
646         $self->{-inbox}->git->cleanup;
647 }
648
649 sub fill_alternates ($$) {
650         my ($self, $epoch) = @_;
651
652         my $pfx = "$self->{-inbox}->{mainrepo}/git";
653         my $all = "$self->{-inbox}->{mainrepo}/all.git";
654         my @cmd;
655         unless (-d $all) {
656                 PublicInbox::Import::init_bare($all);
657         }
658         @cmd = (qw/git config/, "--file=$pfx/$epoch.git/config",
659                         'include.path', '../../all.git/config');
660         PublicInbox::Import::run_die(\@cmd);
661
662         my $alt = "$all/objects/info/alternates";
663         my %alts;
664         my @add;
665         if (-e $alt) {
666                 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
667                 %alts = map { chomp; $_ => 1 } (<$fh>);
668         }
669         foreach my $i (0..$epoch) {
670                 my $dir = "../../git/$i.git/objects";
671                 push @add, $dir if !$alts{$dir} && -d "$pfx/$i.git";
672         }
673         return unless @add;
674         open my $fh, '>>', $alt or die "open >> $alt: $!\n";
675         foreach my $dir (@add) {
676                 print $fh "$dir\n" or die "print >> $alt: $!\n";
677         }
678         close $fh or die "close $alt: $!\n";
679 }
680
681 sub git_init {
682         my ($self, $epoch) = @_;
683         my $git_dir = "$self->{-inbox}->{mainrepo}/git/$epoch.git";
684         my @cmd = (qw(git init --bare -q), $git_dir);
685         PublicInbox::Import::run_die(\@cmd);
686         fill_alternates($self, $epoch);
687         $git_dir
688 }
689
690 sub git_dir_latest {
691         my ($self, $max) = @_;
692         $$max = -1;
693         my $pfx = "$self->{-inbox}->{mainrepo}/git";
694         return unless -d $pfx;
695         my $latest;
696         opendir my $dh, $pfx or die "opendir $pfx: $!\n";
697         while (defined(my $git_dir = readdir($dh))) {
698                 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
699                 if ($1 > $$max) {
700                         $$max = $1;
701                         $latest = "$pfx/$git_dir";
702                 }
703         }
704         $latest;
705 }
706
707 sub importer {
708         my ($self) = @_;
709         my $im = $self->{im};
710         if ($im) {
711                 if ($im->{bytes_added} < $self->{rotate_bytes}) {
712                         return $im;
713                 } else {
714                         $self->{im} = undef;
715                         $im->done;
716                         $im = undef;
717                         $self->checkpoint;
718                         my $git_dir = $self->git_init(++$self->{epoch_max});
719                         my $git = PublicInbox::Git->new($git_dir);
720                         return $self->import_init($git, 0);
721                 }
722         }
723         my $epoch = 0;
724         my $max;
725         my $latest = git_dir_latest($self, \$max);
726         if (defined $latest) {
727                 my $git = PublicInbox::Git->new($latest);
728                 my $packed_bytes = $git->packed_bytes;
729                 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
730
731                 if ($unpacked_bytes >= $self->{rotate_bytes}) {
732                         $epoch = $max + 1;
733                 } else {
734                         $self->{epoch_max} = $max;
735                         return $self->import_init($git, $packed_bytes);
736                 }
737         }
738         $self->{epoch_max} = $epoch;
739         $latest = $self->git_init($epoch);
740         $self->import_init(PublicInbox::Git->new($latest), 0);
741 }
742
743 sub import_init {
744         my ($self, $git, $packed_bytes, $tmp) = @_;
745         my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
746         $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
747         $im->{want_object_info} = 1;
748         $im->{lock_path} = undef;
749         $im->{path_type} = 'v2';
750         $self->{im} = $im unless $tmp;
751         $im;
752 }
753
754 # XXX experimental
755 sub diff ($$$) {
756         my ($mid, $cur, $new) = @_;
757         use File::Temp qw(tempfile);
758
759         my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
760         print $ah $cur->as_string or die "print: $!";
761         close $ah or die "close: $!";
762         my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
763         PublicInbox::Import::drop_unwanted_headers($new);
764         print $bh $new->as_string or die "print: $!";
765         close $bh or die "close: $!";
766         my $cmd = [ qw(diff -u), $an, $bn ];
767         print STDERR "# MID conflict <$mid>\n";
768         my $pid = spawn($cmd, undef, { 1 => 2 });
769         defined $pid or die "diff failed to spawn $!";
770         waitpid($pid, 0) == $pid or die "diff did not finish";
771         unlink($an, $bn);
772 }
773
774 sub get_blob ($$) {
775         my ($self, $smsg) = @_;
776         if (my $im = $self->{im}) {
777                 my $msg = $im->cat_blob($smsg->{blob});
778                 return $msg if $msg;
779         }
780         # older message, should be in alternates
781         my $ibx = $self->{-inbox};
782         $ibx->msg_by_smsg($smsg);
783 }
784
785 sub lookup_content ($$$) {
786         my ($self, $mime, $mid) = @_;
787         my $over = $self->{over};
788         my $cids = content_ids($mime);
789         my ($id, $prev);
790         while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
791                 my $msg = get_blob($self, $smsg);
792                 if (!defined($msg)) {
793                         warn "broken smsg for $mid\n";
794                         next;
795                 }
796                 my $cur = PublicInbox::MIME->new($msg);
797                 if (content_matches($cids, $cur)) {
798                         $smsg->{mime} = $cur;
799                         return $smsg;
800                 }
801
802
803                 # XXX DEBUG_DIFF is experimental and may be removed
804                 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
805         }
806         undef;
807 }
808
809 sub atfork_child {
810         my ($self) = @_;
811         my $fh = delete $self->{reindex_pipe};
812         close $fh if $fh;
813         if (my $parts = $self->{idx_parts}) {
814                 $_->atfork_child foreach @$parts;
815         }
816         if (my $im = $self->{im}) {
817                 $im->atfork_child;
818         }
819         die "unexpected mm" if $self->{mm};
820         close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
821         $self->{bnote}->[1];
822 }
823
824 sub mark_deleted ($$$$) {
825         my ($self, $sync, $git, $oid) = @_;
826         my $msgref = $git->cat_file($oid);
827         my $mime = PublicInbox::MIME->new($$msgref);
828         my $mids = mids($mime->header_obj);
829         my $cid = content_id($mime);
830         foreach my $mid (@$mids) {
831                 $sync->{D}->{"$mid\0$cid"} = $oid;
832         }
833 }
834
835 sub reindex_oid ($$$$) {
836         my ($self, $sync, $git, $oid) = @_;
837         my $len;
838         my $msgref = $git->cat_file($oid, \$len);
839         my $mime = PublicInbox::MIME->new($$msgref);
840         my $mids = mids($mime->header_obj);
841         my $cid = content_id($mime);
842
843         # get the NNTP article number we used before, highest number wins
844         # and gets deleted from sync->{mm_tmp};
845         my $mid0;
846         my $num = -1;
847         my $del = 0;
848         foreach my $mid (@$mids) {
849                 $del += delete($sync->{D}->{"$mid\0$cid"}) ? 1 : 0;
850                 my $n = $sync->{mm_tmp}->num_for($mid);
851                 if (defined $n && $n > $num) {
852                         $mid0 = $mid;
853                         $num = $n;
854                         $self->{mm}->mid_set($num, $mid0);
855                 }
856         }
857         if (!defined($mid0) && !$del) {
858                 $num = $sync->{regen}--;
859                 die "BUG: ran out of article numbers\n" if $num <= 0;
860                 my $mm = $self->{mm};
861                 foreach my $mid (reverse @$mids) {
862                         if ($mm->mid_set($num, $mid) == 1) {
863                                 $mid0 = $mid;
864                                 last;
865                         }
866                 }
867                 if (!defined($mid0)) {
868                         my $id = '<' . join('> <', @$mids) . '>';
869                         warn "Message-ID $id unusable for $num\n";
870                         foreach my $mid (@$mids) {
871                                 defined(my $n = $mm->num_for($mid)) or next;
872                                 warn "#$n previously mapped for <$mid>\n";
873                         }
874                 }
875         }
876
877         if (!defined($mid0) || $del) {
878                 if (!defined($mid0) && $del) { # expected for deletes
879                         $num = $sync->{regen}--;
880                         $self->{mm}->num_highwater($num) if !$sync->{reindex};
881                         return
882                 }
883
884                 my $id = '<' . join('> <', @$mids) . '>';
885                 defined($mid0) or
886                         warn "Skipping $id, no article number found\n";
887                 if ($del && defined($mid0)) {
888                         warn "$id was deleted $del " .
889                                 "time(s) but mapped to article #$num\n";
890                 }
891                 return;
892
893         }
894         $sync->{mm_tmp}->mid_delete($mid0) or
895                 die "failed to delete <$mid0> for article #$num\n";
896         $sync->{nr}++;
897         if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
898                 $git->cleanup;
899                 $sync->{mm_tmp}->atfork_prepare;
900                 $self->done; # release lock
901
902                 if (my $pr = $sync->{-opt}->{-progress}) {
903                         my ($bn) = (split('/', $git->{git_dir}))[-1];
904                         $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
905                 }
906
907                 # allow -watch or -mda to write...
908                 $self->idx_init; # reacquire lock
909                 $sync->{mm_tmp}->atfork_parent;
910         }
911 }
912
913 # only update last_commit for $i on reindex iff newer than current
914 sub update_last_commit ($$$$) {
915         my ($self, $git, $i, $cmt) = @_;
916         my $last = last_commit_part($self, $i);
917         if (defined $last && is_ancestor($git, $last, $cmt)) {
918                 my @cmd = (qw(rev-list --count), "$last..$cmt");
919                 chomp(my $n = $git->qx(@cmd));
920                 return if $n ne '' && $n == 0;
921         }
922         last_commit_part($self, $i, $cmt);
923 }
924
925 sub git_dir_n ($$) { "$_[0]->{-inbox}->{mainrepo}/git/$_[1].git" }
926
927 sub last_commits ($$) {
928         my ($self, $epoch_max) = @_;
929         my $heads = [];
930         for (my $i = $epoch_max; $i >= 0; $i--) {
931                 $heads->[$i] = last_commit_part($self, $i);
932         }
933         $heads;
934 }
935
936 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
937
938 # returns a revision range for git-log(1)
939 sub log_range ($$$$$) {
940         my ($self, $sync, $git, $i, $tip) = @_;
941         my $opt = $sync->{-opt};
942         my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
943         my $cur = $sync->{ranges}->[$i] or do {
944                 $pr->("$i.git indexing all of $tip") if $pr;
945                 return $tip; # all of it
946         };
947
948         # fast equality check to avoid (v)fork+execve overhead
949         if ($cur eq $tip) {
950                 $sync->{ranges}->[$i] = undef;
951                 return;
952         }
953
954         my $range = "$cur..$tip";
955         $pr->("$i.git checking contiguity... ") if $pr;
956         if (is_ancestor($git, $cur, $tip)) { # common case
957                 $pr->("OK\n") if $pr;
958                 my $n = $git->qx(qw(rev-list --count), $range);
959                 chomp($n);
960                 if ($n == 0) {
961                         $sync->{ranges}->[$i] = undef;
962                         $pr->("$i.git has nothing new\n") if $pr;
963                         return; # nothing to do
964                 }
965                 $pr->("$i.git has $n changes since $cur\n") if $pr;
966         } else {
967                 $pr->("FAIL\n") if $pr;
968                 warn <<"";
969 discontiguous range: $range
970 Rewritten history? (in $git->{git_dir})
971
972                 chomp(my $base = $git->qx('merge-base', $tip, $cur));
973                 if ($base) {
974                         $range = "$base..$tip";
975                         warn "found merge-base: $base\n"
976                 } else {
977                         $range = $tip;
978                         warn "discarding history at $cur\n";
979                 }
980                 warn <<"";
981 reindexing $git->{git_dir} starting at
982 $range
983
984                 $sync->{unindex_range}->{$i} = "$base..$cur";
985         }
986         $range;
987 }
988
989 sub sync_prepare ($$$) {
990         my ($self, $sync, $epoch_max) = @_;
991         my $pr = $sync->{-opt}->{-progress};
992         my $regen_max = 0;
993         my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
994
995         # reindex stops at the current heads and we later rerun index_sync
996         # without {reindex}
997         my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
998
999         for (my $i = $epoch_max; $i >= 0; $i--) {
1000                 die 'BUG: already indexing!' if $self->{reindex_pipe};
1001                 my $git_dir = git_dir_n($self, $i);
1002                 -d $git_dir or next; # missing parts are fine
1003                 my $git = PublicInbox::Git->new($git_dir);
1004                 if ($reindex_heads) {
1005                         $head = $reindex_heads->[$i] or next;
1006                 }
1007                 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1008
1009                 next if $?; # new repo
1010                 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1011                 $sync->{ranges}->[$i] = $range;
1012
1013                 # can't use 'rev-list --count' if we use --diff-filter
1014                 $pr->("$i.git counting $range ... ") if $pr;
1015                 my $n = 0;
1016                 my $fh = $git->popen(qw(log --pretty=tformat:%H
1017                                 --no-notes --no-color --no-renames
1018                                 --diff-filter=AM), $range, '--', 'm');
1019                 ++$n while <$fh>;
1020                 $pr->("$n\n") if $pr;
1021                 $regen_max += $n;
1022         }
1023
1024         return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1025
1026         # reindex should NOT see new commits anymore, if we do,
1027         # it's a problem and we need to notice it via die()
1028         my $pad = length($regen_max) + 1;
1029         $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1030         $sync->{nr} = 0;
1031         return -1 if $sync->{reindex};
1032         $regen_max + $self->{mm}->num_highwater() || 0;
1033 }
1034
1035 sub unindex_oid_remote ($$$) {
1036         my ($self, $oid, $mid) = @_;
1037         $_->remote_remove($oid, $mid) foreach @{$self->{idx_parts}};
1038         $self->{over}->remove_oid($oid, $mid);
1039 }
1040
1041 sub unindex_oid ($$$) {
1042         my ($self, $git, $oid) = @_;
1043         my $msgref = $git->cat_file($oid);
1044         my $mime = PublicInbox::MIME->new($msgref);
1045         my $mids = mids($mime->header_obj);
1046         $mime = $msgref = undef;
1047         my $over = $self->{over};
1048         foreach my $mid (@$mids) {
1049                 my %gone;
1050                 my ($id, $prev);
1051                 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1052                         $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1053                         1; # continue
1054                 }
1055                 my $n = scalar keys %gone;
1056                 next unless $n;
1057                 if ($n > 1) {
1058                         warn "BUG: multiple articles linked to $oid\n",
1059                                 join(',',sort keys %gone), "\n";
1060                 }
1061                 foreach my $num (keys %gone) {
1062                         $self->{unindexed}->{$_}++;
1063                         $self->{mm}->num_delete($num);
1064                 }
1065                 unindex_oid_remote($self, $oid, $mid);
1066         }
1067 }
1068
1069 my $x40 = qr/[a-f0-9]{40}/;
1070 sub unindex ($$$$) {
1071         my ($self, $sync, $git, $unindex_range) = @_;
1072         my $un = $self->{unindexed} ||= {}; # num => removal count
1073         my $before = scalar keys %$un;
1074         my @cmd = qw(log --raw -r
1075                         --no-notes --no-color --no-abbrev --no-renames);
1076         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1077         while (<$fh>) {
1078                 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1079                 unindex_oid($self, $git, $1);
1080         }
1081         delete $self->{reindex_pipe};
1082         $fh = undef;
1083
1084         return unless $sync->{-opt}->{prune};
1085         my $after = scalar keys %$un;
1086         return if $before == $after;
1087
1088         # ensure any blob can not longer be accessed via dumb HTTP
1089         PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1090                 qw(-c gc.reflogExpire=now gc --prune=all)]);
1091 }
1092
1093 sub sync_ranges ($$$) {
1094         my ($self, $sync, $epoch_max) = @_;
1095         my $reindex = $sync->{reindex};
1096
1097         return last_commits($self, $epoch_max) unless $reindex;
1098         return [] if ref($reindex) ne 'HASH';
1099
1100         my $ranges = $reindex->{from}; # arrayref;
1101         if (ref($ranges) ne 'ARRAY') {
1102                 die 'BUG: $reindex->{from} not an ARRAY';
1103         }
1104         $ranges;
1105 }
1106
1107 sub index_epoch ($$$) {
1108         my ($self, $sync, $i) = @_;
1109
1110         my $git_dir = git_dir_n($self, $i);
1111         die 'BUG: already reindexing!' if $self->{reindex_pipe};
1112         -d $git_dir or return; # missing parts are fine
1113         fill_alternates($self, $i);
1114         my $git = PublicInbox::Git->new($git_dir);
1115         if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1116                 unindex($self, $sync, $git, $unindex_range);
1117         }
1118         defined(my $range = $sync->{ranges}->[$i]) or return;
1119         if (my $pr = $sync->{-opt}->{-progress}) {
1120                 $pr->("$i.git indexing $range\n");
1121         }
1122
1123         my @cmd = qw(log --raw -r --pretty=tformat:%H
1124                         --no-notes --no-color --no-abbrev --no-renames);
1125         my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1126         my $cmt;
1127         while (<$fh>) {
1128                 chomp;
1129                 $self->{current_info} = "$i.git $_";
1130                 if (/\A$x40$/o && !defined($cmt)) {
1131                         $cmt = $_;
1132                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1133                         reindex_oid($self, $sync, $git, $1);
1134                 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1135                         mark_deleted($self, $sync, $git, $1);
1136                 }
1137         }
1138         $fh = undef;
1139         delete $self->{reindex_pipe};
1140         update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1141 }
1142
1143 # public, called by public-inbox-index
1144 sub index_sync {
1145         my ($self, $opt) = @_;
1146         $opt ||= {};
1147         my $pr = $opt->{-progress};
1148         my $epoch_max;
1149         my $latest = git_dir_latest($self, \$epoch_max);
1150         return unless defined $latest;
1151         $self->idx_init($opt); # acquire lock
1152         my $sync = {
1153                 D => {}, # "$mid\0$cid" => $oid
1154                 unindex_range => {}, # EPOCH => oid_old..oid_new
1155                 reindex => $opt->{reindex},
1156                 -opt => $opt
1157         };
1158         $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1159         $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1160
1161         if ($sync->{regen}) {
1162                 # tmp_clone seems to fail if inside a transaction, so
1163                 # we rollback here (because we opened {mm} for reading)
1164                 # Note: we do NOT rely on DBI transactions for atomicity;
1165                 # only for batch performance.
1166                 $self->{mm}->{dbh}->rollback;
1167                 $self->{mm}->{dbh}->begin_work;
1168                 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1169         }
1170
1171         # work backwards through history
1172         for (my $i = $epoch_max; $i >= 0; $i--) {
1173                 index_epoch($self, $sync, $i);
1174         }
1175
1176         # unindex is required for leftovers if "deletes" affect messages
1177         # in a previous fetch+index window:
1178         if (my @leftovers = values %{delete $sync->{D}}) {
1179                 my $git = $self->{-inbox}->git;
1180                 unindex_oid($self, $git, $_) for @leftovers;
1181                 $git->cleanup;
1182         }
1183         $self->done;
1184
1185         if (my $nr = $sync->{nr}) {
1186                 my $pr = $sync->{-opt}->{-progress};
1187                 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1188         }
1189
1190         # reindex does not pick up new changes, so we rerun w/o it:
1191         if ($opt->{reindex}) {
1192                 my %again = %$opt;
1193                 $sync = undef;
1194                 delete @again{qw(reindex -skip_lock)};
1195                 index_sync($self, \%again);
1196         }
1197 }
1198
1199 1;