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 PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
23 use IO::Handle; # ->autoflush
24 use File::Temp qw(tempfile);
26 # an estimate of the post-packed size to the raw uncompressed size
27 my $PACKING_FACTOR = 0.4;
29 # SATA storage lags behind what CPUs are capable of, so relying on
30 # nproc(1) can be misleading and having extra Xapian shards is a
31 # waste of FDs and space. It can also lead to excessive IO latency
32 # and slow things down. Users on NVME or other fast storage can
33 # use the NPROC env or switches in our script/public-inbox-* programs
34 # to increase Xapian shards
35 our $NPROC_MAX_DEFAULT = 4;
38 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
39 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
42 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
43 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
44 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
47 # should we bother with `sysctl hw.ncpu`? Those only give
48 # us total processor count, not online processor count.
52 sub nproc_shards ($) {
54 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
57 # assume 2 cores if not detectable or zero
58 state $NPROC_DETECTED = detect_nproc() || 2;
60 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
63 # subtract for the main process and git-fast-import
68 sub count_shards ($) {
71 my $xpfx = $self->{xpfx};
73 # always load existing shards in case core count changes:
74 # Also, shard count may change while -watch is running
75 # due to "xcpdb --reshard"
77 require PublicInbox::Search;
78 PublicInbox::Search::load_xapian();
79 my $XapianDatabase = $PublicInbox::Search::X{Database};
80 foreach my $shard (<$xpfx/*>) {
81 -d $shard && $shard =~ m!/[0-9]+\z! or next;
83 $XapianDatabase->new($shard)->close;
92 # $creat may be any true value, or 0/undef. A hashref is true,
93 # and $creat->{nproc} may be set to an integer
94 my ($class, $v2ibx, $creat) = @_;
95 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
96 my $dir = $v2ibx->assert_usable_dir;
100 File::Path::mkpath($dir);
102 die "$dir does not exist\n";
105 $v2ibx->umask_prepare;
107 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
110 im => undef, # PublicInbox::Import
115 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
116 lock_path => "$dir/inbox.lock",
117 # limit each git repo (epoch) to 1GB or so
118 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
119 last_commit => [], # git repo -> commit
121 $self->{shards} = count_shards($self) || nproc_shards($creat);
127 my ($self, $shards, $skip_epoch) = @_;
128 if (defined $shards) {
129 $self->{parallel} = 0 if $shards == 0;
130 $self->{shards} = $shards if $shards > 0;
134 git_dir_latest($self, \$epoch_max);
135 if (defined $skip_epoch && $epoch_max == -1) {
136 $epoch_max = $skip_epoch;
138 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
142 # returns undef on duplicate or spam
143 # mimics Import::add and wraps it for v2
145 my ($self, $mime, $check_cb) = @_;
146 $self->{-inbox}->with_umask(sub {
147 _add($self, $mime, $check_cb)
151 # indexes a message, returns true if checkpointing is needed
153 my ($self, $msgref, $mime, $smsg) = @_;
154 $smsg->{ds} //= msg_datestamp($mime->header_obj, $self->{autime});
155 $smsg->{ts} //= msg_timestamp($mime->header_obj, $self->{cotime});
156 $self->{over}->add_overview($mime, $smsg);
157 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
158 $idx->index_raw($msgref, $mime, $smsg);
159 my $n = $self->{transact_bytes} += $smsg->{bytes};
160 $n >= (PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
164 my ($self, $mime, $check_cb) = @_;
168 $mime = $check_cb->($mime) or return;
171 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
172 # as does SQLite 3.4.1+ (released in 2007-07-20), and
173 # Xapian 1.3.2+ (released 2015-03-15).
174 # For the most part, we can spawn git-fast-import without
175 # leaking FDs to it...
178 my ($num, $mid0) = v2_num_for($self, $mime);
179 defined $num or return; # duplicate
180 defined $mid0 or die "BUG: $mid0 undefined\n";
181 my $im = $self->importer;
182 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
183 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
184 $cmt = $im->get_mark($cmt);
185 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
187 my $msgref = delete $smsg->{-raw_email};
188 if (do_idx($self, $msgref, $mime, $smsg)) {
196 my ($self, $mime) = @_;
197 my $mids = mids($mime->header_obj);
199 my $mid = $mids->[0];
200 my $num = $self->{mm}->mid_insert($mid);
201 if (defined $num) { # common case
205 # crap, Message-ID is already known, hope somebody just resent:
206 foreach my $m (@$mids) {
207 # read-only lookup now safe to do after above barrier
208 # easy, don't store duplicates
209 # note: do not add more diagnostic info here since
210 # it gets noisy on public-inbox-watch restarts
211 return () if content_exists($self, $mime, $m);
214 # AltId may pre-populate article numbers (e.g. X-Mail-Count
215 # or NNTP article number), use that article number if it's
217 my $altid = $self->{-inbox}->{altid};
218 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
219 my $num = $self->{mm}->num_for($mid);
221 if (defined $num && !$self->{over}->get_art($num)) {
227 warn "<$mid> reused for mismatched content\n";
229 # try the rest of the mids
230 for(my $i = $#$mids; $i >= 1; $i--) {
232 $num = $self->{mm}->mid_insert($m);
234 warn "alternative <$m> for <$mid> found\n";
239 # none of the existing Message-IDs are good, generate a new one:
240 v2_num_for_harder($self, $mime);
243 sub v2_num_for_harder {
244 my ($self, $mime) = @_;
246 my $hdr = $mime->header_obj;
247 my $dig = content_digest($mime);
248 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
249 my $num = $self->{mm}->mid_insert($mid0);
250 unless (defined $num) {
251 # it's hard to spoof the last Received: header
252 my @recvd = $hdr->header_raw('Received');
253 $dig->add("Received: $_") foreach (@recvd);
254 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
255 $num = $self->{mm}->mid_insert($mid0);
257 # fall back to a random Message-ID and give up determinism:
258 until (defined($num)) {
260 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
261 warn "using random Message-ID <$mid0> as fallback\n";
262 $num = $self->{mm}->mid_insert($mid0);
265 PublicInbox::Import::append_mid($hdr, $mid0);
270 my ($self, $shard_i) = @_;
271 $self->{idx_shards}->[$shard_i];
276 my ($self, $opt) = @_;
277 return if $self->{idx_shards};
278 my $ibx = $self->{-inbox};
280 # do not leak read-only FDs to child processes, we only have these
281 # FDs for duplicate detection so they should not be
282 # frequently activated.
283 delete $ibx->{$_} foreach (qw(git mm search));
285 my $indexlevel = $ibx->{indexlevel};
286 if ($indexlevel && $indexlevel eq 'basic') {
287 $self->{parallel} = 0;
290 if ($self->{parallel}) {
291 pipe(my ($r, $w)) or die "pipe failed: $!";
292 # pipe for barrier notifications doesn't need to be big,
294 fcntl($w, 1031, 4096) if $^O eq 'linux';
295 $self->{bnote} = [ $r, $w ];
299 my $over = $self->{over};
301 $ibx->with_umask(sub {
302 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
305 # xcpdb can change shard count while -watch is idle
306 my $nshards = count_shards($self);
307 if ($nshards && $nshards != $self->{shards}) {
308 $self->{shards} = $nshards;
311 # need to create all shards before initializing msgmap FD
312 my $max = $self->{shards} - 1;
314 # idx_shards must be visible to all forked processes
315 my $idx = $self->{idx_shards} = [];
316 for my $i (0..$max) {
317 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
320 # Now that all subprocesses are up, we can open the FDs
322 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
323 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
324 $mm->{dbh}->begin_work;
328 # returns an array mapping [ epoch => latest_commit ]
329 # latest_commit may be undef if nothing was done to that epoch
330 # $replace_map = { $object_id => $strref, ... }
331 sub _replace_oids ($$$) {
332 my ($self, $mime, $replace_map) = @_;
334 my $pfx = "$self->{-inbox}->{inboxdir}/git";
335 my $rewrites = []; # epoch => commit
336 my $max = $self->{epoch_max};
338 unless (defined($max)) {
339 defined(my $latest = git_dir_latest($self, \$max)) or return;
340 $self->{epoch_max} = $max;
343 foreach my $i (0..$max) {
344 my $git_dir = "$pfx/$i.git";
346 my $git = PublicInbox::Git->new($git_dir);
347 my $im = $self->import_init($git, 0, 1);
348 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
354 sub content_ids ($) {
356 my @cids = ( content_id($mime) );
358 # Email::MIME->as_string doesn't always round-trip, so we may
359 # use a second content_id
360 my $rt = content_id(PublicInbox::MIME->new(\($mime->as_string)));
361 push @cids, $rt if $cids[0] ne $rt;
365 sub content_matches ($$) {
366 my ($cids, $existing) = @_;
367 my $cid = content_id($existing);
369 return 1 if $_ eq $cid
374 # used for removing or replacing (purging)
375 sub rewrite_internal ($$;$$$) {
376 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
378 my ($im, $need_reindex, $replace_map);
380 $replace_map = {}; # oid => sref
381 $need_reindex = [] if $new_mime;
383 $im = $self->importer;
385 my $over = $self->{over};
386 my $cids = content_ids($old_mime);
388 my $mids = mids($old_mime->header_obj);
390 # We avoid introducing new blobs into git since the raw content
391 # can be slightly different, so we do not need the user-supplied
392 # message now that we have the mids and content_id
396 foreach my $mid (@$mids) {
397 my %gone; # num => [ smsg, $mime, raw ]
399 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
400 my $msg = get_blob($self, $smsg);
401 if (!defined($msg)) {
402 warn "broken smsg for $mid\n";
406 my $cur = PublicInbox::MIME->new($msg);
407 if (content_matches($cids, $cur)) {
408 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
411 my $n = scalar keys %gone;
414 warn "BUG: multiple articles linked to <$mid>\n",
415 join(',', sort keys %gone), "\n";
417 foreach my $num (keys %gone) {
418 my ($smsg, $mime, $orig) = @{$gone{$num}};
419 # @removed should only be set once assuming
420 # no bugs in our deduplication code:
421 @removed = (undef, $mime, $smsg);
422 my $oid = $smsg->{blob};
424 $replace_map->{$oid} = $sref;
426 ($mark, undef) = $im->remove($orig, $cmt_msg);
430 if ($need_reindex) { # ->replace
431 push @$need_reindex, $smsg;
432 } else { # ->purge or ->remove
433 $self->{mm}->num_delete($num);
435 unindex_oid_remote($self, $oid, $mid);
440 my $cmt = $im->get_mark($mark);
441 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
443 if ($replace_map && scalar keys %$replace_map) {
444 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
445 return { rewrites => $rewrites, need_reindex => $need_reindex };
447 defined($mark) ? @removed : undef;
450 # public (see PublicInbox::Import->remove), but note the 3rd element
451 # (retval[2]) is not part of the stable API shared with Import->remove
453 my ($self, $mime, $cmt_msg) = @_;
455 $self->{-inbox}->with_umask(sub {
456 @ret = rewrite_internal($self, $mime, $cmt_msg);
458 defined($ret[0]) ? @ret : undef;
461 sub _replace ($$;$$) {
462 my ($self, $old_mime, $new_mime, $sref) = @_;
463 my $rewritten = $self->{-inbox}->with_umask(sub {
464 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
467 my $rewrites = $rewritten->{rewrites};
468 # ->done is called if there are rewrites since we gc+prune from git
469 $self->idx_init if @$rewrites;
471 for my $i (0..$#$rewrites) {
472 defined(my $cmt = $rewrites->[$i]) or next;
473 $self->{last_commit}->[$i] = $cmt;
480 my ($self, $mime) = @_;
481 my $rewritten = _replace($self, $mime, undef, \'') or return;
482 $rewritten->{rewrites}
485 # returns the git object_id of $fh, does not write the object to FS
486 sub git_hash_raw ($$) {
487 my ($self, $raw) = @_;
488 # grab the expected OID we have to reindex:
489 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
490 $tmp_fh->autoflush(1);
491 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
492 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
494 my $git_dir = $self->{-inbox}->git->{git_dir};
495 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
496 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
498 chomp(my $oid = <$r>);
499 close $r or die "git hash-object failed: $?";
500 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
504 sub _check_mids_match ($$$) {
505 my ($old_list, $new_list, $hdrs) = @_;
506 my %old_mids = map { $_ => 1 } @$old_list;
507 my %new_mids = map { $_ => 1 } @$new_list;
508 my @old = keys %old_mids;
509 my @new = keys %new_mids;
510 my $err = "$hdrs may not be changed when replacing\n";
511 die $err if scalar(@old) != scalar(@new);
512 delete @new_mids{@old};
513 delete @old_mids{@new};
514 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
517 # Changing Message-IDs or References with ->replace isn't supported.
518 # The rules for dealing with messages with multiple or conflicting
519 # Message-IDs are pretty complex and rethreading hasn't been fully
521 sub check_mids_match ($$) {
522 my ($old_mime, $new_mime) = @_;
523 my $old = $old_mime->header_obj;
524 my $new = $new_mime->header_obj;
525 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
526 _check_mids_match(references($old), references($new),
527 'References/In-Reply-To');
532 my ($self, $old_mime, $new_mime) = @_;
534 check_mids_match($old_mime, $new_mime);
536 # mutt will always add Content-Length:, Status:, Lines: when editing
537 PublicInbox::Import::drop_unwanted_headers($new_mime);
539 my $raw = $new_mime->as_string;
540 my $expect_oid = git_hash_raw($self, \$raw);
541 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
542 my $need_reindex = $rewritten->{need_reindex};
544 # just in case we have bugs in deduplication code:
545 my $n = scalar(@$need_reindex);
547 my $list = join(', ', map {
548 "$_->{num}: <$_->{mid}>"
551 W: rewritten $n messages matching content of original message (expected: 1).
552 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
557 # make sure we really got the OID:
558 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
559 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
561 # don't leak FDs to Xapian:
562 $self->{-inbox}->git->cleanup;
564 # reindex modified messages:
565 for my $smsg (@$need_reindex) {
566 my $new_smsg = bless {
571 }, 'PublicInbox::Smsg';
572 do_idx($self, \$raw, $new_mime, $new_smsg);
574 $rewritten->{rewrites};
577 sub last_epoch_commit ($$;$) {
578 my ($self, $i, $cmt) = @_;
579 my $v = PublicInbox::Search::SCHEMA_VERSION();
580 $self->{mm}->last_commit_xap($v, $i, $cmt);
583 sub set_last_commits ($) {
585 defined(my $epoch_max = $self->{epoch_max}) or return;
586 my $last_commit = $self->{last_commit};
587 foreach my $i (0..$epoch_max) {
588 defined(my $cmt = $last_commit->[$i]) or next;
589 $last_commit->[$i] = undef;
590 last_epoch_commit($self, $i, $cmt);
596 $self->{bnote} or return;
598 my $barrier = { map { $_ => 1 } (0..$n) };
602 my ($self, $barrier) = @_;
603 my $bnote = $self->{bnote} or return;
605 while (scalar keys %$barrier) {
606 defined(my $l = $r->getline) or die "EOF on barrier_wait: $!";
607 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
608 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
613 sub checkpoint ($;$) {
614 my ($self, $wait) = @_;
616 if (my $im = $self->{im}) {
623 my $shards = $self->{idx_shards};
625 my $dbh = $self->{mm}->{dbh};
627 # SQLite msgmap data is second in importance
630 # SQLite overview is third
631 $self->{over}->commit_lazy;
633 # Now deal with Xapian
635 my $barrier = $self->barrier_init(scalar @$shards);
637 # each shard needs to issue a barrier command
638 $_->remote_barrier for @$shards;
640 # wait for each Xapian shard
641 $self->barrier_wait($barrier);
643 $_->remote_commit for @$shards;
646 # last_commit is special, don't commit these until
647 # remote shards are done:
649 set_last_commits($self);
654 $self->{transact_bytes} = 0;
657 # issue a write barrier to ensure all data is visible to other processes
658 # and read-only ops. Order of data importance is: git > SQLite > Xapian
660 sub barrier { checkpoint($_[0], 1) };
665 my $im = delete $self->{im};
666 $im->done if $im; # PublicInbox::Import::done
668 my $mm = delete $self->{mm};
669 $mm->{dbh}->commit if $mm;
670 my $shards = delete $self->{idx_shards};
672 $_->remote_close for @$shards;
674 $self->{over}->disconnect;
675 delete $self->{bnote};
676 $self->{transact_bytes} = 0;
677 $self->lock_release if $shards;
678 $self->{-inbox}->git->cleanup;
681 sub fill_alternates ($$) {
682 my ($self, $epoch) = @_;
684 my $pfx = "$self->{-inbox}->{inboxdir}/git";
685 my $all = "$self->{-inbox}->{inboxdir}/all.git";
688 PublicInbox::Import::init_bare($all);
690 my $info_dir = "$all/objects/info";
691 my $alt = "$info_dir/alternates";
695 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
696 $mode = (stat($fh))[2] & 07777;
698 # we assign a sort score to every alternate and favor
699 # the newest (highest numbered) one when we
701 my $other = 0; # in case admin adds non-epoch repos
703 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
709 } split(/\n+/, do { local $/; <$fh> });
712 foreach my $i (0..$epoch) {
713 my $dir = "../../git/$i.git/objects";
714 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
721 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
722 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
723 or die "print $tmp: $!\n";
724 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
725 close $fh or die "close $tmp $!\n";
726 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
730 my ($self, $epoch) = @_;
731 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
732 my @cmd = (qw(git init --bare -q), $git_dir);
733 PublicInbox::Import::run_die(\@cmd);
734 @cmd = (qw/git config/, "--file=$git_dir/config",
735 'include.path', '../../all.git/config');
736 PublicInbox::Import::run_die(\@cmd);
737 fill_alternates($self, $epoch);
742 my ($self, $max) = @_;
744 my $pfx = "$self->{-inbox}->{inboxdir}/git";
745 return unless -d $pfx;
747 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
748 while (defined(my $git_dir = readdir($dh))) {
749 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
752 $latest = "$pfx/$git_dir";
760 my $im = $self->{im};
762 if ($im->{bytes_added} < $self->{rotate_bytes}) {
769 my $git_dir = $self->git_init(++$self->{epoch_max});
770 my $git = PublicInbox::Git->new($git_dir);
771 return $self->import_init($git, 0);
776 my $latest = git_dir_latest($self, \$max);
777 if (defined $latest) {
778 my $git = PublicInbox::Git->new($latest);
779 my $packed_bytes = $git->packed_bytes;
780 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
782 if ($unpacked_bytes >= $self->{rotate_bytes}) {
785 $self->{epoch_max} = $max;
786 return $self->import_init($git, $packed_bytes);
789 $self->{epoch_max} = $epoch;
790 $latest = $self->git_init($epoch);
791 $self->import_init(PublicInbox::Git->new($latest), 0);
795 my ($self, $git, $packed_bytes, $tmp) = @_;
796 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
797 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
798 $im->{lock_path} = undef;
799 $im->{path_type} = 'v2';
800 $self->{im} = $im unless $tmp;
806 my ($mid, $cur, $new) = @_;
808 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
809 print $ah $cur->as_string or die "print: $!";
810 close $ah or die "close: $!";
811 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
812 PublicInbox::Import::drop_unwanted_headers($new);
813 print $bh $new->as_string or die "print: $!";
814 close $bh or die "close: $!";
815 my $cmd = [ qw(diff -u), $an, $bn ];
816 print STDERR "# MID conflict <$mid>\n";
817 my $pid = spawn($cmd, undef, { 1 => 2 });
818 waitpid($pid, 0) == $pid or die "diff did not finish";
823 my ($self, $smsg) = @_;
824 if (my $im = $self->{im}) {
825 my $msg = $im->cat_blob($smsg->{blob});
828 # older message, should be in alternates
829 my $ibx = $self->{-inbox};
830 $ibx->msg_by_smsg($smsg);
833 sub content_exists ($$$) {
834 my ($self, $mime, $mid) = @_;
835 my $over = $self->{over};
836 my $cids = content_ids($mime);
838 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
839 my $msg = get_blob($self, $smsg);
840 if (!defined($msg)) {
841 warn "broken smsg for $mid\n";
844 my $cur = PublicInbox::MIME->new($msg);
845 return 1 if content_matches($cids, $cur);
847 # XXX DEBUG_DIFF is experimental and may be removed
848 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
855 my $fh = delete $self->{reindex_pipe};
857 if (my $shards = $self->{idx_shards}) {
858 $_->atfork_child foreach @$shards;
860 if (my $im = $self->{im}) {
863 die "unexpected mm" if $self->{mm};
864 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
868 sub mark_deleted ($$$$) {
869 my ($self, $sync, $git, $oid) = @_;
870 my $msgref = $git->cat_file($oid);
871 my $mime = PublicInbox::MIME->new($$msgref);
872 my $mids = mids($mime->header_obj);
873 my $cid = content_id($mime);
874 foreach my $mid (@$mids) {
875 $sync->{D}->{"$mid\0$cid"} = $oid;
879 sub reindex_checkpoint ($$$) {
880 my ($self, $sync, $git) = @_;
883 $sync->{mm_tmp}->atfork_prepare;
884 $self->done; # release lock
886 if (my $pr = $sync->{-opt}->{-progress}) {
887 my ($bn) = (split('/', $git->{git_dir}))[-1];
888 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
891 # allow -watch or -mda to write...
892 $self->idx_init; # reacquire lock
893 $sync->{mm_tmp}->atfork_parent;
896 # only for a few odd messages with multiple Message-IDs
897 sub reindex_oid_m ($$$$;$) {
898 my ($self, $sync, $git, $oid, $regen_num) = @_;
899 $self->{current_info} = "multi_mid $oid";
900 my ($num, $mid0, $len);
901 my $msgref = $git->cat_file($oid, \$len);
902 my $mime = PublicInbox::MIME->new($$msgref);
903 my $mids = mids($mime->header_obj);
904 my $cid = content_id($mime);
905 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
907 for my $mid (reverse @$mids) {
908 delete($sync->{D}->{"$mid\0$cid"}) and
909 die "BUG: reindex_oid should handle <$mid> delete";
911 my $over = $self->{over};
912 for my $mid (reverse @$mids) {
913 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
914 next unless defined $num;
915 if (defined($regen_num) && $regen_num != $num) {
916 die "BUG: regen(#$regen_num) != over(#$num)";
919 unless (defined($num)) {
920 for my $mid (reverse @$mids) {
921 # is this a number we got before?
922 my $n = $sync->{mm_tmp}->num_for($mid);
923 next unless defined $n;
924 next if defined($regen_num) && $regen_num != $n;
925 ($num, $mid0) = ($n, $mid);
930 $sync->{mm_tmp}->num_delete($num);
931 } elsif (defined $regen_num) {
933 for my $mid (reverse @$mids) {
934 $self->{mm}->mid_set($num, $mid) == 1 or next;
938 unless (defined $mid0) {
939 warn "E: cannot regen #$num\n";
942 } else { # fixup bugs in old mirrors on reindex
943 for my $mid (reverse @$mids) {
944 $num = $self->{mm}->mid_insert($mid);
945 next unless defined $num;
950 if ($sync->{reindex}) {
951 warn "reindex added #$num <$mid0>\n";
954 warn "E: cannot find article #\n";
964 }, 'PublicInbox::Smsg';
965 if (do_idx($self, $msgref, $mime, $smsg)) {
966 reindex_checkpoint($self, $sync, $git);
970 sub check_unindexed ($$$) {
971 my ($self, $num, $mid0) = @_;
972 my $unindexed = $self->{unindexed} // {};
973 my $n = delete($unindexed->{$mid0});
974 defined $n or return;
976 die "BUG: unindexed $n != $num <$mid0>\n";
978 $self->{mm}->mid_set($num, $mid0);
982 # reuse Msgmap to store num => oid mapping (rather than num => mid)
983 sub multi_mid_q_new () {
984 my ($fh, $fn) = tempfile('multi_mid-XXXXXXX', EXLOCK => 0, TMPDIR => 1);
985 my $multi_mid = PublicInbox::Msgmap->new_file($fn, 1);
986 $multi_mid->{dbh}->do('PRAGMA synchronous = OFF');
987 # for Msgmap->DESTROY:
988 $multi_mid->{tmp_name} = $fn;
989 $multi_mid->{pid} = $$;
990 close $fh or die "failed to close $fn: $!";
994 sub multi_mid_q_push ($$) {
995 my ($sync, $oid) = @_;
996 my $multi_mid = $sync->{multi_mid} //= multi_mid_q_new();
997 if ($sync->{reindex}) { # no regen on reindex
998 $multi_mid->mid_insert($oid);
1000 my $num = $sync->{regen}--;
1001 die "BUG: ran out of article numbers" if $num <= 0;
1002 $multi_mid->mid_set($num, $oid);
1006 sub reindex_oid ($$$$) {
1007 my ($self, $sync, $git, $oid) = @_;
1008 my ($num, $mid0, $len);
1009 my $msgref = $git->cat_file($oid, \$len);
1010 return if $len == 0; # purged
1011 my $mime = PublicInbox::MIME->new($$msgref);
1012 my $mids = mids($mime->header_obj);
1013 my $cid = content_id($mime);
1015 if (scalar(@$mids) == 0) {
1016 warn "E: $oid has no Message-ID, skipping\n";
1018 } elsif (scalar(@$mids) == 1) {
1019 my $mid = $mids->[0];
1021 # was the file previously marked as deleted?, skip if so
1022 if (delete($sync->{D}->{"$mid\0$cid"})) {
1023 if (!$sync->{reindex}) {
1024 $num = $sync->{regen}--;
1025 $self->{mm}->num_highwater($num);
1030 # is this a number we got before?
1031 $num = $sync->{mm_tmp}->num_for($mid);
1034 check_unindexed($self, $num, $mid0);
1036 $num = $sync->{regen}--;
1037 die "BUG: ran out of article numbers" if $num <= 0;
1038 if ($self->{mm}->mid_set($num, $mid) != 1) {
1039 warn "E: unable to assign $num => <$mid>\n";
1044 } else { # multiple MIDs are a weird case:
1047 $del += delete($sync->{D}->{"$_\0$cid"}) // 0;
1050 unindex_oid_remote($self, $oid, $_) for @$mids;
1051 # do not delete from {mm_tmp}, since another
1052 # single-MID message may use it.
1053 } else { # handle them at the end:
1054 multi_mid_q_push($sync, $oid);
1058 $sync->{mm_tmp}->mid_delete($mid0) or
1059 die "failed to delete <$mid0> for article #$num\n";
1066 }, 'PublicInbox::Smsg';
1067 if (do_idx($self, $msgref, $mime, $smsg)) {
1068 reindex_checkpoint($self, $sync, $git);
1072 # only update last_commit for $i on reindex iff newer than current
1073 sub update_last_commit ($$$$) {
1074 my ($self, $git, $i, $cmt) = @_;
1075 my $last = last_epoch_commit($self, $i);
1076 if (defined $last && is_ancestor($git, $last, $cmt)) {
1077 my @cmd = (qw(rev-list --count), "$last..$cmt");
1078 chomp(my $n = $git->qx(@cmd));
1079 return if $n ne '' && $n == 0;
1081 last_epoch_commit($self, $i, $cmt);
1084 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1086 sub last_commits ($$) {
1087 my ($self, $epoch_max) = @_;
1089 for (my $i = $epoch_max; $i >= 0; $i--) {
1090 $heads->[$i] = last_epoch_commit($self, $i);
1095 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1097 # returns a revision range for git-log(1)
1098 sub log_range ($$$$$) {
1099 my ($self, $sync, $git, $i, $tip) = @_;
1100 my $opt = $sync->{-opt};
1101 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1102 my $cur = $sync->{ranges}->[$i] or do {
1103 $pr->("$i.git indexing all of $tip") if $pr;
1104 return $tip; # all of it
1107 # fast equality check to avoid (v)fork+execve overhead
1109 $sync->{ranges}->[$i] = undef;
1113 my $range = "$cur..$tip";
1114 $pr->("$i.git checking contiguity... ") if $pr;
1115 if (is_ancestor($git, $cur, $tip)) { # common case
1116 $pr->("OK\n") if $pr;
1117 my $n = $git->qx(qw(rev-list --count), $range);
1120 $sync->{ranges}->[$i] = undef;
1121 $pr->("$i.git has nothing new\n") if $pr;
1122 return; # nothing to do
1124 $pr->("$i.git has $n changes since $cur\n") if $pr;
1126 $pr->("FAIL\n") if $pr;
1128 discontiguous range: $range
1129 Rewritten history? (in $git->{git_dir})
1131 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1133 $range = "$base..$tip";
1134 warn "found merge-base: $base\n"
1137 warn "discarding history at $cur\n";
1140 reindexing $git->{git_dir} starting at
1143 $sync->{unindex_range}->{$i} = "$base..$cur";
1148 sub sync_prepare ($$$) {
1149 my ($self, $sync, $epoch_max) = @_;
1150 my $pr = $sync->{-opt}->{-progress};
1152 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1154 # reindex stops at the current heads and we later rerun index_sync
1156 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1158 for (my $i = $epoch_max; $i >= 0; $i--) {
1159 die 'BUG: already indexing!' if $self->{reindex_pipe};
1160 my $git_dir = git_dir_n($self, $i);
1161 -d $git_dir or next; # missing epochs are fine
1162 my $git = PublicInbox::Git->new($git_dir);
1163 if ($reindex_heads) {
1164 $head = $reindex_heads->[$i] or next;
1166 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1168 next if $?; # new repo
1169 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1170 $sync->{ranges}->[$i] = $range;
1172 # can't use 'rev-list --count' if we use --diff-filter
1173 $pr->("$i.git counting $range ... ") if $pr;
1175 my $fh = $git->popen(qw(log --pretty=tformat:%H
1176 --no-notes --no-color --no-renames
1177 --diff-filter=AM), $range, '--', 'm');
1179 close $fh or die "git log failed: \$?=$?";
1180 $pr->("$n\n") if $pr;
1184 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1186 # reindex should NOT see new commits anymore, if we do,
1187 # it's a problem and we need to notice it via die()
1188 my $pad = length($regen_max) + 1;
1189 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1191 return -1 if $sync->{reindex};
1192 $regen_max + $self->{mm}->num_highwater() || 0;
1195 sub unindex_oid_remote ($$$) {
1196 my ($self, $oid, $mid) = @_;
1197 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1198 $self->{over}->remove_oid($oid, $mid);
1201 sub unindex_oid ($$$;$) {
1202 my ($self, $git, $oid, $unindexed) = @_;
1203 my $mm = $self->{mm};
1204 my $msgref = $git->cat_file($oid);
1205 my $mime = PublicInbox::MIME->new($msgref);
1206 my $mids = mids($mime->header_obj);
1207 $mime = $msgref = undef;
1208 my $over = $self->{over};
1209 foreach my $mid (@$mids) {
1212 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1213 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1216 my $n = scalar keys %gone;
1219 warn "BUG: multiple articles linked to $oid\n",
1220 join(',',sort keys %gone), "\n";
1222 foreach my $num (keys %gone) {
1224 my $mid0 = $mm->mid_for($num);
1225 $unindexed->{$mid0} = $num;
1227 $mm->num_delete($num);
1229 unindex_oid_remote($self, $oid, $mid);
1233 my $x40 = qr/[a-f0-9]{40}/;
1234 sub unindex ($$$$) {
1235 my ($self, $sync, $git, $unindex_range) = @_;
1236 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1237 my $before = scalar keys %$unindexed;
1238 # order does not matter, here:
1239 my @cmd = qw(log --raw -r
1240 --no-notes --no-color --no-abbrev --no-renames);
1241 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1243 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1244 unindex_oid($self, $git, $1, $unindexed);
1246 delete $self->{reindex_pipe};
1247 close $fh or die "git log failed: \$?=$?";
1249 return unless $sync->{-opt}->{prune};
1250 my $after = scalar keys %$unindexed;
1251 return if $before == $after;
1253 # ensure any blob can not longer be accessed via dumb HTTP
1254 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1255 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1258 sub sync_ranges ($$$) {
1259 my ($self, $sync, $epoch_max) = @_;
1260 my $reindex = $sync->{reindex};
1262 return last_commits($self, $epoch_max) unless $reindex;
1263 return [] if ref($reindex) ne 'HASH';
1265 my $ranges = $reindex->{from}; # arrayref;
1266 if (ref($ranges) ne 'ARRAY') {
1267 die 'BUG: $reindex->{from} not an ARRAY';
1272 sub index_epoch ($$$) {
1273 my ($self, $sync, $i) = @_;
1275 my $git_dir = git_dir_n($self, $i);
1276 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1277 -d $git_dir or return; # missing epochs are fine
1278 fill_alternates($self, $i);
1279 my $git = PublicInbox::Git->new($git_dir);
1280 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1281 unindex($self, $sync, $git, $unindex_range);
1283 defined(my $range = $sync->{ranges}->[$i]) or return;
1284 if (my $pr = $sync->{-opt}->{-progress}) {
1285 $pr->("$i.git indexing $range\n");
1288 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1289 --no-notes --no-color --no-abbrev --no-renames);
1290 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1294 $self->{current_info} = "$i.git $_";
1295 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1297 $self->{autime} = $2;
1298 $self->{cotime} = $3;
1299 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1300 reindex_oid($self, $sync, $git, $1);
1301 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1302 mark_deleted($self, $sync, $git, $1);
1305 close $fh or die "git log failed: \$?=$?";
1306 delete $self->{reindex_pipe};
1307 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1310 # public, called by public-inbox-index
1312 my ($self, $opt) = @_;
1314 my $pr = $opt->{-progress};
1316 my $latest = git_dir_latest($self, \$epoch_max);
1317 return unless defined $latest;
1318 $self->idx_init($opt); # acquire lock
1320 D => {}, # "$mid\0$cid" => $oid
1321 unindex_range => {}, # EPOCH => oid_old..oid_new
1322 reindex => $opt->{reindex},
1325 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1326 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1328 if ($sync->{regen}) {
1329 # tmp_clone seems to fail if inside a transaction, so
1330 # we rollback here (because we opened {mm} for reading)
1331 # Note: we do NOT rely on DBI transactions for atomicity;
1332 # only for batch performance.
1333 $self->{mm}->{dbh}->rollback;
1334 $self->{mm}->{dbh}->begin_work;
1335 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1338 # work backwards through history
1339 for (my $i = $epoch_max; $i >= 0; $i--) {
1340 index_epoch($self, $sync, $i);
1343 # unindex is required for leftovers if "deletes" affect messages
1344 # in a previous fetch+index window:
1346 if (my @leftovers = values %{delete $sync->{D}}) {
1347 $git = $self->{-inbox}->git;
1348 for my $oid (@leftovers) {
1349 $self->{current_info} = "leftover $oid";
1350 unindex_oid($self, $git, $oid);
1353 if (my $multi_mid = delete $sync->{multi_mid}) {
1354 $git //= $self->{-inbox}->git;
1355 my ($min, $max) = $multi_mid->minmax;
1356 if ($sync->{reindex}) {
1357 # we may need to create new Message-IDs if mirrors
1358 # were initially indexed with old versions
1359 for (my $i = $max; $i >= $min; $i--) {
1360 my $oid = $multi_mid->mid_for($i);
1361 next unless defined $oid;
1362 reindex_oid_m($self, $sync, $git, $oid);
1364 } else { # regen on initial index
1365 for my $num ($min..$max) {
1366 my $oid = $multi_mid->mid_for($num);
1367 next unless defined $oid;
1368 reindex_oid_m($self, $sync, $git, $oid, $num);
1372 $git->cleanup if $git;
1375 if (my $nr = $sync->{nr}) {
1376 my $pr = $sync->{-opt}->{-progress};
1377 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1380 # reindex does not pick up new changes, so we rerun w/o it:
1381 if ($opt->{reindex}) {
1384 delete @again{qw(reindex -skip_lock)};
1385 index_sync($self, \%again);