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
26 my $OID = qr/[a-f0-9]{40,}/;
27 # an estimate of the post-packed size to the raw uncompressed size
28 our $PACKING_FACTOR = 0.4;
30 # SATA storage lags behind what CPUs are capable of, so relying on
31 # nproc(1) can be misleading and having extra Xapian shards is a
32 # waste of FDs and space. It can also lead to excessive IO latency
33 # and slow things down. Users on NVME or other fast storage can
34 # use the NPROC env or switches in our script/public-inbox-* programs
35 # to increase Xapian shards
36 our $NPROC_MAX_DEFAULT = 4;
39 # _SC_NPROCESSORS_ONLN = 84 on both Linux glibc and musl
40 return POSIX::sysconf(84) if $^O eq 'linux';
41 return POSIX::sysconf(58) if $^O eq 'freebsd';
44 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
45 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
46 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
48 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
49 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
52 # should we bother with `sysctl hw.ncpu`? Those only give
53 # us total processor count, not online processor count.
57 sub nproc_shards ($) {
59 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
62 # assume 2 cores if not detectable or zero
63 state $NPROC_DETECTED = detect_nproc() || 2;
65 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
68 # subtract for the main process and git-fast-import
73 sub count_shards ($) {
75 if (my $ibx = $self->{ibx}) {
76 # always load existing shards in case core count changes:
77 # Also, shard count may change while -watch is running
78 my $srch = $ibx->search or return 0;
79 delete $ibx->{search};
81 } else { # ExtSearchIdx
82 $self->{nshard} ||= scalar($self->xdb_shards_flat);
87 # $creat may be any true value, or 0/undef. A hashref is true,
88 # and $creat->{nproc} may be set to an integer
89 my ($class, $v2ibx, $creat) = @_;
90 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
91 my $dir = $v2ibx->assert_usable_dir;
95 File::Path::mkpath($dir);
97 die "$dir does not exist\n";
100 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
103 im => undef, # PublicInbox::Import
109 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
110 lock_path => "$dir/inbox.lock",
111 # limit each git repo (epoch) to 1GB or so
112 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
113 last_commit => [], # git epoch -> commit
115 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
116 $self->{shards} = count_shards($self) || nproc_shards($creat);
122 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
123 if (defined $shards) {
124 $self->{parallel} = 0 if $shards == 0;
125 $self->{shards} = $shards if $shards > 0;
128 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
129 my $max = $self->{ibx}->max_git_epoch;
130 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
131 $self->git_init($max // 0);
135 # returns undef on duplicate or spam
136 # mimics Import::add and wraps it for v2
138 my ($self, $eml, $check_cb) = @_;
139 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
143 my ($self, $num) = @_;
144 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
147 # indexes a message, returns true if checkpointing is needed
149 my ($self, $eml, $smsg) = @_;
150 $self->{oidx}->add_overview($eml, $smsg);
151 if ($self->{-need_xapian}) {
152 my $idx = idx_shard($self, $smsg->{num});
153 $idx->index_eml($eml, $smsg);
155 my $n = $self->{transact_bytes} += $smsg->{bytes};
156 $n >= $self->{batch_bytes};
160 my ($self, $mime, $check_cb) = @_;
164 $mime = $check_cb->($mime, $self->{ibx}) or return;
167 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
168 # as does SQLite 3.4.1+ (released in 2007-07-20), and
169 # Xapian 1.3.2+ (released 2015-03-15).
170 # For the most part, we can spawn git-fast-import without
171 # leaking FDs to it...
174 my ($num, $mid0) = v2_num_for($self, $mime);
175 defined $num or return; # duplicate
176 defined $mid0 or die "BUG: \$mid0 undefined\n";
177 my $im = $self->importer;
178 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
179 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
180 $cmt = $im->get_mark($cmt);
181 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
183 if (do_idx($self, $mime, $smsg)) {
191 my ($self, $mime) = @_;
192 my $mids = mids($mime);
194 my $mid = $mids->[0];
195 my $num = $self->{mm}->mid_insert($mid);
196 if (defined $num) { # common case
200 # crap, Message-ID is already known, hope somebody just resent:
201 foreach my $m (@$mids) {
202 # read-only lookup now safe to do after above barrier
203 # easy, don't store duplicates
204 # note: do not add more diagnostic info here since
205 # it gets noisy on public-inbox-watch restarts
206 return () if content_exists($self, $mime, $m);
209 # AltId may pre-populate article numbers (e.g. X-Mail-Count
210 # or NNTP article number), use that article number if it's
212 my $altid = $self->{ibx}->{altid};
213 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
214 my $num = $self->{mm}->num_for($mid);
216 if (defined $num && !$self->{oidx}->get_art($num)) {
222 warn "<$mid> reused for mismatched content\n";
224 # try the rest of the mids
225 for(my $i = $#$mids; $i >= 1; $i--) {
227 $num = $self->{mm}->mid_insert($m);
229 warn "alternative <$m> for <$mid> found\n";
234 # none of the existing Message-IDs are good, generate a new one:
235 v2_num_for_harder($self, $mime);
238 sub v2_num_for_harder {
239 my ($self, $eml) = @_;
241 my $dig = content_digest($eml);
242 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
243 my $num = $self->{mm}->mid_insert($mid0);
244 unless (defined $num) {
245 # it's hard to spoof the last Received: header
246 my @recvd = $eml->header_raw('Received');
247 $dig->add("Received: $_") foreach (@recvd);
248 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
249 $num = $self->{mm}->mid_insert($mid0);
251 # fall back to a random Message-ID and give up determinism:
252 until (defined($num)) {
254 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
255 warn "using random Message-ID <$mid0> as fallback\n";
256 $num = $self->{mm}->mid_insert($mid0);
259 PublicInbox::Import::append_mid($eml, $mid0);
263 sub _idx_init { # with_umask callback
264 my ($self, $opt) = @_;
265 $self->lock_acquire unless $opt && $opt->{-skip_lock};
266 $self->{oidx}->create;
268 # xcpdb can change shard count while -watch is idle
269 my $nshards = count_shards($self);
270 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
271 $self->{batch_bytes} = $opt->{batch_size} //
272 $PublicInbox::SearchIdx::BATCH_BYTES;
274 # need to create all shards before initializing msgmap FD
275 # idx_shards must be visible to all forked processes
276 my $max = $self->{shards} - 1;
277 my $idx = $self->{idx_shards} = [];
278 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
279 $self->{-need_xapian} = $idx->[0]->need_xapian;
281 # SearchIdxShard may do their own flushing, so don't scale
282 # until after forking
283 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
285 my $ibx = $self->{ibx} or return; # ExtIdxSearch
287 # Now that all subprocesses are up, we can open the FDs
289 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
290 "$ibx->{inboxdir}/msgmap.sqlite3",
291 $ibx->{-no_fsync} ? 2 : 1);
292 $mm->{dbh}->begin_work;
295 sub parallel_init ($$) {
296 my ($self, $indexlevel) = @_;
297 $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
302 my ($self, $opt) = @_;
303 return if $self->{idx_shards};
304 my $ibx = $self->{ibx};
306 # do not leak read-only FDs to child processes, we only have these
307 # FDs for duplicate detection so they should not be
308 # frequently activated.
309 delete @$ibx{qw(mm search)};
312 parallel_init($self, $ibx->{indexlevel});
313 $ibx->with_umask(\&_idx_init, $self, $opt);
316 # returns an array mapping [ epoch => latest_commit ]
317 # latest_commit may be undef if nothing was done to that epoch
318 # $replace_map = { $object_id => $strref, ... }
319 sub _replace_oids ($$$) {
320 my ($self, $mime, $replace_map) = @_;
322 my $ibx = $self->{ibx};
323 my $pfx = "$ibx->{inboxdir}/git";
324 my $rewrites = []; # epoch => commit
325 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
327 foreach my $i (0..$max) {
328 my $git_dir = "$pfx/$i.git";
330 my $git = PublicInbox::Git->new($git_dir);
331 my $im = $self->import_init($git, 0, 1);
332 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
338 sub content_hashes ($) {
340 my @chashes = ( content_hash($mime) );
342 # We still support Email::MIME, here, and
343 # Email::MIME->as_string doesn't always round-trip, so we may
344 # use a second content_hash
345 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
346 push @chashes, $rt if $chashes[0] ne $rt;
350 sub content_matches ($$) {
351 my ($chashes, $existing) = @_;
352 my $chash = content_hash($existing);
353 foreach (@$chashes) {
354 return 1 if $_ eq $chash
359 # used for removing or replacing (purging)
360 sub rewrite_internal ($$;$$$) {
361 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
363 my ($im, $need_reindex, $replace_map);
365 $replace_map = {}; # oid => sref
366 $need_reindex = [] if $new_eml;
368 $im = $self->importer;
370 my $oidx = $self->{oidx};
371 my $chashes = content_hashes($old_eml);
373 my $mids = mids($old_eml);
375 # We avoid introducing new blobs into git since the raw content
376 # can be slightly different, so we do not need the user-supplied
377 # message now that we have the mids and content_hash
381 foreach my $mid (@$mids) {
382 my %gone; # num => [ smsg, $mime, raw ]
384 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
385 my $msg = get_blob($self, $smsg);
386 if (!defined($msg)) {
387 warn "broken smsg for $mid\n";
391 my $cur = PublicInbox::Eml->new($msg);
392 if (content_matches($chashes, $cur)) {
393 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
396 my $n = scalar keys %gone;
399 warn "BUG: multiple articles linked to <$mid>\n",
400 join(',', sort keys %gone), "\n";
402 foreach my $num (keys %gone) {
403 my ($smsg, $mime, $orig) = @{$gone{$num}};
404 # $removed should only be set once assuming
405 # no bugs in our deduplication code:
406 $removed = [ undef, $mime, $smsg ];
407 my $oid = $smsg->{blob};
409 $replace_map->{$oid} = $sref;
411 ($mark, undef) = $im->remove($orig, $cmt_msg);
412 $removed->[0] = $mark;
415 if ($need_reindex) { # ->replace
416 push @$need_reindex, $smsg;
417 } else { # ->purge or ->remove
418 $self->{mm}->num_delete($num);
420 unindex_oid_aux($self, $oid, $mid);
425 my $cmt = $im->get_mark($mark);
426 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
428 if ($replace_map && scalar keys %$replace_map) {
429 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
430 return { rewrites => $rewrites, need_reindex => $need_reindex };
432 defined($mark) ? $removed : undef;
435 # public (see PublicInbox::Import->remove), but note the 3rd element
436 # (retval[2]) is not part of the stable API shared with Import->remove
438 my ($self, $eml, $cmt_msg) = @_;
439 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
440 $self, $eml, $cmt_msg);
441 defined($r) && defined($r->[0]) ? @$r: undef;
444 sub _replace ($$;$$) {
445 my ($self, $old_eml, $new_eml, $sref) = @_;
446 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
447 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
448 $self, $old_eml, undef, $new_eml, $sref) or return;
450 my $rewrites = $rewritten->{rewrites};
451 # ->done is called if there are rewrites since we gc+prune from git
452 $self->idx_init if @$rewrites;
454 for my $i (0..$#$rewrites) {
455 defined(my $cmt = $rewrites->[$i]) or next;
456 $self->{last_commit}->[$i] = $cmt;
463 my ($self, $mime) = @_;
464 my $rewritten = _replace($self, $mime, undef, \'') or return;
465 $rewritten->{rewrites}
468 # returns the git object_id of $fh, does not write the object to FS
469 sub git_hash_raw ($$) {
470 my ($self, $raw) = @_;
471 # grab the expected OID we have to reindex:
472 pipe(my($in, $w)) or die "pipe: $!";
473 my $git_dir = $self->git->{git_dir};
474 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
475 my $r = popen_rd($cmd, undef, { 0 => $in });
476 print $w $$raw or die "print \$w: $!";
477 close $w or die "close \$w: $!";
479 chomp(my $oid = <$r>);
480 close $r or die "git hash-object failed: $?";
481 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
485 sub _check_mids_match ($$$) {
486 my ($old_list, $new_list, $hdrs) = @_;
487 my %old_mids = map { $_ => 1 } @$old_list;
488 my %new_mids = map { $_ => 1 } @$new_list;
489 my @old = keys %old_mids;
490 my @new = keys %new_mids;
491 my $err = "$hdrs may not be changed when replacing\n";
492 die $err if scalar(@old) != scalar(@new);
493 delete @new_mids{@old};
494 delete @old_mids{@new};
495 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
498 # Changing Message-IDs or References with ->replace isn't supported.
499 # The rules for dealing with messages with multiple or conflicting
500 # Message-IDs are pretty complex and rethreading hasn't been fully
502 sub check_mids_match ($$) {
503 my ($old, $new) = @_;
504 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
505 _check_mids_match(references($old), references($new),
506 'References/In-Reply-To');
511 my ($self, $old_mime, $new_mime) = @_;
513 check_mids_match($old_mime, $new_mime);
515 # mutt will always add Content-Length:, Status:, Lines: when editing
516 PublicInbox::Import::drop_unwanted_headers($new_mime);
518 my $raw = $new_mime->as_string;
519 my $expect_oid = git_hash_raw($self, \$raw);
520 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
521 my $need_reindex = $rewritten->{need_reindex};
523 # just in case we have bugs in deduplication code:
524 my $n = scalar(@$need_reindex);
526 my $list = join(', ', map {
527 "$_->{num}: <$_->{mid}>"
530 W: rewritten $n messages matching content of original message (expected: 1).
531 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
536 # make sure we really got the OID:
537 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
538 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
540 # don't leak FDs to Xapian:
543 # reindex modified messages:
544 for my $smsg (@$need_reindex) {
545 my $new_smsg = bless {
549 }, 'PublicInbox::Smsg';
550 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
551 $new_smsg->populate($new_mime, $sync);
552 $new_smsg->set_bytes($raw, $bytes);
553 do_idx($self, $new_mime, $new_smsg);
555 $rewritten->{rewrites};
558 sub last_epoch_commit ($$;$) {
559 my ($self, $i, $cmt) = @_;
560 my $v = PublicInbox::Search::SCHEMA_VERSION();
561 $self->{mm}->last_commit_xap($v, $i, $cmt);
564 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
566 defined(my $epoch_max = $self->{epoch_max}) or return;
567 my $last_commit = $self->{last_commit};
568 foreach my $i (0..$epoch_max) {
569 defined(my $cmt = $last_commit->[$i]) or next;
570 $last_commit->[$i] = undef;
571 last_epoch_commit($self, $i, $cmt);
576 sub checkpoint ($;$) {
577 my ($self, $wait) = @_;
579 if (my $im = $self->{im}) {
586 my $shards = $self->{idx_shards};
588 my $mm = $self->{mm};
589 my $dbh = $mm->{dbh} if $mm;
591 # SQLite msgmap data is second in importance
592 $dbh->commit if $dbh;
594 # SQLite overview is third
595 $self->{oidx}->commit_lazy;
597 # Now deal with Xapian
599 # start commit_txn_lazy asynchronously on all parallel shards
600 # (non-parallel waits here)
601 $_->ipc_do('commit_txn_lazy') for @$shards;
603 # transactions started on parallel shards,
604 # wait for them by issuing an echo command (echo can only
605 # run after commit_txn_lazy is done)
606 if ($wait && $self->{parallel}) {
608 for my $shard (@$shards) {
609 my $echo = $shard->ipc_do('echo', $i);
610 $echo == $i or die <<"";
611 shard[$i] bad echo:$echo != $i waiting for txn commit
617 my $midx = $self->{midx}; # misc index
620 $PublicInbox::Search::X{CLOEXEC_UNSET} and
624 # last_commit is special, don't commit these until
625 # Xapian shards are done:
626 $dbh->begin_work if $dbh;
627 set_last_commits($self);
633 $self->{total_bytes} += $self->{transact_bytes};
634 $self->{transact_bytes} = 0;
637 # issue a write barrier to ensure all data is visible to other processes
638 # and read-only ops. Order of data importance is: git > SQLite > Xapian
640 sub barrier { checkpoint($_[0], 1) };
642 # true if locked and active
643 sub active { !!$_[0]->{im} }
649 if (my $im = delete $self->{im}) {
650 eval { $im->done }; # PublicInbox::Import::done
651 $err .= "import done: $@\n" if $@;
654 eval { checkpoint($self) };
655 $err .= "checkpoint: $@\n" if $@;
657 if (my $mm = delete $self->{mm}) {
658 my $m = $err ? 'rollback' : 'commit';
659 eval { $mm->{dbh}->$m };
660 $err .= "msgmap $m: $@\n" if $@;
662 my $shards = delete $self->{idx_shards};
665 eval { $_->shard_close };
666 $err .= "shard close: $@\n" if $@;
669 eval { $self->{oidx}->dbh_close };
670 $err .= "over close: $@\n" if $@;
671 delete $self->{midx};
672 my $nbytes = $self->{total_bytes};
673 $self->{total_bytes} = 0;
674 $self->lock_release(!!$nbytes) if $shards;
679 sub write_alternates ($$$) {
680 my ($info_dir, $mode, $out) = @_;
681 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
682 my $tmp = $fh->filename;
683 print $fh @$out or die "print $tmp: $!\n";
684 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
685 close $fh or die "close $tmp $!\n";
686 my $alt = "$info_dir/alternates";
687 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
688 $fh->unlink_on_destroy(0);
691 sub fill_alternates ($$) {
692 my ($self, $epoch) = @_;
694 my $pfx = "$self->{ibx}->{inboxdir}/git";
695 my $all = "$self->{ibx}->{inboxdir}/all.git";
696 PublicInbox::Import::init_bare($all) unless -d $all;
697 my $info_dir = "$all/objects/info";
698 my $alt = "$info_dir/alternates";
702 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
703 $mode = (stat($fh))[2] & 07777;
705 # we assign a sort score to every alternate and favor
706 # the newest (highest numbered) one because loose objects
707 # require scanning epochs and only the latest epoch is
708 # expected to see loose objects
710 my $other = 0; # in case admin adds non-epoch repos
712 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
718 } split(/\n+/, do { local $/; <$fh> });
721 foreach my $i (0..$epoch) {
722 my $dir = "../../git/$i.git/objects";
723 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
729 write_alternates($info_dir, $mode,
730 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
734 my ($self, $epoch) = @_;
735 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
736 PublicInbox::Import::init_bare($git_dir);
737 run_die([qw(git config), "--file=$git_dir/config",
738 qw(include.path ../../all.git/config)]);
739 fill_alternates($self, $epoch);
745 my $im = $self->{im};
747 if ($im->{bytes_added} < $self->{rotate_bytes}) {
754 my $git_dir = $self->git_init(++$self->{epoch_max});
755 my $git = PublicInbox::Git->new($git_dir);
756 return $self->import_init($git, 0);
761 my $latest = $self->{ibx}->git_dir_latest(\$max);
762 if (defined $latest) {
763 my $git = PublicInbox::Git->new($latest);
764 my $packed_bytes = $git->packed_bytes;
765 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
767 if ($unpacked_bytes >= $self->{rotate_bytes}) {
770 $self->{epoch_max} = $max;
771 return $self->import_init($git, $packed_bytes);
774 $self->{epoch_max} = $epoch;
775 $latest = $self->git_init($epoch);
776 $self->import_init(PublicInbox::Git->new($latest), 0);
780 my ($self, $git, $packed_bytes, $tmp) = @_;
781 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
782 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
783 $im->{lock_path} = undef;
784 $im->{path_type} = 'v2';
785 $self->{im} = $im unless $tmp;
791 my ($mid, $cur, $new) = @_;
793 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
794 print $ah $cur->as_string or die "print: $!";
795 $ah->flush or die "flush: $!";
796 PublicInbox::Import::drop_unwanted_headers($new);
797 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
798 print $bh $new->as_string or die "print: $!";
799 $bh->flush or die "flush: $!";
800 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
801 print STDERR "# MID conflict <$mid>\n";
802 my $pid = spawn($cmd, undef, { 1 => 2 });
803 waitpid($pid, 0) == $pid or die "diff did not finish";
807 my ($self, $smsg) = @_;
808 if (my $im = $self->{im}) {
809 my $msg = $im->cat_blob($smsg->{blob});
812 # older message, should be in alternates
813 $self->{ibx}->msg_by_smsg($smsg);
816 sub content_exists ($$$) {
817 my ($self, $mime, $mid) = @_;
818 my $oidx = $self->{oidx};
819 my $chashes = content_hashes($mime);
821 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
822 my $msg = get_blob($self, $smsg);
823 if (!defined($msg)) {
824 warn "broken smsg for $mid\n";
827 my $cur = PublicInbox::Eml->new($msg);
828 return 1 if content_matches($chashes, $cur);
830 # XXX DEBUG_DIFF is experimental and may be removed
831 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
838 if (my $older_siblings = $self->{idx_shards}) {
839 $_->ipc_sibling_atfork_child for @$older_siblings;
841 if (my $im = $self->{im}) {
844 die "BUG: unexpected mm" if $self->{mm};
847 sub reindex_checkpoint ($$) {
848 my ($self, $sync) = @_;
850 $self->git->async_wait_all;
851 $self->update_last_commit($sync);
852 ${$sync->{need_checkpoint}} = 0;
853 my $mm_tmp = $sync->{mm_tmp};
854 $mm_tmp->atfork_prepare if $mm_tmp;
855 die 'BUG: {im} during reindex' if $self->{im};
856 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
857 checkpoint($self, 1); # no need to release lock on pure index
859 $self->done; # release lock
862 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
863 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
866 # allow -watch or -mda to write...
867 $self->idx_init($sync->{-opt}); # reacquire lock
868 if (my $intvl = $sync->{check_intvl}) { # eidx
869 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
871 $mm_tmp->atfork_parent if $mm_tmp;
874 sub index_finalize ($$) {
875 my ($arg, $index) = @_;
876 ++$arg->{self}->{nidx};
877 if (defined(my $cur = $arg->{cur_cmt})) {
878 ${$arg->{latest_cmt}} = $cur;
880 die 'BUG: {cur_cmt} missing';
881 } # else { unindexing @leftovers doesn't set {cur_cmt}
884 sub index_oid { # cat_async callback
885 my ($bref, $oid, $type, $size, $arg) = @_;
886 is_bad_blob($oid, $type, $size, $arg->{oid}) and
887 return index_finalize($arg, 1); # size == 0 purged returns here
888 my $self = $arg->{self};
889 local $self->{current_info} = "$self->{current_info} $oid";
891 my $eml = PublicInbox::Eml->new($$bref);
892 my $mids = mids($eml);
893 my $chash = content_hash($eml);
895 if (scalar(@$mids) == 0) {
896 warn "E: $oid has no Message-ID, skipping\n";
900 # {unindexed} is unlikely
901 if (my $unindexed = $arg->{unindexed}) {
902 my $oidbin = pack('H*', $oid);
903 my $u = $unindexed->{$oidbin};
904 ($num, $mid0) = splice(@$u, 0, 2) if $u;
906 $self->{mm}->mid_set($num, $mid0);
907 if (scalar(@$u) == 0) { # done with current OID
908 delete $unindexed->{$oidbin};
909 delete($arg->{unindexed}) if !keys(%$unindexed);
913 if (!defined($num)) { # reuse if reindexing (or duplicates)
914 my $oidx = $self->{oidx};
915 for my $mid (@$mids) {
916 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
917 last if defined $num;
920 $mid0 //= do { # is this a number we got before?
921 $num = $arg->{mm_tmp}->num_for($mids->[0]);
922 defined($num) ? $mids->[0] : undef;
924 if (!defined($num)) {
925 for (my $i = $#$mids; $i >= 1; $i--) {
926 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
934 $arg->{mm_tmp}->num_delete($num);
935 } else { # never seen
936 $num = $self->{mm}->mid_insert($mids->[0]);
939 } else { # rare, try the rest of them, backwards
940 for (my $i = $#$mids; $i >= 1; $i--) {
941 $num = $self->{mm}->mid_insert($mids->[$i]);
949 if (!defined($num)) {
950 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
958 }, 'PublicInbox::Smsg';
959 $smsg->populate($eml, $arg);
960 $smsg->set_bytes($$bref, $size);
961 if (do_idx($self, $eml, $smsg)) {
962 ${$arg->{need_checkpoint}} = 1;
964 index_finalize($arg, 1);
967 # only update last_commit for $i on reindex iff newer than current
968 sub update_last_commit {
969 my ($self, $sync, $stk) = @_;
970 my $unit = $sync->{unit} // return;
971 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
972 defined($latest_cmt) or return;
973 my $last = last_epoch_commit($self, $unit->{epoch});
974 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
975 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
976 chomp(my $n = $unit->{git}->qx(@cmd));
977 return if $n ne '' && $n == 0;
979 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
983 my ($self, $sync) = @_;
985 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
986 $heads->[$i] = last_epoch_commit($self, $i);
991 # returns a revision range for git-log(1)
992 sub log_range ($$$) {
993 my ($sync, $unit, $tip) = @_;
994 my $opt = $sync->{-opt};
995 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
996 my $i = $unit->{epoch};
997 my $cur = $sync->{ranges}->[$i] or do {
998 $pr->("$i.git indexing all of $tip\n") if $pr;
999 return $tip; # all of it
1002 # fast equality check to avoid (v)fork+execve overhead
1004 $sync->{ranges}->[$i] = undef;
1008 my $range = "$cur..$tip";
1009 $pr->("$i.git checking contiguity... ") if $pr;
1010 my $git = $unit->{git};
1011 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1012 $pr->("OK\n") if $pr;
1013 my $n = $git->qx(qw(rev-list --count), $range);
1016 $sync->{ranges}->[$i] = undef;
1017 $pr->("$i.git has nothing new\n") if $pr;
1018 return; # nothing to do
1020 $pr->("$i.git has $n changes since $cur\n") if $pr;
1022 $pr->("FAIL\n") if $pr;
1024 discontiguous range: $range
1025 Rewritten history? (in $git->{git_dir})
1027 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1029 $range = "$base..$tip";
1030 warn "found merge-base: $base\n"
1033 warn "discarding history at $cur\n";
1036 reindexing $git->{git_dir}
1039 # $cur^0 may no longer exist if pruned by git
1040 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1041 $unit->{unindex_range} = "$base..$cur";
1042 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1043 $unit->{unindex_range} = "$base..";
1045 warn "W: unable to unindex before $range\n";
1051 # overridden by ExtSearchIdx
1052 sub artnum_max { $_[0]->{mm}->num_highwater }
1054 sub sync_prepare ($$) {
1055 my ($self, $sync) = @_;
1056 $sync->{ranges} = sync_ranges($self, $sync);
1057 my $pr = $sync->{-opt}->{-progress};
1059 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1062 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1063 $pfx //= $sync->{ibx}->{inboxdir};
1067 if ($self->{ibx_map}) {
1068 # ExtSearchIdx won't index messages unless they're in
1069 # over.sqlite3 for a given inbox, so don't read beyond
1070 # what's in the per-inbox index.
1071 $reindex_heads = [];
1072 my $v = PublicInbox::Search::SCHEMA_VERSION;
1073 my $mm = $sync->{ibx}->mm;
1074 for my $i (0..$sync->{epoch_max}) {
1075 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1077 } elsif ($sync->{reindex}) { # V2 inbox
1078 # reindex stops at the current heads and we later
1079 # rerun index_sync without {reindex}
1080 $reindex_heads = $self->last_commits($sync);
1082 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1083 $sync->{index_oid} = $self->can('index_oid');
1085 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1086 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1087 my $git_dir = "$git_pfx/$i.git";
1088 -d $git_dir or next; # missing epochs are fine
1089 my $git = PublicInbox::Git->new($git_dir);
1090 my $unit = { git => $git, epoch => $i };
1092 if ($reindex_heads) {
1093 $tip = $head = $reindex_heads->[$i] or next;
1095 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1096 next if $?; # new repo
1099 my $range = log_range($sync, $unit, $tip) or next;
1100 # can't use 'rev-list --count' if we use --diff-filter
1101 $pr->("$pfx $i.git counting $range ... ") if $pr;
1102 # Don't bump num_highwater on --reindex by using {D}.
1103 # We intentionally do NOT use {D} in the non-reindex case
1104 # because we want NNTP article number gaps from unindexed
1105 # messages to show up in mirrors, too.
1106 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1107 my $stk = log2stack($sync, $git, $range);
1108 return 0 if $sync->{quit};
1109 my $nr = $stk ? $stk->num_records : 0;
1110 $pr->("$nr\n") if $pr;
1111 $unit->{stack} = $stk; # may be undef
1112 unshift @{$sync->{todo}}, $unit;
1115 return 0 if $sync->{quit};
1117 # XXX this should not happen unless somebody bypasses checks in
1118 # our code and blindly injects "d" file history into git repos
1119 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1120 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1121 local $self->{current_info} = 'leftover ';
1122 my $unindex_oid = $self->can('unindex_oid');
1123 for my $oid (@leftovers) {
1124 last if $sync->{quit};
1125 $oid = unpack('H*', $oid);
1126 my $req = { %$sync, oid => $oid };
1127 $self->git->cat_async($oid, $unindex_oid, $req);
1129 $self->git->cat_async_wait;
1131 return 0 if $sync->{quit};
1133 $sync->{-regen_fmt} = "%u/?\n";
1137 # reindex should NOT see new commits anymore, if we do,
1138 # it's a problem and we need to notice it via die()
1139 my $pad = length($regen_max) + 1;
1140 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1141 $sync->{nr} = \(my $nr = 0);
1142 return -1 if $sync->{reindex};
1143 $regen_max + $self->artnum_max || 0;
1146 sub unindex_oid_aux ($$$) {
1147 my ($self, $oid, $mid) = @_;
1148 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1149 return unless $self->{-need_xapian};
1150 for my $num (@removed) {
1151 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1155 sub unindex_oid ($$;$) { # git->cat_async callback
1156 my ($bref, $oid, $type, $size, $arg) = @_;
1157 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1158 return index_finalize($arg, 0);
1159 my $self = $arg->{self};
1160 local $self->{current_info} = "$self->{current_info} $oid";
1161 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1162 my $mm = $self->{mm};
1163 my $mids = mids(PublicInbox::Eml->new($bref));
1165 my $oidx = $self->{oidx};
1166 foreach my $mid (@$mids) {
1169 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1170 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1172 my $n = scalar(keys(%gone)) or next;
1174 warn "BUG: multiple articles linked to $oid\n",
1175 join(',',sort keys %gone), "\n";
1177 # reuse (num => mid) mapping in ascending numeric order
1178 for my $num (sort { $a <=> $b } keys %gone) {
1181 my $mid0 = $mm->mid_for($num);
1182 my $oidbin = pack('H*', $oid);
1183 push @{$unindexed->{$oidbin}}, $num, $mid0;
1185 $mm->num_delete($num);
1187 unindex_oid_aux($self, $oid, $mid);
1189 index_finalize($arg, 0);
1192 sub git { $_[0]->{ibx}->git }
1194 # this is rare, it only happens when we get discontiguous history in
1195 # a mirror because the source used -purge or -edit
1196 sub unindex_todo ($$$) {
1197 my ($self, $sync, $unit) = @_;
1198 my $unindex_range = delete($unit->{unindex_range}) // return;
1199 my $unindexed = $sync->{unindexed} //= {}; # $oidbin => [$num, $mid0]
1200 my $before = scalar keys %$unindexed;
1201 # order does not matter, here:
1202 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1203 --no-abbrev --no-renames), $unindex_range);
1204 local $sync->{in_unindex} = 1;
1205 my $unindex_oid = $self->can('unindex_oid');
1207 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1208 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1210 close $fh or die "git log failed: \$?=$?";
1211 $self->git->cat_async_wait;
1213 return unless $sync->{-opt}->{prune};
1214 my $after = scalar keys %$unindexed;
1215 return if $before == $after;
1217 # ensure any blob can not longer be accessed via dumb HTTP
1218 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1219 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1222 sub sync_ranges ($$) {
1223 my ($self, $sync) = @_;
1224 my $reindex = $sync->{reindex};
1225 return $self->last_commits($sync) unless $reindex;
1226 return [] if ref($reindex) ne 'HASH';
1228 my $ranges = $reindex->{from}; # arrayref;
1229 if (ref($ranges) ne 'ARRAY') {
1230 die 'BUG: $reindex->{from} not an ARRAY';
1235 sub index_xap_only { # git->cat_async callback
1236 my ($bref, $oid, $type, $size, $smsg) = @_;
1237 my $self = $smsg->{self};
1238 my $idx = idx_shard($self, $smsg->{num});
1239 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1240 $self->{transact_bytes} += $smsg->{bytes};
1243 sub index_xap_step ($$$;$) {
1244 my ($self, $sync, $beg, $step) = @_;
1245 my $end = $sync->{art_end};
1246 return if $beg > $end; # nothing to do
1248 $step //= $self->{shards};
1249 my $ibx = $self->{ibx};
1250 if (my $pr = $sync->{-opt}->{-progress}) {
1251 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1252 "$beg..$end (% $step)\n");
1254 for (my $num = $beg; $num <= $end; $num += $step) {
1255 last if $sync->{quit};
1256 my $smsg = $ibx->over->get_art($num) or next;
1257 $smsg->{self} = $self;
1258 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1259 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1260 ${$sync->{nr}} = $num;
1261 reindex_checkpoint($self, $sync);
1266 sub index_todo ($$$) {
1267 my ($self, $sync, $unit) = @_;
1268 return if $sync->{quit};
1269 unindex_todo($self, $sync, $unit);
1270 my $stk = delete($unit->{stack}) or return;
1271 my $all = $self->git;
1272 my $index_oid = $self->can('index_oid');
1273 my $unindex_oid = $self->can('unindex_oid');
1275 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1276 $pfx = "$1 $2"; # v2
1278 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1279 $pfx //= $unit->{git}->{git_dir};
1281 local $self->{current_info} = "$pfx ";
1282 local $sync->{latest_cmt} = \(my $latest_cmt);
1283 local $sync->{unit} = $unit;
1284 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1285 if ($sync->{quit}) {
1286 warn "waiting to quit...\n";
1287 $all->async_wait_all;
1288 $self->update_last_commit($sync);
1299 if ($sync->{max_size}) {
1300 $all->check_async($oid, \&check_size, $req);
1302 $all->cat_async($oid, $index_oid, $req);
1304 } elsif ($f eq 'd') {
1305 $all->cat_async($oid, $unindex_oid, $req);
1307 if (${$sync->{need_checkpoint}}) {
1308 reindex_checkpoint($self, $sync);
1311 $all->async_wait_all;
1312 $self->update_last_commit($sync, $stk);
1316 my ($self, $opt, $sync, $art_beg) = @_;
1317 my $seq = $opt->{sequential_shard};
1319 local $self->{parallel} = 0 if $seq;
1320 $self->idx_init($opt); # acquire lock
1321 if (my $art_end = $self->{ibx}->mm->max) {
1323 need_checkpoint => \(my $bool = 0),
1326 nr => \(my $nr = 0),
1327 -regen_fmt => "%u/?\n",
1329 $sync->{art_end} = $art_end;
1330 if ($seq || !$self->{parallel}) {
1331 my $shard_end = $self->{shards} - 1;
1332 for my $i (0..$shard_end) {
1333 last if $sync->{quit};
1334 index_xap_step($self, $sync, $art_beg + $i);
1335 if ($i != $shard_end) {
1336 reindex_checkpoint($self, $sync);
1339 } else { # parallel (maybe)
1340 index_xap_step($self, $sync, $art_beg, 1);
1343 $self->git->cat_async_wait;
1347 # public, called by public-inbox-index
1349 my ($self, $opt) = @_;
1351 return xapian_only($self, $opt) if $opt->{xapian_only};
1354 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1355 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1356 use Time::HiRes qw(stat);
1357 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1358 my $c = $mm[10]; # 10 = ctime (nsec NV)
1359 my @hd = stat("$latest/refs/heads");
1360 my @pr = stat("$latest/packed-refs");
1361 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1365 my $pr = $opt->{-progress};
1366 my $seq = $opt->{sequential_shard};
1367 my $art_beg; # the NNTP article number we start xapian_only at
1368 my $idxlevel = $self->{ibx}->{indexlevel};
1369 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1371 $self->idx_init($opt); # acquire lock
1372 fill_alternates($self, $epoch_max);
1373 $self->{oidx}->rethread_prepare($opt);
1375 need_checkpoint => \(my $bool = 0),
1376 reindex => $opt->{reindex},
1379 ibx => $self->{ibx},
1380 epoch_max => $epoch_max,
1382 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1383 local $SIG{QUIT} = $quit;
1384 local $SIG{INT} = $quit;
1385 local $SIG{TERM} = $quit;
1387 if (sync_prepare($self, $sync)) {
1388 # tmp_clone seems to fail if inside a transaction, so
1389 # we rollback here (because we opened {mm} for reading)
1390 # Note: we do NOT rely on DBI transactions for atomicity;
1391 # only for batch performance.
1392 $self->{mm}->{dbh}->rollback;
1393 $self->{mm}->{dbh}->begin_work;
1395 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1397 # xapian_only works incrementally w/o --reindex
1398 if ($seq && !$opt->{reindex}) {
1399 $art_beg = $sync->{mm_tmp}->max || -1;
1403 # work forwards through history
1404 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1405 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1408 if (my $nr = $sync->{nr}) {
1409 my $pr = $sync->{-opt}->{-progress};
1410 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1414 # deal with Xapian shards sequentially
1415 if ($seq && delete($sync->{mm_tmp})) {
1416 if ($sync->{quit}) {
1419 $self->{ibx}->{indexlevel} = $idxlevel;
1420 xapian_only($self, $opt, $sync, $art_beg);
1421 $quit_warn = 1 if $sync->{quit};
1425 # --reindex on the command-line
1426 if (!$sync->{quit} && $opt->{reindex} &&
1427 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1428 $self->lock_acquire;
1429 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1430 if (my $xdb = $s0->idx_acquire) {
1431 my $n = $xdb->get_metadata('has_threadid');
1432 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1435 $self->lock_release;
1438 # reindex does not pick up new changes, so we rerun w/o it:
1439 if ($opt->{reindex} && !$sync->{quit}) {
1442 delete @again{qw(rethread reindex -skip_lock)};
1443 index_sync($self, \%again);
1444 $opt->{quit} = $again{quit}; # propagate to caller
1446 warn <<EOF if $quit_warn;
1447 W: interrupted, --xapian-only --reindex required upon restart