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>
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);
154 my $idx = idx_shard($self, $num % $self->{shards});
155 $idx->index_raw($len, $msgref, $num, $oid, $mid0, $mime);
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);
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 my $existing = lookup_content($self, $mime, $m);
205 # easy, don't store duplicates
206 # note: do not add more diagnostic info here since
207 # it gets noisy on public-inbox-watch restarts
208 return () if $existing;
211 # AltId may pre-populate article numbers (e.g. X-Mail-Count
212 # or NNTP article number), use that article number if it's
214 my $altid = $self->{-inbox}->{altid};
215 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
216 my $num = $self->{mm}->num_for($mid);
218 if (defined $num && !$self->{over}->get_art($num)) {
224 warn "<$mid> reused for mismatched content\n";
226 # try the rest of the mids
227 for(my $i = $#$mids; $i >= 1; $i--) {
229 $num = $self->{mm}->mid_insert($m);
231 warn "alternative <$m> for <$mid> found\n";
236 # none of the existing Message-IDs are good, generate a new one:
237 v2_num_for_harder($self, $mime);
240 sub v2_num_for_harder {
241 my ($self, $mime) = @_;
243 my $hdr = $mime->header_obj;
244 my $dig = content_digest($mime);
245 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
246 my $num = $self->{mm}->mid_insert($mid0);
247 unless (defined $num) {
248 # it's hard to spoof the last Received: header
249 my @recvd = $hdr->header_raw('Received');
250 $dig->add("Received: $_") foreach (@recvd);
251 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
252 $num = $self->{mm}->mid_insert($mid0);
254 # fall back to a random Message-ID and give up determinism:
255 until (defined($num)) {
257 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
258 warn "using random Message-ID <$mid0> as fallback\n";
259 $num = $self->{mm}->mid_insert($mid0);
262 PublicInbox::Import::append_mid($hdr, $mid0);
267 my ($self, $shard_i) = @_;
268 $self->{idx_shards}->[$shard_i];
273 my ($self, $opt) = @_;
274 return if $self->{idx_shards};
275 my $ibx = $self->{-inbox};
277 # do not leak read-only FDs to child processes, we only have these
278 # FDs for duplicate detection so they should not be
279 # frequently activated.
280 delete $ibx->{$_} foreach (qw(git mm search));
282 my $indexlevel = $ibx->{indexlevel};
283 if ($indexlevel && $indexlevel eq 'basic') {
284 $self->{parallel} = 0;
287 if ($self->{parallel}) {
288 pipe(my ($r, $w)) or die "pipe failed: $!";
289 # pipe for barrier notifications doesn't need to be big,
291 fcntl($w, 1031, 4096) if $^O eq 'linux';
292 $self->{bnote} = [ $r, $w ];
296 my $over = $self->{over};
298 $ibx->with_umask(sub {
299 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
302 # xcpdb can change shard count while -watch is idle
303 my $nshards = count_shards($self);
304 if ($nshards && $nshards != $self->{shards}) {
305 $self->{shards} = $nshards;
308 # need to create all shards before initializing msgmap FD
309 my $max = $self->{shards} - 1;
311 # idx_shards must be visible to all forked processes
312 my $idx = $self->{idx_shards} = [];
313 for my $i (0..$max) {
314 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
317 # Now that all subprocesses are up, we can open the FDs
319 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
320 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
321 $mm->{dbh}->begin_work;
325 # returns an array mapping [ epoch => latest_commit ]
326 # latest_commit may be undef if nothing was done to that epoch
327 # $replace_map = { $object_id => $strref, ... }
328 sub _replace_oids ($$$) {
329 my ($self, $mime, $replace_map) = @_;
331 my $pfx = "$self->{-inbox}->{inboxdir}/git";
332 my $rewrites = []; # epoch => commit
333 my $max = $self->{epoch_max};
335 unless (defined($max)) {
336 defined(my $latest = git_dir_latest($self, \$max)) or return;
337 $self->{epoch_max} = $max;
340 foreach my $i (0..$max) {
341 my $git_dir = "$pfx/$i.git";
343 my $git = PublicInbox::Git->new($git_dir);
344 my $im = $self->import_init($git, 0, 1);
345 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
351 sub content_ids ($) {
353 my @cids = ( content_id($mime) );
355 # Email::MIME->as_string doesn't always round-trip, so we may
356 # use a second content_id
357 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
358 push @cids, $rt if $cids[0] ne $rt;
362 sub content_matches ($$) {
363 my ($cids, $existing) = @_;
364 my $cid = content_id($existing);
366 return 1 if $_ eq $cid
371 # used for removing or replacing (purging)
372 sub rewrite_internal ($$;$$$) {
373 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
375 my ($im, $need_reindex, $replace_map);
377 $replace_map = {}; # oid => sref
378 $need_reindex = [] if $new_mime;
380 $im = $self->importer;
382 my $over = $self->{over};
383 my $cids = content_ids($old_mime);
385 my $mids = mids($old_mime->header_obj);
387 # We avoid introducing new blobs into git since the raw content
388 # can be slightly different, so we do not need the user-supplied
389 # message now that we have the mids and content_id
393 foreach my $mid (@$mids) {
394 my %gone; # num => [ smsg, raw ]
396 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
397 my $msg = get_blob($self, $smsg);
398 if (!defined($msg)) {
399 warn "broken smsg for $mid\n";
403 my $cur = PublicInbox::MIME->new($msg);
404 if (content_matches($cids, $cur)) {
405 $smsg->{mime} = $cur;
406 $gone{$smsg->{num}} = [ $smsg, \$orig ];
409 my $n = scalar keys %gone;
412 warn "BUG: multiple articles linked to <$mid>\n",
413 join(',', sort keys %gone), "\n";
415 foreach my $num (keys %gone) {
416 my ($smsg, $orig) = @{$gone{$num}};
417 # $removed should only be set once assuming
418 # no bugs in our deduplication code:
420 my $oid = $smsg->{blob};
422 $replace_map->{$oid} = $sref;
424 ($mark, undef) = $im->remove($orig, $cmt_msg);
427 if ($need_reindex) { # ->replace
428 push @$need_reindex, $smsg;
429 } else { # ->purge or ->remove
430 $self->{mm}->num_delete($num);
432 unindex_oid_remote($self, $oid, $mid);
437 my $cmt = $im->get_mark($mark);
438 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
440 if ($replace_map && scalar keys %$replace_map) {
441 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
442 return { rewrites => $rewrites, need_reindex => $need_reindex };
449 my ($self, $mime, $cmt_msg) = @_;
450 $self->{-inbox}->with_umask(sub {
451 rewrite_internal($self, $mime, $cmt_msg);
455 sub _replace ($$;$$) {
456 my ($self, $old_mime, $new_mime, $sref) = @_;
457 my $rewritten = $self->{-inbox}->with_umask(sub {
458 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
461 my $rewrites = $rewritten->{rewrites};
462 # ->done is called if there are rewrites since we gc+prune from git
463 $self->idx_init if @$rewrites;
465 for my $i (0..$#$rewrites) {
466 defined(my $cmt = $rewrites->[$i]) or next;
467 $self->{last_commit}->[$i] = $cmt;
474 my ($self, $mime) = @_;
475 my $rewritten = _replace($self, $mime, undef, \'') or return;
476 $rewritten->{rewrites}
479 # returns the git object_id of $fh, does not write the object to FS
480 sub git_hash_raw ($$) {
481 my ($self, $raw) = @_;
482 # grab the expected OID we have to reindex:
483 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
484 $tmp_fh->autoflush(1);
485 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
486 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
488 my $git_dir = $self->{-inbox}->git->{git_dir};
489 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
490 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
492 chomp(my $oid = <$r>);
493 close $r or die "git hash-object failed: $?";
494 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
498 sub _check_mids_match ($$$) {
499 my ($old_list, $new_list, $hdrs) = @_;
500 my %old_mids = map { $_ => 1 } @$old_list;
501 my %new_mids = map { $_ => 1 } @$new_list;
502 my @old = keys %old_mids;
503 my @new = keys %new_mids;
504 my $err = "$hdrs may not be changed when replacing\n";
505 die $err if scalar(@old) != scalar(@new);
506 delete @new_mids{@old};
507 delete @old_mids{@new};
508 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
511 # Changing Message-IDs or References with ->replace isn't supported.
512 # The rules for dealing with messages with multiple or conflicting
513 # Message-IDs are pretty complex and rethreading hasn't been fully
515 sub check_mids_match ($$) {
516 my ($old_mime, $new_mime) = @_;
517 my $old = $old_mime->header_obj;
518 my $new = $new_mime->header_obj;
519 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
520 _check_mids_match(references($old), references($new),
521 'References/In-Reply-To');
526 my ($self, $old_mime, $new_mime) = @_;
528 check_mids_match($old_mime, $new_mime);
530 # mutt will always add Content-Length:, Status:, Lines: when editing
531 PublicInbox::Import::drop_unwanted_headers($new_mime);
533 my $raw = $new_mime->as_string;
534 my $expect_oid = git_hash_raw($self, \$raw);
535 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
536 my $need_reindex = $rewritten->{need_reindex};
538 # just in case we have bugs in deduplication code:
539 my $n = scalar(@$need_reindex);
541 my $list = join(', ', map {
542 "$_->{num}: <$_->{mid}>"
545 W: rewritten $n messages matching content of original message (expected: 1).
546 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
551 # make sure we really got the OID:
552 my ($oid, $type, $len) = $self->{-inbox}->git->check($expect_oid);
553 $oid eq $expect_oid or die "BUG: $expect_oid not found after replace";
555 # don't leak FDs to Xapian:
556 $self->{-inbox}->git->cleanup;
558 # reindex modified messages:
559 for my $smsg (@$need_reindex) {
560 my $num = $smsg->{num};
561 my $mid0 = $smsg->{mid};
562 do_idx($self, \$raw, $new_mime, $len, $num, $oid, $mid0);
564 $rewritten->{rewrites};
567 sub last_epoch_commit ($$;$) {
568 my ($self, $i, $cmt) = @_;
569 my $v = PublicInbox::Search::SCHEMA_VERSION();
570 $self->{mm}->last_commit_xap($v, $i, $cmt);
573 sub set_last_commits ($) {
575 defined(my $epoch_max = $self->{epoch_max}) or return;
576 my $last_commit = $self->{last_commit};
577 foreach my $i (0..$epoch_max) {
578 defined(my $cmt = $last_commit->[$i]) or next;
579 $last_commit->[$i] = undef;
580 last_epoch_commit($self, $i, $cmt);
586 $self->{bnote} or return;
588 my $barrier = { map { $_ => 1 } (0..$n) };
592 my ($self, $barrier) = @_;
593 my $bnote = $self->{bnote} or return;
595 while (scalar keys %$barrier) {
596 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
597 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
598 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
603 sub checkpoint ($;$) {
604 my ($self, $wait) = @_;
606 if (my $im = $self->{im}) {
613 my $shards = $self->{idx_shards};
615 my $dbh = $self->{mm}->{dbh};
617 # SQLite msgmap data is second in importance
620 # SQLite overview is third
621 $self->{over}->commit_lazy;
623 # Now deal with Xapian
625 my $barrier = $self->barrier_init(scalar @$shards);
627 # each shard needs to issue a barrier command
628 $_->remote_barrier for @$shards;
630 # wait for each Xapian shard
631 $self->barrier_wait($barrier);
633 $_->remote_commit for @$shards;
636 # last_commit is special, don't commit these until
637 # remote shards are done:
639 set_last_commits($self);
644 $self->{transact_bytes} = 0;
647 # issue a write barrier to ensure all data is visible to other processes
648 # and read-only ops. Order of data importance is: git > SQLite > Xapian
650 sub barrier { checkpoint($_[0], 1) };
655 my $im = delete $self->{im};
656 $im->done if $im; # PublicInbox::Import::done
658 my $mm = delete $self->{mm};
659 $mm->{dbh}->commit if $mm;
660 my $shards = delete $self->{idx_shards};
662 $_->remote_close for @$shards;
664 $self->{over}->disconnect;
665 delete $self->{bnote};
666 $self->{transact_bytes} = 0;
667 $self->lock_release if $shards;
668 $self->{-inbox}->git->cleanup;
671 sub fill_alternates ($$) {
672 my ($self, $epoch) = @_;
674 my $pfx = "$self->{-inbox}->{inboxdir}/git";
675 my $all = "$self->{-inbox}->{inboxdir}/all.git";
678 PublicInbox::Import::init_bare($all);
680 my $info_dir = "$all/objects/info";
681 my $alt = "$info_dir/alternates";
685 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
686 $mode = (stat($fh))[2] & 07777;
688 # we assign a sort score to every alternate and favor
689 # the newest (highest numbered) one when we
691 my $other = 0; # in case admin adds non-epoch repos
693 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
699 } split(/\n+/, do { local $/; <$fh> });
702 foreach my $i (0..$epoch) {
703 my $dir = "../../git/$i.git/objects";
704 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
711 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
712 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
713 or die "print $tmp: $!\n";
714 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
715 close $fh or die "close $tmp $!\n";
716 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
720 my ($self, $epoch) = @_;
721 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
722 my @cmd = (qw(git init --bare -q), $git_dir);
723 PublicInbox::Import::run_die(\@cmd);
724 @cmd = (qw/git config/, "--file=$git_dir/config",
725 'include.path', '../../all.git/config');
726 PublicInbox::Import::run_die(\@cmd);
727 fill_alternates($self, $epoch);
732 my ($self, $max) = @_;
734 my $pfx = "$self->{-inbox}->{inboxdir}/git";
735 return unless -d $pfx;
737 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
738 while (defined(my $git_dir = readdir($dh))) {
739 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
742 $latest = "$pfx/$git_dir";
750 my $im = $self->{im};
752 if ($im->{bytes_added} < $self->{rotate_bytes}) {
759 my $git_dir = $self->git_init(++$self->{epoch_max});
760 my $git = PublicInbox::Git->new($git_dir);
761 return $self->import_init($git, 0);
766 my $latest = git_dir_latest($self, \$max);
767 if (defined $latest) {
768 my $git = PublicInbox::Git->new($latest);
769 my $packed_bytes = $git->packed_bytes;
770 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
772 if ($unpacked_bytes >= $self->{rotate_bytes}) {
775 $self->{epoch_max} = $max;
776 return $self->import_init($git, $packed_bytes);
779 $self->{epoch_max} = $epoch;
780 $latest = $self->git_init($epoch);
781 $self->import_init(PublicInbox::Git->new($latest), 0);
785 my ($self, $git, $packed_bytes, $tmp) = @_;
786 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
787 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
788 $im->{want_object_info} = 1;
789 $im->{lock_path} = undef;
790 $im->{path_type} = 'v2';
791 $self->{im} = $im unless $tmp;
797 my ($mid, $cur, $new) = @_;
799 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
800 print $ah $cur->as_string or die "print: $!";
801 close $ah or die "close: $!";
802 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
803 PublicInbox::Import::drop_unwanted_headers($new);
804 print $bh $new->as_string or die "print: $!";
805 close $bh or die "close: $!";
806 my $cmd = [ qw(diff -u), $an, $bn ];
807 print STDERR "# MID conflict <$mid>\n";
808 my $pid = spawn($cmd, undef, { 1 => 2 });
809 waitpid($pid, 0) == $pid or die "diff did not finish";
814 my ($self, $smsg) = @_;
815 if (my $im = $self->{im}) {
816 my $msg = $im->cat_blob($smsg->{blob});
819 # older message, should be in alternates
820 my $ibx = $self->{-inbox};
821 $ibx->msg_by_smsg($smsg);
824 sub lookup_content ($$$) {
825 my ($self, $mime, $mid) = @_;
826 my $over = $self->{over};
827 my $cids = content_ids($mime);
829 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
830 my $msg = get_blob($self, $smsg);
831 if (!defined($msg)) {
832 warn "broken smsg for $mid\n";
835 my $cur = PublicInbox::MIME->new($msg);
836 if (content_matches($cids, $cur)) {
837 $smsg->{mime} = $cur;
842 # XXX DEBUG_DIFF is experimental and may be removed
843 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
850 my $fh = delete $self->{reindex_pipe};
852 if (my $shards = $self->{idx_shards}) {
853 $_->atfork_child foreach @$shards;
855 if (my $im = $self->{im}) {
858 die "unexpected mm" if $self->{mm};
859 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
863 sub mark_deleted ($$$$) {
864 my ($self, $sync, $git, $oid) = @_;
865 my $msgref = $git->cat_file($oid);
866 my $mime = PublicInbox::MIME->new($$msgref);
867 my $mids = mids($mime->header_obj);
868 my $cid = content_id($mime);
869 foreach my $mid (@$mids) {
870 $sync->{D}->{"$mid\0$cid"} = $oid;
874 sub reindex_checkpoint ($$$) {
875 my ($self, $sync, $git) = @_;
878 $sync->{mm_tmp}->atfork_prepare;
879 $self->done; # release lock
881 if (my $pr = $sync->{-opt}->{-progress}) {
882 my ($bn) = (split('/', $git->{git_dir}))[-1];
883 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
886 # allow -watch or -mda to write...
887 $self->idx_init; # reacquire lock
888 $sync->{mm_tmp}->atfork_parent;
891 # only for a few odd messages with multiple Message-IDs
892 sub reindex_oid_m ($$$$;$) {
893 my ($self, $sync, $git, $oid, $regen_num) = @_;
894 $self->{current_info} = "multi_mid $oid";
895 my ($num, $mid0, $len);
896 my $msgref = $git->cat_file($oid, \$len);
897 my $mime = PublicInbox::MIME->new($$msgref);
898 my $mids = mids($mime->header_obj);
899 my $cid = content_id($mime);
900 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
902 for my $mid (reverse @$mids) {
903 delete($sync->{D}->{"$mid\0$cid"}) and
904 die "BUG: reindex_oid should handle <$mid> delete";
906 my $over = $self->{over};
907 for my $mid (reverse @$mids) {
908 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
909 next unless defined $num;
910 if (defined($regen_num) && $regen_num != $num) {
911 die "BUG: regen(#$regen_num) != over(#$num)";
914 unless (defined($num)) {
915 for my $mid (reverse @$mids) {
916 # is this a number we got before?
917 my $n = $sync->{mm_tmp}->num_for($mid);
918 next unless defined $n;
919 next if defined($regen_num) && $regen_num != $n;
920 ($num, $mid0) = ($n, $mid);
925 $sync->{mm_tmp}->num_delete($num);
926 } elsif (defined $regen_num) {
928 for my $mid (reverse @$mids) {
929 $self->{mm}->mid_set($num, $mid) == 1 or next;
933 unless (defined $mid0) {
934 warn "E: cannot regen #$num\n";
937 } else { # fixup bugs in old mirrors on reindex
938 for my $mid (reverse @$mids) {
939 $num = $self->{mm}->mid_insert($mid);
940 next unless defined $num;
945 if ($sync->{reindex}) {
946 warn "reindex added #$num <$mid0>\n";
949 warn "E: cannot find article #\n";
954 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
955 reindex_checkpoint($self, $sync, $git);
959 sub check_unindexed ($$$) {
960 my ($self, $num, $mid0) = @_;
961 my $unindexed = $self->{unindexed} // {};
962 my $n = delete($unindexed->{$mid0});
963 defined $n or return;
965 die "BUG: unindexed $n != $num <$mid0>\n";
967 $self->{mm}->mid_set($num, $mid0);
971 # reuse Msgmap to store num => oid mapping (rather than num => mid)
972 sub multi_mid_q_new () {
973 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
974 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
975 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
976 # for Msgmap->DESTROY:
977 $multi_mid->{tmp_name} = $fn;
978 $multi_mid->{pid} = $$;
979 close $fh or die "failed to close $fn: $!";
983 sub multi_mid_q_push ($$) {
984 my ($sync, $oid) = @_;
985 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
986 if ($sync->{reindex}) { # no regen on reindex
987 $multi_mid->mid_insert($oid);
989 my $num = $sync->{regen}--;
990 die "BUG: ran out of article numbers" if $num <= 0;
991 $multi_mid->mid_set($num, $oid);
995 sub reindex_oid ($$$$) {
996 my ($self, $sync, $git, $oid) = @_;
997 my ($num, $mid0, $len);
998 my $msgref = $git->cat_file($oid, \$len);
999 return if $len == 0; # purged
1000 my $mime = PublicInbox::MIME->new($$msgref);
1001 my $mids = mids($mime->header_obj);
1002 my $cid = content_id($mime);
1004 if (scalar(@$mids) == 0) {
1005 warn "E: $oid has no Message-ID, skipping\n";
1007 } elsif (scalar(@$mids) == 1) {
1008 my $mid = $mids->[0];
1010 # was the file previously marked as deleted?, skip if so
1011 if (delete($sync->{D}->{"$mid\0$cid"})) {
1012 if (!$sync->{reindex}) {
1013 $num = $sync->{regen}--;
1014 $self->{mm}->num_highwater($num);
1019 # is this a number we got before?
1020 $num = $sync->{mm_tmp}->num_for($mid);
1023 check_unindexed($self, $num, $mid0);
1025 $num = $sync->{regen}--;
1026 die "BUG: ran out of article numbers" if $num <= 0;
1027 if ($self->{mm}->mid_set($num, $mid) != 1) {
1028 warn "E: unable to assign $num => <$mid>\n";
1033 } else { # multiple MIDs are a weird case:
1036 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1039 unindex_oid_remote($self, $oid, $_) for @$mids;
1040 # do not delete from {mm_tmp}, since another
1041 # single-MID message may use it.
1042 } else { # handle them at the end:
1043 multi_mid_q_push($sync, $oid);
1047 $sync->{mm_tmp}->mid_delete($mid0) or
1048 die "failed to delete <$mid0> for article #$num\n";
1050 if (do_idx($self, $msgref, $mime, $len, $num, $oid, $mid0)) {
1051 reindex_checkpoint($self, $sync, $git);
1055 # only update last_commit for $i on reindex iff newer than current
1056 sub update_last_commit ($$$$) {
1057 my ($self, $git, $i, $cmt) = @_;
1058 my $last = last_epoch_commit($self, $i);
1059 if (defined $last && is_ancestor($git, $last, $cmt)) {
1060 my @cmd = (qw(rev-list --count), "$last..$cmt");
1061 chomp(my $n = $git->qx(@cmd));
1062 return if $n ne '' && $n == 0;
1064 last_epoch_commit($self, $i, $cmt);
1067 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1069 sub last_commits ($$) {
1070 my ($self, $epoch_max) = @_;
1072 for (my $i = $epoch_max; $i >= 0; $i--) {
1073 $heads->[$i] = last_epoch_commit($self, $i);
1078 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1080 # returns a revision range for git-log(1)
1081 sub log_range ($$$$$) {
1082 my ($self, $sync, $git, $i, $tip) = @_;
1083 my $opt = $sync->{-opt};
1084 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1085 my $cur = $sync->{ranges}->[$i] or do {
1086 $pr->("$i.git indexing all of $tip") if $pr;
1087 return $tip; # all of it
1090 # fast equality check to avoid (v)fork+execve overhead
1092 $sync->{ranges}->[$i] = undef;
1096 my $range = "$cur..$tip";
1097 $pr->("$i.git checking contiguity... ") if $pr;
1098 if (is_ancestor($git, $cur, $tip)) { # common case
1099 $pr->("OK\n") if $pr;
1100 my $n = $git->qx(qw(rev-list --count), $range);
1103 $sync->{ranges}->[$i] = undef;
1104 $pr->("$i.git has nothing new\n") if $pr;
1105 return; # nothing to do
1107 $pr->("$i.git has $n changes since $cur\n") if $pr;
1109 $pr->("FAIL\n") if $pr;
1111 discontiguous range: $range
1112 Rewritten history? (in $git->{git_dir})
1114 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1116 $range = "$base..$tip";
1117 warn "found merge-base: $base\n"
1120 warn "discarding history at $cur\n";
1123 reindexing $git->{git_dir} starting at
1126 $sync->{unindex_range}->{$i} = "$base..$cur";
1131 sub sync_prepare ($$$) {
1132 my ($self, $sync, $epoch_max) = @_;
1133 my $pr = $sync->{-opt}->{-progress};
1135 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1137 # reindex stops at the current heads and we later rerun index_sync
1139 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1141 for (my $i = $epoch_max; $i >= 0; $i--) {
1142 die 'BUG: already indexing!' if $self->{reindex_pipe};
1143 my $git_dir = git_dir_n($self, $i);
1144 -d $git_dir or next; # missing epochs are fine
1145 my $git = PublicInbox::Git->new($git_dir);
1146 if ($reindex_heads) {
1147 $head = $reindex_heads->[$i] or next;
1149 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1151 next if $?; # new repo
1152 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1153 $sync->{ranges}->[$i] = $range;
1155 # can't use 'rev-list --count' if we use --diff-filter
1156 $pr->("$i.git counting $range ... ") if $pr;
1158 my $fh = $git->popen(qw(log --pretty=tformat:%H
1159 --no-notes --no-color --no-renames
1160 --diff-filter=AM), $range, '--', 'm');
1162 close $fh or die "git log failed: \$?=$?";
1163 $pr->("$n\n") if $pr;
1167 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1169 # reindex should NOT see new commits anymore, if we do,
1170 # it's a problem and we need to notice it via die()
1171 my $pad = length($regen_max) + 1;
1172 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1174 return -1 if $sync->{reindex};
1175 $regen_max + $self->{mm}->num_highwater() || 0;
1178 sub unindex_oid_remote ($$$) {
1179 my ($self, $oid, $mid) = @_;
1180 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1181 $self->{over}->remove_oid($oid, $mid);
1184 sub unindex_oid ($$$;$) {
1185 my ($self, $git, $oid, $unindexed) = @_;
1186 my $mm = $self->{mm};
1187 my $msgref = $git->cat_file($oid);
1188 my $mime = PublicInbox::MIME->new($msgref);
1189 my $mids = mids($mime->header_obj);
1190 $mime = $msgref = undef;
1191 my $over = $self->{over};
1192 foreach my $mid (@$mids) {
1195 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1196 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1199 my $n = scalar keys %gone;
1202 warn "BUG: multiple articles linked to $oid\n",
1203 join(',',sort keys %gone), "\n";
1205 foreach my $num (keys %gone) {
1207 my $mid0 = $mm->mid_for($num);
1208 $unindexed->{$mid0} = $num;
1210 $mm->num_delete($num);
1212 unindex_oid_remote($self, $oid, $mid);
1216 my $x40 = qr/[a-f0-9]{40}/;
1217 sub unindex ($$$$) {
1218 my ($self, $sync, $git, $unindex_range) = @_;
1219 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1220 my $before = scalar keys %$unindexed;
1221 # order does not matter, here:
1222 my @cmd = qw(log --raw -r
1223 --no-notes --no-color --no-abbrev --no-renames);
1224 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1226 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1227 unindex_oid($self, $git, $1, $unindexed);
1229 delete $self->{reindex_pipe};
1230 close $fh or die "git log failed: \$?=$?";
1232 return unless $sync->{-opt}->{prune};
1233 my $after = scalar keys %$unindexed;
1234 return if $before == $after;
1236 # ensure any blob can not longer be accessed via dumb HTTP
1237 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1238 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1241 sub sync_ranges ($$$) {
1242 my ($self, $sync, $epoch_max) = @_;
1243 my $reindex = $sync->{reindex};
1245 return last_commits($self, $epoch_max) unless $reindex;
1246 return [] if ref($reindex) ne 'HASH';
1248 my $ranges = $reindex->{from}; # arrayref;
1249 if (ref($ranges) ne 'ARRAY') {
1250 die 'BUG: $reindex->{from} not an ARRAY';
1255 sub index_epoch ($$$) {
1256 my ($self, $sync, $i) = @_;
1258 my $git_dir = git_dir_n($self, $i);
1259 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1260 -d $git_dir or return; # missing epochs are fine
1261 fill_alternates($self, $i);
1262 my $git = PublicInbox::Git->new($git_dir);
1263 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1264 unindex($self, $sync, $git, $unindex_range);
1266 defined(my $range = $sync->{ranges}->[$i]) or return;
1267 if (my $pr = $sync->{-opt}->{-progress}) {
1268 $pr->("$i.git indexing $range\n");
1271 my @cmd = qw(log --raw -r --pretty=tformat:%H
1272 --no-notes --no-color --no-abbrev --no-renames);
1273 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1277 $self->{current_info} = "$i.git $_";
1278 if (/\A$x40$/o && !defined($cmt)) {
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);