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 parent qw(PublicInbox::Lock);
10 use PublicInbox::SearchIdxShard;
13 use PublicInbox::Import;
14 use PublicInbox::MID qw(mids references);
15 use PublicInbox::ContentHash qw(content_hash content_digest);
16 use PublicInbox::InboxWritable;
17 use PublicInbox::OverIdx;
18 use PublicInbox::Msgmap;
19 use PublicInbox::Spawn qw(spawn popen_rd);
20 use PublicInbox::SearchIdx;
21 use PublicInbox::MultiMidQueue;
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"
77 foreach my $shard (<$xpfx/*>) {
78 -d $shard && $shard =~ m!/[0-9]+\z! or next;
79 $XapianDatabase //= do {
80 require PublicInbox::Search;
81 PublicInbox::Search::load_xapian();
82 $PublicInbox::Search::X{Database};
85 $XapianDatabase->new($shard)->close;
94 # $creat may be any true value, or 0/undef. A hashref is true,
95 # and $creat->{nproc} may be set to an integer
96 my ($class, $v2ibx, $creat) = @_;
97 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
98 my $dir = $v2ibx->assert_usable_dir;
102 File::Path::mkpath($dir);
104 die "$dir does not exist\n";
107 $v2ibx->umask_prepare;
109 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
112 im => undef, # PublicInbox::Import
118 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
119 lock_path => "$dir/inbox.lock",
120 # limit each git repo (epoch) to 1GB or so
121 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
122 last_commit => [], # git repo -> commit
124 $self->{shards} = count_shards($self) || nproc_shards($creat);
125 $self->{index_max_size} = $v2ibx->{index_max_size};
131 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
132 if (defined $shards) {
133 $self->{parallel} = 0 if $shards == 0;
134 $self->{shards} = $shards if $shards > 0;
137 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
139 git_dir_latest($self, \$epoch_max);
140 if (defined $skip_epoch && $epoch_max == -1) {
141 $epoch_max = $skip_epoch;
143 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
147 # returns undef on duplicate or spam
148 # mimics Import::add and wraps it for v2
150 my ($self, $eml, $check_cb) = @_;
151 $self->{-inbox}->with_umask(\&_add, $self, $eml, $check_cb);
154 # indexes a message, returns true if checkpointing is needed
156 my ($self, $msgref, $mime, $smsg) = @_;
157 $smsg->{bytes} = $smsg->{raw_bytes} +
158 PublicInbox::SearchIdx::crlf_adjust($$msgref);
159 $self->{over}->add_overview($mime, $smsg);
160 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
161 $idx->index_raw($msgref, $mime, $smsg);
162 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
163 $n >= ($PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
167 my ($self, $mime, $check_cb) = @_;
171 $mime = $check_cb->($mime, $self->{-inbox}) or return;
174 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
175 # as does SQLite 3.4.1+ (released in 2007-07-20), and
176 # Xapian 1.3.2+ (released 2015-03-15).
177 # For the most part, we can spawn git-fast-import without
178 # leaking FDs to it...
181 my ($num, $mid0) = v2_num_for($self, $mime);
182 defined $num or return; # duplicate
183 defined $mid0 or die "BUG: \$mid0 undefined\n";
184 my $im = $self->importer;
185 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
186 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
187 $cmt = $im->get_mark($cmt);
188 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
190 my $msgref = delete $smsg->{-raw_email};
191 if (do_idx($self, $msgref, $mime, $smsg)) {
199 my ($self, $mime) = @_;
200 my $mids = mids($mime->header_obj);
202 my $mid = $mids->[0];
203 my $num = $self->{mm}->mid_insert($mid);
204 if (defined $num) { # common case
208 # crap, Message-ID is already known, hope somebody just resent:
209 foreach my $m (@$mids) {
210 # read-only lookup now safe to do after above barrier
211 # easy, don't store duplicates
212 # note: do not add more diagnostic info here since
213 # it gets noisy on public-inbox-watch restarts
214 return () if content_exists($self, $mime, $m);
217 # AltId may pre-populate article numbers (e.g. X-Mail-Count
218 # or NNTP article number), use that article number if it's
220 my $altid = $self->{-inbox}->{altid};
221 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
222 my $num = $self->{mm}->num_for($mid);
224 if (defined $num && !$self->{over}->get_art($num)) {
230 warn "<$mid> reused for mismatched content\n";
232 # try the rest of the mids
233 for(my $i = $#$mids; $i >= 1; $i--) {
235 $num = $self->{mm}->mid_insert($m);
237 warn "alternative <$m> for <$mid> found\n";
242 # none of the existing Message-IDs are good, generate a new one:
243 v2_num_for_harder($self, $mime);
246 sub v2_num_for_harder {
247 my ($self, $mime) = @_;
249 my $hdr = $mime->header_obj;
250 my $dig = content_digest($mime);
251 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
252 my $num = $self->{mm}->mid_insert($mid0);
253 unless (defined $num) {
254 # it's hard to spoof the last Received: header
255 my @recvd = $hdr->header_raw('Received');
256 $dig->add("Received: $_") foreach (@recvd);
257 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
258 $num = $self->{mm}->mid_insert($mid0);
260 # fall back to a random Message-ID and give up determinism:
261 until (defined($num)) {
263 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
264 warn "using random Message-ID <$mid0> as fallback\n";
265 $num = $self->{mm}->mid_insert($mid0);
268 PublicInbox::Import::append_mid($hdr, $mid0);
273 my ($self, $shard_i) = @_;
274 $self->{idx_shards}->[$shard_i];
277 sub _idx_init { # with_umask callback
278 my ($self, $opt) = @_;
279 $self->lock_acquire unless $opt && $opt->{-skip_lock};
280 $self->{over}->create;
282 # xcpdb can change shard count while -watch is idle
283 my $nshards = count_shards($self);
284 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
286 # need to create all shards before initializing msgmap FD
287 # idx_shards must be visible to all forked processes
288 my $max = $self->{shards} - 1;
289 my $idx = $self->{idx_shards} = [];
290 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
292 # Now that all subprocesses are up, we can open the FDs
294 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
295 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
296 $mm->{dbh}->begin_work;
301 my ($self, $opt) = @_;
302 return if $self->{idx_shards};
303 my $ibx = $self->{-inbox};
305 # do not leak read-only FDs to child processes, we only have these
306 # FDs for duplicate detection so they should not be
307 # frequently activated.
308 # delete @$ibx{qw(git mm search)};
309 delete $ibx->{$_} foreach (qw(git mm search));
311 $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
312 if ($self->{parallel}) {
313 pipe(my ($r, $w)) or die "pipe failed: $!";
314 # pipe for barrier notifications doesn't need to be big,
316 fcntl($w, 1031, 4096) if $^O eq 'linux';
317 $self->{bnote} = [ $r, $w ];
322 $ibx->with_umask(\&_idx_init, $self, $opt);
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_hashes ($) {
353 my @chashes = ( content_hash($mime) );
355 # We still support Email::MIME, here, and
356 # Email::MIME->as_string doesn't always round-trip, so we may
357 # use a second content_hash
358 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
359 push @chashes, $rt if $chashes[0] ne $rt;
363 sub content_matches ($$) {
364 my ($chashes, $existing) = @_;
365 my $chash = content_hash($existing);
366 foreach (@$chashes) {
367 return 1 if $_ eq $chash
372 # used for removing or replacing (purging)
373 sub rewrite_internal ($$;$$$) {
374 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
376 my ($im, $need_reindex, $replace_map);
378 $replace_map = {}; # oid => sref
379 $need_reindex = [] if $new_eml;
381 $im = $self->importer;
383 my $over = $self->{over};
384 my $chashes = content_hashes($old_eml);
386 my $mids = mids($old_eml->header_obj);
388 # We avoid introducing new blobs into git since the raw content
389 # can be slightly different, so we do not need the user-supplied
390 # message now that we have the mids and content_hash
394 foreach my $mid (@$mids) {
395 my %gone; # num => [ smsg, $mime, raw ]
397 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
398 my $msg = get_blob($self, $smsg);
399 if (!defined($msg)) {
400 warn "broken smsg for $mid\n";
404 my $cur = PublicInbox::Eml->new($msg);
405 if (content_matches($chashes, $cur)) {
406 $gone{$smsg->{num}} = [ $smsg, $cur, \$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, $mime, $orig) = @{$gone{$num}};
417 # $removed should only be set once assuming
418 # no bugs in our deduplication code:
419 $removed = [ undef, $mime, $smsg ];
420 my $oid = $smsg->{blob};
422 $replace_map->{$oid} = $sref;
424 ($mark, undef) = $im->remove($orig, $cmt_msg);
425 $removed->[0] = $mark;
428 if ($need_reindex) { # ->replace
429 push @$need_reindex, $smsg;
430 } else { # ->purge or ->remove
431 $self->{mm}->num_delete($num);
433 unindex_oid_remote($self, $oid, $mid);
438 my $cmt = $im->get_mark($mark);
439 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
441 if ($replace_map && scalar keys %$replace_map) {
442 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
443 return { rewrites => $rewrites, need_reindex => $need_reindex };
445 defined($mark) ? $removed : undef;
448 # public (see PublicInbox::Import->remove), but note the 3rd element
449 # (retval[2]) is not part of the stable API shared with Import->remove
451 my ($self, $eml, $cmt_msg) = @_;
452 my $r = $self->{-inbox}->with_umask(\&rewrite_internal,
453 $self, $eml, $cmt_msg);
454 defined($r) && defined($r->[0]) ? @$r: undef;
457 sub _replace ($$;$$) {
458 my ($self, $old_eml, $new_eml, $sref) = @_;
459 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
460 my $rewritten = $self->{-inbox}->with_umask(\&rewrite_internal,
461 $self, $old_eml, undef, $new_eml, $sref) or return;
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 pipe(my($in, $w)) or die "pipe: $!";
486 my $git_dir = $self->{-inbox}->git->{git_dir};
487 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
488 my $r = popen_rd($cmd, undef, { 0 => $in });
489 print $w $$raw or die "print \$w: $!";
490 close $w or die "close \$w: $!";
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 ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
553 $blob 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 $new_smsg = bless {
565 }, 'PublicInbox::Smsg';
566 my $v2w = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
567 $new_smsg->populate($new_mime, $v2w);
568 do_idx($self, \$raw, $new_mime, $new_smsg);
570 $rewritten->{rewrites};
573 sub last_epoch_commit ($$;$) {
574 my ($self, $i, $cmt) = @_;
575 my $v = PublicInbox::Search::SCHEMA_VERSION();
576 $self->{mm}->last_commit_xap($v, $i, $cmt);
579 sub set_last_commits ($) {
581 defined(my $epoch_max = $self->{epoch_max}) or return;
582 my $last_commit = $self->{last_commit};
583 foreach my $i (0..$epoch_max) {
584 defined(my $cmt = $last_commit->[$i]) or next;
585 $last_commit->[$i] = undef;
586 last_epoch_commit($self, $i, $cmt);
592 $self->{bnote} or return;
594 my $barrier = { map { $_ => 1 } (0..$n) };
598 my ($self, $barrier) = @_;
599 my $bnote = $self->{bnote} or return;
601 while (scalar keys %$barrier) {
602 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
603 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
604 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
609 sub checkpoint ($;$) {
610 my ($self, $wait) = @_;
612 if (my $im = $self->{im}) {
619 my $shards = $self->{idx_shards};
621 my $dbh = $self->{mm}->{dbh};
623 # SQLite msgmap data is second in importance
626 # SQLite overview is third
627 $self->{over}->commit_lazy;
629 # Now deal with Xapian
631 my $barrier = $self->barrier_init(scalar @$shards);
633 # each shard needs to issue a barrier command
634 $_->remote_barrier for @$shards;
636 # wait for each Xapian shard
637 $self->barrier_wait($barrier);
639 $_->remote_commit for @$shards;
642 # last_commit is special, don't commit these until
643 # remote shards are done:
645 set_last_commits($self);
650 $self->{total_bytes} += $self->{transact_bytes};
651 $self->{transact_bytes} = 0;
654 # issue a write barrier to ensure all data is visible to other processes
655 # and read-only ops. Order of data importance is: git > SQLite > Xapian
657 sub barrier { checkpoint($_[0], 1) };
662 my $im = delete $self->{im};
663 $im->done if $im; # PublicInbox::Import::done
665 my $mm = delete $self->{mm};
666 $mm->{dbh}->commit if $mm;
667 my $shards = delete $self->{idx_shards};
669 $_->remote_close for @$shards;
671 $self->{over}->disconnect;
672 delete $self->{bnote};
673 my $nbytes = $self->{total_bytes};
674 $self->{total_bytes} = 0;
675 $self->lock_release(!!$nbytes) if $shards;
676 $self->{-inbox}->git->cleanup;
679 sub fill_alternates ($$) {
680 my ($self, $epoch) = @_;
682 my $pfx = "$self->{-inbox}->{inboxdir}/git";
683 my $all = "$self->{-inbox}->{inboxdir}/all.git";
686 PublicInbox::Import::init_bare($all);
688 my $info_dir = "$all/objects/info";
689 my $alt = "$info_dir/alternates";
693 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
694 $mode = (stat($fh))[2] & 07777;
696 # we assign a sort score to every alternate and favor
697 # the newest (highest numbered) one when we
699 my $other = 0; # in case admin adds non-epoch repos
701 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
707 } split(/\n+/, do { local $/; <$fh> });
710 foreach my $i (0..$epoch) {
711 my $dir = "../../git/$i.git/objects";
712 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
719 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
720 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
721 or die "print $tmp: $!\n";
722 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
723 close $fh or die "close $tmp $!\n";
724 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
728 my ($self, $epoch) = @_;
729 my $git_dir = "$self->{-inbox}->{inboxdir}/git/$epoch.git";
730 PublicInbox::Import::init_bare($git_dir);
731 my @cmd = (qw/git config/, "--file=$git_dir/config",
732 'include.path', '../../all.git/config');
733 PublicInbox::Import::run_die(\@cmd);
734 fill_alternates($self, $epoch);
739 my ($self, $max) = @_;
741 my $pfx = "$self->{-inbox}->{inboxdir}/git";
742 return unless -d $pfx;
744 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
745 while (defined(my $git_dir = readdir($dh))) {
746 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
749 $latest = "$pfx/$git_dir";
757 my $im = $self->{im};
759 if ($im->{bytes_added} < $self->{rotate_bytes}) {
766 my $git_dir = $self->git_init(++$self->{epoch_max});
767 my $git = PublicInbox::Git->new($git_dir);
768 return $self->import_init($git, 0);
773 my $latest = git_dir_latest($self, \$max);
774 if (defined $latest) {
775 my $git = PublicInbox::Git->new($latest);
776 my $packed_bytes = $git->packed_bytes;
777 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
779 if ($unpacked_bytes >= $self->{rotate_bytes}) {
782 $self->{epoch_max} = $max;
783 return $self->import_init($git, $packed_bytes);
786 $self->{epoch_max} = $epoch;
787 $latest = $self->git_init($epoch);
788 $self->import_init(PublicInbox::Git->new($latest), 0);
792 my ($self, $git, $packed_bytes, $tmp) = @_;
793 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
794 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
795 $im->{lock_path} = undef;
796 $im->{path_type} = 'v2';
797 $self->{im} = $im unless $tmp;
803 my ($mid, $cur, $new) = @_;
805 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
806 print $ah $cur->as_string or die "print: $!";
807 close $ah or die "close: $!";
808 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
809 PublicInbox::Import::drop_unwanted_headers($new);
810 print $bh $new->as_string or die "print: $!";
811 close $bh or die "close: $!";
812 my $cmd = [ qw(diff -u), $an, $bn ];
813 print STDERR "# MID conflict <$mid>\n";
814 my $pid = spawn($cmd, undef, { 1 => 2 });
815 waitpid($pid, 0) == $pid or die "diff did not finish";
820 my ($self, $smsg) = @_;
821 if (my $im = $self->{im}) {
822 my $msg = $im->cat_blob($smsg->{blob});
825 # older message, should be in alternates
826 my $ibx = $self->{-inbox};
827 $ibx->msg_by_smsg($smsg);
830 sub content_exists ($$$) {
831 my ($self, $mime, $mid) = @_;
832 my $over = $self->{over};
833 my $chashes = content_hashes($mime);
835 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
836 my $msg = get_blob($self, $smsg);
837 if (!defined($msg)) {
838 warn "broken smsg for $mid\n";
841 my $cur = PublicInbox::Eml->new($msg);
842 return 1 if content_matches($chashes, $cur);
844 # XXX DEBUG_DIFF is experimental and may be removed
845 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
852 my $fh = delete $self->{reindex_pipe};
854 if (my $shards = $self->{idx_shards}) {
855 $_->atfork_child foreach @$shards;
857 if (my $im = $self->{im}) {
860 die "unexpected mm" if $self->{mm};
861 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
865 sub mark_deleted ($$$$) {
866 my ($self, $sync, $git, $oid) = @_;
867 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
868 my $msgref = $git->cat_file($oid);
869 my $mime = PublicInbox::Eml->new($$msgref);
870 my $mids = mids($mime->header_obj);
871 my $chash = content_hash($mime);
872 foreach my $mid (@$mids) {
873 $sync->{D}->{"$mid\0$chash"} = $oid;
877 sub reindex_checkpoint ($$$) {
878 my ($self, $sync, $git) = @_;
881 $sync->{mm_tmp}->atfork_prepare;
882 $self->done; # release lock
884 if (my $pr = $sync->{-opt}->{-progress}) {
885 my ($bn) = (split('/', $git->{git_dir}))[-1];
886 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
889 # allow -watch or -mda to write...
890 $self->idx_init; # reacquire lock
891 $sync->{mm_tmp}->atfork_parent;
894 # only for a few odd messages with multiple Message-IDs
895 sub reindex_oid_m ($$$$;$) {
896 my ($self, $sync, $git, $oid, $regen_num) = @_;
897 $self->{current_info} = "multi_mid $oid";
898 my ($num, $mid0, $len);
899 my $msgref = $git->cat_file($oid, \$len);
900 my $mime = PublicInbox::Eml->new($$msgref);
901 my $mids = mids($mime->header_obj);
902 my $chash = content_hash($mime);
903 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
905 for my $mid (reverse @$mids) {
906 delete($sync->{D}->{"$mid\0$chash"}) and
907 die "BUG: reindex_oid should handle <$mid> delete";
909 my $over = $self->{over};
910 for my $mid (reverse @$mids) {
911 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
912 next unless defined $num;
913 if (defined($regen_num) && $regen_num != $num) {
914 die "BUG: regen(#$regen_num) != over(#$num)";
917 unless (defined($num)) {
918 for my $mid (reverse @$mids) {
919 # is this a number we got before?
920 my $n = $sync->{mm_tmp}->num_for($mid);
921 next unless defined $n;
922 next if defined($regen_num) && $regen_num != $n;
923 ($num, $mid0) = ($n, $mid);
928 $sync->{mm_tmp}->num_delete($num);
929 } elsif (defined $regen_num) {
931 for my $mid (reverse @$mids) {
932 $self->{mm}->mid_set($num, $mid) == 1 or next;
936 unless (defined $mid0) {
937 warn "E: cannot regen #$num\n";
940 } else { # fixup bugs in old mirrors on reindex
941 for my $mid (reverse @$mids) {
942 $num = $self->{mm}->mid_insert($mid);
943 next unless defined $num;
948 if ($sync->{reindex}) {
949 warn "reindex added #$num <$mid0>\n";
952 warn "E: cannot find article #\n";
962 }, 'PublicInbox::Smsg';
963 $smsg->populate($mime, $self);
964 if (do_idx($self, $msgref, $mime, $smsg)) {
965 reindex_checkpoint($self, $sync, $git);
969 sub check_unindexed ($$$) {
970 my ($self, $num, $mid0) = @_;
971 my $unindexed = $self->{unindexed} // {};
972 my $n = delete($unindexed->{$mid0});
973 defined $n or return;
975 die "BUG: unindexed $n != $num <$mid0>\n";
977 $self->{mm}->mid_set($num, $mid0);
981 sub multi_mid_q_push ($$$) {
982 my ($self, $sync, $oid) = @_;
983 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
984 if ($sync->{reindex}) { # no regen on reindex
985 $multi_mid->push_oid($oid, $self);
987 my $num = $sync->{regen}--;
988 die "BUG: ran out of article numbers" if $num <= 0;
989 $multi_mid->set_oid($num, $oid, $self);
993 sub reindex_oid ($$$$) {
994 my ($self, $sync, $git, $oid) = @_;
995 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
996 my ($num, $mid0, $len);
997 my $msgref = $git->cat_file($oid, \$len);
998 return if $len == 0; # purged
999 my $mime = PublicInbox::Eml->new($$msgref);
1000 my $mids = mids($mime->header_obj);
1001 my $chash = content_hash($mime);
1003 if (scalar(@$mids) == 0) {
1004 warn "E: $oid has no Message-ID, skipping\n";
1006 } elsif (scalar(@$mids) == 1) {
1007 my $mid = $mids->[0];
1009 # was the file previously marked as deleted?, skip if so
1010 if (delete($sync->{D}->{"$mid\0$chash"})) {
1011 if (!$sync->{reindex}) {
1012 $num = $sync->{regen}--;
1013 $self->{mm}->num_highwater($num);
1018 # is this a number we got before?
1019 $num = $sync->{mm_tmp}->num_for($mid);
1022 check_unindexed($self, $num, $mid0);
1024 $num = $sync->{regen}--;
1025 die "BUG: ran out of article numbers" if $num <= 0;
1026 if ($self->{mm}->mid_set($num, $mid) != 1) {
1027 warn "E: unable to assign $num => <$mid>\n";
1032 } else { # multiple MIDs are a weird case:
1035 $del += delete($sync->{D}->{"$_\0$chash"}) // 0;
1038 unindex_oid_remote($self, $oid, $_) for @$mids;
1039 # do not delete from {mm_tmp}, since another
1040 # single-MID message may use it.
1041 } else { # handle them at the end:
1042 multi_mid_q_push($self, $sync, $oid);
1046 $sync->{mm_tmp}->mid_delete($mid0) or
1047 die "failed to delete <$mid0> for article #$num\n";
1054 }, 'PublicInbox::Smsg';
1055 $smsg->populate($mime, $self);
1056 if (do_idx($self, $msgref, $mime, $smsg)) {
1057 reindex_checkpoint($self, $sync, $git);
1061 # only update last_commit for $i on reindex iff newer than current
1062 sub update_last_commit ($$$$) {
1063 my ($self, $git, $i, $cmt) = @_;
1064 my $last = last_epoch_commit($self, $i);
1065 if (defined $last && is_ancestor($git, $last, $cmt)) {
1066 my @cmd = (qw(rev-list --count), "$last..$cmt");
1067 chomp(my $n = $git->qx(@cmd));
1068 return if $n ne '' && $n == 0;
1070 last_epoch_commit($self, $i, $cmt);
1073 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1075 sub last_commits ($$) {
1076 my ($self, $epoch_max) = @_;
1078 for (my $i = $epoch_max; $i >= 0; $i--) {
1079 $heads->[$i] = last_epoch_commit($self, $i);
1084 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1086 # returns a revision range for git-log(1)
1087 sub log_range ($$$$$) {
1088 my ($self, $sync, $git, $i, $tip) = @_;
1089 my $opt = $sync->{-opt};
1090 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1091 my $cur = $sync->{ranges}->[$i] or do {
1092 $pr->("$i.git indexing all of $tip") if $pr;
1093 return $tip; # all of it
1096 # fast equality check to avoid (v)fork+execve overhead
1098 $sync->{ranges}->[$i] = undef;
1102 my $range = "$cur..$tip";
1103 $pr->("$i.git checking contiguity... ") if $pr;
1104 if (is_ancestor($git, $cur, $tip)) { # common case
1105 $pr->("OK\n") if $pr;
1106 my $n = $git->qx(qw(rev-list --count), $range);
1109 $sync->{ranges}->[$i] = undef;
1110 $pr->("$i.git has nothing new\n") if $pr;
1111 return; # nothing to do
1113 $pr->("$i.git has $n changes since $cur\n") if $pr;
1115 $pr->("FAIL\n") if $pr;
1117 discontiguous range: $range
1118 Rewritten history? (in $git->{git_dir})
1120 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1122 $range = "$base..$tip";
1123 warn "found merge-base: $base\n"
1126 warn "discarding history at $cur\n";
1129 reindexing $git->{git_dir} starting at
1132 $sync->{unindex_range}->{$i} = "$base..$cur";
1137 sub sync_prepare ($$$) {
1138 my ($self, $sync, $epoch_max) = @_;
1139 my $pr = $sync->{-opt}->{-progress};
1141 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1143 # reindex stops at the current heads and we later rerun index_sync
1145 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1147 for (my $i = $epoch_max; $i >= 0; $i--) {
1148 die 'BUG: already indexing!' if $self->{reindex_pipe};
1149 my $git_dir = git_dir_n($self, $i);
1150 -d $git_dir or next; # missing epochs are fine
1151 my $git = PublicInbox::Git->new($git_dir);
1152 if ($reindex_heads) {
1153 $head = $reindex_heads->[$i] or next;
1155 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1157 next if $?; # new repo
1158 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1159 $sync->{ranges}->[$i] = $range;
1161 # can't use 'rev-list --count' if we use --diff-filter
1162 $pr->("$i.git counting $range ... ") if $pr;
1164 my $fh = $git->popen(qw(log --pretty=tformat:%H
1165 --no-notes --no-color --no-renames
1166 --diff-filter=AM), $range, '--', 'm');
1168 close $fh or die "git log failed: \$?=$?";
1169 $pr->("$n\n") if $pr;
1173 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1175 # reindex should NOT see new commits anymore, if we do,
1176 # it's a problem and we need to notice it via die()
1177 my $pad = length($regen_max) + 1;
1178 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1180 return -1 if $sync->{reindex};
1181 $regen_max + $self->{mm}->num_highwater() || 0;
1184 sub unindex_oid_remote ($$$) {
1185 my ($self, $oid, $mid) = @_;
1186 my @removed = $self->{over}->remove_oid($oid, $mid);
1187 for my $num (@removed) {
1188 my $idx = idx_shard($self, $num % $self->{shards});
1189 $idx->remote_remove($oid, $num);
1193 sub unindex_oid ($$$;$) {
1194 my ($self, $git, $oid, $unindexed) = @_;
1195 my $mm = $self->{mm};
1196 my $msgref = $git->cat_file($oid);
1197 my $mime = PublicInbox::Eml->new($msgref);
1198 my $mids = mids($mime->header_obj);
1199 $mime = $msgref = undef;
1200 my $over = $self->{over};
1201 foreach my $mid (@$mids) {
1204 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1205 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1208 my $n = scalar keys %gone;
1211 warn "BUG: multiple articles linked to $oid\n",
1212 join(',',sort keys %gone), "\n";
1214 foreach my $num (keys %gone) {
1216 my $mid0 = $mm->mid_for($num);
1217 $unindexed->{$mid0} = $num;
1219 $mm->num_delete($num);
1221 unindex_oid_remote($self, $oid, $mid);
1225 my $x40 = qr/[a-f0-9]{40}/;
1226 sub unindex ($$$$) {
1227 my ($self, $sync, $git, $unindex_range) = @_;
1228 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1229 my $before = scalar keys %$unindexed;
1230 # order does not matter, here:
1231 my @cmd = qw(log --raw -r
1232 --no-notes --no-color --no-abbrev --no-renames);
1233 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1235 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1236 unindex_oid($self, $git, $1, $unindexed);
1238 delete $self->{reindex_pipe};
1239 close $fh or die "git log failed: \$?=$?";
1241 return unless $sync->{-opt}->{prune};
1242 my $after = scalar keys %$unindexed;
1243 return if $before == $after;
1245 # ensure any blob can not longer be accessed via dumb HTTP
1246 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1247 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1250 sub sync_ranges ($$$) {
1251 my ($self, $sync, $epoch_max) = @_;
1252 my $reindex = $sync->{reindex};
1254 return last_commits($self, $epoch_max) unless $reindex;
1255 return [] if ref($reindex) ne 'HASH';
1257 my $ranges = $reindex->{from}; # arrayref;
1258 if (ref($ranges) ne 'ARRAY') {
1259 die 'BUG: $reindex->{from} not an ARRAY';
1264 sub index_epoch ($$$) {
1265 my ($self, $sync, $i) = @_;
1267 my $git_dir = git_dir_n($self, $i);
1268 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1269 -d $git_dir or return; # missing epochs are fine
1270 fill_alternates($self, $i);
1271 my $git = PublicInbox::Git->new($git_dir);
1272 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1273 unindex($self, $sync, $git, $unindex_range);
1275 defined(my $range = $sync->{ranges}->[$i]) or return;
1276 if (my $pr = $sync->{-opt}->{-progress}) {
1277 $pr->("$i.git indexing $range\n");
1280 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1281 --no-notes --no-color --no-abbrev --no-renames);
1282 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1286 $self->{current_info} = "$i.git $_";
1287 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1289 $self->{autime} = $2;
1290 $self->{cotime} = $3;
1291 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1292 reindex_oid($self, $sync, $git, $1);
1293 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1294 mark_deleted($self, $sync, $git, $1);
1297 close $fh or die "git log failed: \$?=$?";
1298 delete @$self{qw(reindex_pipe autime cotime)};
1299 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1302 # public, called by public-inbox-index
1304 my ($self, $opt) = @_;
1306 my $pr = $opt->{-progress};
1308 my $latest = git_dir_latest($self, \$epoch_max);
1309 return unless defined $latest;
1310 $self->idx_init($opt); # acquire lock
1312 D => {}, # "$mid\0$chash" => $oid
1313 unindex_range => {}, # EPOCH => oid_old..oid_new
1314 reindex => $opt->{reindex},
1317 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1318 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1320 if ($sync->{regen}) {
1321 # tmp_clone seems to fail if inside a transaction, so
1322 # we rollback here (because we opened {mm} for reading)
1323 # Note: we do NOT rely on DBI transactions for atomicity;
1324 # only for batch performance.
1325 $self->{mm}->{dbh}->rollback;
1326 $self->{mm}->{dbh}->begin_work;
1327 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1330 # work backwards through history
1331 for (my $i = $epoch_max; $i >= 0; $i--) {
1332 index_epoch($self, $sync, $i);
1335 # unindex is required for leftovers if "deletes" affect messages
1336 # in a previous fetch+index window:
1338 if (my @leftovers = values %{delete $sync->{D}}) {
1339 $git = $self->{-inbox}->git;
1340 for my $oid (@leftovers) {
1341 $self->{current_info} = "leftover $oid";
1342 unindex_oid($self, $git, $oid);
1345 if (my $multi_mid = delete $sync->{multi_mid}) {
1346 $git //= $self->{-inbox}->git;
1347 my $min = $multi_mid->{min};
1348 my $max = $multi_mid->{max};
1349 if ($sync->{reindex}) {
1350 # we may need to create new Message-IDs if mirrors
1351 # were initially indexed with old versions
1352 for (my $i = $max; $i >= $min; $i--) {
1354 $oid = $multi_mid->get_oid($i, $self) or next;
1355 next unless defined $oid;
1356 reindex_oid_m($self, $sync, $git, $oid);
1358 } else { # regen on initial index
1359 for my $num ($min..$max) {
1361 $oid = $multi_mid->get_oid($num, $self) or next;
1362 reindex_oid_m($self, $sync, $git, $oid, $num);
1366 $git->cleanup if $git;
1369 if (my $nr = $sync->{nr}) {
1370 my $pr = $sync->{-opt}->{-progress};
1371 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1374 # reindex does not pick up new changes, so we rerun w/o it:
1375 if ($opt->{reindex}) {
1378 delete @again{qw(reindex -skip_lock)};
1379 index_sync($self, \%again);