1 # Copyright (C) 2018-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
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;
9 use base qw(PublicInbox::Lock);
11 use PublicInbox::SearchIdxShard;
12 use PublicInbox::MIME;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentId qw(content_id content_digest);
17 use PublicInbox::Inbox;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd);
21 use PublicInbox::SearchIdx;
22 use IO::Handle; # ->autoflush
23 use File::Temp qw(tempfile);
25 # an estimate of the post-packed size to the raw uncompressed size
26 my $PACKING_FACTOR = 0.4;
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space. It can also lead to excessive IO latency
31 # and slow things down. Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
37 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
38 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
41 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
42 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
43 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
46 # should we bother with `sysctl hw.ncpu`? Those only give
47 # us total processor count, not online processor count.
51 sub nproc_shards ($) {
53 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
56 # assume 2 cores if not detectable or zero
57 state $NPROC_DETECTED = detect_nproc() || 2;
59 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
62 # subtract for the main process and git-fast-import
67 sub count_shards ($) {
70 my $xpfx = $self->{xpfx};
72 # always load existing shards in case core count changes:
73 # Also, shard count may change while -watch is running
74 # due to "xcpdb --reshard"
76 require PublicInbox::Search;
77 PublicInbox::Search::load_xapian();
78 my $XapianDatabase = $PublicInbox::Search::X{Database};
79 foreach my $shard (<$xpfx/*>) {
80 -d $shard && $shard =~ m!/[0-9]+\z! or next;
82 $XapianDatabase->new($shard)->close;
91 # $creat may be any true value, or 0/undef. A hashref is true,
92 # and $creat->{nproc} may be set to an integer
93 my ($class, $v2ibx, $creat) = @_;
94 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
95 my $dir = $v2ibx->assert_usable_dir;
99 File::Path::mkpath($dir);
101 die "$dir does not exist\n";
104 $v2ibx->umask_prepare;
106 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
109 im => undef, # PublicInbox::Import
114 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
115 lock_path => "$dir/inbox.lock",
116 # limit each git repo (epoch) to 1GB or so
117 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
118 last_commit => [], # git repo -> commit
120 $self->{shards} = count_shards($self) || nproc_shards($creat);
126 my ($self, $shards, $skip_epoch) = @_;
127 if (defined $shards) {
128 $self->{parallel} = 0 if $shards == 0;
129 $self->{shards} = $shards if $shards > 0;
133 git_dir_latest($self, \$epoch_max);
134 if (defined $skip_epoch && $epoch_max == -1) {
135 $epoch_max = $skip_epoch;
137 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
141 # returns undef on duplicate or spam
142 # mimics Import::add and wraps it for v2
144 my ($self, $mime, $check_cb) = @_;
145 $self->{-inbox}->with_umask(sub {
146 _add($self, $mime, $check_cb)
150 # indexes a message, returns true if checkpointing is needed
151 sub do_idx ($$$$$$$) {
152 my ($self, $msgref, $mime, $len, $num, $oid, $mid0) = @_;
153 $self->{over}->add_overview($mime, $len, $num, $oid, $mid0, $self);
154 my $idx = idx_shard($self, $num % $self->{shards});
155 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime, $self);
156 my $n = $self->{transact_bytes} += $len;
157 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
161 my ($self, $mime, $check_cb) = @_;
165 $mime = $check_cb->($mime) or return;
168 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
169 # as does SQLite 3.4.1+ (released in 2007-07-20), and
170 # Xapian 1.3.2+ (released 2015-03-15).
171 # For the most part, we can spawn git-fast-import without
172 # leaking FDs to it...
175 my ($num, $mid0) = v2_num_for($self, $mime);
176 defined $num or return; # duplicate
177 defined $mid0 or die "BUG: $mid0 undefined\n";
178 my $im = $self->importer;
179 my $cmt = $im->add($mime, undef, $self); # sets $self->{(au|co)time}
180 $cmt = $im->get_mark($cmt);
181 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
183 my ($oid, $len, $msgref) = @{$im->{last_object}};
184 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
192 my ($self, $mime) = @_;
193 my $mids = mids($mime->header_obj);
195 my $mid = $mids->[0];
196 my $num = $self->{mm}->mid_insert($mid);
197 if (defined $num) { # common case
201 # crap, Message-ID is already known, hope somebody just resent:
202 foreach my $m (@$mids) {
203 # read-only lookup now safe to do after above barrier
204 # easy, don't store duplicates
205 # note: do not add more diagnostic info here since
206 # it gets noisy on public-inbox-watch restarts
207 return () if content_exists($self, $mime, $m);
210 # AltId may pre-populate article numbers (e.g. X-Mail-Count
211 # or NNTP article number), use that article number if it's
213 my $altid = $self->{-inbox}->{altid};
214 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
215 my $num = $self->{mm}->num_for($mid);
217 if (defined $num && !$self->{over}->get_art($num)) {
223 warn "<$mid> reused for mismatched content\n";
225 # try the rest of the mids
226 for(my $i = $#$mids; $i >= 1; $i--) {
228 $num = $self->{mm}->mid_insert($m);
230 warn "alternative <$m> for <$mid> found\n";
235 # none of the existing Message-IDs are good, generate a new one:
236 v2_num_for_harder($self, $mime);
239 sub v2_num_for_harder {
240 my ($self, $mime) = @_;
242 my $hdr = $mime->header_obj;
243 my $dig = content_digest($mime);
244 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
245 my $num = $self->{mm}->mid_insert($mid0);
246 unless (defined $num) {
247 # it's hard to spoof the last Received: header
248 my @recvd = $hdr->header_raw('Received');
249 $dig->add("Received: $_") foreach (@recvd);
250 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
251 $num = $self->{mm}->mid_insert($mid0);
253 # fall back to a random Message-ID and give up determinism:
254 until (defined($num)) {
256 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
257 warn "using random Message-ID <$mid0> as fallback\n";
258 $num = $self->{mm}->mid_insert($mid0);
261 PublicInbox::Import::append_mid($hdr, $mid0);
266 my ($self, $shard_i) = @_;
267 $self->{idx_shards}->[$shard_i];
272 my ($self, $opt) = @_;
273 return if $self->{idx_shards};
274 my $ibx = $self->{-inbox};
276 # do not leak read-only FDs to child processes, we only have these
277 # FDs for duplicate detection so they should not be
278 # frequently activated.
279 delete $ibx->{$_} foreach (qw(git mm search));
281 my $indexlevel = $ibx->{indexlevel};
282 if ($indexlevel && $indexlevel eq 'basic') {
283 $self->{parallel} = 0;
286 if ($self->{parallel}) {
287 pipe(my ($r, $w)) or die "pipe failed: $!";
288 # pipe for barrier notifications doesn't need to be big,
290 fcntl($w, 1031, 4096) if $^O eq 'linux';
291 $self->{bnote} = [ $r, $w ];
295 my $over = $self->{over};
297 $ibx->with_umask(sub {
298 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
301 # xcpdb can change shard count while -watch is idle
302 my $nshards = count_shards($self);
303 if ($nshards && $nshards != $self->{shards}) {
304 $self->{shards} = $nshards;
307 # need to create all shards before initializing msgmap FD
308 my $max = $self->{shards} - 1;
310 # idx_shards must be visible to all forked processes
311 my $idx = $self->{idx_shards} = [];
312 for my $i (0..$max) {
313 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
316 # Now that all subprocesses are up, we can open the FDs
318 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
319 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
320 $mm->{dbh}->begin_work;
324 # returns an array mapping [ epoch => latest_commit ]
325 # latest_commit may be undef if nothing was done to that epoch
326 # $replace_map = { $object_id => $strref, ... }
327 sub _replace_oids ($$$) {
328 my ($self, $mime, $replace_map) = @_;
330 my $pfx = "$self->{-inbox}->{inboxdir}/git";
331 my $rewrites = []; # epoch => commit
332 my $max = $self->{epoch_max};
334 unless (defined($max)) {
335 defined(my $latest = git_dir_latest($self, \$max)) or return;
336 $self->{epoch_max} = $max;
339 foreach my $i (0..$max) {
340 my $git_dir = "$pfx/$i.git";
342 my $git = PublicInbox::Git->new($git_dir);
343 my $im = $self->import_init($git, 0, 1);
344 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
350 sub content_ids ($) {
352 my @cids = ( content_id($mime) );
354 # Email::MIME->as_string doesn't always round-trip, so we may
355 # use a second content_id
356 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
357 push @cids, $rt if $cids[0] ne $rt;
361 sub content_matches ($$) {
362 my ($cids, $existing) = @_;
363 my $cid = content_id($existing);
365 return 1 if $_ eq $cid
370 # used for removing or replacing (purging)
371 sub rewrite_internal ($$;$$$) {
372 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
374 my ($im, $need_reindex, $replace_map);
376 $replace_map = {}; # oid => sref
377 $need_reindex = [] if $new_mime;
379 $im = $self->importer;
381 my $over = $self->{over};
382 my $cids = content_ids($old_mime);
384 my $mids = mids($old_mime->header_obj);
386 # We avoid introducing new blobs into git since the raw content
387 # can be slightly different, so we do not need the user-supplied
388 # message now that we have the mids and content_id
392 foreach my $mid (@$mids) {
393 my %gone; # num => [ smsg, $mime, raw ]
395 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
396 my $msg = get_blob($self, $smsg);
397 if (!defined($msg)) {
398 warn "broken smsg for $mid\n";
402 my $cur = PublicInbox::MIME->new($msg);
403 if (content_matches($cids, $cur)) {
404 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
407 my $n = scalar keys %gone;
410 warn "BUG: multiple articles linked to <$mid>\n",
411 join(',', sort keys %gone), "\n";
413 foreach my $num (keys %gone) {
414 my ($smsg, $mime, $orig) = @{$gone{$num}};
415 # @removed should only be set once assuming
416 # no bugs in our deduplication code:
417 @removed = (undef, $mime, $smsg);
418 my $oid = $smsg->{blob};
420 $replace_map->{$oid} = $sref;
422 ($mark, undef) = $im->remove($orig, $cmt_msg);
426 if ($need_reindex) { # ->replace
427 push @$need_reindex, $smsg;
428 } else { # ->purge or ->remove
429 $self->{mm}->num_delete($num);
431 unindex_oid_remote($self, $oid, $mid);
436 my $cmt = $im->get_mark($mark);
437 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
439 if ($replace_map && scalar keys %$replace_map) {
440 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
441 return { rewrites => $rewrites, need_reindex => $need_reindex };
443 defined($mark) ? @removed : undef;
446 # public (see PublicInbox::Import->remove), but note the 3rd element
447 # (retval[2]) is not part of the stable API shared with Import->remove
449 my ($self, $mime, $cmt_msg) = @_;
451 $self->{-inbox}->with_umask(sub {
452 @ret = rewrite_internal($self, $mime, $cmt_msg);
454 defined($ret[0]) ? @ret : undef;
457 sub _replace ($$;$$) {
458 my ($self, $old_mime, $new_mime, $sref) = @_;
459 my $rewritten = $self->{-inbox}->with_umask(sub {
460 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
463 my $rewrites = $rewritten->{rewrites};
464 # ->done is called if there are rewrites since we gc+prune from git
465 $self->idx_init if @$rewrites;
467 for my $i (0..$#$rewrites) {
468 defined(my $cmt = $rewrites->[$i]) or next;
469 $self->{last_commit}->[$i] = $cmt;
476 my ($self, $mime) = @_;
477 my $rewritten = _replace($self, $mime, undef, \'') or return;
478 $rewritten->{rewrites}
481 # returns the git object_id of $fh, does not write the object to FS
482 sub git_hash_raw ($$) {
483 my ($self, $raw) = @_;
484 # grab the expected OID we have to reindex:
485 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
486 $tmp_fh->autoflush(1);
487 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
488 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
490 my $git_dir = $self->{-inbox}->git->{git_dir};
491 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
492 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
494 chomp(my $oid = <$r>);
495 close $r or die "git hash-object failed: $?";
496 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
500 sub _check_mids_match ($$$) {
501 my ($old_list, $new_list, $hdrs) = @_;
502 my %old_mids = map { $_ => 1 } @$old_list;
503 my %new_mids = map { $_ => 1 } @$new_list;
504 my @old = keys %old_mids;
505 my @new = keys %new_mids;
506 my $err = "$hdrs may not be changed when replacing\n";
507 die $err if scalar(@old) != scalar(@new);
508 delete @new_mids{@old};
509 delete @old_mids{@new};
510 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
513 # Changing Message-IDs or References with ->replace isn't supported.
514 # The rules for dealing with messages with multiple or conflicting
515 # Message-IDs are pretty complex and rethreading hasn't been fully
517 sub check_mids_match ($$) {
518 my ($old_mime, $new_mime) = @_;
519 my $old = $old_mime->header_obj;
520 my $new = $new_mime->header_obj;
521 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
522 _check_mids_match(references($old), references($new),
523 'References/In-Reply-To');
528 my ($self, $old_mime, $new_mime) = @_;
530 check_mids_match($old_mime, $new_mime);
532 # mutt will always add Content-Length:, Status:, Lines: when editing
533 PublicInbox::Import::drop_unwanted_headers($new_mime);
535 my $raw = $new_mime->as_string;
536 my $expect_oid = git_hash_raw($self, \$raw);
537 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
538 my $need_reindex = $rewritten->{need_reindex};
540 # just in case we have bugs in deduplication code:
541 my $n = scalar(@$need_reindex);
543 my $list = join(', ', map {
544 "$_->{num}: <$_->{mid}>"
547 W: rewritten $n messages matching content of original message (expected: 1).
548 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
553 # make sure we really got the OID:
554 my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
555 $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
557 # don't leak FDs to Xapian:
558 $self->{-inbox}->git->cleanup;
560 # reindex modified messages:
561 for my $smsg (@$need_reindex) {
562 my $num = $smsg->{num};
563 my $mid0 = $smsg->{mid};
564 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
566 $rewritten->{rewrites};
569 sub last_epoch_commit ($$;$) {
570 my ($self, $i, $cmt) = @_;
571 my $v = PublicInbox::Search::SCHEMA_VERSION();
572 $self->{mm}->last_commit_xap($v, $i, $cmt);
575 sub set_last_commits ($) {
577 defined(my $epoch_max = $self->{epoch_max}) or return;
578 my $last_commit = $self->{last_commit};
579 foreach my $i (0..$epoch_max) {
580 defined(my $cmt = $last_commit->[$i]) or next;
581 $last_commit->[$i] = undef;
582 last_epoch_commit($self, $i, $cmt);
588 $self->{bnote} or return;
590 my $barrier = { map { $_ => 1 } (0..$n) };
594 my ($self, $barrier) = @_;
595 my $bnote = $self->{bnote} or return;
597 while (scalar keys %$barrier) {
598 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
599 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
600 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
605 sub checkpoint ($;$) {
606 my ($self, $wait) = @_;
608 if (my $im = $self->{im}) {
615 my $shards = $self->{idx_shards};
617 my $dbh = $self->{mm}->{dbh};
619 # SQLite msgmap data is second in importance
622 # SQLite overview is third
623 $self->{over}->commit_lazy;
625 # Now deal with Xapian
627 my $barrier = $self->barrier_init(scalar @$shards);
629 # each shard needs to issue a barrier command
630 $_->remote_barrier for @$shards;
632 # wait for each Xapian shard
633 $self->barrier_wait($barrier);
635 $_->remote_commit for @$shards;
638 # last_commit is special, don't commit these until
639 # remote shards are done:
641 set_last_commits($self);
646 $self->{transact_bytes} = 0;
649 # issue a write barrier to ensure all data is visible to other processes
650 # and read-only ops. Order of data importance is: git > SQLite > Xapian
652 sub barrier { checkpoint($_[0], 1) };
657 my $im = delete $self->{im};
658 $im->done if $im; # PublicInbox::Import::done
660 my $mm = delete $self->{mm};
661 $mm->{dbh}->commit if $mm;
662 my $shards = delete $self->{idx_shards};
664 $_->remote_close for @$shards;
666 $self->{over}->disconnect;
667 delete $self->{bnote};
668 $self->{transact_bytes} = 0;
669 $self->lock_release if $shards;
670 $self->{-inbox}->git->cleanup;
673 sub fill_alternates ($$) {
674 my ($self, $epoch) = @_;
676 my $pfx = "$self->{-inbox}->{inboxdir}/git";
677 my $all = "$self->{-inbox}->{inboxdir}/all.git";
680 PublicInbox::Import::init_bare($all);
682 my $info_dir = "$all/objects/info";
683 my $alt = "$info_dir/alternates";
687 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
688 $mode = (stat($fh))[2] & 07777;
690 # we assign a sort score to every alternate and favor
691 # the newest (highest numbered) one when we
693 my $other = 0; # in case admin adds non-epoch repos
695 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
701 } split(/\n+/, do { local $/; <$fh> });
704 foreach my $i (0..$epoch) {
705 my $dir = "../../git/$i.git/objects";
706 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
713 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
714 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
715 or die "print $tmp: $!\n";
716 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
717 close $fh or die "close $tmp $!\n";
718 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
722 my ($self, $epoch) = @_;
723 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
724 my @cmd = (qw(git init --bare -q), $git_dir);
725 PublicInbox::Import::run_die(\@cmd);
726 @cmd = (qw/git config/, "--file=$git_dir/config",
727 'include.path', '../../all.git/config');
728 PublicInbox::Import::run_die(\@cmd);
729 fill_alternates($self, $epoch);
734 my ($self, $max) = @_;
736 my $pfx = "$self->{-inbox}->{inboxdir}/git";
737 return unless -d $pfx;
739 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
740 while (defined(my $git_dir = readdir($dh))) {
741 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
744 $latest = "$pfx/$git_dir";
752 my $im = $self->{im};
754 if ($im->{bytes_added} < $self->{rotate_bytes}) {
761 my $git_dir = $self->git_init(++$self->{epoch_max});
762 my $git = PublicInbox::Git->new($git_dir);
763 return $self->import_init($git, 0);
768 my $latest = git_dir_latest($self, \$max);
769 if (defined $latest) {
770 my $git = PublicInbox::Git->new($latest);
771 my $packed_bytes = $git->packed_bytes;
772 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
774 if ($unpacked_bytes >= $self->{rotate_bytes}) {
777 $self->{epoch_max} = $max;
778 return $self->import_init($git, $packed_bytes);
781 $self->{epoch_max} = $epoch;
782 $latest = $self->git_init($epoch);
783 $self->import_init(PublicInbox::Git->new($latest), 0);
787 my ($self, $git, $packed_bytes, $tmp) = @_;
788 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
789 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
790 $im->{want_object_info} = 1;
791 $im->{lock_path} = undef;
792 $im->{path_type} = 'v2';
793 $self->{im} = $im unless $tmp;
799 my ($mid, $cur, $new) = @_;
801 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
802 print $ah $cur->as_string or die "print: $!";
803 close $ah or die "close: $!";
804 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
805 PublicInbox::Import::drop_unwanted_headers($new);
806 print $bh $new->as_string or die "print: $!";
807 close $bh or die "close: $!";
808 my $cmd = [ qw(diff -u), $an, $bn ];
809 print STDERR "# MID conflict <$mid>\n";
810 my $pid = spawn($cmd, undef, { 1 => 2 });
811 waitpid($pid, 0) == $pid or die "diff did not finish";
816 my ($self, $smsg) = @_;
817 if (my $im = $self->{im}) {
818 my $msg = $im->cat_blob($smsg->{blob});
821 # older message, should be in alternates
822 my $ibx = $self->{-inbox};
823 $ibx->msg_by_smsg($smsg);
826 sub content_exists ($$$) {
827 my ($self, $mime, $mid) = @_;
828 my $over = $self->{over};
829 my $cids = content_ids($mime);
831 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
832 my $msg = get_blob($self, $smsg);
833 if (!defined($msg)) {
834 warn "broken smsg for $mid\n";
837 my $cur = PublicInbox::MIME->new($msg);
838 return 1 if content_matches($cids, $cur);
840 # XXX DEBUG_DIFF is experimental and may be removed
841 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
848 my $fh = delete $self->{reindex_pipe};
850 if (my $shards = $self->{idx_shards}) {
851 $_->atfork_child foreach @$shards;
853 if (my $im = $self->{im}) {
856 die "unexpected mm" if $self->{mm};
857 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
861 sub mark_deleted ($$$$) {
862 my ($self, $sync, $git, $oid) = @_;
863 my $msgref = $git->cat_file($oid);
864 my $mime = PublicInbox::MIME->new($$msgref);
865 my $mids = mids($mime->header_obj);
866 my $cid = content_id($mime);
867 foreach my $mid (@$mids) {
868 $sync->{D}->{"$mid\0$cid"} = $oid;
872 sub reindex_checkpoint ($$$) {
873 my ($self, $sync, $git) = @_;
876 $sync->{mm_tmp}->atfork_prepare;
877 $self->done; # release lock
879 if (my $pr = $sync->{-opt}->{-progress}) {
880 my ($bn) = (split('/', $git->{git_dir}))[-1];
881 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
884 # allow -watch or -mda to write...
885 $self->idx_init; # reacquire lock
886 $sync->{mm_tmp}->atfork_parent;
889 # only for a few odd messages with multiple Message-IDs
890 sub reindex_oid_m ($$$$;$) {
891 my ($self, $sync, $git, $oid, $regen_num) = @_;
892 $self->{current_info} = "multi_mid $oid";
893 my ($num, $mid0, $len);
894 my $msgref = $git->cat_file($oid, \$len);
895 my $mime = PublicInbox::MIME->new($$msgref);
896 my $mids = mids($mime->header_obj);
897 my $cid = content_id($mime);
898 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
900 for my $mid (reverse @$mids) {
901 delete($sync->{D}->{"$mid\0$cid"}) and
902 die "BUG: reindex_oid should handle <$mid> delete";
904 my $over = $self->{over};
905 for my $mid (reverse @$mids) {
906 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
907 next unless defined $num;
908 if (defined($regen_num) && $regen_num != $num) {
909 die "BUG: regen(#$regen_num) != over(#$num)";
912 unless (defined($num)) {
913 for my $mid (reverse @$mids) {
914 # is this a number we got before?
915 my $n = $sync->{mm_tmp}->num_for($mid);
916 next unless defined $n;
917 next if defined($regen_num) && $regen_num != $n;
918 ($num, $mid0) = ($n, $mid);
923 $sync->{mm_tmp}->num_delete($num);
924 } elsif (defined $regen_num) {
926 for my $mid (reverse @$mids) {
927 $self->{mm}->mid_set($num, $mid) == 1 or next;
931 unless (defined $mid0) {
932 warn "E: cannot regen #$num\n";
935 } else { # fixup bugs in old mirrors on reindex
936 for my $mid (reverse @$mids) {
937 $num = $self->{mm}->mid_insert($mid);
938 next unless defined $num;
943 if ($sync->{reindex}) {
944 warn "reindex added #$num <$mid0>\n";
947 warn "E: cannot find article #\n";
952 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
953 reindex_checkpoint($self, $sync, $git);
957 sub check_unindexed ($$$) {
958 my ($self, $num, $mid0) = @_;
959 my $unindexed = $self->{unindexed} // {};
960 my $n = delete($unindexed->{$mid0});
961 defined $n or return;
963 die "BUG: unindexed $n != $num <$mid0>\n";
965 $self->{mm}->mid_set($num, $mid0);
969 # reuse Msgmap to store num => oid mapping (rather than num => mid)
970 sub multi_mid_q_new () {
971 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
972 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
973 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
974 # for Msgmap->DESTROY:
975 $multi_mid->{tmp_name} = $fn;
976 $multi_mid->{pid} = $$;
977 close $fh or die "failed to close $fn: $!";
981 sub multi_mid_q_push ($$) {
982 my ($sync, $oid) = @_;
983 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
984 if ($sync->{reindex}) { # no regen on reindex
985 $multi_mid->mid_insert($oid);
987 my $num = $sync->{regen}--;
988 die "BUG: ran out of article numbers" if $num <= 0;
989 $multi_mid->mid_set($num, $oid);
993 sub reindex_oid ($$$$) {
994 my ($self, $sync, $git, $oid) = @_;
995 my ($num, $mid0, $len);
996 my $msgref = $git->cat_file($oid, \$len);
997 return if $len == 0; # purged
998 my $mime = PublicInbox::MIME->new($$msgref);
999 my $mids = mids($mime->header_obj);
1000 my $cid = content_id($mime);
1002 if (scalar(@$mids) == 0) {
1003 warn "E: $oid has no Message-ID, skipping\n";
1005 } elsif (scalar(@$mids) == 1) {
1006 my $mid = $mids->[0];
1008 # was the file previously marked as deleted?, skip if so
1009 if (delete($sync->{D}->{"$mid\0$cid"})) {
1010 if (!$sync->{reindex}) {
1011 $num = $sync->{regen}--;
1012 $self->{mm}->num_highwater($num);
1017 # is this a number we got before?
1018 $num = $sync->{mm_tmp}->num_for($mid);
1021 check_unindexed($self, $num, $mid0);
1023 $num = $sync->{regen}--;
1024 die "BUG: ran out of article numbers" if $num <= 0;
1025 if ($self->{mm}->mid_set($num, $mid) != 1) {
1026 warn "E: unable to assign $num => <$mid>\n";
1031 } else { # multiple MIDs are a weird case:
1034 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1037 unindex_oid_remote($self, $oid, $_) for @$mids;
1038 # do not delete from {mm_tmp}, since another
1039 # single-MID message may use it.
1040 } else { # handle them at the end:
1041 multi_mid_q_push($sync, $oid);
1045 $sync->{mm_tmp}->mid_delete($mid0) or
1046 die "failed to delete <$mid0> for article #$num\n";
1048 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1049 reindex_checkpoint($self, $sync, $git);
1053 # only update last_commit for $i on reindex iff newer than current
1054 sub update_last_commit ($$$$) {
1055 my ($self, $git, $i, $cmt) = @_;
1056 my $last = last_epoch_commit($self, $i);
1057 if (defined $last && is_ancestor($git, $last, $cmt)) {
1058 my @cmd = (qw(rev-list --count), "$last..$cmt");
1059 chomp(my $n = $git->qx(@cmd));
1060 return if $n ne '' && $n == 0;
1062 last_epoch_commit($self, $i, $cmt);
1065 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1067 sub last_commits ($$) {
1068 my ($self, $epoch_max) = @_;
1070 for (my $i = $epoch_max; $i >= 0; $i--) {
1071 $heads->[$i] = last_epoch_commit($self, $i);
1076 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1078 # returns a revision range for git-log(1)
1079 sub log_range ($$$$$) {
1080 my ($self, $sync, $git, $i, $tip) = @_;
1081 my $opt = $sync->{-opt};
1082 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1083 my $cur = $sync->{ranges}->[$i] or do {
1084 $pr->("$i.git indexing all of $tip") if $pr;
1085 return $tip; # all of it
1088 # fast equality check to avoid (v)fork+execve overhead
1090 $sync->{ranges}->[$i] = undef;
1094 my $range = "$cur..$tip";
1095 $pr->("$i.git checking contiguity... ") if $pr;
1096 if (is_ancestor($git, $cur, $tip)) { # common case
1097 $pr->("OK\n") if $pr;
1098 my $n = $git->qx(qw(rev-list --count), $range);
1101 $sync->{ranges}->[$i] = undef;
1102 $pr->("$i.git has nothing new\n") if $pr;
1103 return; # nothing to do
1105 $pr->("$i.git has $n changes since $cur\n") if $pr;
1107 $pr->("FAIL\n") if $pr;
1109 discontiguous range: $range
1110 Rewritten history? (in $git->{git_dir})
1112 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1114 $range = "$base..$tip";
1115 warn "found merge-base: $base\n"
1118 warn "discarding history at $cur\n";
1121 reindexing $git->{git_dir} starting at
1124 $sync->{unindex_range}->{$i} = "$base..$cur";
1129 sub sync_prepare ($$$) {
1130 my ($self, $sync, $epoch_max) = @_;
1131 my $pr = $sync->{-opt}->{-progress};
1133 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1135 # reindex stops at the current heads and we later rerun index_sync
1137 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1139 for (my $i = $epoch_max; $i >= 0; $i--) {
1140 die 'BUG: already indexing!' if $self->{reindex_pipe};
1141 my $git_dir = git_dir_n($self, $i);
1142 -d $git_dir or next; # missing epochs are fine
1143 my $git = PublicInbox::Git->new($git_dir);
1144 if ($reindex_heads) {
1145 $head = $reindex_heads->[$i] or next;
1147 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1149 next if $?; # new repo
1150 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1151 $sync->{ranges}->[$i] = $range;
1153 # can't use 'rev-list --count' if we use --diff-filter
1154 $pr->("$i.git counting $range ... ") if $pr;
1156 my $fh = $git->popen(qw(log --pretty=tformat:%H
1157 --no-notes --no-color --no-renames
1158 --diff-filter=AM), $range, '--', 'm');
1160 close $fh or die "git log failed: \$?=$?";
1161 $pr->("$n\n") if $pr;
1165 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1167 # reindex should NOT see new commits anymore, if we do,
1168 # it's a problem and we need to notice it via die()
1169 my $pad = length($regen_max) + 1;
1170 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1172 return -1 if $sync->{reindex};
1173 $regen_max + $self->{mm}->num_highwater() || 0;
1176 sub unindex_oid_remote ($$$) {
1177 my ($self, $oid, $mid) = @_;
1178 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1179 $self->{over}->remove_oid($oid, $mid);
1182 sub unindex_oid ($$$;$) {
1183 my ($self, $git, $oid, $unindexed) = @_;
1184 my $mm = $self->{mm};
1185 my $msgref = $git->cat_file($oid);
1186 my $mime = PublicInbox::MIME->new($msgref);
1187 my $mids = mids($mime->header_obj);
1188 $mime = $msgref = undef;
1189 my $over = $self->{over};
1190 foreach my $mid (@$mids) {
1193 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1194 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1197 my $n = scalar keys %gone;
1200 warn "BUG: multiple articles linked to $oid\n",
1201 join(',',sort keys %gone), "\n";
1203 foreach my $num (keys %gone) {
1205 my $mid0 = $mm->mid_for($num);
1206 $unindexed->{$mid0} = $num;
1208 $mm->num_delete($num);
1210 unindex_oid_remote($self, $oid, $mid);
1214 my $x40 = qr/[a-f0-9]{40}/;
1215 sub unindex ($$$$) {
1216 my ($self, $sync, $git, $unindex_range) = @_;
1217 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1218 my $before = scalar keys %$unindexed;
1219 # order does not matter, here:
1220 my @cmd = qw(log --raw -r
1221 --no-notes --no-color --no-abbrev --no-renames);
1222 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1224 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1225 unindex_oid($self, $git, $1, $unindexed);
1227 delete $self->{reindex_pipe};
1228 close $fh or die "git log failed: \$?=$?";
1230 return unless $sync->{-opt}->{prune};
1231 my $after = scalar keys %$unindexed;
1232 return if $before == $after;
1234 # ensure any blob can not longer be accessed via dumb HTTP
1235 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1236 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1239 sub sync_ranges ($$$) {
1240 my ($self, $sync, $epoch_max) = @_;
1241 my $reindex = $sync->{reindex};
1243 return last_commits($self, $epoch_max) unless $reindex;
1244 return [] if ref($reindex) ne 'HASH';
1246 my $ranges = $reindex->{from}; # arrayref;
1247 if (ref($ranges) ne 'ARRAY') {
1248 die 'BUG: $reindex->{from} not an ARRAY';
1253 sub index_epoch ($$$) {
1254 my ($self, $sync, $i) = @_;
1256 my $git_dir = git_dir_n($self, $i);
1257 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1258 -d $git_dir or return; # missing epochs are fine
1259 fill_alternates($self, $i);
1260 my $git = PublicInbox::Git->new($git_dir);
1261 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1262 unindex($self, $sync, $git, $unindex_range);
1264 defined(my $range = $sync->{ranges}->[$i]) or return;
1265 if (my $pr = $sync->{-opt}->{-progress}) {
1266 $pr->("$i.git indexing $range\n");
1269 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1270 --no-notes --no-color --no-abbrev --no-renames);
1271 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1275 $self->{current_info} = "$i.git $_";
1276 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1278 $self->{autime} = $2;
1279 $self->{cotime} = $3;
1280 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1281 reindex_oid($self, $sync, $git, $1);
1282 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1283 mark_deleted($self, $sync, $git, $1);
1286 close $fh or die "git log failed: \$?=$?";
1287 delete $self->{reindex_pipe};
1288 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1291 # public, called by public-inbox-index
1293 my ($self, $opt) = @_;
1295 my $pr = $opt->{-progress};
1297 my $latest = git_dir_latest($self, \$epoch_max);
1298 return unless defined $latest;
1299 $self->idx_init($opt); # acquire lock
1301 D => {}, # "$mid\0$cid" => $oid
1302 unindex_range => {}, # EPOCH => oid_old..oid_new
1303 reindex => $opt->{reindex},
1306 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1307 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1309 if ($sync->{regen}) {
1310 # tmp_clone seems to fail if inside a transaction, so
1311 # we rollback here (because we opened {mm} for reading)
1312 # Note: we do NOT rely on DBI transactions for atomicity;
1313 # only for batch performance.
1314 $self->{mm}->{dbh}->rollback;
1315 $self->{mm}->{dbh}->begin_work;
1316 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1319 # work backwards through history
1320 for (my $i = $epoch_max; $i >= 0; $i--) {
1321 index_epoch($self, $sync, $i);
1324 # unindex is required for leftovers if "deletes" affect messages
1325 # in a previous fetch+index window:
1327 if (my @leftovers = values %{delete $sync->{D}}) {
1328 $git = $self->{-inbox}->git;
1329 for my $oid (@leftovers) {
1330 $self->{current_info} = "leftover $oid";
1331 unindex_oid($self, $git, $oid);
1334 if (my $multi_mid = delete $sync->{multi_mid}) {
1335 $git //= $self->{-inbox}->git;
1336 my ($min, $max) = $multi_mid->minmax;
1337 if ($sync->{reindex}) {
1338 # we may need to create new Message-IDs if mirrors
1339 # were initially indexed with old versions
1340 for (my $i = $max; $i >= $min; $i--) {
1341 my $oid = $multi_mid->mid_for($i);
1342 next unless defined $oid;
1343 reindex_oid_m($self, $sync, $git, $oid);
1345 } else { # regen on initial index
1346 for my $num ($min..$max) {
1347 my $oid = $multi_mid->mid_for($num);
1348 next unless defined $oid;
1349 reindex_oid_m($self, $sync, $git, $oid, $num);
1353 $git->cleanup if $git;
1356 if (my $nr = $sync->{nr}) {
1357 my $pr = $sync->{-opt}->{-progress};
1358 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1361 # reindex does not pick up new changes, so we rerun w/o it:
1362 if ($opt->{reindex}) {
1365 delete @again{qw(reindex -skip_lock)};
1366 index_sync($self, \%again);