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