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->{total_bytes} += $self->{transact_bytes};
628 $self->{transact_bytes} = 0;
631 # issue a write barrier to ensure all data is visible to other processes
632 # and read-only ops. Order of data importance is: git > SQLite > Xapian
634 sub barrier { checkpoint($_[0], 1) };
636 # true if locked and active
637 sub active { !!$_[0]->{im} }
643 if (my $im = delete $self->{im}) {
644 eval { $im->done }; # PublicInbox::Import::done
645 $err .= "import done: $@\n" if $@;
648 eval { checkpoint($self) };
649 $err .= "checkpoint: $@\n" if $@;
651 if (my $mm = delete $self->{mm}) {
652 my $m = $err ? 'rollback' : 'commit';
653 eval { $mm->{dbh}->$m };
654 $err .= "msgmap $m: $@\n" if $@;
656 my $shards = delete $self->{idx_shards};
659 eval { $_->shard_close };
660 $err .= "shard close: $@\n" if $@;
663 eval { $self->{oidx}->dbh_close };
664 $err .= "over close: $@\n" if $@;
665 delete $self->{midx};
666 my $nbytes = $self->{total_bytes};
667 $self->{total_bytes} = 0;
668 $self->lock_release(!!$nbytes) if $shards;
673 sub write_alternates ($$$) {
674 my ($info_dir, $mode, $out) = @_;
675 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
676 my $tmp = $fh->filename;
677 print $fh @$out or die "print $tmp: $!\n";
678 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
679 close $fh or die "close $tmp $!\n";
680 my $alt = "$info_dir/alternates";
681 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
682 $fh->unlink_on_destroy(0);
685 sub fill_alternates ($$) {
686 my ($self, $epoch) = @_;
688 my $pfx = "$self->{ibx}->{inboxdir}/git";
689 my $all = "$self->{ibx}->{inboxdir}/all.git";
690 PublicInbox::Import::init_bare($all) unless -d $all;
691 my $info_dir = "$all/objects/info";
692 my $alt = "$info_dir/alternates";
696 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
697 $mode = (stat($fh))[2] & 07777;
699 # we assign a sort score to every alternate and favor
700 # the newest (highest numbered) one because loose objects
701 # require scanning epochs and only the latest epoch is
702 # expected to see loose objects
704 my $other = 0; # in case admin adds non-epoch repos
706 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
712 } split(/\n+/, do { local $/; <$fh> });
715 foreach my $i (0..$epoch) {
716 my $dir = "../../git/$i.git/objects";
717 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
723 write_alternates($info_dir, $mode,
724 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
728 my ($self, $epoch) = @_;
729 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
730 PublicInbox::Import::init_bare($git_dir);
731 run_die([qw(git config), "--file=$git_dir/config",
732 qw(include.path ../../all.git/config)]);
733 fill_alternates($self, $epoch);
739 my $im = $self->{im};
741 if ($im->{bytes_added} < $self->{rotate_bytes}) {
748 my $git_dir = $self->git_init(++$self->{epoch_max});
749 my $git = PublicInbox::Git->new($git_dir);
750 return $self->import_init($git, 0);
755 my $latest = $self->{ibx}->git_dir_latest(\$max);
756 if (defined $latest) {
757 my $git = PublicInbox::Git->new($latest);
758 my $packed_bytes = $git->packed_bytes;
759 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
761 if ($unpacked_bytes >= $self->{rotate_bytes}) {
764 $self->{epoch_max} = $max;
765 return $self->import_init($git, $packed_bytes);
768 $self->{epoch_max} = $epoch;
769 $latest = $self->git_init($epoch);
770 $self->import_init(PublicInbox::Git->new($latest), 0);
774 my ($self, $git, $packed_bytes, $tmp) = @_;
775 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
776 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
777 $im->{lock_path} = undef;
778 $im->{path_type} = 'v2';
779 $self->{im} = $im unless $tmp;
785 my ($mid, $cur, $new) = @_;
787 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
788 print $ah $cur->as_string or die "print: $!";
789 $ah->flush or die "flush: $!";
790 PublicInbox::Import::drop_unwanted_headers($new);
791 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
792 print $bh $new->as_string or die "print: $!";
793 $bh->flush or die "flush: $!";
794 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
795 print STDERR "# MID conflict <$mid>\n";
796 my $pid = spawn($cmd, undef, { 1 => 2 });
797 waitpid($pid, 0) == $pid or die "diff did not finish";
801 my ($self, $smsg) = @_;
802 if (my $im = $self->{im}) {
803 my $msg = $im->cat_blob($smsg->{blob});
806 # older message, should be in alternates
807 $self->{ibx}->msg_by_smsg($smsg);
810 sub content_exists ($$$) {
811 my ($self, $mime, $mid) = @_;
812 my $oidx = $self->{oidx};
813 my $chashes = content_hashes($mime);
815 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
816 my $msg = get_blob($self, $smsg);
817 if (!defined($msg)) {
818 warn "broken smsg for $mid\n";
821 my $cur = PublicInbox::Eml->new($msg);
822 return 1 if content_matches($chashes, $cur);
824 # XXX DEBUG_DIFF is experimental and may be removed
825 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
832 if (my $older_siblings = $self->{idx_shards}) {
833 $_->ipc_sibling_atfork_child for @$older_siblings;
835 if (my $im = $self->{im}) {
838 die "BUG: unexpected mm" if $self->{mm};
841 sub reindex_checkpoint ($$) {
842 my ($self, $sync) = @_;
844 $self->git->async_wait_all;
845 $self->update_last_commit($sync);
846 ${$sync->{need_checkpoint}} = 0;
847 my $mm_tmp = $sync->{mm_tmp};
848 $mm_tmp->atfork_prepare if $mm_tmp;
849 die 'BUG: {im} during reindex' if $self->{im};
850 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
851 checkpoint($self, 1); # no need to release lock on pure index
853 $self->done; # release lock
856 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
857 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
860 # allow -watch or -mda to write...
861 $self->idx_init($sync->{-opt}); # reacquire lock
862 if (my $intvl = $sync->{check_intvl}) { # eidx
863 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
865 $mm_tmp->atfork_parent if $mm_tmp;
868 sub index_finalize ($$) {
869 my ($arg, $index) = @_;
870 ++$arg->{self}->{nidx};
871 if (defined(my $cur = $arg->{cur_cmt})) {
872 ${$arg->{latest_cmt}} = $cur;
874 die 'BUG: {cur_cmt} missing';
875 } # else { unindexing @leftovers doesn't set {cur_cmt}
878 sub index_oid { # cat_async callback
879 my ($bref, $oid, $type, $size, $arg) = @_;
880 is_bad_blob($oid, $type, $size, $arg->{oid}) and
881 return index_finalize($arg, 1); # size == 0 purged returns here
882 my $self = $arg->{self};
883 local $self->{current_info} = "$self->{current_info} $oid";
885 my $eml = PublicInbox::Eml->new($$bref);
886 my $mids = mids($eml);
887 my $chash = content_hash($eml);
889 if (scalar(@$mids) == 0) {
890 warn "E: $oid has no Message-ID, skipping\n";
894 # {unindexed} is unlikely
895 if (my $unindexed = $arg->{unindexed}) {
896 my $oidbin = pack('H*', $oid);
897 my $u = $unindexed->{$oidbin};
898 ($num, $mid0) = splice(@$u, 0, 2) if $u;
900 $self->{mm}->mid_set($num, $mid0);
901 if (scalar(@$u) == 0) { # done with current OID
902 delete $unindexed->{$oidbin};
903 delete($arg->{unindexed}) if !keys(%$unindexed);
907 if (!defined($num)) { # reuse if reindexing (or duplicates)
908 my $oidx = $self->{oidx};
909 for my $mid (@$mids) {
910 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
911 last if defined $num;
914 $mid0 //= do { # is this a number we got before?
915 $num = $arg->{mm_tmp}->num_for($mids->[0]);
916 defined($num) ? $mids->[0] : undef;
918 if (!defined($num)) {
919 for (my $i = $#$mids; $i >= 1; $i--) {
920 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
928 $arg->{mm_tmp}->num_delete($num);
929 } else { # never seen
930 $num = $self->{mm}->mid_insert($mids->[0]);
933 } else { # rare, try the rest of them, backwards
934 for (my $i = $#$mids; $i >= 1; $i--) {
935 $num = $self->{mm}->mid_insert($mids->[$i]);
943 if (!defined($num)) {
944 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
952 }, 'PublicInbox::Smsg';
953 $smsg->populate($eml, $arg);
954 $smsg->set_bytes($$bref, $size);
955 if (do_idx($self, $eml, $smsg)) {
956 ${$arg->{need_checkpoint}} = 1;
958 index_finalize($arg, 1);
961 # only update last_commit for $i on reindex iff newer than current
962 sub update_last_commit {
963 my ($self, $sync, $stk) = @_;
964 my $unit = $sync->{unit} // return;
965 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
966 defined($latest_cmt) or return;
967 my $last = last_epoch_commit($self, $unit->{epoch});
968 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
969 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
970 chomp(my $n = $unit->{git}->qx(@cmd));
971 return if $n ne '' && $n == 0;
973 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
977 my ($self, $sync) = @_;
979 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
980 $heads->[$i] = last_epoch_commit($self, $i);
985 # returns a revision range for git-log(1)
986 sub log_range ($$$) {
987 my ($sync, $unit, $tip) = @_;
988 my $opt = $sync->{-opt};
989 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
990 my $i = $unit->{epoch};
991 my $cur = $sync->{ranges}->[$i] or do {
992 $pr->("$i.git indexing all of $tip\n") if $pr;
993 return $tip; # all of it
996 # fast equality check to avoid (v)fork+execve overhead
998 $sync->{ranges}->[$i] = undef;
1002 my $range = "$cur..$tip";
1003 $pr->("$i.git checking contiguity... ") if $pr;
1004 my $git = $unit->{git};
1005 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1006 $pr->("OK\n") if $pr;
1007 my $n = $git->qx(qw(rev-list --count), $range);
1010 $sync->{ranges}->[$i] = undef;
1011 $pr->("$i.git has nothing new\n") if $pr;
1012 return; # nothing to do
1014 $pr->("$i.git has $n changes since $cur\n") if $pr;
1016 $pr->("FAIL\n") if $pr;
1018 discontiguous range: $range
1019 Rewritten history? (in $git->{git_dir})
1021 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1023 $range = "$base..$tip";
1024 warn "found merge-base: $base\n"
1027 warn "discarding history at $cur\n";
1030 reindexing $git->{git_dir}
1033 # $cur^0 may no longer exist if pruned by git
1034 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1035 $unit->{unindex_range} = "$base..$cur";
1036 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1037 $unit->{unindex_range} = "$base..";
1039 warn "W: unable to unindex before $range\n";
1045 # overridden by ExtSearchIdx
1046 sub artnum_max { $_[0]->{mm}->num_highwater }
1048 sub sync_prepare ($$) {
1049 my ($self, $sync) = @_;
1050 $sync->{ranges} = sync_ranges($self, $sync);
1051 my $pr = $sync->{-opt}->{-progress};
1053 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1056 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1057 $pfx //= $sync->{ibx}->{inboxdir};
1061 if ($self->{ibx_map}) {
1062 # ExtSearchIdx won't index messages unless they're in
1063 # over.sqlite3 for a given inbox, so don't read beyond
1064 # what's in the per-inbox index.
1065 $reindex_heads = [];
1066 my $v = PublicInbox::Search::SCHEMA_VERSION;
1067 my $mm = $sync->{ibx}->mm;
1068 for my $i (0..$sync->{epoch_max}) {
1069 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1071 } elsif ($sync->{reindex}) { # V2 inbox
1072 # reindex stops at the current heads and we later
1073 # rerun index_sync without {reindex}
1074 $reindex_heads = $self->last_commits($sync);
1076 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1077 $sync->{index_oid} = $self->can('index_oid');
1079 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1080 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1081 my $git_dir = "$git_pfx/$i.git";
1082 -d $git_dir or next; # missing epochs are fine
1083 my $git = PublicInbox::Git->new($git_dir);
1084 my $unit = { git => $git, epoch => $i };
1086 if ($reindex_heads) {
1087 $tip = $head = $reindex_heads->[$i] or next;
1089 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1090 next if $?; # new repo
1093 my $range = log_range($sync, $unit, $tip) or next;
1094 # can't use 'rev-list --count' if we use --diff-filter
1095 $pr->("$pfx $i.git counting $range ... ") if $pr;
1096 # Don't bump num_highwater on --reindex by using {D}.
1097 # We intentionally do NOT use {D} in the non-reindex case
1098 # because we want NNTP article number gaps from unindexed
1099 # messages to show up in mirrors, too.
1100 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1101 my $stk = log2stack($sync, $git, $range);
1102 return 0 if $sync->{quit};
1103 my $nr = $stk ? $stk->num_records : 0;
1104 $pr->("$nr\n") if $pr;
1105 $unit->{stack} = $stk; # may be undef
1106 unshift @{$sync->{todo}}, $unit;
1109 return 0 if $sync->{quit};
1111 # XXX this should not happen unless somebody bypasses checks in
1112 # our code and blindly injects "d" file history into git repos
1113 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1114 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1115 local $self->{current_info} = 'leftover ';
1116 my $unindex_oid = $self->can('unindex_oid');
1117 for my $oid (@leftovers) {
1118 last if $sync->{quit};
1119 $oid = unpack('H*', $oid);
1120 my $req = { %$sync, oid => $oid };
1121 $self->git->cat_async($oid, $unindex_oid, $req);
1123 $self->git->cat_async_wait;
1125 return 0 if $sync->{quit};
1127 $sync->{-regen_fmt} = "%u/?\n";
1131 # reindex should NOT see new commits anymore, if we do,
1132 # it's a problem and we need to notice it via die()
1133 my $pad = length($regen_max) + 1;
1134 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1135 $sync->{nr} = \(my $nr = 0);
1136 return -1 if $sync->{reindex};
1137 $regen_max + $self->artnum_max || 0;
1140 sub unindex_oid_aux ($$$) {
1141 my ($self, $oid, $mid) = @_;
1142 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1143 return unless $self->{-need_xapian};
1144 for my $num (@removed) {
1145 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1149 sub unindex_oid ($$;$) { # git->cat_async callback
1150 my ($bref, $oid, $type, $size, $arg) = @_;
1151 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1152 return index_finalize($arg, 0);
1153 my $self = $arg->{self};
1154 local $self->{current_info} = "$self->{current_info} $oid";
1155 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1156 my $mm = $self->{mm};
1157 my $mids = mids(PublicInbox::Eml->new($bref));
1159 my $oidx = $self->{oidx};
1160 foreach my $mid (@$mids) {
1163 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1164 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1166 my $n = scalar(keys(%gone)) or next;
1168 warn "BUG: multiple articles linked to $oid\n",
1169 join(',',sort keys %gone), "\n";
1171 # reuse (num => mid) mapping in ascending numeric order
1172 for my $num (sort { $a <=> $b } keys %gone) {
1175 my $mid0 = $mm->mid_for($num);
1176 my $oidbin = pack('H*', $oid);
1177 push @{$unindexed->{$oidbin}}, $num, $mid0;
1179 $mm->num_delete($num);
1181 unindex_oid_aux($self, $oid, $mid);
1183 index_finalize($arg, 0);
1186 sub git { $_[0]->{ibx}->git }
1188 # this is rare, it only happens when we get discontiguous history in
1189 # a mirror because the source used -purge or -edit
1190 sub unindex_todo ($$$) {
1191 my ($self, $sync, $unit) = @_;
1192 my $unindex_range = delete($unit->{unindex_range}) // return;
1193 my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1194 my $before = scalar keys %$unindexed;
1195 # order does not matter, here:
1196 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1197 --no-abbrev --no-renames), $unindex_range);
1198 local $sync->{in_unindex} = 1;
1199 my $unindex_oid = $self->can('unindex_oid');
1201 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1202 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1204 close $fh or die "git log failed: \$?=$?";
1205 $self->git->cat_async_wait;
1207 return unless $sync->{-opt}->{prune};
1208 my $after = scalar keys %$unindexed;
1209 return if $before == $after;
1211 # ensure any blob can not longer be accessed via dumb HTTP
1212 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1213 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1216 sub sync_ranges ($$) {
1217 my ($self, $sync) = @_;
1218 my $reindex = $sync->{reindex};
1219 return $self->last_commits($sync) unless $reindex;
1220 return [] if ref($reindex) ne 'HASH';
1222 my $ranges = $reindex->{from}; # arrayref;
1223 if (ref($ranges) ne 'ARRAY') {
1224 die 'BUG: $reindex->{from} not an ARRAY';
1229 sub index_xap_only { # git->cat_async callback
1230 my ($bref, $oid, $type, $size, $smsg) = @_;
1231 my $self = $smsg->{self};
1232 my $idx = idx_shard($self, $smsg->{num});
1233 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1234 $self->{transact_bytes} += $smsg->{bytes};
1237 sub index_xap_step ($$$;$) {
1238 my ($self, $sync, $beg, $step) = @_;
1239 my $end = $sync->{art_end};
1240 return if $beg > $end; # nothing to do
1242 $step //= $self->{shards};
1243 my $ibx = $self->{ibx};
1244 if (my $pr = $sync->{-opt}->{-progress}) {
1245 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1246 "$beg..$end (% $step)\n");
1248 for (my $num = $beg; $num <= $end; $num += $step) {
1249 last if $sync->{quit};
1250 my $smsg = $ibx->over->get_art($num) or next;
1251 $smsg->{self} = $self;
1252 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1253 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1254 ${$sync->{nr}} = $num;
1255 reindex_checkpoint($self, $sync);
1260 sub index_todo ($$$) {
1261 my ($self, $sync, $unit) = @_;
1262 return if $sync->{quit};
1263 unindex_todo($self, $sync, $unit);
1264 my $stk = delete($unit->{stack}) or return;
1265 my $all = $self->git;
1266 my $index_oid = $self->can('index_oid');
1267 my $unindex_oid = $self->can('unindex_oid');
1269 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1270 $pfx = "$1 $2"; # v2
1272 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1273 $pfx //= $unit->{git}->{git_dir};
1275 local $self->{current_info} = "$pfx ";
1276 local $sync->{latest_cmt} = \(my $latest_cmt);
1277 local $sync->{unit} = $unit;
1278 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1279 if ($sync->{quit}) {
1280 warn "waiting to quit...\n";
1281 $all->async_wait_all;
1282 $self->update_last_commit($sync);
1293 if ($sync->{max_size}) {
1294 $all->check_async($oid, \&check_size, $req);
1296 $all->cat_async($oid, $index_oid, $req);
1298 } elsif ($f eq 'd') {
1299 $all->cat_async($oid, $unindex_oid, $req);
1301 if (${$sync->{need_checkpoint}}) {
1302 reindex_checkpoint($self, $sync);
1305 $all->async_wait_all;
1306 $self->update_last_commit($sync, $stk);
1310 my ($self, $opt, $sync, $art_beg) = @_;
1311 my $seq = $opt->{sequential_shard};
1313 local $self->{parallel} = 0 if $seq;
1314 $self->idx_init($opt); # acquire lock
1315 if (my $art_end = $self->{ibx}->mm->max) {
1317 need_checkpoint => \(my $bool = 0),
1320 nr => \(my $nr = 0),
1321 -regen_fmt => "%u/?\n",
1323 $sync->{art_end} = $art_end;
1324 if ($seq || !$self->{parallel}) {
1325 my $shard_end = $self->{shards} - 1;
1326 for my $i (0..$shard_end) {
1327 last if $sync->{quit};
1328 index_xap_step($self, $sync, $art_beg + $i);
1329 if ($i != $shard_end) {
1330 reindex_checkpoint($self, $sync);
1333 } else { # parallel (maybe)
1334 index_xap_step($self, $sync, $art_beg, 1);
1337 $self->git->cat_async_wait;
1341 # public, called by public-inbox-index
1343 my ($self, $opt) = @_;
1345 return xapian_only($self, $opt) if $opt->{xapian_only};
1348 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1349 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1350 use Time::HiRes qw(stat);
1351 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1352 my $c = $mm[10]; # 10 = ctime (nsec NV)
1353 my @hd = stat("$latest/refs/heads");
1354 my @pr = stat("$latest/packed-refs");
1355 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1359 my $pr = $opt->{-progress};
1360 my $seq = $opt->{sequential_shard};
1361 my $art_beg; # the NNTP article number we start xapian_only at
1362 my $idxlevel = $self->{ibx}->{indexlevel};
1363 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1365 $self->idx_init($opt); # acquire lock
1366 fill_alternates($self, $epoch_max);
1367 $self->{oidx}->rethread_prepare($opt);
1369 need_checkpoint => \(my $bool = 0),
1370 reindex => $opt->{reindex},
1373 ibx => $self->{ibx},
1374 epoch_max => $epoch_max,
1376 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1377 local $SIG{QUIT} = $quit;
1378 local $SIG{INT} = $quit;
1379 local $SIG{TERM} = $quit;
1381 if (sync_prepare($self, $sync)) {
1382 # tmp_clone seems to fail if inside a transaction, so
1383 # we rollback here (because we opened {mm} for reading)
1384 # Note: we do NOT rely on DBI transactions for atomicity;
1385 # only for batch performance.
1386 $self->{mm}->{dbh}->rollback;
1387 $self->{mm}->{dbh}->begin_work;
1389 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1391 # xapian_only works incrementally w/o --reindex
1392 if ($seq && !$opt->{reindex}) {
1393 $art_beg = $sync->{mm_tmp}->max || -1;
1397 # work forwards through history
1398 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1399 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1402 if (my $nr = $sync->{nr}) {
1403 my $pr = $sync->{-opt}->{-progress};
1404 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1408 # deal with Xapian shards sequentially
1409 if ($seq && delete($sync->{mm_tmp})) {
1410 if ($sync->{quit}) {
1413 $self->{ibx}->{indexlevel} = $idxlevel;
1414 xapian_only($self, $opt, $sync, $art_beg);
1415 $quit_warn = 1 if $sync->{quit};
1419 # --reindex on the command-line
1420 if (!$sync->{quit} && $opt->{reindex} &&
1421 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1422 $self->lock_acquire;
1423 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1424 if (my $xdb = $s0->idx_acquire) {
1425 my $n = $xdb->get_metadata('has_threadid');
1426 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1429 $self->lock_release;
1432 # reindex does not pick up new changes, so we rerun w/o it:
1433 if ($opt->{reindex} && !$sync->{quit}) {
1436 delete @again{qw(rethread reindex -skip_lock)};
1437 index_sync($self, \%again);
1438 $opt->{quit} = $again{quit}; # propagate to caller
1440 warn <<EOF if $quit_warn;
1441 W: interrupted, --xapian-only --reindex required upon restart