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 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
486 $tmp_fh->autoflush(1);
487 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
488 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
490 my $git_dir = $self->{-inbox}->git->{git_dir};
491 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
492 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
494 chomp(my $oid = <$r>);
495 close $r or die "git hash-object failed: $?";
496 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
500 sub _check_mids_match ($$$) {
501 my ($old_list, $new_list, $hdrs) = @_;
502 my %old_mids = map { $_ => 1 } @$old_list;
503 my %new_mids = map { $_ => 1 } @$new_list;
504 my @old = keys %old_mids;
505 my @new = keys %new_mids;
506 my $err = "$hdrs may not be changed when replacing\n";
507 die $err if scalar(@old) != scalar(@new);
508 delete @new_mids{@old};
509 delete @old_mids{@new};
510 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
513 # Changing Message-IDs or References with ->replace isn't supported.
514 # The rules for dealing with messages with multiple or conflicting
515 # Message-IDs are pretty complex and rethreading hasn't been fully
517 sub check_mids_match ($$) {
518 my ($old_mime, $new_mime) = @_;
519 my $old = $old_mime->header_obj;
520 my $new = $new_mime->header_obj;
521 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
522 _check_mids_match(references($old), references($new),
523 'References/In-Reply-To');
528 my ($self, $old_mime, $new_mime) = @_;
530 check_mids_match($old_mime, $new_mime);
532 # mutt will always add Content-Length:, Status:, Lines: when editing
533 PublicInbox::Import::drop_unwanted_headers($new_mime);
535 my $raw = $new_mime->as_string;
536 my $expect_oid = git_hash_raw($self, \$raw);
537 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
538 my $need_reindex = $rewritten->{need_reindex};
540 # just in case we have bugs in deduplication code:
541 my $n = scalar(@$need_reindex);
543 my $list = join(', ', map {
544 "$_->{num}: <$_->{mid}>"
547 W: rewritten $n messages matching content of original message (expected: 1).
548 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
553 # make sure we really got the OID:
554 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
555 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
557 # don't leak FDs to Xapian:
558 $self->{-inbox}->git->cleanup;
560 # reindex modified messages:
561 for my $smsg (@$need_reindex) {
562 my $new_smsg = bless {
567 }, 'PublicInbox::Smsg';
568 my $v2w = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
569 $new_smsg->populate($new_mime, $v2w);
570 do_idx($self, \$raw, $new_mime, $new_smsg);
572 $rewritten->{rewrites};
575 sub last_epoch_commit ($$;$) {
576 my ($self, $i, $cmt) = @_;
577 my $v = PublicInbox::Search::SCHEMA_VERSION();
578 $self->{mm}->last_commit_xap($v, $i, $cmt);
581 sub set_last_commits ($) {
583 defined(my $epoch_max = $self->{epoch_max}) or return;
584 my $last_commit = $self->{last_commit};
585 foreach my $i (0..$epoch_max) {
586 defined(my $cmt = $last_commit->[$i]) or next;
587 $last_commit->[$i] = undef;
588 last_epoch_commit($self, $i, $cmt);
594 $self->{bnote} or return;
596 my $barrier = { map { $_ => 1 } (0..$n) };
600 my ($self, $barrier) = @_;
601 my $bnote = $self->{bnote} or return;
603 while (scalar keys %$barrier) {
604 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
605 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
606 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
611 sub checkpoint ($;$) {
612 my ($self, $wait) = @_;
614 if (my $im = $self->{im}) {
621 my $shards = $self->{idx_shards};
623 my $dbh = $self->{mm}->{dbh};
625 # SQLite msgmap data is second in importance
628 # SQLite overview is third
629 $self->{over}->commit_lazy;
631 # Now deal with Xapian
633 my $barrier = $self->barrier_init(scalar @$shards);
635 # each shard needs to issue a barrier command
636 $_->remote_barrier for @$shards;
638 # wait for each Xapian shard
639 $self->barrier_wait($barrier);
641 $_->remote_commit for @$shards;
644 # last_commit is special, don't commit these until
645 # remote shards are done:
647 set_last_commits($self);
652 $self->{total_bytes} += $self->{transact_bytes};
653 $self->{transact_bytes} = 0;
656 # issue a write barrier to ensure all data is visible to other processes
657 # and read-only ops. Order of data importance is: git > SQLite > Xapian
659 sub barrier { checkpoint($_[0], 1) };
664 my $im = delete $self->{im};
665 $im->done if $im; # PublicInbox::Import::done
667 my $mm = delete $self->{mm};
668 $mm->{dbh}->commit if $mm;
669 my $shards = delete $self->{idx_shards};
671 $_->remote_close for @$shards;
673 $self->{over}->disconnect;
674 delete $self->{bnote};
675 my $nbytes = $self->{total_bytes};
676 $self->{total_bytes} = 0;
677 $self->lock_release(!!$nbytes) 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 PublicInbox::Import::init_bare($git_dir);
733 my @cmd = (qw/git config/, "--file=$git_dir/config",
734 'include.path', '../../all.git/config');
735 PublicInbox::Import::run_die(\@cmd);
736 fill_alternates($self, $epoch);
741 my ($self, $max) = @_;
743 my $pfx = "$self->{-inbox}->{inboxdir}/git";
744 return unless -d $pfx;
746 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
747 while (defined(my $git_dir = readdir($dh))) {
748 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
751 $latest = "$pfx/$git_dir";
759 my $im = $self->{im};
761 if ($im->{bytes_added} < $self->{rotate_bytes}) {
768 my $git_dir = $self->git_init(++$self->{epoch_max});
769 my $git = PublicInbox::Git->new($git_dir);
770 return $self->import_init($git, 0);
775 my $latest = git_dir_latest($self, \$max);
776 if (defined $latest) {
777 my $git = PublicInbox::Git->new($latest);
778 my $packed_bytes = $git->packed_bytes;
779 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
781 if ($unpacked_bytes >= $self->{rotate_bytes}) {
784 $self->{epoch_max} = $max;
785 return $self->import_init($git, $packed_bytes);
788 $self->{epoch_max} = $epoch;
789 $latest = $self->git_init($epoch);
790 $self->import_init(PublicInbox::Git->new($latest), 0);
794 my ($self, $git, $packed_bytes, $tmp) = @_;
795 my $im = PublicInbox::Import->new($git, undef, undef, $self->{-inbox});
796 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
797 $im->{lock_path} = undef;
798 $im->{path_type} = 'v2';
799 $self->{im} = $im unless $tmp;
805 my ($mid, $cur, $new) = @_;
807 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
808 print $ah $cur->as_string or die "print: $!";
809 close $ah or die "close: $!";
810 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
811 PublicInbox::Import::drop_unwanted_headers($new);
812 print $bh $new->as_string or die "print: $!";
813 close $bh or die "close: $!";
814 my $cmd = [ qw(diff -u), $an, $bn ];
815 print STDERR "# MID conflict <$mid>\n";
816 my $pid = spawn($cmd, undef, { 1 => 2 });
817 waitpid($pid, 0) == $pid or die "diff did not finish";
822 my ($self, $smsg) = @_;
823 if (my $im = $self->{im}) {
824 my $msg = $im->cat_blob($smsg->{blob});
827 # older message, should be in alternates
828 my $ibx = $self->{-inbox};
829 $ibx->msg_by_smsg($smsg);
832 sub content_exists ($$$) {
833 my ($self, $mime, $mid) = @_;
834 my $over = $self->{over};
835 my $chashes = content_hashes($mime);
837 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
838 my $msg = get_blob($self, $smsg);
839 if (!defined($msg)) {
840 warn "broken smsg for $mid\n";
843 my $cur = PublicInbox::Eml->new($msg);
844 return 1 if content_matches($chashes, $cur);
846 # XXX DEBUG_DIFF is experimental and may be removed
847 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
854 my $fh = delete $self->{reindex_pipe};
856 if (my $shards = $self->{idx_shards}) {
857 $_->atfork_child foreach @$shards;
859 if (my $im = $self->{im}) {
862 die "unexpected mm" if $self->{mm};
863 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
867 sub mark_deleted ($$$$) {
868 my ($self, $sync, $git, $oid) = @_;
869 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
870 my $msgref = $git->cat_file($oid);
871 my $mime = PublicInbox::Eml->new($$msgref);
872 my $mids = mids($mime->header_obj);
873 my $chash = content_hash($mime);
874 foreach my $mid (@$mids) {
875 $sync->{D}->{"$mid\0$chash"} = $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::Eml->new($$msgref);
903 my $mids = mids($mime->header_obj);
904 my $chash = content_hash($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$chash"}) 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 $smsg->populate($mime, $self);
966 if (do_idx($self, $msgref, $mime, $smsg)) {
967 reindex_checkpoint($self, $sync, $git);
971 sub check_unindexed ($$$) {
972 my ($self, $num, $mid0) = @_;
973 my $unindexed = $self->{unindexed} // {};
974 my $n = delete($unindexed->{$mid0});
975 defined $n or return;
977 die "BUG: unindexed $n != $num <$mid0>\n";
979 $self->{mm}->mid_set($num, $mid0);
983 sub multi_mid_q_push ($$$) {
984 my ($self, $sync, $oid) = @_;
985 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
986 if ($sync->{reindex}) { # no regen on reindex
987 $multi_mid->push_oid($oid, $self);
989 my $num = $sync->{regen}--;
990 die "BUG: ran out of article numbers" if $num <= 0;
991 $multi_mid->set_oid($num, $oid, $self);
995 sub reindex_oid ($$$$) {
996 my ($self, $sync, $git, $oid) = @_;
997 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
998 my ($num, $mid0, $len);
999 my $msgref = $git->cat_file($oid, \$len);
1000 return if $len == 0; # purged
1001 my $mime = PublicInbox::Eml->new($$msgref);
1002 my $mids = mids($mime->header_obj);
1003 my $chash = content_hash($mime);
1005 if (scalar(@$mids) == 0) {
1006 warn "E: $oid has no Message-ID, skipping\n";
1008 } elsif (scalar(@$mids) == 1) {
1009 my $mid = $mids->[0];
1011 # was the file previously marked as deleted?, skip if so
1012 if (delete($sync->{D}->{"$mid\0$chash"})) {
1013 if (!$sync->{reindex}) {
1014 $num = $sync->{regen}--;
1015 $self->{mm}->num_highwater($num);
1020 # is this a number we got before?
1021 $num = $sync->{mm_tmp}->num_for($mid);
1024 check_unindexed($self, $num, $mid0);
1026 $num = $sync->{regen}--;
1027 die "BUG: ran out of article numbers" if $num <= 0;
1028 if ($self->{mm}->mid_set($num, $mid) != 1) {
1029 warn "E: unable to assign $num => <$mid>\n";
1034 } else { # multiple MIDs are a weird case:
1037 $del += delete($sync->{D}->{"$_\0$chash"}) // 0;
1040 unindex_oid_remote($self, $oid, $_) for @$mids;
1041 # do not delete from {mm_tmp}, since another
1042 # single-MID message may use it.
1043 } else { # handle them at the end:
1044 multi_mid_q_push($self, $sync, $oid);
1048 $sync->{mm_tmp}->mid_delete($mid0) or
1049 die "failed to delete <$mid0> for article #$num\n";
1056 }, 'PublicInbox::Smsg';
1057 $smsg->populate($mime, $self);
1058 if (do_idx($self, $msgref, $mime, $smsg)) {
1059 reindex_checkpoint($self, $sync, $git);
1063 # only update last_commit for $i on reindex iff newer than current
1064 sub update_last_commit ($$$$) {
1065 my ($self, $git, $i, $cmt) = @_;
1066 my $last = last_epoch_commit($self, $i);
1067 if (defined $last && is_ancestor($git, $last, $cmt)) {
1068 my @cmd = (qw(rev-list --count), "$last..$cmt");
1069 chomp(my $n = $git->qx(@cmd));
1070 return if $n ne '' && $n == 0;
1072 last_epoch_commit($self, $i, $cmt);
1075 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1077 sub last_commits ($$) {
1078 my ($self, $epoch_max) = @_;
1080 for (my $i = $epoch_max; $i >= 0; $i--) {
1081 $heads->[$i] = last_epoch_commit($self, $i);
1086 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1088 # returns a revision range for git-log(1)
1089 sub log_range ($$$$$) {
1090 my ($self, $sync, $git, $i, $tip) = @_;
1091 my $opt = $sync->{-opt};
1092 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1093 my $cur = $sync->{ranges}->[$i] or do {
1094 $pr->("$i.git indexing all of $tip") if $pr;
1095 return $tip; # all of it
1098 # fast equality check to avoid (v)fork+execve overhead
1100 $sync->{ranges}->[$i] = undef;
1104 my $range = "$cur..$tip";
1105 $pr->("$i.git checking contiguity... ") if $pr;
1106 if (is_ancestor($git, $cur, $tip)) { # common case
1107 $pr->("OK\n") if $pr;
1108 my $n = $git->qx(qw(rev-list --count), $range);
1111 $sync->{ranges}->[$i] = undef;
1112 $pr->("$i.git has nothing new\n") if $pr;
1113 return; # nothing to do
1115 $pr->("$i.git has $n changes since $cur\n") if $pr;
1117 $pr->("FAIL\n") if $pr;
1119 discontiguous range: $range
1120 Rewritten history? (in $git->{git_dir})
1122 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1124 $range = "$base..$tip";
1125 warn "found merge-base: $base\n"
1128 warn "discarding history at $cur\n";
1131 reindexing $git->{git_dir} starting at
1134 $sync->{unindex_range}->{$i} = "$base..$cur";
1139 sub sync_prepare ($$$) {
1140 my ($self, $sync, $epoch_max) = @_;
1141 my $pr = $sync->{-opt}->{-progress};
1143 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1145 # reindex stops at the current heads and we later rerun index_sync
1147 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1149 for (my $i = $epoch_max; $i >= 0; $i--) {
1150 die 'BUG: already indexing!' if $self->{reindex_pipe};
1151 my $git_dir = git_dir_n($self, $i);
1152 -d $git_dir or next; # missing epochs are fine
1153 my $git = PublicInbox::Git->new($git_dir);
1154 if ($reindex_heads) {
1155 $head = $reindex_heads->[$i] or next;
1157 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1159 next if $?; # new repo
1160 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1161 $sync->{ranges}->[$i] = $range;
1163 # can't use 'rev-list --count' if we use --diff-filter
1164 $pr->("$i.git counting $range ... ") if $pr;
1166 my $fh = $git->popen(qw(log --pretty=tformat:%H
1167 --no-notes --no-color --no-renames
1168 --diff-filter=AM), $range, '--', 'm');
1170 close $fh or die "git log failed: \$?=$?";
1171 $pr->("$n\n") if $pr;
1175 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1177 # reindex should NOT see new commits anymore, if we do,
1178 # it's a problem and we need to notice it via die()
1179 my $pad = length($regen_max) + 1;
1180 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1182 return -1 if $sync->{reindex};
1183 $regen_max + $self->{mm}->num_highwater() || 0;
1186 sub unindex_oid_remote ($$$) {
1187 my ($self, $oid, $mid) = @_;
1188 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1189 $self->{over}->remove_oid($oid, $mid);
1192 sub unindex_oid ($$$;$) {
1193 my ($self, $git, $oid, $unindexed) = @_;
1194 my $mm = $self->{mm};
1195 my $msgref = $git->cat_file($oid);
1196 my $mime = PublicInbox::Eml->new($msgref);
1197 my $mids = mids($mime->header_obj);
1198 $mime = $msgref = undef;
1199 my $over = $self->{over};
1200 foreach my $mid (@$mids) {
1203 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1204 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1207 my $n = scalar keys %gone;
1210 warn "BUG: multiple articles linked to $oid\n",
1211 join(',',sort keys %gone), "\n";
1213 foreach my $num (keys %gone) {
1215 my $mid0 = $mm->mid_for($num);
1216 $unindexed->{$mid0} = $num;
1218 $mm->num_delete($num);
1220 unindex_oid_remote($self, $oid, $mid);
1224 my $x40 = qr/[a-f0-9]{40}/;
1225 sub unindex ($$$$) {
1226 my ($self, $sync, $git, $unindex_range) = @_;
1227 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1228 my $before = scalar keys %$unindexed;
1229 # order does not matter, here:
1230 my @cmd = qw(log --raw -r
1231 --no-notes --no-color --no-abbrev --no-renames);
1232 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1234 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1235 unindex_oid($self, $git, $1, $unindexed);
1237 delete $self->{reindex_pipe};
1238 close $fh or die "git log failed: \$?=$?";
1240 return unless $sync->{-opt}->{prune};
1241 my $after = scalar keys %$unindexed;
1242 return if $before == $after;
1244 # ensure any blob can not longer be accessed via dumb HTTP
1245 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1246 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1249 sub sync_ranges ($$$) {
1250 my ($self, $sync, $epoch_max) = @_;
1251 my $reindex = $sync->{reindex};
1253 return last_commits($self, $epoch_max) unless $reindex;
1254 return [] if ref($reindex) ne 'HASH';
1256 my $ranges = $reindex->{from}; # arrayref;
1257 if (ref($ranges) ne 'ARRAY') {
1258 die 'BUG: $reindex->{from} not an ARRAY';
1263 sub index_epoch ($$$) {
1264 my ($self, $sync, $i) = @_;
1266 my $git_dir = git_dir_n($self, $i);
1267 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1268 -d $git_dir or return; # missing epochs are fine
1269 fill_alternates($self, $i);
1270 my $git = PublicInbox::Git->new($git_dir);
1271 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1272 unindex($self, $sync, $git, $unindex_range);
1274 defined(my $range = $sync->{ranges}->[$i]) or return;
1275 if (my $pr = $sync->{-opt}->{-progress}) {
1276 $pr->("$i.git indexing $range\n");
1279 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1280 --no-notes --no-color --no-abbrev --no-renames);
1281 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1285 $self->{current_info} = "$i.git $_";
1286 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1288 $self->{autime} = $2;
1289 $self->{cotime} = $3;
1290 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1291 reindex_oid($self, $sync, $git, $1);
1292 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1293 mark_deleted($self, $sync, $git, $1);
1296 close $fh or die "git log failed: \$?=$?";
1297 delete @$self{qw(reindex_pipe autime cotime)};
1298 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1301 # public, called by public-inbox-index
1303 my ($self, $opt) = @_;
1305 my $pr = $opt->{-progress};
1307 my $latest = git_dir_latest($self, \$epoch_max);
1308 return unless defined $latest;
1309 $self->idx_init($opt); # acquire lock
1311 D => {}, # "$mid\0$chash" => $oid
1312 unindex_range => {}, # EPOCH => oid_old..oid_new
1313 reindex => $opt->{reindex},
1316 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1317 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1319 if ($sync->{regen}) {
1320 # tmp_clone seems to fail if inside a transaction, so
1321 # we rollback here (because we opened {mm} for reading)
1322 # Note: we do NOT rely on DBI transactions for atomicity;
1323 # only for batch performance.
1324 $self->{mm}->{dbh}->rollback;
1325 $self->{mm}->{dbh}->begin_work;
1326 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1329 # work backwards through history
1330 for (my $i = $epoch_max; $i >= 0; $i--) {
1331 index_epoch($self, $sync, $i);
1334 # unindex is required for leftovers if "deletes" affect messages
1335 # in a previous fetch+index window:
1337 if (my @leftovers = values %{delete $sync->{D}}) {
1338 $git = $self->{-inbox}->git;
1339 for my $oid (@leftovers) {
1340 $self->{current_info} = "leftover $oid";
1341 unindex_oid($self, $git, $oid);
1344 if (my $multi_mid = delete $sync->{multi_mid}) {
1345 $git //= $self->{-inbox}->git;
1346 my $min = $multi_mid->{min};
1347 my $max = $multi_mid->{max};
1348 if ($sync->{reindex}) {
1349 # we may need to create new Message-IDs if mirrors
1350 # were initially indexed with old versions
1351 for (my $i = $max; $i >= $min; $i--) {
1353 $oid = $multi_mid->get_oid($i, $self) or next;
1354 next unless defined $oid;
1355 reindex_oid_m($self, $sync, $git, $oid);
1357 } else { # regen on initial index
1358 for my $num ($min..$max) {
1360 $oid = $multi_mid->get_oid($num, $self) or next;
1361 reindex_oid_m($self, $sync, $git, $oid, $num);
1365 $git->cleanup if $git;
1368 if (my $nr = $sync->{nr}) {
1369 my $pr = $sync->{-opt}->{-progress};
1370 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1373 # reindex does not pick up new changes, so we rerun w/o it:
1374 if ($opt->{reindex}) {
1377 delete @again{qw(reindex -skip_lock)};
1378 index_sync($self, \%again);