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