1 # Copyright (C) 2018-2021 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 run_die);
20 use PublicInbox::Search;
21 use PublicInbox::SearchIdx qw(log2stack is_ancestor check_size is_bad_blob);
22 use IO::Handle; # ->autoflush
25 my $OID = qr/[a-f0-9]{40,}/;
26 # an estimate of the post-packed size to the raw uncompressed size
27 our $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 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
39 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
40 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
42 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
43 `$nproc 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 ($) {
69 if (my $ibx = $self->{ibx}) {
70 # always load existing shards in case core count changes:
71 # Also, shard count may change while -watch is running
72 my $srch = $ibx->search or return 0;
73 delete $ibx->{search};
75 } else { # ExtSearchIdx
76 $self->{nshard} ||= scalar($self->xdb_shards_flat);
81 # $creat may be any true value, or 0/undef. A hashref is true,
82 # and $creat->{nproc} may be set to an integer
83 my ($class, $v2ibx, $creat) = @_;
84 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
85 my $dir = $v2ibx->assert_usable_dir;
89 File::Path::mkpath($dir);
91 die "$dir does not exist\n";
94 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
97 im => undef, # PublicInbox::Import
103 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
104 lock_path => "$dir/inbox.lock",
105 # limit each git repo (epoch) to 1GB or so
106 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
107 last_commit => [], # git epoch -> commit
109 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
110 $self->{shards} = count_shards($self) || nproc_shards($creat);
116 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
117 if (defined $shards) {
118 $self->{parallel} = 0 if $shards == 0;
119 $self->{shards} = $shards if $shards > 0;
122 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
123 my $max = $self->{ibx}->max_git_epoch;
124 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
125 $self->git_init($max // 0);
129 # returns undef on duplicate or spam
130 # mimics Import::add and wraps it for v2
132 my ($self, $eml, $check_cb) = @_;
133 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
137 my ($self, $num) = @_;
138 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
141 # indexes a message, returns true if checkpointing is needed
143 my ($self, $eml, $smsg) = @_;
144 $self->{oidx}->add_overview($eml, $smsg);
145 if ($self->{-need_xapian}) {
146 my $idx = idx_shard($self, $smsg->{num});
147 $idx->index_eml($eml, $smsg);
149 my $n = $self->{transact_bytes} += $smsg->{bytes};
150 $n >= $self->{batch_bytes};
154 my ($self, $mime, $check_cb) = @_;
158 $mime = $check_cb->($mime, $self->{ibx}) or return;
161 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
162 # as does SQLite 3.4.1+ (released in 2007-07-20), and
163 # Xapian 1.3.2+ (released 2015-03-15).
164 # For the most part, we can spawn git-fast-import without
165 # leaking FDs to it...
168 my ($num, $mid0) = v2_num_for($self, $mime);
169 defined $num or return; # duplicate
170 defined $mid0 or die "BUG: \$mid0 undefined\n";
171 my $im = $self->importer;
172 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
173 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
174 $cmt = $im->get_mark($cmt);
175 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
177 if (do_idx($self, $mime, $smsg)) {
185 my ($self, $mime) = @_;
186 my $mids = mids($mime);
188 my $mid = $mids->[0];
189 my $num = $self->{mm}->mid_insert($mid);
190 if (defined $num) { # common case
194 # crap, Message-ID is already known, hope somebody just resent:
195 foreach my $m (@$mids) {
196 # read-only lookup now safe to do after above barrier
197 # easy, don't store duplicates
198 # note: do not add more diagnostic info here since
199 # it gets noisy on public-inbox-watch restarts
200 return () if content_exists($self, $mime, $m);
203 # AltId may pre-populate article numbers (e.g. X-Mail-Count
204 # or NNTP article number), use that article number if it's
206 my $altid = $self->{ibx}->{altid};
207 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
208 my $num = $self->{mm}->num_for($mid);
210 if (defined $num && !$self->{oidx}->get_art($num)) {
216 warn "<$mid> reused for mismatched content\n";
218 # try the rest of the mids
219 for(my $i = $#$mids; $i >= 1; $i--) {
221 $num = $self->{mm}->mid_insert($m);
223 warn "alternative <$m> for <$mid> found\n";
228 # none of the existing Message-IDs are good, generate a new one:
229 v2_num_for_harder($self, $mime);
232 sub v2_num_for_harder {
233 my ($self, $eml) = @_;
235 my $dig = content_digest($eml);
236 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
237 my $num = $self->{mm}->mid_insert($mid0);
238 unless (defined $num) {
239 # it's hard to spoof the last Received: header
240 my @recvd = $eml->header_raw('Received');
241 $dig->add("Received: $_") foreach (@recvd);
242 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
243 $num = $self->{mm}->mid_insert($mid0);
245 # fall back to a random Message-ID and give up determinism:
246 until (defined($num)) {
248 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
249 warn "using random Message-ID <$mid0> as fallback\n";
250 $num = $self->{mm}->mid_insert($mid0);
253 PublicInbox::Import::append_mid($eml, $mid0);
257 sub _idx_init { # with_umask callback
258 my ($self, $opt) = @_;
259 $self->lock_acquire unless $opt && $opt->{-skip_lock};
260 $self->{oidx}->create;
262 # xcpdb can change shard count while -watch is idle
263 my $nshards = count_shards($self);
264 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
265 $self->{batch_bytes} = $opt->{batch_size} //
266 $PublicInbox::SearchIdx::BATCH_BYTES;
268 # need to create all shards before initializing msgmap FD
269 # idx_shards must be visible to all forked processes
270 my $max = $self->{shards} - 1;
271 my $idx = $self->{idx_shards} = [];
272 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
273 $self->{-need_xapian} = $idx->[0]->need_xapian;
275 # SearchIdxShard may do their own flushing, so don't scale
276 # until after forking
277 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
279 my $ibx = $self->{ibx} or return; # ExtIdxSearch
281 # Now that all subprocesses are up, we can open the FDs
283 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
284 "$ibx->{inboxdir}/msgmap.sqlite3",
285 $ibx->{-no_fsync} ? 2 : 1);
286 $mm->{dbh}->begin_work;
289 sub parallel_init ($$) {
290 my ($self, $indexlevel) = @_;
291 $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
296 my ($self, $opt) = @_;
297 return if $self->{idx_shards};
298 my $ibx = $self->{ibx};
300 # do not leak read-only FDs to child processes, we only have these
301 # FDs for duplicate detection so they should not be
302 # frequently activated.
303 delete @$ibx{qw(mm search)};
306 parallel_init($self, $ibx->{indexlevel});
307 $ibx->with_umask(\&_idx_init, $self, $opt);
310 # returns an array mapping [ epoch => latest_commit ]
311 # latest_commit may be undef if nothing was done to that epoch
312 # $replace_map = { $object_id => $strref, ... }
313 sub _replace_oids ($$$) {
314 my ($self, $mime, $replace_map) = @_;
316 my $ibx = $self->{ibx};
317 my $pfx = "$ibx->{inboxdir}/git";
318 my $rewrites = []; # epoch => commit
319 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
321 foreach my $i (0..$max) {
322 my $git_dir = "$pfx/$i.git";
324 my $git = PublicInbox::Git->new($git_dir);
325 my $im = $self->import_init($git, 0, 1);
326 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
332 sub content_hashes ($) {
334 my @chashes = ( content_hash($mime) );
336 # We still support Email::MIME, here, and
337 # Email::MIME->as_string doesn't always round-trip, so we may
338 # use a second content_hash
339 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
340 push @chashes, $rt if $chashes[0] ne $rt;
344 sub content_matches ($$) {
345 my ($chashes, $existing) = @_;
346 my $chash = content_hash($existing);
347 foreach (@$chashes) {
348 return 1 if $_ eq $chash
353 # used for removing or replacing (purging)
354 sub rewrite_internal ($$;$$$) {
355 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
357 my ($im, $need_reindex, $replace_map);
359 $replace_map = {}; # oid => sref
360 $need_reindex = [] if $new_eml;
362 $im = $self->importer;
364 my $oidx = $self->{oidx};
365 my $chashes = content_hashes($old_eml);
367 my $mids = mids($old_eml);
369 # We avoid introducing new blobs into git since the raw content
370 # can be slightly different, so we do not need the user-supplied
371 # message now that we have the mids and content_hash
375 foreach my $mid (@$mids) {
376 my %gone; # num => [ smsg, $mime, raw ]
378 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
379 my $msg = get_blob($self, $smsg);
380 if (!defined($msg)) {
381 warn "broken smsg for $mid\n";
385 my $cur = PublicInbox::Eml->new($msg);
386 if (content_matches($chashes, $cur)) {
387 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
390 my $n = scalar keys %gone;
393 warn "BUG: multiple articles linked to <$mid>\n",
394 join(',', sort keys %gone), "\n";
396 foreach my $num (keys %gone) {
397 my ($smsg, $mime, $orig) = @{$gone{$num}};
398 # $removed should only be set once assuming
399 # no bugs in our deduplication code:
400 $removed = [ undef, $mime, $smsg ];
401 my $oid = $smsg->{blob};
403 $replace_map->{$oid} = $sref;
405 ($mark, undef) = $im->remove($orig, $cmt_msg);
406 $removed->[0] = $mark;
409 if ($need_reindex) { # ->replace
410 push @$need_reindex, $smsg;
411 } else { # ->purge or ->remove
412 $self->{mm}->num_delete($num);
414 unindex_oid_aux($self, $oid, $mid);
419 my $cmt = $im->get_mark($mark);
420 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
422 if ($replace_map && scalar keys %$replace_map) {
423 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
424 return { rewrites => $rewrites, need_reindex => $need_reindex };
426 defined($mark) ? $removed : undef;
429 # public (see PublicInbox::Import->remove), but note the 3rd element
430 # (retval[2]) is not part of the stable API shared with Import->remove
432 my ($self, $eml, $cmt_msg) = @_;
433 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
434 $self, $eml, $cmt_msg);
435 defined($r) && defined($r->[0]) ? @$r: undef;
438 sub _replace ($$;$$) {
439 my ($self, $old_eml, $new_eml, $sref) = @_;
440 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
441 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
442 $self, $old_eml, undef, $new_eml, $sref) or return;
444 my $rewrites = $rewritten->{rewrites};
445 # ->done is called if there are rewrites since we gc+prune from git
446 $self->idx_init if @$rewrites;
448 for my $i (0..$#$rewrites) {
449 defined(my $cmt = $rewrites->[$i]) or next;
450 $self->{last_commit}->[$i] = $cmt;
457 my ($self, $mime) = @_;
458 my $rewritten = _replace($self, $mime, undef, \'') or return;
459 $rewritten->{rewrites}
462 # returns the git object_id of $fh, does not write the object to FS
463 sub git_hash_raw ($$) {
464 my ($self, $raw) = @_;
465 # grab the expected OID we have to reindex:
466 pipe(my($in, $w)) or die "pipe: $!";
467 my $git_dir = $self->git->{git_dir};
468 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
469 my $r = popen_rd($cmd, undef, { 0 => $in });
470 print $w $$raw or die "print \$w: $!";
471 close $w or die "close \$w: $!";
473 chomp(my $oid = <$r>);
474 close $r or die "git hash-object failed: $?";
475 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
479 sub _check_mids_match ($$$) {
480 my ($old_list, $new_list, $hdrs) = @_;
481 my %old_mids = map { $_ => 1 } @$old_list;
482 my %new_mids = map { $_ => 1 } @$new_list;
483 my @old = keys %old_mids;
484 my @new = keys %new_mids;
485 my $err = "$hdrs may not be changed when replacing\n";
486 die $err if scalar(@old) != scalar(@new);
487 delete @new_mids{@old};
488 delete @old_mids{@new};
489 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
492 # Changing Message-IDs or References with ->replace isn't supported.
493 # The rules for dealing with messages with multiple or conflicting
494 # Message-IDs are pretty complex and rethreading hasn't been fully
496 sub check_mids_match ($$) {
497 my ($old, $new) = @_;
498 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
499 _check_mids_match(references($old), references($new),
500 'References/In-Reply-To');
505 my ($self, $old_mime, $new_mime) = @_;
507 check_mids_match($old_mime, $new_mime);
509 # mutt will always add Content-Length:, Status:, Lines: when editing
510 PublicInbox::Import::drop_unwanted_headers($new_mime);
512 my $raw = $new_mime->as_string;
513 my $expect_oid = git_hash_raw($self, \$raw);
514 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
515 my $need_reindex = $rewritten->{need_reindex};
517 # just in case we have bugs in deduplication code:
518 my $n = scalar(@$need_reindex);
520 my $list = join(', ', map {
521 "$_->{num}: <$_->{mid}>"
524 W: rewritten $n messages matching content of original message (expected: 1).
525 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
530 # make sure we really got the OID:
531 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
532 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
534 # don't leak FDs to Xapian:
537 # reindex modified messages:
538 for my $smsg (@$need_reindex) {
539 my $new_smsg = bless {
543 }, 'PublicInbox::Smsg';
544 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
545 $new_smsg->populate($new_mime, $sync);
546 $new_smsg->set_bytes($raw, $bytes);
547 do_idx($self, $new_mime, $new_smsg);
549 $rewritten->{rewrites};
552 sub last_epoch_commit ($$;$) {
553 my ($self, $i, $cmt) = @_;
554 my $v = PublicInbox::Search::SCHEMA_VERSION();
555 $self->{mm}->last_commit_xap($v, $i, $cmt);
558 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
560 defined(my $epoch_max = $self->{epoch_max}) or return;
561 my $last_commit = $self->{last_commit};
562 foreach my $i (0..$epoch_max) {
563 defined(my $cmt = $last_commit->[$i]) or next;
564 $last_commit->[$i] = undef;
565 last_epoch_commit($self, $i, $cmt);
570 sub checkpoint ($;$) {
571 my ($self, $wait) = @_;
573 if (my $im = $self->{im}) {
580 my $shards = $self->{idx_shards};
582 my $mm = $self->{mm};
583 my $dbh = $mm->{dbh} if $mm;
585 # SQLite msgmap data is second in importance
586 $dbh->commit if $dbh;
588 # SQLite overview is third
589 $self->{oidx}->commit_lazy;
591 # Now deal with Xapian
593 # start commit_txn_lazy asynchronously on all parallel shards
594 # (non-parallel waits here)
595 $_->ipc_do('commit_txn_lazy') for @$shards;
597 # transactions started on parallel shards,
598 # wait for them by issuing an echo command (echo can only
599 # run after commit_txn_lazy is done)
600 if ($wait && $self->{parallel}) {
602 for my $shard (@$shards) {
603 my $echo = $shard->ipc_do('echo', $i);
604 $echo == $i or die <<"";
605 shard[$i] bad echo:$echo != $i waiting for txn commit
611 my $midx = $self->{midx}; # misc index
614 $PublicInbox::Search::X{CLOEXEC_UNSET} and
618 # last_commit is special, don't commit these until
619 # Xapian shards are done:
620 $dbh->begin_work if $dbh;
621 set_last_commits($self);
627 $self->git->batch_prepare;
631 $self->{total_bytes} += $self->{transact_bytes};
632 $self->{transact_bytes} = 0;
635 # issue a write barrier to ensure all data is visible to other processes
636 # and read-only ops. Order of data importance is: git > SQLite > Xapian
638 sub barrier { checkpoint($_[0], 1) };
640 # true if locked and active
641 sub active { !!$_[0]->{im} }
647 if (my $im = delete $self->{im}) {
648 eval { $im->done }; # PublicInbox::Import::done
649 $err .= "import done: $@\n" if $@;
652 eval { checkpoint($self) };
653 $err .= "checkpoint: $@\n" if $@;
655 if (my $mm = delete $self->{mm}) {
656 my $m = $err ? 'rollback' : 'commit';
657 eval { $mm->{dbh}->$m };
658 $err .= "msgmap $m: $@\n" if $@;
660 my $shards = delete $self->{idx_shards};
663 eval { $_->shard_close };
664 $err .= "shard close: $@\n" if $@;
667 eval { $self->{oidx}->dbh_close };
668 $err .= "over close: $@\n" if $@;
669 delete $self->{midx};
670 my $nbytes = $self->{total_bytes};
671 $self->{total_bytes} = 0;
672 $self->lock_release(!!$nbytes) if $shards;
677 sub write_alternates ($$$) {
678 my ($info_dir, $mode, $out) = @_;
679 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
680 my $tmp = $fh->filename;
681 print $fh @$out or die "print $tmp: $!\n";
682 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
683 close $fh or die "close $tmp $!\n";
684 my $alt = "$info_dir/alternates";
685 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
686 $fh->unlink_on_destroy(0);
689 sub fill_alternates ($$) {
690 my ($self, $epoch) = @_;
692 my $pfx = "$self->{ibx}->{inboxdir}/git";
693 my $all = "$self->{ibx}->{inboxdir}/all.git";
694 PublicInbox::Import::init_bare($all) unless -d $all;
695 my $info_dir = "$all/objects/info";
696 my $alt = "$info_dir/alternates";
700 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
701 $mode = (stat($fh))[2] & 07777;
703 # we assign a sort score to every alternate and favor
704 # the newest (highest numbered) one because loose objects
705 # require scanning epochs and only the latest epoch is
706 # expected to see loose objects
708 my $other = 0; # in case admin adds non-epoch repos
710 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
716 } split(/\n+/, do { local $/; <$fh> });
719 foreach my $i (0..$epoch) {
720 my $dir = "../../git/$i.git/objects";
721 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
727 write_alternates($info_dir, $mode,
728 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
732 my ($self, $epoch) = @_;
733 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
734 PublicInbox::Import::init_bare($git_dir);
735 run_die([qw(git config), "--file=$git_dir/config",
736 qw(include.path ../../all.git/config)]);
737 fill_alternates($self, $epoch);
743 my $im = $self->{im};
745 if ($im->{bytes_added} < $self->{rotate_bytes}) {
752 my $git_dir = $self->git_init(++$self->{epoch_max});
753 my $git = PublicInbox::Git->new($git_dir);
754 return $self->import_init($git, 0);
759 my $latest = $self->{ibx}->git_dir_latest(\$max);
760 if (defined $latest) {
761 my $git = PublicInbox::Git->new($latest);
762 my $packed_bytes = $git->packed_bytes;
763 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
765 if ($unpacked_bytes >= $self->{rotate_bytes}) {
768 $self->{epoch_max} = $max;
769 return $self->import_init($git, $packed_bytes);
772 $self->{epoch_max} = $epoch;
773 $latest = $self->git_init($epoch);
774 $self->import_init(PublicInbox::Git->new($latest), 0);
778 my ($self, $git, $packed_bytes, $tmp) = @_;
779 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
780 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
781 $im->{lock_path} = undef;
782 $im->{path_type} = 'v2';
783 $self->{im} = $im unless $tmp;
789 my ($mid, $cur, $new) = @_;
791 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
792 print $ah $cur->as_string or die "print: $!";
793 $ah->flush or die "flush: $!";
794 PublicInbox::Import::drop_unwanted_headers($new);
795 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
796 print $bh $new->as_string or die "print: $!";
797 $bh->flush or die "flush: $!";
798 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
799 print STDERR "# MID conflict <$mid>\n";
800 my $pid = spawn($cmd, undef, { 1 => 2 });
801 waitpid($pid, 0) == $pid or die "diff did not finish";
805 my ($self, $smsg) = @_;
806 if (my $im = $self->{im}) {
807 my $msg = $im->cat_blob($smsg->{blob});
810 # older message, should be in alternates
811 $self->{ibx}->msg_by_smsg($smsg);
814 sub content_exists ($$$) {
815 my ($self, $mime, $mid) = @_;
816 my $oidx = $self->{oidx};
817 my $chashes = content_hashes($mime);
819 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
820 my $msg = get_blob($self, $smsg);
821 if (!defined($msg)) {
822 warn "broken smsg for $mid\n";
825 my $cur = PublicInbox::Eml->new($msg);
826 return 1 if content_matches($chashes, $cur);
828 # XXX DEBUG_DIFF is experimental and may be removed
829 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
836 if (my $older_siblings = $self->{idx_shards}) {
837 $_->ipc_sibling_atfork_child for @$older_siblings;
839 if (my $im = $self->{im}) {
842 die "BUG: unexpected mm" if $self->{mm};
845 sub reindex_checkpoint ($$) {
846 my ($self, $sync) = @_;
848 $self->git->async_wait_all;
849 $self->update_last_commit($sync);
850 ${$sync->{need_checkpoint}} = 0;
851 my $mm_tmp = $sync->{mm_tmp};
852 $mm_tmp->atfork_prepare if $mm_tmp;
853 die 'BUG: {im} during reindex' if $self->{im};
854 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
855 checkpoint($self, 1); # no need to release lock on pure index
857 $self->done; # release lock
860 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
861 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
864 # allow -watch or -mda to write...
865 $self->idx_init($sync->{-opt}); # reacquire lock
866 if (my $intvl = $sync->{check_intvl}) { # eidx
867 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
869 $mm_tmp->atfork_parent if $mm_tmp;
872 sub index_finalize ($$) {
873 my ($arg, $index) = @_;
874 ++$arg->{self}->{nidx};
875 if (defined(my $cur = $arg->{cur_cmt})) {
876 ${$arg->{latest_cmt}} = $cur;
878 die 'BUG: {cur_cmt} missing';
879 } # else { unindexing @leftovers doesn't set {cur_cmt}
882 sub index_oid { # cat_async callback
883 my ($bref, $oid, $type, $size, $arg) = @_;
884 is_bad_blob($oid, $type, $size, $arg->{oid}) and
885 return index_finalize($arg, 1); # size == 0 purged returns here
886 my $self = $arg->{self};
887 local $self->{current_info} = "$self->{current_info} $oid";
889 my $eml = PublicInbox::Eml->new($$bref);
890 my $mids = mids($eml);
891 my $chash = content_hash($eml);
893 if (scalar(@$mids) == 0) {
894 warn "E: $oid has no Message-ID, skipping\n";
898 # {unindexed} is unlikely
899 if (my $unindexed = $arg->{unindexed}) {
900 my $oidbin = pack('H*', $oid);
901 my $u = $unindexed->{$oidbin};
902 ($num, $mid0) = splice(@$u, 0, 2) if $u;
904 $self->{mm}->mid_set($num, $mid0);
905 if (scalar(@$u) == 0) { # done with current OID
906 delete $unindexed->{$oidbin};
907 delete($arg->{unindexed}) if !keys(%$unindexed);
911 if (!defined($num)) { # reuse if reindexing (or duplicates)
912 my $oidx = $self->{oidx};
913 for my $mid (@$mids) {
914 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
915 last if defined $num;
918 $mid0 //= do { # is this a number we got before?
919 $num = $arg->{mm_tmp}->num_for($mids->[0]);
920 defined($num) ? $mids->[0] : undef;
922 if (!defined($num)) {
923 for (my $i = $#$mids; $i >= 1; $i--) {
924 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
932 $arg->{mm_tmp}->num_delete($num);
933 } else { # never seen
934 $num = $self->{mm}->mid_insert($mids->[0]);
937 } else { # rare, try the rest of them, backwards
938 for (my $i = $#$mids; $i >= 1; $i--) {
939 $num = $self->{mm}->mid_insert($mids->[$i]);
947 if (!defined($num)) {
948 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
956 }, 'PublicInbox::Smsg';
957 $smsg->populate($eml, $arg);
958 $smsg->set_bytes($$bref, $size);
959 if (do_idx($self, $eml, $smsg)) {
960 ${$arg->{need_checkpoint}} = 1;
962 index_finalize($arg, 1);
965 # only update last_commit for $i on reindex iff newer than current
966 sub update_last_commit {
967 my ($self, $sync, $stk) = @_;
968 my $unit = $sync->{unit} // return;
969 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
970 defined($latest_cmt) or return;
971 my $last = last_epoch_commit($self, $unit->{epoch});
972 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
973 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
974 chomp(my $n = $unit->{git}->qx(@cmd));
975 return if $n ne '' && $n == 0;
977 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
981 my ($self, $sync) = @_;
983 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
984 $heads->[$i] = last_epoch_commit($self, $i);
989 # returns a revision range for git-log(1)
990 sub log_range ($$$) {
991 my ($sync, $unit, $tip) = @_;
992 my $opt = $sync->{-opt};
993 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
994 my $i = $unit->{epoch};
995 my $cur = $sync->{ranges}->[$i] or do {
996 $pr->("$i.git indexing all of $tip\n") if $pr;
997 return $tip; # all of it
1000 # fast equality check to avoid (v)fork+execve overhead
1002 $sync->{ranges}->[$i] = undef;
1006 my $range = "$cur..$tip";
1007 $pr->("$i.git checking contiguity... ") if $pr;
1008 my $git = $unit->{git};
1009 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1010 $pr->("OK\n") if $pr;
1011 my $n = $git->qx(qw(rev-list --count), $range);
1014 $sync->{ranges}->[$i] = undef;
1015 $pr->("$i.git has nothing new\n") if $pr;
1016 return; # nothing to do
1018 $pr->("$i.git has $n changes since $cur\n") if $pr;
1020 $pr->("FAIL\n") if $pr;
1022 discontiguous range: $range
1023 Rewritten history? (in $git->{git_dir})
1025 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1027 $range = "$base..$tip";
1028 warn "found merge-base: $base\n"
1031 warn "discarding history at $cur\n";
1034 reindexing $git->{git_dir}
1037 # $cur^0 may no longer exist if pruned by git
1038 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1039 $unit->{unindex_range} = "$base..$cur";
1040 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1041 $unit->{unindex_range} = "$base..";
1043 warn "W: unable to unindex before $range\n";
1049 # overridden by ExtSearchIdx
1050 sub artnum_max { $_[0]->{mm}->num_highwater }
1052 sub sync_prepare ($$) {
1053 my ($self, $sync) = @_;
1054 $sync->{ranges} = sync_ranges($self, $sync);
1055 my $pr = $sync->{-opt}->{-progress};
1057 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1060 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1061 $pfx //= $sync->{ibx}->{inboxdir};
1065 if ($self->{ibx_map}) {
1066 # ExtSearchIdx won't index messages unless they're in
1067 # over.sqlite3 for a given inbox, so don't read beyond
1068 # what's in the per-inbox index.
1069 $reindex_heads = [];
1070 my $v = PublicInbox::Search::SCHEMA_VERSION;
1071 my $mm = $sync->{ibx}->mm;
1072 for my $i (0..$sync->{epoch_max}) {
1073 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1075 } elsif ($sync->{reindex}) { # V2 inbox
1076 # reindex stops at the current heads and we later
1077 # rerun index_sync without {reindex}
1078 $reindex_heads = $self->last_commits($sync);
1080 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1081 $sync->{index_oid} = $self->can('index_oid');
1083 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1084 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1085 my $git_dir = "$git_pfx/$i.git";
1086 -d $git_dir or next; # missing epochs are fine
1087 my $git = PublicInbox::Git->new($git_dir);
1088 my $unit = { git => $git, epoch => $i };
1090 if ($reindex_heads) {
1091 $tip = $head = $reindex_heads->[$i] or next;
1093 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1094 next if $?; # new repo
1097 my $range = log_range($sync, $unit, $tip) or next;
1098 # can't use 'rev-list --count' if we use --diff-filter
1099 $pr->("$pfx $i.git counting $range ... ") if $pr;
1100 # Don't bump num_highwater on --reindex by using {D}.
1101 # We intentionally do NOT use {D} in the non-reindex case
1102 # because we want NNTP article number gaps from unindexed
1103 # messages to show up in mirrors, too.
1104 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1105 my $stk = log2stack($sync, $git, $range);
1106 return 0 if $sync->{quit};
1107 my $nr = $stk ? $stk->num_records : 0;
1108 $pr->("$nr\n") if $pr;
1109 $unit->{stack} = $stk; # may be undef
1110 unshift @{$sync->{todo}}, $unit;
1113 return 0 if $sync->{quit};
1115 # XXX this should not happen unless somebody bypasses checks in
1116 # our code and blindly injects "d" file history into git repos
1117 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1118 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1119 local $self->{current_info} = 'leftover ';
1120 my $unindex_oid = $self->can('unindex_oid');
1121 for my $oid (@leftovers) {
1122 last if $sync->{quit};
1123 $oid = unpack('H*', $oid);
1124 my $req = { %$sync, oid => $oid };
1125 $self->git->cat_async($oid, $unindex_oid, $req);
1127 $self->git->cat_async_wait;
1129 return 0 if $sync->{quit};
1131 $sync->{-regen_fmt} = "%u/?\n";
1135 # reindex should NOT see new commits anymore, if we do,
1136 # it's a problem and we need to notice it via die()
1137 my $pad = length($regen_max) + 1;
1138 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1139 $sync->{nr} = \(my $nr = 0);
1140 return -1 if $sync->{reindex};
1141 $regen_max + $self->artnum_max || 0;
1144 sub unindex_oid_aux ($$$) {
1145 my ($self, $oid, $mid) = @_;
1146 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1147 return unless $self->{-need_xapian};
1148 for my $num (@removed) {
1149 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1153 sub unindex_oid ($$;$) { # git->cat_async callback
1154 my ($bref, $oid, $type, $size, $arg) = @_;
1155 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1156 return index_finalize($arg, 0);
1157 my $self = $arg->{self};
1158 local $self->{current_info} = "$self->{current_info} $oid";
1159 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1160 my $mm = $self->{mm};
1161 my $mids = mids(PublicInbox::Eml->new($bref));
1163 my $oidx = $self->{oidx};
1164 foreach my $mid (@$mids) {
1167 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1168 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1170 my $n = scalar(keys(%gone)) or next;
1172 warn "BUG: multiple articles linked to $oid\n",
1173 join(',',sort keys %gone), "\n";
1175 # reuse (num => mid) mapping in ascending numeric order
1176 for my $num (sort { $a <=> $b } keys %gone) {
1179 my $mid0 = $mm->mid_for($num);
1180 my $oidbin = pack('H*', $oid);
1181 push @{$unindexed->{$oidbin}}, $num, $mid0;
1183 $mm->num_delete($num);
1185 unindex_oid_aux($self, $oid, $mid);
1187 index_finalize($arg, 0);
1190 sub git { $_[0]->{ibx}->git }
1192 # this is rare, it only happens when we get discontiguous history in
1193 # a mirror because the source used -purge or -edit
1194 sub unindex_todo ($$$) {
1195 my ($self, $sync, $unit) = @_;
1196 my $unindex_range = delete($unit->{unindex_range}) // return;
1197 my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1198 my $before = scalar keys %$unindexed;
1199 # order does not matter, here:
1200 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1201 --no-abbrev --no-renames), $unindex_range);
1202 local $sync->{in_unindex} = 1;
1203 my $unindex_oid = $self->can('unindex_oid');
1205 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1206 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1208 close $fh or die "git log failed: \$?=$?";
1209 $self->git->cat_async_wait;
1211 return unless $sync->{-opt}->{prune};
1212 my $after = scalar keys %$unindexed;
1213 return if $before == $after;
1215 # ensure any blob can not longer be accessed via dumb HTTP
1216 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1217 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1220 sub sync_ranges ($$) {
1221 my ($self, $sync) = @_;
1222 my $reindex = $sync->{reindex};
1223 return $self->last_commits($sync) unless $reindex;
1224 return [] if ref($reindex) ne 'HASH';
1226 my $ranges = $reindex->{from}; # arrayref;
1227 if (ref($ranges) ne 'ARRAY') {
1228 die 'BUG: $reindex->{from} not an ARRAY';
1233 sub index_xap_only { # git->cat_async callback
1234 my ($bref, $oid, $type, $size, $smsg) = @_;
1235 my $self = $smsg->{self};
1236 my $idx = idx_shard($self, $smsg->{num});
1237 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1238 $self->{transact_bytes} += $smsg->{bytes};
1241 sub index_xap_step ($$$;$) {
1242 my ($self, $sync, $beg, $step) = @_;
1243 my $end = $sync->{art_end};
1244 return if $beg > $end; # nothing to do
1246 $step //= $self->{shards};
1247 my $ibx = $self->{ibx};
1248 if (my $pr = $sync->{-opt}->{-progress}) {
1249 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1250 "$beg..$end (% $step)\n");
1252 for (my $num = $beg; $num <= $end; $num += $step) {
1253 last if $sync->{quit};
1254 my $smsg = $ibx->over->get_art($num) or next;
1255 $smsg->{self} = $self;
1256 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1257 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1258 ${$sync->{nr}} = $num;
1259 reindex_checkpoint($self, $sync);
1264 sub index_todo ($$$) {
1265 my ($self, $sync, $unit) = @_;
1266 return if $sync->{quit};
1267 unindex_todo($self, $sync, $unit);
1268 my $stk = delete($unit->{stack}) or return;
1269 my $all = $self->git;
1270 my $index_oid = $self->can('index_oid');
1271 my $unindex_oid = $self->can('unindex_oid');
1273 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1274 $pfx = "$1 $2"; # v2
1276 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1277 $pfx //= $unit->{git}->{git_dir};
1279 local $self->{current_info} = "$pfx ";
1280 local $sync->{latest_cmt} = \(my $latest_cmt);
1281 local $sync->{unit} = $unit;
1282 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1283 if ($sync->{quit}) {
1284 warn "waiting to quit...\n";
1285 $all->async_wait_all;
1286 $self->update_last_commit($sync);
1297 if ($sync->{max_size}) {
1298 $all->check_async($oid, \&check_size, $req);
1300 $all->cat_async($oid, $index_oid, $req);
1302 } elsif ($f eq 'd') {
1303 $all->cat_async($oid, $unindex_oid, $req);
1305 if (${$sync->{need_checkpoint}}) {
1306 reindex_checkpoint($self, $sync);
1309 $all->async_wait_all;
1310 $self->update_last_commit($sync, $stk);
1314 my ($self, $opt, $sync, $art_beg) = @_;
1315 my $seq = $opt->{sequential_shard};
1317 local $self->{parallel} = 0 if $seq;
1318 $self->idx_init($opt); # acquire lock
1319 if (my $art_end = $self->{ibx}->mm->max) {
1321 need_checkpoint => \(my $bool = 0),
1324 nr => \(my $nr = 0),
1325 -regen_fmt => "%u/?\n",
1327 $sync->{art_end} = $art_end;
1328 if ($seq || !$self->{parallel}) {
1329 my $shard_end = $self->{shards} - 1;
1330 for my $i (0..$shard_end) {
1331 last if $sync->{quit};
1332 index_xap_step($self, $sync, $art_beg + $i);
1333 if ($i != $shard_end) {
1334 reindex_checkpoint($self, $sync);
1337 } else { # parallel (maybe)
1338 index_xap_step($self, $sync, $art_beg, 1);
1341 $self->git->cat_async_wait;
1345 # public, called by public-inbox-index
1347 my ($self, $opt) = @_;
1349 return xapian_only($self, $opt) if $opt->{xapian_only};
1352 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1353 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1354 use Time::HiRes qw(stat);
1355 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1356 my $c = $mm[10]; # 10 = ctime (nsec NV)
1357 my @hd = stat("$latest/refs/heads");
1358 my @pr = stat("$latest/packed-refs");
1359 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1363 my $pr = $opt->{-progress};
1364 my $seq = $opt->{sequential_shard};
1365 my $art_beg; # the NNTP article number we start xapian_only at
1366 my $idxlevel = $self->{ibx}->{indexlevel};
1367 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1369 $self->idx_init($opt); # acquire lock
1370 fill_alternates($self, $epoch_max);
1371 $self->{oidx}->rethread_prepare($opt);
1373 need_checkpoint => \(my $bool = 0),
1374 reindex => $opt->{reindex},
1377 ibx => $self->{ibx},
1378 epoch_max => $epoch_max,
1380 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1381 local $SIG{QUIT} = $quit;
1382 local $SIG{INT} = $quit;
1383 local $SIG{TERM} = $quit;
1385 if (sync_prepare($self, $sync)) {
1386 # tmp_clone seems to fail if inside a transaction, so
1387 # we rollback here (because we opened {mm} for reading)
1388 # Note: we do NOT rely on DBI transactions for atomicity;
1389 # only for batch performance.
1390 $self->{mm}->{dbh}->rollback;
1391 $self->{mm}->{dbh}->begin_work;
1393 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1395 # xapian_only works incrementally w/o --reindex
1396 if ($seq && !$opt->{reindex}) {
1397 $art_beg = $sync->{mm_tmp}->max || -1;
1401 # work forwards through history
1402 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1403 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1406 if (my $nr = $sync->{nr}) {
1407 my $pr = $sync->{-opt}->{-progress};
1408 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1412 # deal with Xapian shards sequentially
1413 if ($seq && delete($sync->{mm_tmp})) {
1414 if ($sync->{quit}) {
1417 $self->{ibx}->{indexlevel} = $idxlevel;
1418 xapian_only($self, $opt, $sync, $art_beg);
1419 $quit_warn = 1 if $sync->{quit};
1423 # --reindex on the command-line
1424 if (!$sync->{quit} && $opt->{reindex} &&
1425 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1426 $self->lock_acquire;
1427 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1428 if (my $xdb = $s0->idx_acquire) {
1429 my $n = $xdb->get_metadata('has_threadid');
1430 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1433 $self->lock_release;
1436 # reindex does not pick up new changes, so we rerun w/o it:
1437 if ($opt->{reindex} && !$sync->{quit}) {
1440 delete @again{qw(rethread reindex -skip_lock)};
1441 index_sync($self, \%again);
1442 $opt->{quit} = $again{quit}; # propagate to caller
1444 warn <<EOF if $quit_warn;
1445 W: interrupted, --xapian-only --reindex required upon restart