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::SearchIdx qw(log2stack is_ancestor check_size is_bad_blob);
21 use IO::Handle; # ->autoflush
24 my $OID = qr/[a-f0-9]{40,}/;
25 # an estimate of the post-packed size to the raw uncompressed size
26 our $PACKING_FACTOR = 0.4;
28 # SATA storage lags behind what CPUs are capable of, so relying on
29 # nproc(1) can be misleading and having extra Xapian shards is a
30 # waste of FDs and space. It can also lead to excessive IO latency
31 # and slow things down. Users on NVME or other fast storage can
32 # use the NPROC env or switches in our script/public-inbox-* programs
33 # to increase Xapian shards
34 our $NPROC_MAX_DEFAULT = 4;
37 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
38 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
39 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
41 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
42 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
45 # should we bother with `sysctl hw.ncpu`? Those only give
46 # us total processor count, not online processor count.
50 sub nproc_shards ($) {
52 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
55 # assume 2 cores if not detectable or zero
56 state $NPROC_DETECTED = detect_nproc() || 2;
58 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
61 # subtract for the main process and git-fast-import
66 sub count_shards ($) {
68 if (my $ibx = $self->{ibx}) {
69 # always load existing shards in case core count changes:
70 # Also, shard count may change while -watch is running
71 my $srch = $ibx->search or return 0;
72 delete $ibx->{search};
74 } else { # ExtSearchIdx
75 $self->{nshard} ||= scalar($self->xdb_shards_flat);
80 # $creat may be any true value, or 0/undef. A hashref is true,
81 # and $creat->{nproc} may be set to an integer
82 my ($class, $v2ibx, $creat) = @_;
83 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
84 my $dir = $v2ibx->assert_usable_dir;
88 File::Path::mkpath($dir);
90 die "$dir does not exist\n";
93 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
96 im => undef, # PublicInbox::Import
102 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
103 lock_path => "$dir/inbox.lock",
104 # limit each git repo (epoch) to 1GB or so
105 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
106 last_commit => [], # git epoch -> commit
108 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
109 $self->{shards} = count_shards($self) || nproc_shards($creat);
115 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
116 if (defined $shards) {
117 $self->{parallel} = 0 if $shards == 0;
118 $self->{shards} = $shards if $shards > 0;
121 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
122 my $max = $self->{ibx}->max_git_epoch;
123 $max = $skip_epoch if (defined($skip_epoch) && !defined($max));
124 $self->git_init($max // 0);
128 # returns undef on duplicate or spam
129 # mimics Import::add and wraps it for v2
131 my ($self, $eml, $check_cb) = @_;
132 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
136 my ($self, $num) = @_;
137 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
140 # indexes a message, returns true if checkpointing is needed
142 my ($self, $eml, $smsg) = @_;
143 $self->{oidx}->add_overview($eml, $smsg);
144 my $idx = idx_shard($self, $smsg->{num});
145 $idx->index_eml($eml, $smsg);
146 my $n = $self->{transact_bytes} += $smsg->{bytes};
147 $n >= $self->{batch_bytes};
151 my ($self, $mime, $check_cb) = @_;
155 $mime = $check_cb->($mime, $self->{ibx}) or return;
158 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
159 # as does SQLite 3.4.1+ (released in 2007-07-20), and
160 # Xapian 1.3.2+ (released 2015-03-15).
161 # For the most part, we can spawn git-fast-import without
162 # leaking FDs to it...
165 my ($num, $mid0) = v2_num_for($self, $mime);
166 defined $num or return; # duplicate
167 defined $mid0 or die "BUG: \$mid0 undefined\n";
168 my $im = $self->importer;
169 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
170 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
171 $cmt = $im->get_mark($cmt);
172 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
174 if (do_idx($self, $mime, $smsg)) {
182 my ($self, $mime) = @_;
183 my $mids = mids($mime);
185 my $mid = $mids->[0];
186 my $num = $self->{mm}->mid_insert($mid);
187 if (defined $num) { # common case
191 # crap, Message-ID is already known, hope somebody just resent:
192 foreach my $m (@$mids) {
193 # read-only lookup now safe to do after above barrier
194 # easy, don't store duplicates
195 # note: do not add more diagnostic info here since
196 # it gets noisy on public-inbox-watch restarts
197 return () if content_exists($self, $mime, $m);
200 # AltId may pre-populate article numbers (e.g. X-Mail-Count
201 # or NNTP article number), use that article number if it's
203 my $altid = $self->{ibx}->{altid};
204 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
205 my $num = $self->{mm}->num_for($mid);
207 if (defined $num && !$self->{oidx}->get_art($num)) {
213 warn "<$mid> reused for mismatched content\n";
215 # try the rest of the mids
216 for(my $i = $#$mids; $i >= 1; $i--) {
218 $num = $self->{mm}->mid_insert($m);
220 warn "alternative <$m> for <$mid> found\n";
225 # none of the existing Message-IDs are good, generate a new one:
226 v2_num_for_harder($self, $mime);
229 sub v2_num_for_harder {
230 my ($self, $eml) = @_;
232 my $dig = content_digest($eml);
233 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
234 my $num = $self->{mm}->mid_insert($mid0);
235 unless (defined $num) {
236 # it's hard to spoof the last Received: header
237 my @recvd = $eml->header_raw('Received');
238 $dig->add("Received: $_") foreach (@recvd);
239 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
240 $num = $self->{mm}->mid_insert($mid0);
242 # fall back to a random Message-ID and give up determinism:
243 until (defined($num)) {
245 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
246 warn "using random Message-ID <$mid0> as fallback\n";
247 $num = $self->{mm}->mid_insert($mid0);
250 PublicInbox::Import::append_mid($eml, $mid0);
254 sub _idx_init { # with_umask callback
255 my ($self, $opt) = @_;
256 $self->lock_acquire unless $opt && $opt->{-skip_lock};
257 $self->{oidx}->create;
259 # xcpdb can change shard count while -watch is idle
260 my $nshards = count_shards($self);
261 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
262 $self->{batch_bytes} = $opt->{batch_size} //
263 $PublicInbox::SearchIdx::BATCH_BYTES;
265 # need to create all shards before initializing msgmap FD
266 # idx_shards must be visible to all forked processes
267 my $max = $self->{shards} - 1;
268 my $idx = $self->{idx_shards} = [];
269 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
271 # SearchIdxShard may do their own flushing, so don't scale
272 # until after forking
273 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
275 my $ibx = $self->{ibx} or return; # ExtIdxSearch
277 # Now that all subprocesses are up, we can open the FDs
279 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
280 "$ibx->{inboxdir}/msgmap.sqlite3",
281 $ibx->{-no_fsync} ? 2 : 1);
282 $mm->{dbh}->begin_work;
285 sub parallel_init ($$) {
286 my ($self, $indexlevel) = @_;
287 $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
292 my ($self, $opt) = @_;
293 return if $self->{idx_shards};
294 my $ibx = $self->{ibx};
296 # do not leak read-only FDs to child processes, we only have these
297 # FDs for duplicate detection so they should not be
298 # frequently activated.
299 delete @$ibx{qw(mm search)};
302 parallel_init($self, $ibx->{indexlevel});
303 $ibx->with_umask(\&_idx_init, $self, $opt);
306 # returns an array mapping [ epoch => latest_commit ]
307 # latest_commit may be undef if nothing was done to that epoch
308 # $replace_map = { $object_id => $strref, ... }
309 sub _replace_oids ($$$) {
310 my ($self, $mime, $replace_map) = @_;
312 my $ibx = $self->{ibx};
313 my $pfx = "$ibx->{inboxdir}/git";
314 my $rewrites = []; # epoch => commit
315 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
317 foreach my $i (0..$max) {
318 my $git_dir = "$pfx/$i.git";
320 my $git = PublicInbox::Git->new($git_dir);
321 my $im = $self->import_init($git, 0, 1);
322 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
328 sub content_hashes ($) {
330 my @chashes = ( content_hash($mime) );
332 # We still support Email::MIME, here, and
333 # Email::MIME->as_string doesn't always round-trip, so we may
334 # use a second content_hash
335 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
336 push @chashes, $rt if $chashes[0] ne $rt;
340 sub content_matches ($$) {
341 my ($chashes, $existing) = @_;
342 my $chash = content_hash($existing);
343 foreach (@$chashes) {
344 return 1 if $_ eq $chash
349 # used for removing or replacing (purging)
350 sub rewrite_internal ($$;$$$) {
351 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
353 my ($im, $need_reindex, $replace_map);
355 $replace_map = {}; # oid => sref
356 $need_reindex = [] if $new_eml;
358 $im = $self->importer;
360 my $oidx = $self->{oidx};
361 my $chashes = content_hashes($old_eml);
363 my $mids = mids($old_eml);
365 # We avoid introducing new blobs into git since the raw content
366 # can be slightly different, so we do not need the user-supplied
367 # message now that we have the mids and content_hash
371 foreach my $mid (@$mids) {
372 my %gone; # num => [ smsg, $mime, raw ]
374 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
375 my $msg = get_blob($self, $smsg);
376 if (!defined($msg)) {
377 warn "broken smsg for $mid\n";
381 my $cur = PublicInbox::Eml->new($msg);
382 if (content_matches($chashes, $cur)) {
383 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
386 my $n = scalar keys %gone;
389 warn "BUG: multiple articles linked to <$mid>\n",
390 join(',', sort keys %gone), "\n";
392 foreach my $num (keys %gone) {
393 my ($smsg, $mime, $orig) = @{$gone{$num}};
394 # $removed should only be set once assuming
395 # no bugs in our deduplication code:
396 $removed = [ undef, $mime, $smsg ];
397 my $oid = $smsg->{blob};
399 $replace_map->{$oid} = $sref;
401 ($mark, undef) = $im->remove($orig, $cmt_msg);
402 $removed->[0] = $mark;
405 if ($need_reindex) { # ->replace
406 push @$need_reindex, $smsg;
407 } else { # ->purge or ->remove
408 $self->{mm}->num_delete($num);
410 unindex_oid_aux($self, $oid, $mid);
415 my $cmt = $im->get_mark($mark);
416 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
418 if ($replace_map && scalar keys %$replace_map) {
419 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
420 return { rewrites => $rewrites, need_reindex => $need_reindex };
422 defined($mark) ? $removed : undef;
425 # public (see PublicInbox::Import->remove), but note the 3rd element
426 # (retval[2]) is not part of the stable API shared with Import->remove
428 my ($self, $eml, $cmt_msg) = @_;
429 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
430 $self, $eml, $cmt_msg);
431 defined($r) && defined($r->[0]) ? @$r: undef;
434 sub _replace ($$;$$) {
435 my ($self, $old_eml, $new_eml, $sref) = @_;
436 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
437 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
438 $self, $old_eml, undef, $new_eml, $sref) or return;
440 my $rewrites = $rewritten->{rewrites};
441 # ->done is called if there are rewrites since we gc+prune from git
442 $self->idx_init if @$rewrites;
444 for my $i (0..$#$rewrites) {
445 defined(my $cmt = $rewrites->[$i]) or next;
446 $self->{last_commit}->[$i] = $cmt;
453 my ($self, $mime) = @_;
454 my $rewritten = _replace($self, $mime, undef, \'') or return;
455 $rewritten->{rewrites}
458 # returns the git object_id of $fh, does not write the object to FS
459 sub git_hash_raw ($$) {
460 my ($self, $raw) = @_;
461 # grab the expected OID we have to reindex:
462 pipe(my($in, $w)) or die "pipe: $!";
463 my $git_dir = $self->git->{git_dir};
464 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
465 my $r = popen_rd($cmd, undef, { 0 => $in });
466 print $w $$raw or die "print \$w: $!";
467 close $w or die "close \$w: $!";
469 chomp(my $oid = <$r>);
470 close $r or die "git hash-object failed: $?";
471 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
475 sub _check_mids_match ($$$) {
476 my ($old_list, $new_list, $hdrs) = @_;
477 my %old_mids = map { $_ => 1 } @$old_list;
478 my %new_mids = map { $_ => 1 } @$new_list;
479 my @old = keys %old_mids;
480 my @new = keys %new_mids;
481 my $err = "$hdrs may not be changed when replacing\n";
482 die $err if scalar(@old) != scalar(@new);
483 delete @new_mids{@old};
484 delete @old_mids{@new};
485 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
488 # Changing Message-IDs or References with ->replace isn't supported.
489 # The rules for dealing with messages with multiple or conflicting
490 # Message-IDs are pretty complex and rethreading hasn't been fully
492 sub check_mids_match ($$) {
493 my ($old, $new) = @_;
494 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
495 _check_mids_match(references($old), references($new),
496 'References/In-Reply-To');
501 my ($self, $old_mime, $new_mime) = @_;
503 check_mids_match($old_mime, $new_mime);
505 # mutt will always add Content-Length:, Status:, Lines: when editing
506 PublicInbox::Import::drop_unwanted_headers($new_mime);
508 my $raw = $new_mime->as_string;
509 my $expect_oid = git_hash_raw($self, \$raw);
510 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
511 my $need_reindex = $rewritten->{need_reindex};
513 # just in case we have bugs in deduplication code:
514 my $n = scalar(@$need_reindex);
516 my $list = join(', ', map {
517 "$_->{num}: <$_->{mid}>"
520 W: rewritten $n messages matching content of original message (expected: 1).
521 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
526 # make sure we really got the OID:
527 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
528 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
530 # don't leak FDs to Xapian:
533 # reindex modified messages:
534 for my $smsg (@$need_reindex) {
535 my $new_smsg = bless {
539 }, 'PublicInbox::Smsg';
540 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
541 $new_smsg->populate($new_mime, $sync);
542 $new_smsg->set_bytes($raw, $bytes);
543 do_idx($self, $new_mime, $new_smsg);
545 $rewritten->{rewrites};
548 sub last_epoch_commit ($$;$) {
549 my ($self, $i, $cmt) = @_;
550 my $v = PublicInbox::Search::SCHEMA_VERSION();
551 $self->{mm}->last_commit_xap($v, $i, $cmt);
554 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
556 defined(my $epoch_max = $self->{epoch_max}) or return;
557 my $last_commit = $self->{last_commit};
558 foreach my $i (0..$epoch_max) {
559 defined(my $cmt = $last_commit->[$i]) or next;
560 $last_commit->[$i] = undef;
561 last_epoch_commit($self, $i, $cmt);
566 sub checkpoint ($;$) {
567 my ($self, $wait) = @_;
569 if (my $im = $self->{im}) {
576 my $shards = $self->{idx_shards};
578 my $mm = $self->{mm};
579 my $dbh = $mm->{dbh} if $mm;
581 # SQLite msgmap data is second in importance
582 $dbh->commit if $dbh;
584 # SQLite overview is third
585 $self->{oidx}->commit_lazy;
587 # Now deal with Xapian
589 # start commit_txn_lazy asynchronously on all parallel shards
590 # (non-parallel waits here)
591 $_->ipc_do('commit_txn_lazy') for @$shards;
593 # transactions started on parallel shards,
594 # wait for them by issuing an echo command (echo can only
595 # run after commit_txn_lazy is done)
596 if ($wait && $self->{parallel}) {
598 for my $shard (@$shards) {
599 my $echo = $shard->ipc_do('echo', $i);
600 $echo == $i or die <<"";
601 shard[$i] bad echo:$echo != $i waiting for txn commit
607 my $midx = $self->{midx}; # misc index
608 $midx->commit_txn if $midx;
610 # last_commit is special, don't commit these until
611 # Xapian shards are done:
612 $dbh->begin_work if $dbh;
613 set_last_commits($self);
618 $midx->begin_txn if $midx;
620 $self->{total_bytes} += $self->{transact_bytes};
621 $self->{transact_bytes} = 0;
624 # issue a write barrier to ensure all data is visible to other processes
625 # and read-only ops. Order of data importance is: git > SQLite > Xapian
627 sub barrier { checkpoint($_[0], 1) };
629 # true if locked and active
630 sub active { !!$_[0]->{im} }
636 if (my $im = delete $self->{im}) {
637 eval { $im->done }; # PublicInbox::Import::done
638 $err .= "import done: $@\n" if $@;
641 eval { checkpoint($self) };
642 $err .= "checkpoint: $@\n" if $@;
644 if (my $mm = delete $self->{mm}) {
645 my $m = $err ? 'rollback' : 'commit';
646 eval { $mm->{dbh}->$m };
647 $err .= "msgmap $m: $@\n" if $@;
649 my $shards = delete $self->{idx_shards};
652 eval { $_->shard_close };
653 $err .= "shard close: $@\n" if $@;
656 eval { $self->{oidx}->dbh_close };
657 $err .= "over close: $@\n" if $@;
658 delete $self->{midx};
659 my $nbytes = $self->{total_bytes};
660 $self->{total_bytes} = 0;
661 $self->lock_release(!!$nbytes) if $shards;
666 sub write_alternates ($$$) {
667 my ($info_dir, $mode, $out) = @_;
668 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
669 my $tmp = $fh->filename;
670 print $fh @$out or die "print $tmp: $!\n";
671 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
672 close $fh or die "close $tmp $!\n";
673 my $alt = "$info_dir/alternates";
674 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
675 $fh->unlink_on_destroy(0);
678 sub fill_alternates ($$) {
679 my ($self, $epoch) = @_;
681 my $pfx = "$self->{ibx}->{inboxdir}/git";
682 my $all = "$self->{ibx}->{inboxdir}/all.git";
683 PublicInbox::Import::init_bare($all) unless -d $all;
684 my $info_dir = "$all/objects/info";
685 my $alt = "$info_dir/alternates";
689 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
690 $mode = (stat($fh))[2] & 07777;
692 # we assign a sort score to every alternate and favor
693 # the newest (highest numbered) one because loose objects
694 # require scanning epochs and only the latest epoch is
695 # expected to see loose objects
697 my $other = 0; # in case admin adds non-epoch repos
699 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
705 } split(/\n+/, do { local $/; <$fh> });
708 foreach my $i (0..$epoch) {
709 my $dir = "../../git/$i.git/objects";
710 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
716 write_alternates($info_dir, $mode,
717 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
721 my ($self, $epoch) = @_;
722 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
723 PublicInbox::Import::init_bare($git_dir);
724 run_die([qw(git config), "--file=$git_dir/config",
725 qw(include.path ../../all.git/config)]);
726 fill_alternates($self, $epoch);
732 my $im = $self->{im};
734 if ($im->{bytes_added} < $self->{rotate_bytes}) {
741 my $git_dir = $self->git_init(++$self->{epoch_max});
742 my $git = PublicInbox::Git->new($git_dir);
743 return $self->import_init($git, 0);
748 my $latest = $self->{ibx}->git_dir_latest(\$max);
749 if (defined $latest) {
750 my $git = PublicInbox::Git->new($latest);
751 my $packed_bytes = $git->packed_bytes;
752 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
754 if ($unpacked_bytes >= $self->{rotate_bytes}) {
757 $self->{epoch_max} = $max;
758 return $self->import_init($git, $packed_bytes);
761 $self->{epoch_max} = $epoch;
762 $latest = $self->git_init($epoch);
763 $self->import_init(PublicInbox::Git->new($latest), 0);
767 my ($self, $git, $packed_bytes, $tmp) = @_;
768 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
769 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
770 $im->{lock_path} = undef;
771 $im->{path_type} = 'v2';
772 $self->{im} = $im unless $tmp;
778 my ($mid, $cur, $new) = @_;
780 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
781 print $ah $cur->as_string or die "print: $!";
782 $ah->flush or die "flush: $!";
783 PublicInbox::Import::drop_unwanted_headers($new);
784 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
785 print $bh $new->as_string or die "print: $!";
786 $bh->flush or die "flush: $!";
787 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
788 print STDERR "# MID conflict <$mid>\n";
789 my $pid = spawn($cmd, undef, { 1 => 2 });
790 waitpid($pid, 0) == $pid or die "diff did not finish";
794 my ($self, $smsg) = @_;
795 if (my $im = $self->{im}) {
796 my $msg = $im->cat_blob($smsg->{blob});
799 # older message, should be in alternates
800 $self->{ibx}->msg_by_smsg($smsg);
803 sub content_exists ($$$) {
804 my ($self, $mime, $mid) = @_;
805 my $oidx = $self->{oidx};
806 my $chashes = content_hashes($mime);
808 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
809 my $msg = get_blob($self, $smsg);
810 if (!defined($msg)) {
811 warn "broken smsg for $mid\n";
814 my $cur = PublicInbox::Eml->new($msg);
815 return 1 if content_matches($chashes, $cur);
817 # XXX DEBUG_DIFF is experimental and may be removed
818 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
825 if (my $older_siblings = $self->{idx_shards}) {
826 $_->ipc_sibling_atfork_child for @$older_siblings;
828 if (my $im = $self->{im}) {
831 die "BUG: unexpected mm" if $self->{mm};
834 sub reindex_checkpoint ($$) {
835 my ($self, $sync) = @_;
837 $self->git->async_wait_all;
838 $self->update_last_commit($sync);
839 ${$sync->{need_checkpoint}} = 0;
840 my $mm_tmp = $sync->{mm_tmp};
841 $mm_tmp->atfork_prepare if $mm_tmp;
842 die 'BUG: {im} during reindex' if $self->{im};
843 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
844 checkpoint($self, 1); # no need to release lock on pure index
846 $self->done; # release lock
849 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
850 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
853 # allow -watch or -mda to write...
854 $self->idx_init($sync->{-opt}); # reacquire lock
855 if (my $intvl = $sync->{check_intvl}) { # eidx
856 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
858 $mm_tmp->atfork_parent if $mm_tmp;
861 sub index_finalize ($$) {
862 my ($arg, $index) = @_;
863 ++$arg->{self}->{nidx};
864 if (defined(my $cur = $arg->{cur_cmt})) {
865 ${$arg->{latest_cmt}} = $cur;
867 die 'BUG: {cur_cmt} missing';
868 } # else { unindexing @leftovers doesn't set {cur_cmt}
871 sub index_oid { # cat_async callback
872 my ($bref, $oid, $type, $size, $arg) = @_;
873 is_bad_blob($oid, $type, $size, $arg->{oid}) and
874 return index_finalize($arg, 1); # size == 0 purged returns here
875 my $self = $arg->{self};
876 local $self->{current_info} = "$self->{current_info} $oid";
878 my $eml = PublicInbox::Eml->new($$bref);
879 my $mids = mids($eml);
880 my $chash = content_hash($eml);
882 if (scalar(@$mids) == 0) {
883 warn "E: $oid has no Message-ID, skipping\n";
887 # {unindexed} is unlikely
888 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
889 $num = delete($unindexed->{$mids->[0]});
892 $self->{mm}->mid_set($num, $mid0);
893 delete($arg->{unindexed}) if !keys(%$unindexed);
896 if (!defined($num)) { # reuse if reindexing (or duplicates)
897 my $oidx = $self->{oidx};
898 for my $mid (@$mids) {
899 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
900 last if defined $num;
903 $mid0 //= do { # is this a number we got before?
904 $num = $arg->{mm_tmp}->num_for($mids->[0]);
905 defined($num) ? $mids->[0] : undef;
907 if (!defined($num)) {
908 for (my $i = $#$mids; $i >= 1; $i--) {
909 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
917 $arg->{mm_tmp}->num_delete($num);
918 } else { # never seen
919 $num = $self->{mm}->mid_insert($mids->[0]);
922 } else { # rare, try the rest of them, backwards
923 for (my $i = $#$mids; $i >= 1; $i--) {
924 $num = $self->{mm}->mid_insert($mids->[$i]);
932 if (!defined($num)) {
933 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
941 }, 'PublicInbox::Smsg';
942 $smsg->populate($eml, $arg);
943 $smsg->set_bytes($$bref, $size);
944 if (do_idx($self, $eml, $smsg)) {
945 ${$arg->{need_checkpoint}} = 1;
947 index_finalize($arg, 1);
950 # only update last_commit for $i on reindex iff newer than current
951 sub update_last_commit {
952 my ($self, $sync, $stk) = @_;
953 my $unit = $sync->{unit} // return;
954 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
955 defined($latest_cmt) or return;
956 my $last = last_epoch_commit($self, $unit->{epoch});
957 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
958 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
959 chomp(my $n = $unit->{git}->qx(@cmd));
960 return if $n ne '' && $n == 0;
962 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
966 my ($self, $sync) = @_;
968 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
969 $heads->[$i] = last_epoch_commit($self, $i);
974 # returns a revision range for git-log(1)
975 sub log_range ($$$) {
976 my ($sync, $unit, $tip) = @_;
977 my $opt = $sync->{-opt};
978 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
979 my $i = $unit->{epoch};
980 my $cur = $sync->{ranges}->[$i] or do {
981 $pr->("$i.git indexing all of $tip\n") if $pr;
982 return $tip; # all of it
985 # fast equality check to avoid (v)fork+execve overhead
987 $sync->{ranges}->[$i] = undef;
991 my $range = "$cur..$tip";
992 $pr->("$i.git checking contiguity... ") if $pr;
993 my $git = $unit->{git};
994 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
995 $pr->("OK\n") if $pr;
996 my $n = $git->qx(qw(rev-list --count), $range);
999 $sync->{ranges}->[$i] = undef;
1000 $pr->("$i.git has nothing new\n") if $pr;
1001 return; # nothing to do
1003 $pr->("$i.git has $n changes since $cur\n") if $pr;
1005 $pr->("FAIL\n") if $pr;
1007 discontiguous range: $range
1008 Rewritten history? (in $git->{git_dir})
1010 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1012 $range = "$base..$tip";
1013 warn "found merge-base: $base\n"
1016 warn "discarding history at $cur\n";
1019 reindexing $git->{git_dir}
1022 # $cur^0 may no longer exist if pruned by git
1023 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1024 $unit->{unindex_range} = "$base..$cur";
1025 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1026 $unit->{unindex_range} = "$base..";
1028 warn "W: unable to unindex before $range\n";
1034 # overridden by ExtSearchIdx
1035 sub artnum_max { $_[0]->{mm}->num_highwater }
1037 sub sync_prepare ($$) {
1038 my ($self, $sync) = @_;
1039 $sync->{ranges} = sync_ranges($self, $sync);
1040 my $pr = $sync->{-opt}->{-progress};
1042 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1045 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1046 $pfx //= $sync->{ibx}->{inboxdir};
1050 if ($self->{ibx_map}) {
1051 # ExtSearchIdx won't index messages unless they're in
1052 # over.sqlite3 for a given inbox, so don't read beyond
1053 # what's in the per-inbox index.
1054 $reindex_heads = [];
1055 my $v = PublicInbox::Search::SCHEMA_VERSION;
1056 my $mm = $sync->{ibx}->mm;
1057 for my $i (0..$sync->{epoch_max}) {
1058 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1060 } elsif ($sync->{reindex}) { # V2 inbox
1061 # reindex stops at the current heads and we later
1062 # rerun index_sync without {reindex}
1063 $reindex_heads = $self->last_commits($sync);
1065 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1066 $sync->{index_oid} = $self->can('index_oid');
1068 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1069 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1070 my $git_dir = "$git_pfx/$i.git";
1071 -d $git_dir or next; # missing epochs are fine
1072 my $git = PublicInbox::Git->new($git_dir);
1073 my $unit = { git => $git, epoch => $i };
1075 if ($reindex_heads) {
1076 $tip = $head = $reindex_heads->[$i] or next;
1078 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1079 next if $?; # new repo
1082 my $range = log_range($sync, $unit, $tip) or next;
1083 # can't use 'rev-list --count' if we use --diff-filter
1084 $pr->("$pfx $i.git counting $range ... ") if $pr;
1085 # Don't bump num_highwater on --reindex by using {D}.
1086 # We intentionally do NOT use {D} in the non-reindex case
1087 # because we want NNTP article number gaps from unindexed
1088 # messages to show up in mirrors, too.
1089 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1090 my $stk = log2stack($sync, $git, $range);
1091 return 0 if $sync->{quit};
1092 my $nr = $stk ? $stk->num_records : 0;
1093 $pr->("$nr\n") if $pr;
1094 $unit->{stack} = $stk; # may be undef
1095 unshift @{$sync->{todo}}, $unit;
1098 return 0 if $sync->{quit};
1100 # XXX this should not happen unless somebody bypasses checks in
1101 # our code and blindly injects "d" file history into git repos
1102 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1103 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1104 local $self->{current_info} = 'leftover ';
1105 my $unindex_oid = $self->can('unindex_oid');
1106 for my $oid (@leftovers) {
1107 last if $sync->{quit};
1108 $oid = unpack('H*', $oid);
1109 my $req = { %$sync, oid => $oid };
1110 $self->git->cat_async($oid, $unindex_oid, $req);
1112 $self->git->cat_async_wait;
1114 return 0 if $sync->{quit};
1116 $sync->{-regen_fmt} = "%u/?\n";
1120 # reindex should NOT see new commits anymore, if we do,
1121 # it's a problem and we need to notice it via die()
1122 my $pad = length($regen_max) + 1;
1123 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1124 $sync->{nr} = \(my $nr = 0);
1125 return -1 if $sync->{reindex};
1126 $regen_max + $self->artnum_max || 0;
1129 sub unindex_oid_aux ($$$) {
1130 my ($self, $oid, $mid) = @_;
1131 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1132 for my $num (@removed) {
1133 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1137 sub unindex_oid ($$;$) { # git->cat_async callback
1138 my ($bref, $oid, $type, $size, $arg) = @_;
1139 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1140 return index_finalize($arg, 0);
1141 my $self = $arg->{self};
1142 local $self->{current_info} = "$self->{current_info} $oid";
1143 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1144 my $mm = $self->{mm};
1145 my $mids = mids(PublicInbox::Eml->new($bref));
1147 my $oidx = $self->{oidx};
1148 foreach my $mid (@$mids) {
1151 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1152 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1154 my $n = scalar(keys(%gone)) or next;
1156 warn "BUG: multiple articles linked to $oid\n",
1157 join(',',sort keys %gone), "\n";
1159 foreach my $num (keys %gone) {
1161 my $mid0 = $mm->mid_for($num);
1162 $unindexed->{$mid0} = $num;
1164 $mm->num_delete($num);
1166 unindex_oid_aux($self, $oid, $mid);
1168 index_finalize($arg, 0);
1171 sub git { $_[0]->{ibx}->git }
1173 # this is rare, it only happens when we get discontiguous history in
1174 # a mirror because the source used -purge or -edit
1175 sub unindex_todo ($$$) {
1176 my ($self, $sync, $unit) = @_;
1177 my $unindex_range = delete($unit->{unindex_range}) // return;
1178 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1179 my $before = scalar keys %$unindexed;
1180 # order does not matter, here:
1181 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1182 --no-abbrev --no-renames), $unindex_range);
1183 local $sync->{in_unindex} = 1;
1184 my $unindex_oid = $self->can('unindex_oid');
1186 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1187 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1189 close $fh or die "git log failed: \$?=$?";
1190 $self->git->cat_async_wait;
1192 return unless $sync->{-opt}->{prune};
1193 my $after = scalar keys %$unindexed;
1194 return if $before == $after;
1196 # ensure any blob can not longer be accessed via dumb HTTP
1197 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1198 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1201 sub sync_ranges ($$) {
1202 my ($self, $sync) = @_;
1203 my $reindex = $sync->{reindex};
1204 return $self->last_commits($sync) unless $reindex;
1205 return [] if ref($reindex) ne 'HASH';
1207 my $ranges = $reindex->{from}; # arrayref;
1208 if (ref($ranges) ne 'ARRAY') {
1209 die 'BUG: $reindex->{from} not an ARRAY';
1214 sub index_xap_only { # git->cat_async callback
1215 my ($bref, $oid, $type, $size, $smsg) = @_;
1216 my $self = $smsg->{self};
1217 my $idx = idx_shard($self, $smsg->{num});
1218 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1219 $self->{transact_bytes} += $smsg->{bytes};
1222 sub index_xap_step ($$$;$) {
1223 my ($self, $sync, $beg, $step) = @_;
1224 my $end = $sync->{art_end};
1225 return if $beg > $end; # nothing to do
1227 $step //= $self->{shards};
1228 my $ibx = $self->{ibx};
1229 if (my $pr = $sync->{-opt}->{-progress}) {
1230 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1231 "$beg..$end (% $step)\n");
1233 for (my $num = $beg; $num <= $end; $num += $step) {
1234 last if $sync->{quit};
1235 my $smsg = $ibx->over->get_art($num) or next;
1236 $smsg->{self} = $self;
1237 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1238 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1239 ${$sync->{nr}} = $num;
1240 reindex_checkpoint($self, $sync);
1245 sub index_todo ($$$) {
1246 my ($self, $sync, $unit) = @_;
1247 return if $sync->{quit};
1248 unindex_todo($self, $sync, $unit);
1249 my $stk = delete($unit->{stack}) or return;
1250 my $all = $self->git;
1251 my $index_oid = $self->can('index_oid');
1252 my $unindex_oid = $self->can('unindex_oid');
1254 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1255 $pfx = "$1 $2"; # v2
1257 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1258 $pfx //= $unit->{git}->{git_dir};
1260 local $self->{current_info} = "$pfx ";
1261 local $sync->{latest_cmt} = \(my $latest_cmt);
1262 local $sync->{unit} = $unit;
1263 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1264 if ($sync->{quit}) {
1265 warn "waiting to quit...\n";
1266 $all->async_wait_all;
1267 $self->update_last_commit($sync);
1278 if ($sync->{max_size}) {
1279 $all->check_async($oid, \&check_size, $req);
1281 $all->cat_async($oid, $index_oid, $req);
1283 } elsif ($f eq 'd') {
1284 $all->cat_async($oid, $unindex_oid, $req);
1286 if (${$sync->{need_checkpoint}}) {
1287 reindex_checkpoint($self, $sync);
1290 $all->async_wait_all;
1291 $self->update_last_commit($sync, $stk);
1295 my ($self, $opt, $sync, $art_beg) = @_;
1296 my $seq = $opt->{sequential_shard};
1298 local $self->{parallel} = 0 if $seq;
1299 $self->idx_init($opt); # acquire lock
1300 if (my $art_end = $self->{ibx}->mm->max) {
1302 need_checkpoint => \(my $bool = 0),
1305 nr => \(my $nr = 0),
1306 -regen_fmt => "%u/?\n",
1308 $sync->{art_end} = $art_end;
1309 if ($seq || !$self->{parallel}) {
1310 my $shard_end = $self->{shards} - 1;
1311 for my $i (0..$shard_end) {
1312 last if $sync->{quit};
1313 index_xap_step($self, $sync, $art_beg + $i);
1314 if ($i != $shard_end) {
1315 reindex_checkpoint($self, $sync);
1318 } else { # parallel (maybe)
1319 index_xap_step($self, $sync, $art_beg, 1);
1322 $self->git->cat_async_wait;
1326 # public, called by public-inbox-index
1328 my ($self, $opt) = @_;
1330 return xapian_only($self, $opt) if $opt->{xapian_only};
1333 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1334 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1335 use Time::HiRes qw(stat);
1336 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1337 my $c = $mm[10]; # 10 = ctime (nsec NV)
1338 my @hd = stat("$latest/refs/heads");
1339 my @pr = stat("$latest/packed-refs");
1340 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1344 my $pr = $opt->{-progress};
1345 my $seq = $opt->{sequential_shard};
1346 my $art_beg; # the NNTP article number we start xapian_only at
1347 my $idxlevel = $self->{ibx}->{indexlevel};
1348 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1350 $self->idx_init($opt); # acquire lock
1351 fill_alternates($self, $epoch_max);
1352 $self->{oidx}->rethread_prepare($opt);
1354 need_checkpoint => \(my $bool = 0),
1355 reindex => $opt->{reindex},
1358 ibx => $self->{ibx},
1359 epoch_max => $epoch_max,
1361 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1362 local $SIG{QUIT} = $quit;
1363 local $SIG{INT} = $quit;
1364 local $SIG{TERM} = $quit;
1366 if (sync_prepare($self, $sync)) {
1367 # tmp_clone seems to fail if inside a transaction, so
1368 # we rollback here (because we opened {mm} for reading)
1369 # Note: we do NOT rely on DBI transactions for atomicity;
1370 # only for batch performance.
1371 $self->{mm}->{dbh}->rollback;
1372 $self->{mm}->{dbh}->begin_work;
1374 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1376 # xapian_only works incrementally w/o --reindex
1377 if ($seq && !$opt->{reindex}) {
1378 $art_beg = $sync->{mm_tmp}->max || -1;
1382 # work forwards through history
1383 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1384 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1387 if (my $nr = $sync->{nr}) {
1388 my $pr = $sync->{-opt}->{-progress};
1389 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1393 # deal with Xapian shards sequentially
1394 if ($seq && delete($sync->{mm_tmp})) {
1395 if ($sync->{quit}) {
1398 $self->{ibx}->{indexlevel} = $idxlevel;
1399 xapian_only($self, $opt, $sync, $art_beg);
1400 $quit_warn = 1 if $sync->{quit};
1404 # --reindex on the command-line
1405 if (!$sync->{quit} && $opt->{reindex} &&
1406 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1407 $self->lock_acquire;
1408 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1409 if (my $xdb = $s0->idx_acquire) {
1410 my $n = $xdb->get_metadata('has_threadid');
1411 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1414 $self->lock_release;
1417 # reindex does not pick up new changes, so we rerun w/o it:
1418 if ($opt->{reindex} && !$sync->{quit}) {
1421 delete @again{qw(rethread reindex -skip_lock)};
1422 index_sync($self, \%again);
1423 $opt->{quit} = $again{quit}; # propagate to caller
1425 warn <<EOF if $quit_warn;
1426 W: interrupted, --xapian-only --reindex required upon restart