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 crlf_adjust is_ancestor check_size
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, $msgref, $eml, $smsg) = @_;
144 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
145 $self->{oidx}->add_overview($eml, $smsg);
146 my $idx = idx_shard($self, $smsg->{num});
147 $idx->index_eml($eml, $smsg);
148 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
149 $n >= $self->{batch_bytes};
153 my ($self, $mime, $check_cb) = @_;
157 $mime = $check_cb->($mime, $self->{ibx}) or return;
160 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
161 # as does SQLite 3.4.1+ (released in 2007-07-20), and
162 # Xapian 1.3.2+ (released 2015-03-15).
163 # For the most part, we can spawn git-fast-import without
164 # leaking FDs to it...
167 my ($num, $mid0) = v2_num_for($self, $mime);
168 defined $num or return; # duplicate
169 defined $mid0 or die "BUG: \$mid0 undefined\n";
170 my $im = $self->importer;
171 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
172 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
173 $cmt = $im->get_mark($cmt);
174 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
176 if (do_idx($self, delete $smsg->{-raw_email}, $mime, $smsg)) {
184 my ($self, $mime) = @_;
185 my $mids = mids($mime);
187 my $mid = $mids->[0];
188 my $num = $self->{mm}->mid_insert($mid);
189 if (defined $num) { # common case
193 # crap, Message-ID is already known, hope somebody just resent:
194 foreach my $m (@$mids) {
195 # read-only lookup now safe to do after above barrier
196 # easy, don't store duplicates
197 # note: do not add more diagnostic info here since
198 # it gets noisy on public-inbox-watch restarts
199 return () if content_exists($self, $mime, $m);
202 # AltId may pre-populate article numbers (e.g. X-Mail-Count
203 # or NNTP article number), use that article number if it's
205 my $altid = $self->{ibx}->{altid};
206 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
207 my $num = $self->{mm}->num_for($mid);
209 if (defined $num && !$self->{oidx}->get_art($num)) {
215 warn "<$mid> reused for mismatched content\n";
217 # try the rest of the mids
218 for(my $i = $#$mids; $i >= 1; $i--) {
220 $num = $self->{mm}->mid_insert($m);
222 warn "alternative <$m> for <$mid> found\n";
227 # none of the existing Message-IDs are good, generate a new one:
228 v2_num_for_harder($self, $mime);
231 sub v2_num_for_harder {
232 my ($self, $eml) = @_;
234 my $dig = content_digest($eml);
235 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
236 my $num = $self->{mm}->mid_insert($mid0);
237 unless (defined $num) {
238 # it's hard to spoof the last Received: header
239 my @recvd = $eml->header_raw('Received');
240 $dig->add("Received: $_") foreach (@recvd);
241 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
242 $num = $self->{mm}->mid_insert($mid0);
244 # fall back to a random Message-ID and give up determinism:
245 until (defined($num)) {
247 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
248 warn "using random Message-ID <$mid0> as fallback\n";
249 $num = $self->{mm}->mid_insert($mid0);
252 PublicInbox::Import::append_mid($eml, $mid0);
256 sub _idx_init { # with_umask callback
257 my ($self, $opt) = @_;
258 $self->lock_acquire unless $opt && $opt->{-skip_lock};
259 $self->{oidx}->create;
261 # xcpdb can change shard count while -watch is idle
262 my $nshards = count_shards($self);
263 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
264 $self->{batch_bytes} = $opt->{batch_size} //
265 $PublicInbox::SearchIdx::BATCH_BYTES;
267 # need to create all shards before initializing msgmap FD
268 # idx_shards must be visible to all forked processes
269 my $max = $self->{shards} - 1;
270 my $idx = $self->{idx_shards} = [];
271 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
273 # SearchIdxShard may do their own flushing, so don't scale
274 # until after forking
275 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
277 my $ibx = $self->{ibx} or return; # ExtIdxSearch
279 # Now that all subprocesses are up, we can open the FDs
281 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
282 "$ibx->{inboxdir}/msgmap.sqlite3",
283 $ibx->{-no_fsync} ? 2 : 1);
284 $mm->{dbh}->begin_work;
287 sub parallel_init ($$) {
288 my ($self, $indexlevel) = @_;
289 $self->{parallel} = 0 if ($indexlevel // 'full') eq 'basic';
294 my ($self, $opt) = @_;
295 return if $self->{idx_shards};
296 my $ibx = $self->{ibx};
298 # do not leak read-only FDs to child processes, we only have these
299 # FDs for duplicate detection so they should not be
300 # frequently activated.
301 delete @$ibx{qw(mm search)};
304 parallel_init($self, $ibx->{indexlevel});
305 $ibx->with_umask(\&_idx_init, $self, $opt);
308 # returns an array mapping [ epoch => latest_commit ]
309 # latest_commit may be undef if nothing was done to that epoch
310 # $replace_map = { $object_id => $strref, ... }
311 sub _replace_oids ($$$) {
312 my ($self, $mime, $replace_map) = @_;
314 my $ibx = $self->{ibx};
315 my $pfx = "$ibx->{inboxdir}/git";
316 my $rewrites = []; # epoch => commit
317 my $max = $self->{epoch_max} //= $ibx->max_git_epoch // return;
319 foreach my $i (0..$max) {
320 my $git_dir = "$pfx/$i.git";
322 my $git = PublicInbox::Git->new($git_dir);
323 my $im = $self->import_init($git, 0, 1);
324 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
330 sub content_hashes ($) {
332 my @chashes = ( content_hash($mime) );
334 # We still support Email::MIME, here, and
335 # Email::MIME->as_string doesn't always round-trip, so we may
336 # use a second content_hash
337 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
338 push @chashes, $rt if $chashes[0] ne $rt;
342 sub content_matches ($$) {
343 my ($chashes, $existing) = @_;
344 my $chash = content_hash($existing);
345 foreach (@$chashes) {
346 return 1 if $_ eq $chash
351 # used for removing or replacing (purging)
352 sub rewrite_internal ($$;$$$) {
353 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
355 my ($im, $need_reindex, $replace_map);
357 $replace_map = {}; # oid => sref
358 $need_reindex = [] if $new_eml;
360 $im = $self->importer;
362 my $oidx = $self->{oidx};
363 my $chashes = content_hashes($old_eml);
365 my $mids = mids($old_eml);
367 # We avoid introducing new blobs into git since the raw content
368 # can be slightly different, so we do not need the user-supplied
369 # message now that we have the mids and content_hash
373 foreach my $mid (@$mids) {
374 my %gone; # num => [ smsg, $mime, raw ]
376 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
377 my $msg = get_blob($self, $smsg);
378 if (!defined($msg)) {
379 warn "broken smsg for $mid\n";
383 my $cur = PublicInbox::Eml->new($msg);
384 if (content_matches($chashes, $cur)) {
385 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
388 my $n = scalar keys %gone;
391 warn "BUG: multiple articles linked to <$mid>\n",
392 join(',', sort keys %gone), "\n";
394 foreach my $num (keys %gone) {
395 my ($smsg, $mime, $orig) = @{$gone{$num}};
396 # $removed should only be set once assuming
397 # no bugs in our deduplication code:
398 $removed = [ undef, $mime, $smsg ];
399 my $oid = $smsg->{blob};
401 $replace_map->{$oid} = $sref;
403 ($mark, undef) = $im->remove($orig, $cmt_msg);
404 $removed->[0] = $mark;
407 if ($need_reindex) { # ->replace
408 push @$need_reindex, $smsg;
409 } else { # ->purge or ->remove
410 $self->{mm}->num_delete($num);
412 unindex_oid_aux($self, $oid, $mid);
417 my $cmt = $im->get_mark($mark);
418 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
420 if ($replace_map && scalar keys %$replace_map) {
421 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
422 return { rewrites => $rewrites, need_reindex => $need_reindex };
424 defined($mark) ? $removed : undef;
427 # public (see PublicInbox::Import->remove), but note the 3rd element
428 # (retval[2]) is not part of the stable API shared with Import->remove
430 my ($self, $eml, $cmt_msg) = @_;
431 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
432 $self, $eml, $cmt_msg);
433 defined($r) && defined($r->[0]) ? @$r: undef;
436 sub _replace ($$;$$) {
437 my ($self, $old_eml, $new_eml, $sref) = @_;
438 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
439 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
440 $self, $old_eml, undef, $new_eml, $sref) or return;
442 my $rewrites = $rewritten->{rewrites};
443 # ->done is called if there are rewrites since we gc+prune from git
444 $self->idx_init if @$rewrites;
446 for my $i (0..$#$rewrites) {
447 defined(my $cmt = $rewrites->[$i]) or next;
448 $self->{last_commit}->[$i] = $cmt;
455 my ($self, $mime) = @_;
456 my $rewritten = _replace($self, $mime, undef, \'') or return;
457 $rewritten->{rewrites}
460 # returns the git object_id of $fh, does not write the object to FS
461 sub git_hash_raw ($$) {
462 my ($self, $raw) = @_;
463 # grab the expected OID we have to reindex:
464 pipe(my($in, $w)) or die "pipe: $!";
465 my $git_dir = $self->git->{git_dir};
466 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
467 my $r = popen_rd($cmd, undef, { 0 => $in });
468 print $w $$raw or die "print \$w: $!";
469 close $w or die "close \$w: $!";
471 chomp(my $oid = <$r>);
472 close $r or die "git hash-object failed: $?";
473 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
477 sub _check_mids_match ($$$) {
478 my ($old_list, $new_list, $hdrs) = @_;
479 my %old_mids = map { $_ => 1 } @$old_list;
480 my %new_mids = map { $_ => 1 } @$new_list;
481 my @old = keys %old_mids;
482 my @new = keys %new_mids;
483 my $err = "$hdrs may not be changed when replacing\n";
484 die $err if scalar(@old) != scalar(@new);
485 delete @new_mids{@old};
486 delete @old_mids{@new};
487 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
490 # Changing Message-IDs or References with ->replace isn't supported.
491 # The rules for dealing with messages with multiple or conflicting
492 # Message-IDs are pretty complex and rethreading hasn't been fully
494 sub check_mids_match ($$) {
495 my ($old, $new) = @_;
496 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
497 _check_mids_match(references($old), references($new),
498 'References/In-Reply-To');
503 my ($self, $old_mime, $new_mime) = @_;
505 check_mids_match($old_mime, $new_mime);
507 # mutt will always add Content-Length:, Status:, Lines: when editing
508 PublicInbox::Import::drop_unwanted_headers($new_mime);
510 my $raw = $new_mime->as_string;
511 my $expect_oid = git_hash_raw($self, \$raw);
512 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
513 my $need_reindex = $rewritten->{need_reindex};
515 # just in case we have bugs in deduplication code:
516 my $n = scalar(@$need_reindex);
518 my $list = join(', ', map {
519 "$_->{num}: <$_->{mid}>"
522 W: rewritten $n messages matching content of original message (expected: 1).
523 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
528 # make sure we really got the OID:
529 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
530 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
532 # don't leak FDs to Xapian:
535 # reindex modified messages:
536 for my $smsg (@$need_reindex) {
537 my $new_smsg = bless {
542 }, 'PublicInbox::Smsg';
543 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
544 $new_smsg->populate($new_mime, $sync);
545 do_idx($self, \$raw, $new_mime, $new_smsg);
547 $rewritten->{rewrites};
550 sub last_epoch_commit ($$;$) {
551 my ($self, $i, $cmt) = @_;
552 my $v = PublicInbox::Search::SCHEMA_VERSION();
553 $self->{mm}->last_commit_xap($v, $i, $cmt);
556 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
558 defined(my $epoch_max = $self->{epoch_max}) or return;
559 my $last_commit = $self->{last_commit};
560 foreach my $i (0..$epoch_max) {
561 defined(my $cmt = $last_commit->[$i]) or next;
562 $last_commit->[$i] = undef;
563 last_epoch_commit($self, $i, $cmt);
568 sub checkpoint ($;$) {
569 my ($self, $wait) = @_;
571 if (my $im = $self->{im}) {
578 my $shards = $self->{idx_shards};
580 my $mm = $self->{mm};
581 my $dbh = $mm->{dbh} if $mm;
583 # SQLite msgmap data is second in importance
584 $dbh->commit if $dbh;
586 # SQLite overview is third
587 $self->{oidx}->commit_lazy;
589 # Now deal with Xapian
591 # start commit_txn_lazy asynchronously on all parallel shards
592 # (non-parallel waits here)
593 $_->ipc_do('commit_txn_lazy') for @$shards;
595 # transactions started on parallel shards,
596 # wait for them by issuing an echo command (echo can only
597 # run after commit_txn_lazy is done)
598 if ($wait && $self->{parallel}) {
600 for my $shard (@$shards) {
601 my $echo = $shard->ipc_do('echo', $i);
602 $echo == $i or die <<"";
603 shard[$i] bad echo:$echo != $i waiting for txn commit
609 my $midx = $self->{midx}; # misc index
610 $midx->commit_txn if $midx;
612 # last_commit is special, don't commit these until
613 # Xapian shards are done:
614 $dbh->begin_work if $dbh;
615 set_last_commits($self);
620 $midx->begin_txn if $midx;
622 $self->{total_bytes} += $self->{transact_bytes};
623 $self->{transact_bytes} = 0;
626 # issue a write barrier to ensure all data is visible to other processes
627 # and read-only ops. Order of data importance is: git > SQLite > Xapian
629 sub barrier { checkpoint($_[0], 1) };
631 # true if locked and active
632 sub active { !!$_[0]->{im} }
638 if (my $im = delete $self->{im}) {
639 eval { $im->done }; # PublicInbox::Import::done
640 $err .= "import done: $@\n" if $@;
643 eval { checkpoint($self) };
644 $err .= "checkpoint: $@\n" if $@;
646 if (my $mm = delete $self->{mm}) {
647 my $m = $err ? 'rollback' : 'commit';
648 eval { $mm->{dbh}->$m };
649 $err .= "msgmap $m: $@\n" if $@;
651 my $shards = delete $self->{idx_shards};
654 eval { $_->shard_close };
655 $err .= "shard close: $@\n" if $@;
658 eval { $self->{oidx}->dbh_close };
659 $err .= "over close: $@\n" if $@;
660 delete $self->{midx};
661 my $nbytes = $self->{total_bytes};
662 $self->{total_bytes} = 0;
663 $self->lock_release(!!$nbytes) if $shards;
668 sub write_alternates ($$$) {
669 my ($info_dir, $mode, $out) = @_;
670 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
671 my $tmp = $fh->filename;
672 print $fh @$out or die "print $tmp: $!\n";
673 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
674 close $fh or die "close $tmp $!\n";
675 my $alt = "$info_dir/alternates";
676 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
677 $fh->unlink_on_destroy(0);
680 sub fill_alternates ($$) {
681 my ($self, $epoch) = @_;
683 my $pfx = "$self->{ibx}->{inboxdir}/git";
684 my $all = "$self->{ibx}->{inboxdir}/all.git";
685 PublicInbox::Import::init_bare($all) unless -d $all;
686 my $info_dir = "$all/objects/info";
687 my $alt = "$info_dir/alternates";
691 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
692 $mode = (stat($fh))[2] & 07777;
694 # we assign a sort score to every alternate and favor
695 # the newest (highest numbered) one because loose objects
696 # require scanning epochs and only the latest epoch is
697 # expected to see loose objects
699 my $other = 0; # in case admin adds non-epoch repos
701 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
707 } split(/\n+/, do { local $/; <$fh> });
710 foreach my $i (0..$epoch) {
711 my $dir = "../../git/$i.git/objects";
712 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
718 write_alternates($info_dir, $mode,
719 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
723 my ($self, $epoch) = @_;
724 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
725 PublicInbox::Import::init_bare($git_dir);
726 run_die([qw(git config), "--file=$git_dir/config",
727 qw(include.path ../../all.git/config)]);
728 fill_alternates($self, $epoch);
734 my $im = $self->{im};
736 if ($im->{bytes_added} < $self->{rotate_bytes}) {
743 my $git_dir = $self->git_init(++$self->{epoch_max});
744 my $git = PublicInbox::Git->new($git_dir);
745 return $self->import_init($git, 0);
750 my $latest = $self->{ibx}->git_dir_latest(\$max);
751 if (defined $latest) {
752 my $git = PublicInbox::Git->new($latest);
753 my $packed_bytes = $git->packed_bytes;
754 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
756 if ($unpacked_bytes >= $self->{rotate_bytes}) {
759 $self->{epoch_max} = $max;
760 return $self->import_init($git, $packed_bytes);
763 $self->{epoch_max} = $epoch;
764 $latest = $self->git_init($epoch);
765 $self->import_init(PublicInbox::Git->new($latest), 0);
769 my ($self, $git, $packed_bytes, $tmp) = @_;
770 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
771 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
772 $im->{lock_path} = undef;
773 $im->{path_type} = 'v2';
774 $self->{im} = $im unless $tmp;
780 my ($mid, $cur, $new) = @_;
782 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
783 print $ah $cur->as_string or die "print: $!";
784 $ah->flush or die "flush: $!";
785 PublicInbox::Import::drop_unwanted_headers($new);
786 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
787 print $bh $new->as_string or die "print: $!";
788 $bh->flush or die "flush: $!";
789 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
790 print STDERR "# MID conflict <$mid>\n";
791 my $pid = spawn($cmd, undef, { 1 => 2 });
792 waitpid($pid, 0) == $pid or die "diff did not finish";
796 my ($self, $smsg) = @_;
797 if (my $im = $self->{im}) {
798 my $msg = $im->cat_blob($smsg->{blob});
801 # older message, should be in alternates
802 $self->{ibx}->msg_by_smsg($smsg);
805 sub content_exists ($$$) {
806 my ($self, $mime, $mid) = @_;
807 my $oidx = $self->{oidx};
808 my $chashes = content_hashes($mime);
810 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
811 my $msg = get_blob($self, $smsg);
812 if (!defined($msg)) {
813 warn "broken smsg for $mid\n";
816 my $cur = PublicInbox::Eml->new($msg);
817 return 1 if content_matches($chashes, $cur);
819 # XXX DEBUG_DIFF is experimental and may be removed
820 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
827 if (my $older_siblings = $self->{idx_shards}) {
828 $_->shard_atfork_child for @$older_siblings;
830 if (my $im = $self->{im}) {
833 die "BUG: unexpected mm" if $self->{mm};
836 sub reindex_checkpoint ($$) {
837 my ($self, $sync) = @_;
839 $self->git->async_wait_all;
840 $self->update_last_commit($sync);
841 ${$sync->{need_checkpoint}} = 0;
842 my $mm_tmp = $sync->{mm_tmp};
843 $mm_tmp->atfork_prepare if $mm_tmp;
844 die 'BUG: {im} during reindex' if $self->{im};
845 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
846 checkpoint($self, 1); # no need to release lock on pure index
848 $self->done; # release lock
851 if (my $pr = $sync->{-regen_fmt} ? $sync->{-opt}->{-progress} : undef) {
852 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
855 # allow -watch or -mda to write...
856 $self->idx_init($sync->{-opt}); # reacquire lock
857 if (my $intvl = $sync->{check_intvl}) { # eidx
858 $sync->{next_check} = PublicInbox::DS::now() + $intvl;
860 $mm_tmp->atfork_parent if $mm_tmp;
863 sub index_finalize ($$) {
864 my ($arg, $index) = @_;
865 ++$arg->{self}->{nidx};
866 if (defined(my $cur = $arg->{cur_cmt})) {
867 ${$arg->{latest_cmt}} = $cur;
869 die 'BUG: {cur_cmt} missing';
870 } # else { unindexing @leftovers doesn't set {cur_cmt}
873 sub index_oid { # cat_async callback
874 my ($bref, $oid, $type, $size, $arg) = @_;
875 is_bad_blob($oid, $type, $size, $arg->{oid}) and
876 return index_finalize($arg, 1); # size == 0 purged returns here
877 my $self = $arg->{self};
878 local $self->{current_info} = "$self->{current_info} $oid";
880 my $eml = PublicInbox::Eml->new($$bref);
881 my $mids = mids($eml);
882 my $chash = content_hash($eml);
884 if (scalar(@$mids) == 0) {
885 warn "E: $oid has no Message-ID, skipping\n";
889 # {unindexed} is unlikely
890 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
891 $num = delete($unindexed->{$mids->[0]});
894 $self->{mm}->mid_set($num, $mid0);
895 delete($arg->{unindexed}) if !keys(%$unindexed);
898 if (!defined($num)) { # reuse if reindexing (or duplicates)
899 my $oidx = $self->{oidx};
900 for my $mid (@$mids) {
901 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
902 last if defined $num;
905 $mid0 //= do { # is this a number we got before?
906 $num = $arg->{mm_tmp}->num_for($mids->[0]);
907 defined($num) ? $mids->[0] : undef;
909 if (!defined($num)) {
910 for (my $i = $#$mids; $i >= 1; $i--) {
911 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
919 $arg->{mm_tmp}->num_delete($num);
920 } else { # never seen
921 $num = $self->{mm}->mid_insert($mids->[0]);
924 } else { # rare, try the rest of them, backwards
925 for (my $i = $#$mids; $i >= 1; $i--) {
926 $num = $self->{mm}->mid_insert($mids->[$i]);
934 if (!defined($num)) {
935 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
944 }, 'PublicInbox::Smsg';
945 $smsg->populate($eml, $arg);
946 if (do_idx($self, $bref, $eml, $smsg)) {
947 ${$arg->{need_checkpoint}} = 1;
949 index_finalize($arg, 1);
952 # only update last_commit for $i on reindex iff newer than current
953 sub update_last_commit {
954 my ($self, $sync, $stk) = @_;
955 my $unit = $sync->{unit} // return;
956 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
957 defined($latest_cmt) or return;
958 my $last = last_epoch_commit($self, $unit->{epoch});
959 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
960 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
961 chomp(my $n = $unit->{git}->qx(@cmd));
962 return if $n ne '' && $n == 0;
964 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
968 my ($self, $sync) = @_;
970 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
971 $heads->[$i] = last_epoch_commit($self, $i);
976 # returns a revision range for git-log(1)
977 sub log_range ($$$) {
978 my ($sync, $unit, $tip) = @_;
979 my $opt = $sync->{-opt};
980 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
981 my $i = $unit->{epoch};
982 my $cur = $sync->{ranges}->[$i] or do {
983 $pr->("$i.git indexing all of $tip\n") if $pr;
984 return $tip; # all of it
987 # fast equality check to avoid (v)fork+execve overhead
989 $sync->{ranges}->[$i] = undef;
993 my $range = "$cur..$tip";
994 $pr->("$i.git checking contiguity... ") if $pr;
995 my $git = $unit->{git};
996 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
997 $pr->("OK\n") if $pr;
998 my $n = $git->qx(qw(rev-list --count), $range);
1001 $sync->{ranges}->[$i] = undef;
1002 $pr->("$i.git has nothing new\n") if $pr;
1003 return; # nothing to do
1005 $pr->("$i.git has $n changes since $cur\n") if $pr;
1007 $pr->("FAIL\n") if $pr;
1009 discontiguous range: $range
1010 Rewritten history? (in $git->{git_dir})
1012 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1014 $range = "$base..$tip";
1015 warn "found merge-base: $base\n"
1018 warn "discarding history at $cur\n";
1021 reindexing $git->{git_dir}
1024 # $cur^0 may no longer exist if pruned by git
1025 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1026 $unit->{unindex_range} = "$base..$cur";
1027 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1028 $unit->{unindex_range} = "$base..";
1030 warn "W: unable to unindex before $range\n";
1036 # overridden by ExtSearchIdx
1037 sub artnum_max { $_[0]->{mm}->num_highwater }
1039 sub sync_prepare ($$) {
1040 my ($self, $sync) = @_;
1041 $sync->{ranges} = sync_ranges($self, $sync);
1042 my $pr = $sync->{-opt}->{-progress};
1044 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1047 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1048 $pfx //= $sync->{ibx}->{inboxdir};
1052 if ($self->{ibx_map}) {
1053 # ExtSearchIdx won't index messages unless they're in
1054 # over.sqlite3 for a given inbox, so don't read beyond
1055 # what's in the per-inbox index.
1056 $reindex_heads = [];
1057 my $v = PublicInbox::Search::SCHEMA_VERSION;
1058 my $mm = $sync->{ibx}->mm;
1059 for my $i (0..$sync->{epoch_max}) {
1060 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1062 } elsif ($sync->{reindex}) { # V2 inbox
1063 # reindex stops at the current heads and we later
1064 # rerun index_sync without {reindex}
1065 $reindex_heads = $self->last_commits($sync);
1067 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1068 $sync->{index_oid} = $self->can('index_oid');
1070 my $git_pfx = "$sync->{ibx}->{inboxdir}/git";
1071 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1072 my $git_dir = "$git_pfx/$i.git";
1073 -d $git_dir or next; # missing epochs are fine
1074 my $git = PublicInbox::Git->new($git_dir);
1075 my $unit = { git => $git, epoch => $i };
1077 if ($reindex_heads) {
1078 $tip = $head = $reindex_heads->[$i] or next;
1080 $tip = $git->qx(qw(rev-parse -q --verify), $head);
1081 next if $?; # new repo
1084 my $range = log_range($sync, $unit, $tip) or next;
1085 # can't use 'rev-list --count' if we use --diff-filter
1086 $pr->("$pfx $i.git counting $range ... ") if $pr;
1087 # Don't bump num_highwater on --reindex by using {D}.
1088 # We intentionally do NOT use {D} in the non-reindex case
1089 # because we want NNTP article number gaps from unindexed
1090 # messages to show up in mirrors, too.
1091 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1092 my $stk = log2stack($sync, $git, $range);
1093 return 0 if $sync->{quit};
1094 my $nr = $stk ? $stk->num_records : 0;
1095 $pr->("$nr\n") if $pr;
1096 $unit->{stack} = $stk; # may be undef
1097 unshift @{$sync->{todo}}, $unit;
1100 return 0 if $sync->{quit};
1102 # XXX this should not happen unless somebody bypasses checks in
1103 # our code and blindly injects "d" file history into git repos
1104 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1105 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1106 local $self->{current_info} = 'leftover ';
1107 my $unindex_oid = $self->can('unindex_oid');
1108 for my $oid (@leftovers) {
1109 last if $sync->{quit};
1110 $oid = unpack('H*', $oid);
1111 my $req = { %$sync, oid => $oid };
1112 $self->git->cat_async($oid, $unindex_oid, $req);
1114 $self->git->cat_async_wait;
1116 return 0 if $sync->{quit};
1118 $sync->{-regen_fmt} = "%u/?\n";
1122 # reindex should NOT see new commits anymore, if we do,
1123 # it's a problem and we need to notice it via die()
1124 my $pad = length($regen_max) + 1;
1125 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1126 $sync->{nr} = \(my $nr = 0);
1127 return -1 if $sync->{reindex};
1128 $regen_max + $self->artnum_max || 0;
1131 sub unindex_oid_aux ($$$) {
1132 my ($self, $oid, $mid) = @_;
1133 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1134 for my $num (@removed) {
1135 idx_shard($self, $num)->ipc_do('xdb_remove', $num);
1139 sub unindex_oid ($$;$) { # git->cat_async callback
1140 my ($bref, $oid, $type, $size, $arg) = @_;
1141 is_bad_blob($oid, $type, $size, $arg->{oid}) and
1142 return index_finalize($arg, 0);
1143 my $self = $arg->{self};
1144 local $self->{current_info} = "$self->{current_info} $oid";
1145 my $unindexed = $arg->{in_unindex} ? $arg->{unindexed} : undef;
1146 my $mm = $self->{mm};
1147 my $mids = mids(PublicInbox::Eml->new($bref));
1149 my $oidx = $self->{oidx};
1150 foreach my $mid (@$mids) {
1153 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1154 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1156 my $n = scalar(keys(%gone)) or next;
1158 warn "BUG: multiple articles linked to $oid\n",
1159 join(',',sort keys %gone), "\n";
1161 foreach my $num (keys %gone) {
1163 my $mid0 = $mm->mid_for($num);
1164 $unindexed->{$mid0} = $num;
1166 $mm->num_delete($num);
1168 unindex_oid_aux($self, $oid, $mid);
1170 index_finalize($arg, 0);
1173 sub git { $_[0]->{ibx}->git }
1175 # this is rare, it only happens when we get discontiguous history in
1176 # a mirror because the source used -purge or -edit
1177 sub unindex_todo ($$$) {
1178 my ($self, $sync, $unit) = @_;
1179 my $unindex_range = delete($unit->{unindex_range}) // return;
1180 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1181 my $before = scalar keys %$unindexed;
1182 # order does not matter, here:
1183 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1184 --no-abbrev --no-renames), $unindex_range);
1185 local $sync->{in_unindex} = 1;
1186 my $unindex_oid = $self->can('unindex_oid');
1188 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1189 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1191 close $fh or die "git log failed: \$?=$?";
1192 $self->git->cat_async_wait;
1194 return unless $sync->{-opt}->{prune};
1195 my $after = scalar keys %$unindexed;
1196 return if $before == $after;
1198 # ensure any blob can not longer be accessed via dumb HTTP
1199 run_die(['git', "--git-dir=$unit->{git}->{git_dir}",
1200 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1203 sub sync_ranges ($$) {
1204 my ($self, $sync) = @_;
1205 my $reindex = $sync->{reindex};
1206 return $self->last_commits($sync) unless $reindex;
1207 return [] if ref($reindex) ne 'HASH';
1209 my $ranges = $reindex->{from}; # arrayref;
1210 if (ref($ranges) ne 'ARRAY') {
1211 die 'BUG: $reindex->{from} not an ARRAY';
1216 sub index_xap_only { # git->cat_async callback
1217 my ($bref, $oid, $type, $size, $smsg) = @_;
1218 my $self = $smsg->{self};
1219 my $idx = idx_shard($self, $smsg->{num});
1220 $smsg->{raw_bytes} = $size;
1221 $idx->index_eml(PublicInbox::Eml->new($bref), $smsg);
1222 $self->{transact_bytes} += $size;
1225 sub index_xap_step ($$$;$) {
1226 my ($self, $sync, $beg, $step) = @_;
1227 my $end = $sync->{art_end};
1228 return if $beg > $end; # nothing to do
1230 $step //= $self->{shards};
1231 my $ibx = $self->{ibx};
1232 if (my $pr = $sync->{-opt}->{-progress}) {
1233 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1234 "$beg..$end (% $step)\n");
1236 for (my $num = $beg; $num <= $end; $num += $step) {
1237 last if $sync->{quit};
1238 my $smsg = $ibx->over->get_art($num) or next;
1239 $smsg->{self} = $self;
1240 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1241 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1242 ${$sync->{nr}} = $num;
1243 reindex_checkpoint($self, $sync);
1248 sub index_todo ($$$) {
1249 my ($self, $sync, $unit) = @_;
1250 return if $sync->{quit};
1251 unindex_todo($self, $sync, $unit);
1252 my $stk = delete($unit->{stack}) or return;
1253 my $all = $self->git;
1254 my $index_oid = $self->can('index_oid');
1255 my $unindex_oid = $self->can('unindex_oid');
1257 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1258 $pfx = "$1 $2"; # v2
1260 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1261 $pfx //= $unit->{git}->{git_dir};
1263 local $self->{current_info} = "$pfx ";
1264 local $sync->{latest_cmt} = \(my $latest_cmt);
1265 local $sync->{unit} = $unit;
1266 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1267 if ($sync->{quit}) {
1268 warn "waiting to quit...\n";
1269 $all->async_wait_all;
1270 $self->update_last_commit($sync);
1281 if ($sync->{max_size}) {
1282 $all->check_async($oid, \&check_size, $req);
1284 $all->cat_async($oid, $index_oid, $req);
1286 } elsif ($f eq 'd') {
1287 $all->cat_async($oid, $unindex_oid, $req);
1289 if (${$sync->{need_checkpoint}}) {
1290 reindex_checkpoint($self, $sync);
1293 $all->async_wait_all;
1294 $self->update_last_commit($sync, $stk);
1298 my ($self, $opt, $sync, $art_beg) = @_;
1299 my $seq = $opt->{sequential_shard};
1301 local $self->{parallel} = 0 if $seq;
1302 $self->idx_init($opt); # acquire lock
1303 if (my $art_end = $self->{ibx}->mm->max) {
1305 need_checkpoint => \(my $bool = 0),
1308 nr => \(my $nr = 0),
1309 -regen_fmt => "%u/?\n",
1311 $sync->{art_end} = $art_end;
1312 if ($seq || !$self->{parallel}) {
1313 my $shard_end = $self->{shards} - 1;
1314 for my $i (0..$shard_end) {
1315 last if $sync->{quit};
1316 index_xap_step($self, $sync, $art_beg + $i);
1317 if ($i != $shard_end) {
1318 reindex_checkpoint($self, $sync);
1321 } else { # parallel (maybe)
1322 index_xap_step($self, $sync, $art_beg, 1);
1325 $self->git->cat_async_wait;
1329 # public, called by public-inbox-index
1331 my ($self, $opt) = @_;
1333 return xapian_only($self, $opt) if $opt->{xapian_only};
1336 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max) // return;
1337 if ($opt->{'fast-noop'}) { # nanosecond (st_ctim) comparison
1338 use Time::HiRes qw(stat);
1339 if (my @mm = stat("$self->{ibx}->{inboxdir}/msgmap.sqlite3")) {
1340 my $c = $mm[10]; # 10 = ctime (nsec NV)
1341 my @hd = stat("$latest/refs/heads");
1342 my @pr = stat("$latest/packed-refs");
1343 return if $c > ($hd[10] // 0) && $c > ($pr[10] // 0);
1347 my $pr = $opt->{-progress};
1348 my $seq = $opt->{sequential_shard};
1349 my $art_beg; # the NNTP article number we start xapian_only at
1350 my $idxlevel = $self->{ibx}->{indexlevel};
1351 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1353 $self->idx_init($opt); # acquire lock
1354 fill_alternates($self, $epoch_max);
1355 $self->{oidx}->rethread_prepare($opt);
1357 need_checkpoint => \(my $bool = 0),
1358 reindex => $opt->{reindex},
1361 ibx => $self->{ibx},
1362 epoch_max => $epoch_max,
1364 my $quit = PublicInbox::SearchIdx::quit_cb($sync);
1365 local $SIG{QUIT} = $quit;
1366 local $SIG{INT} = $quit;
1367 local $SIG{TERM} = $quit;
1369 if (sync_prepare($self, $sync)) {
1370 # tmp_clone seems to fail if inside a transaction, so
1371 # we rollback here (because we opened {mm} for reading)
1372 # Note: we do NOT rely on DBI transactions for atomicity;
1373 # only for batch performance.
1374 $self->{mm}->{dbh}->rollback;
1375 $self->{mm}->{dbh}->begin_work;
1377 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1379 # xapian_only works incrementally w/o --reindex
1380 if ($seq && !$opt->{reindex}) {
1381 $art_beg = $sync->{mm_tmp}->max || -1;
1385 # work forwards through history
1386 index_todo($self, $sync, $_) for @{delete($sync->{todo}) // []};
1387 $self->{oidx}->rethread_done($opt) unless $sync->{quit};
1390 if (my $nr = $sync->{nr}) {
1391 my $pr = $sync->{-opt}->{-progress};
1392 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1396 # deal with Xapian shards sequentially
1397 if ($seq && delete($sync->{mm_tmp})) {
1398 if ($sync->{quit}) {
1401 $self->{ibx}->{indexlevel} = $idxlevel;
1402 xapian_only($self, $opt, $sync, $art_beg);
1403 $quit_warn = 1 if $sync->{quit};
1407 # --reindex on the command-line
1408 if (!$sync->{quit} && $opt->{reindex} &&
1409 !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1410 $self->lock_acquire;
1411 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1412 if (my $xdb = $s0->idx_acquire) {
1413 my $n = $xdb->get_metadata('has_threadid');
1414 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1417 $self->lock_release;
1420 # reindex does not pick up new changes, so we rerun w/o it:
1421 if ($opt->{reindex} && !$sync->{quit}) {
1424 delete @again{qw(rethread reindex -skip_lock)};
1425 index_sync($self, \%again);
1426 $opt->{quit} = $again{quit}; # propagate to caller
1428 warn <<EOF if $quit_warn;
1429 W: interrupted, --xapian-only --reindex required upon restart