1 # Copyright (C) 2018-2020 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);
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 my $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} // do {
77 if ($self->xdb_sharded) {
78 $self->{nshard} // die 'BUG: {nshard} unset';
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 $v2ibx->umask_prepare;
102 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
105 im => undef, # PublicInbox::Import
111 oidx => PublicInbox::OverIdx->new("$xpfx/over.sqlite3"),
112 lock_path => "$dir/inbox.lock",
113 # limit each git repo (epoch) to 1GB or so
114 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
115 last_commit => [], # git epoch -> commit
117 $self->{oidx}->{-no_fsync} = 1 if $v2ibx->{-no_fsync};
118 $self->{shards} = count_shards($self) || nproc_shards($creat);
124 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
125 if (defined $shards) {
126 $self->{parallel} = 0 if $shards == 0;
127 $self->{shards} = $shards if $shards > 0;
130 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
132 $self->{ibx}->git_dir_latest(\$epoch_max);
133 if (defined $skip_epoch && $epoch_max == -1) {
134 $epoch_max = $skip_epoch;
136 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
140 # returns undef on duplicate or spam
141 # mimics Import::add and wraps it for v2
143 my ($self, $eml, $check_cb) = @_;
144 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
148 my ($self, $num) = @_;
149 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
152 # indexes a message, returns true if checkpointing is needed
154 my ($self, $msgref, $mime, $smsg) = @_;
155 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
156 $self->{oidx}->add_overview($mime, $smsg);
157 my $idx = idx_shard($self, $smsg->{num});
158 $idx->index_raw($msgref, $mime, $smsg);
159 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
160 $n >= $self->{batch_bytes};
164 my ($self, $mime, $check_cb) = @_;
168 $mime = $check_cb->($mime, $self->{ibx}) or return;
171 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
172 # as does SQLite 3.4.1+ (released in 2007-07-20), and
173 # Xapian 1.3.2+ (released 2015-03-15).
174 # For the most part, we can spawn git-fast-import without
175 # leaking FDs to it...
178 my ($num, $mid0) = v2_num_for($self, $mime);
179 defined $num or return; # duplicate
180 defined $mid0 or die "BUG: \$mid0 undefined\n";
181 my $im = $self->importer;
182 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
183 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
184 $cmt = $im->get_mark($cmt);
185 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
187 my $msgref = delete $smsg->{-raw_email};
188 if (do_idx($self, $msgref, $mime, $smsg)) {
196 my ($self, $mime) = @_;
197 my $mids = mids($mime);
199 my $mid = $mids->[0];
200 my $num = $self->{mm}->mid_insert($mid);
201 if (defined $num) { # common case
205 # crap, Message-ID is already known, hope somebody just resent:
206 foreach my $m (@$mids) {
207 # read-only lookup now safe to do after above barrier
208 # easy, don't store duplicates
209 # note: do not add more diagnostic info here since
210 # it gets noisy on public-inbox-watch restarts
211 return () if content_exists($self, $mime, $m);
214 # AltId may pre-populate article numbers (e.g. X-Mail-Count
215 # or NNTP article number), use that article number if it's
217 my $altid = $self->{ibx}->{altid};
218 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
219 my $num = $self->{mm}->num_for($mid);
221 if (defined $num && !$self->{oidx}->get_art($num)) {
227 warn "<$mid> reused for mismatched content\n";
229 # try the rest of the mids
230 for(my $i = $#$mids; $i >= 1; $i--) {
232 $num = $self->{mm}->mid_insert($m);
234 warn "alternative <$m> for <$mid> found\n";
239 # none of the existing Message-IDs are good, generate a new one:
240 v2_num_for_harder($self, $mime);
243 sub v2_num_for_harder {
244 my ($self, $eml) = @_;
246 my $dig = content_digest($eml);
247 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
248 my $num = $self->{mm}->mid_insert($mid0);
249 unless (defined $num) {
250 # it's hard to spoof the last Received: header
251 my @recvd = $eml->header_raw('Received');
252 $dig->add("Received: $_") foreach (@recvd);
253 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
254 $num = $self->{mm}->mid_insert($mid0);
256 # fall back to a random Message-ID and give up determinism:
257 until (defined($num)) {
259 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
260 warn "using random Message-ID <$mid0> as fallback\n";
261 $num = $self->{mm}->mid_insert($mid0);
264 PublicInbox::Import::append_mid($eml, $mid0);
268 sub _idx_init { # with_umask callback
269 my ($self, $opt) = @_;
270 $self->lock_acquire unless $opt && $opt->{-skip_lock};
271 $self->{oidx}->create;
273 # xcpdb can change shard count while -watch is idle
274 my $nshards = count_shards($self);
275 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
276 $self->{batch_bytes} = $opt->{batch_size} //
277 $PublicInbox::SearchIdx::BATCH_BYTES;
279 # need to create all shards before initializing msgmap FD
280 # idx_shards must be visible to all forked processes
281 my $max = $self->{shards} - 1;
282 my $idx = $self->{idx_shards} = [];
283 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
285 # SearchIdxShard may do their own flushing, so don't scale
286 # until after forking
287 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
289 my $ibx = $self->{ibx} or return; # ExtIdxSearch
291 # Now that all subprocesses are up, we can open the FDs
293 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
294 "$ibx->{inboxdir}/msgmap.sqlite3",
295 $ibx->{-no_fsync} ? 2 : 1);
296 $mm->{dbh}->begin_work;
299 sub parallel_init ($$) {
300 my ($self, $indexlevel) = @_;
301 if (($indexlevel // 'full') eq 'basic') {
302 $self->{parallel} = 0;
304 pipe(my ($r, $w)) or die "pipe failed: $!";
305 # pipe for barrier notifications doesn't need to be big,
307 fcntl($w, 1031, 4096) if $^O eq 'linux';
308 $self->{bnote} = [ $r, $w ];
315 my ($self, $opt) = @_;
316 return if $self->{idx_shards};
317 my $ibx = $self->{ibx};
319 # do not leak read-only FDs to child processes, we only have these
320 # FDs for duplicate detection so they should not be
321 # frequently activated.
322 delete @$ibx{qw(mm search)};
325 parallel_init($self, $ibx->{indexlevel});
327 $ibx->with_umask(\&_idx_init, $self, $opt);
330 # returns an array mapping [ epoch => latest_commit ]
331 # latest_commit may be undef if nothing was done to that epoch
332 # $replace_map = { $object_id => $strref, ... }
333 sub _replace_oids ($$$) {
334 my ($self, $mime, $replace_map) = @_;
336 my $ibx = $self->{ibx};
337 my $pfx = "$ibx->{inboxdir}/git";
338 my $rewrites = []; # epoch => commit
339 my $max = $self->{epoch_max};
341 unless (defined($max)) {
342 defined(my $latest = $ibx->git_dir_latest(\$max)) or return;
343 $self->{epoch_max} = $max;
346 foreach my $i (0..$max) {
347 my $git_dir = "$pfx/$i.git";
349 my $git = PublicInbox::Git->new($git_dir);
350 my $im = $self->import_init($git, 0, 1);
351 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
357 sub content_hashes ($) {
359 my @chashes = ( content_hash($mime) );
361 # We still support Email::MIME, here, and
362 # Email::MIME->as_string doesn't always round-trip, so we may
363 # use a second content_hash
364 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
365 push @chashes, $rt if $chashes[0] ne $rt;
369 sub content_matches ($$) {
370 my ($chashes, $existing) = @_;
371 my $chash = content_hash($existing);
372 foreach (@$chashes) {
373 return 1 if $_ eq $chash
378 # used for removing or replacing (purging)
379 sub rewrite_internal ($$;$$$) {
380 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
382 my ($im, $need_reindex, $replace_map);
384 $replace_map = {}; # oid => sref
385 $need_reindex = [] if $new_eml;
387 $im = $self->importer;
389 my $oidx = $self->{oidx};
390 my $chashes = content_hashes($old_eml);
392 my $mids = mids($old_eml);
394 # We avoid introducing new blobs into git since the raw content
395 # can be slightly different, so we do not need the user-supplied
396 # message now that we have the mids and content_hash
400 foreach my $mid (@$mids) {
401 my %gone; # num => [ smsg, $mime, raw ]
403 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
404 my $msg = get_blob($self, $smsg);
405 if (!defined($msg)) {
406 warn "broken smsg for $mid\n";
410 my $cur = PublicInbox::Eml->new($msg);
411 if (content_matches($chashes, $cur)) {
412 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
415 my $n = scalar keys %gone;
418 warn "BUG: multiple articles linked to <$mid>\n",
419 join(',', sort keys %gone), "\n";
421 foreach my $num (keys %gone) {
422 my ($smsg, $mime, $orig) = @{$gone{$num}};
423 # $removed should only be set once assuming
424 # no bugs in our deduplication code:
425 $removed = [ undef, $mime, $smsg ];
426 my $oid = $smsg->{blob};
428 $replace_map->{$oid} = $sref;
430 ($mark, undef) = $im->remove($orig, $cmt_msg);
431 $removed->[0] = $mark;
434 if ($need_reindex) { # ->replace
435 push @$need_reindex, $smsg;
436 } else { # ->purge or ->remove
437 $self->{mm}->num_delete($num);
439 unindex_oid_aux($self, $oid, $mid);
444 my $cmt = $im->get_mark($mark);
445 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
447 if ($replace_map && scalar keys %$replace_map) {
448 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
449 return { rewrites => $rewrites, need_reindex => $need_reindex };
451 defined($mark) ? $removed : undef;
454 # public (see PublicInbox::Import->remove), but note the 3rd element
455 # (retval[2]) is not part of the stable API shared with Import->remove
457 my ($self, $eml, $cmt_msg) = @_;
458 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
459 $self, $eml, $cmt_msg);
460 defined($r) && defined($r->[0]) ? @$r: undef;
463 sub _replace ($$;$$) {
464 my ($self, $old_eml, $new_eml, $sref) = @_;
465 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
466 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
467 $self, $old_eml, undef, $new_eml, $sref) or return;
469 my $rewrites = $rewritten->{rewrites};
470 # ->done is called if there are rewrites since we gc+prune from git
471 $self->idx_init if @$rewrites;
473 for my $i (0..$#$rewrites) {
474 defined(my $cmt = $rewrites->[$i]) or next;
475 $self->{last_commit}->[$i] = $cmt;
482 my ($self, $mime) = @_;
483 my $rewritten = _replace($self, $mime, undef, \'') or return;
484 $rewritten->{rewrites}
487 # returns the git object_id of $fh, does not write the object to FS
488 sub git_hash_raw ($$) {
489 my ($self, $raw) = @_;
490 # grab the expected OID we have to reindex:
491 pipe(my($in, $w)) or die "pipe: $!";
492 my $git_dir = $self->git->{git_dir};
493 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
494 my $r = popen_rd($cmd, undef, { 0 => $in });
495 print $w $$raw or die "print \$w: $!";
496 close $w or die "close \$w: $!";
498 chomp(my $oid = <$r>);
499 close $r or die "git hash-object failed: $?";
500 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
504 sub _check_mids_match ($$$) {
505 my ($old_list, $new_list, $hdrs) = @_;
506 my %old_mids = map { $_ => 1 } @$old_list;
507 my %new_mids = map { $_ => 1 } @$new_list;
508 my @old = keys %old_mids;
509 my @new = keys %new_mids;
510 my $err = "$hdrs may not be changed when replacing\n";
511 die $err if scalar(@old) != scalar(@new);
512 delete @new_mids{@old};
513 delete @old_mids{@new};
514 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
517 # Changing Message-IDs or References with ->replace isn't supported.
518 # The rules for dealing with messages with multiple or conflicting
519 # Message-IDs are pretty complex and rethreading hasn't been fully
521 sub check_mids_match ($$) {
522 my ($old, $new) = @_;
523 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
524 _check_mids_match(references($old), references($new),
525 'References/In-Reply-To');
530 my ($self, $old_mime, $new_mime) = @_;
532 check_mids_match($old_mime, $new_mime);
534 # mutt will always add Content-Length:, Status:, Lines: when editing
535 PublicInbox::Import::drop_unwanted_headers($new_mime);
537 my $raw = $new_mime->as_string;
538 my $expect_oid = git_hash_raw($self, \$raw);
539 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
540 my $need_reindex = $rewritten->{need_reindex};
542 # just in case we have bugs in deduplication code:
543 my $n = scalar(@$need_reindex);
545 my $list = join(', ', map {
546 "$_->{num}: <$_->{mid}>"
549 W: rewritten $n messages matching content of original message (expected: 1).
550 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
555 # make sure we really got the OID:
556 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
557 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
559 # don't leak FDs to Xapian:
562 # reindex modified messages:
563 for my $smsg (@$need_reindex) {
564 my $new_smsg = bless {
569 }, 'PublicInbox::Smsg';
570 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
571 $new_smsg->populate($new_mime, $sync);
572 do_idx($self, \$raw, $new_mime, $new_smsg);
574 $rewritten->{rewrites};
577 sub last_epoch_commit ($$;$) {
578 my ($self, $i, $cmt) = @_;
579 my $v = PublicInbox::Search::SCHEMA_VERSION();
580 $self->{mm}->last_commit_xap($v, $i, $cmt);
583 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
585 defined(my $epoch_max = $self->{epoch_max}) or return;
586 my $last_commit = $self->{last_commit};
587 foreach my $i (0..$epoch_max) {
588 defined(my $cmt = $last_commit->[$i]) or next;
589 $last_commit->[$i] = undef;
590 last_epoch_commit($self, $i, $cmt);
596 $self->{bnote} or return;
598 my $barrier = { map { $_ => 1 } (0..$n) };
602 my ($self, $barrier) = @_;
603 my $bnote = $self->{bnote} or return;
605 while (scalar keys %$barrier) {
606 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
607 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
608 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
613 sub checkpoint ($;$) {
614 my ($self, $wait) = @_;
616 if (my $im = $self->{im}) {
623 my $shards = $self->{idx_shards};
625 my $mm = $self->{mm};
626 my $dbh = $mm->{dbh} if $mm;
628 # SQLite msgmap data is second in importance
629 $dbh->commit if $dbh;
631 # SQLite overview is third
632 $self->{oidx}->commit_lazy;
634 # Now deal with Xapian
636 my $barrier = barrier_init($self, scalar @$shards);
638 # each shard needs to issue a barrier command
639 $_->shard_barrier for @$shards;
641 # wait for each Xapian shard
642 barrier_wait($self, $barrier);
644 $_->shard_commit for @$shards;
647 my $midx = $self->{midx}; # misc index
648 $midx->commit_txn if $midx;
650 # last_commit is special, don't commit these until
651 # Xapian shards are done:
652 $dbh->begin_work if $dbh;
653 set_last_commits($self);
658 $midx->begin_txn if $midx;
660 $self->{total_bytes} += $self->{transact_bytes};
661 $self->{transact_bytes} = 0;
664 # issue a write barrier to ensure all data is visible to other processes
665 # and read-only ops. Order of data importance is: git > SQLite > Xapian
667 sub barrier { checkpoint($_[0], 1) };
669 # true if locked and active
670 sub active { !!$_[0]->{im} }
676 if (my $im = delete $self->{im}) {
677 eval { $im->done }; # PublicInbox::Import::done
678 $err .= "import done: $@\n" if $@;
681 eval { checkpoint($self) };
682 $err .= "checkpoint: $@\n" if $@;
684 if (my $mm = delete $self->{mm}) {
685 my $m = $err ? 'rollback' : 'commit';
686 eval { $mm->{dbh}->$m };
687 $err .= "msgmap $m: $@\n" if $@;
689 my $shards = delete $self->{idx_shards};
692 eval { $_->shard_close };
693 $err .= "shard close: $@\n" if $@;
696 eval { $self->{oidx}->dbh_close };
697 $err .= "over close: $@\n" if $@;
698 delete $self->{midx};
699 delete $self->{bnote};
700 my $nbytes = $self->{total_bytes};
701 $self->{total_bytes} = 0;
702 $self->lock_release(!!$nbytes) if $shards;
707 sub write_alternates ($$$) {
708 my ($info_dir, $mode, $out) = @_;
709 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
710 my $tmp = $fh->filename;
711 print $fh @$out or die "print $tmp: $!\n";
712 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
713 close $fh or die "close $tmp $!\n";
714 my $alt = "$info_dir/alternates";
715 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
716 $fh->unlink_on_destroy(0);
719 sub fill_alternates ($$) {
720 my ($self, $epoch) = @_;
722 my $pfx = "$self->{ibx}->{inboxdir}/git";
723 my $all = "$self->{ibx}->{inboxdir}/all.git";
724 PublicInbox::Import::init_bare($all) unless -d $all;
725 my $info_dir = "$all/objects/info";
726 my $alt = "$info_dir/alternates";
730 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
731 $mode = (stat($fh))[2] & 07777;
733 # we assign a sort score to every alternate and favor
734 # the newest (highest numbered) one because loose objects
735 # require scanning epochs and only the latest epoch is
736 # expected to see loose objects
738 my $other = 0; # in case admin adds non-epoch repos
740 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
746 } split(/\n+/, do { local $/; <$fh> });
749 foreach my $i (0..$epoch) {
750 my $dir = "../../git/$i.git/objects";
751 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
757 write_alternates($info_dir, $mode,
758 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
762 my ($self, $epoch) = @_;
763 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
764 PublicInbox::Import::init_bare($git_dir);
765 my @cmd = (qw/git config/, "--file=$git_dir/config",
766 'include.path', '../../all.git/config');
767 PublicInbox::Import::run_die(\@cmd);
768 fill_alternates($self, $epoch);
774 my $im = $self->{im};
776 if ($im->{bytes_added} < $self->{rotate_bytes}) {
783 my $git_dir = $self->git_init(++$self->{epoch_max});
784 my $git = PublicInbox::Git->new($git_dir);
785 return $self->import_init($git, 0);
790 my $latest = $self->{ibx}->git_dir_latest(\$max);
791 if (defined $latest) {
792 my $git = PublicInbox::Git->new($latest);
793 my $packed_bytes = $git->packed_bytes;
794 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
796 if ($unpacked_bytes >= $self->{rotate_bytes}) {
799 $self->{epoch_max} = $max;
800 return $self->import_init($git, $packed_bytes);
803 $self->{epoch_max} = $epoch;
804 $latest = $self->git_init($epoch);
805 $self->import_init(PublicInbox::Git->new($latest), 0);
809 my ($self, $git, $packed_bytes, $tmp) = @_;
810 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
811 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
812 $im->{lock_path} = undef;
813 $im->{path_type} = 'v2';
814 $self->{im} = $im unless $tmp;
820 my ($mid, $cur, $new) = @_;
822 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
823 print $ah $cur->as_string or die "print: $!";
824 $ah->flush or die "flush: $!";
825 PublicInbox::Import::drop_unwanted_headers($new);
826 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
827 print $bh $new->as_string or die "print: $!";
828 $bh->flush or die "flush: $!";
829 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
830 print STDERR "# MID conflict <$mid>\n";
831 my $pid = spawn($cmd, undef, { 1 => 2 });
832 waitpid($pid, 0) == $pid or die "diff did not finish";
836 my ($self, $smsg) = @_;
837 if (my $im = $self->{im}) {
838 my $msg = $im->cat_blob($smsg->{blob});
841 # older message, should be in alternates
842 $self->{ibx}->msg_by_smsg($smsg);
845 sub content_exists ($$$) {
846 my ($self, $mime, $mid) = @_;
847 my $oidx = $self->{oidx};
848 my $chashes = content_hashes($mime);
850 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
851 my $msg = get_blob($self, $smsg);
852 if (!defined($msg)) {
853 warn "broken smsg for $mid\n";
856 my $cur = PublicInbox::Eml->new($msg);
857 return 1 if content_matches($chashes, $cur);
859 # XXX DEBUG_DIFF is experimental and may be removed
860 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
867 if (my $shards = $self->{idx_shards}) {
868 $_->atfork_child foreach @$shards;
870 if (my $im = $self->{im}) {
873 die "unexpected mm" if $self->{mm};
874 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
878 sub reindex_checkpoint ($$) {
879 my ($self, $sync) = @_;
881 $self->git->async_wait_all;
882 $self->update_last_commit($sync);
883 ${$sync->{need_checkpoint}} = 0;
884 my $mm_tmp = $sync->{mm_tmp};
885 $mm_tmp->atfork_prepare if $mm_tmp;
886 die 'BUG: {im} during reindex' if $self->{im};
887 if ($self->{ibx_map} && !$sync->{checkpoint_unlocks}) {
888 checkpoint($self, 1); # no need to release lock on pure index
890 $self->done; # release lock
893 if (my $pr = $sync->{-opt}->{-progress}) {
894 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
897 # allow -watch or -mda to write...
898 $self->idx_init($sync->{-opt}); # reacquire lock
899 $mm_tmp->atfork_parent if $mm_tmp;
902 sub index_oid { # cat_async callback
903 my ($bref, $oid, $type, $size, $arg) = @_;
904 return if is_bad_blob($oid, $type, $size, $arg->{oid});
905 my $self = $arg->{self};
906 local $self->{current_info} = "$self->{current_info} $oid";
907 return if $size == 0; # purged
909 my $eml = PublicInbox::Eml->new($$bref);
910 my $mids = mids($eml);
911 my $chash = content_hash($eml);
913 if (scalar(@$mids) == 0) {
914 warn "E: $oid has no Message-ID, skipping\n";
918 # {unindexed} is unlikely
919 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
920 $num = delete($unindexed->{$mids->[0]});
923 $self->{mm}->mid_set($num, $mid0);
924 delete($arg->{unindexed}) if !keys(%$unindexed);
927 if (!defined($num)) { # reuse if reindexing (or duplicates)
928 my $oidx = $self->{oidx};
929 for my $mid (@$mids) {
930 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
931 last if defined $num;
934 $mid0 //= do { # is this a number we got before?
935 $num = $arg->{mm_tmp}->num_for($mids->[0]);
936 defined($num) ? $mids->[0] : undef;
938 if (!defined($num)) {
939 for (my $i = $#$mids; $i >= 1; $i--) {
940 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
948 $arg->{mm_tmp}->num_delete($num);
949 } else { # never seen
950 $num = $self->{mm}->mid_insert($mids->[0]);
953 } else { # rare, try the rest of them, backwards
954 for (my $i = $#$mids; $i >= 1; $i--) {
955 $num = $self->{mm}->mid_insert($mids->[$i]);
963 if (!defined($num)) {
964 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
973 }, 'PublicInbox::Smsg';
974 $smsg->populate($eml, $arg);
975 if (do_idx($self, $bref, $eml, $smsg)) {
976 ${$arg->{need_checkpoint}} = 1;
978 ${$arg->{latest_cmt}} = $arg->{cur_cmt} // die 'BUG: {cur_cmt} missing';
981 # only update last_commit for $i on reindex iff newer than current
982 sub update_last_commit {
983 my ($self, $sync, $stk) = @_;
984 my $unit = $sync->{unit} // return;
985 my $latest_cmt = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
986 defined($latest_cmt) or return;
987 my $last = last_epoch_commit($self, $unit->{epoch});
988 if (defined $last && is_ancestor($self->git, $last, $latest_cmt)) {
989 my @cmd = (qw(rev-list --count), "$last..$latest_cmt");
990 chomp(my $n = $unit->{git}->qx(@cmd));
991 return if $n ne '' && $n == 0;
993 last_epoch_commit($self, $unit->{epoch}, $latest_cmt);
997 my ($self, $sync) = @_;
999 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1000 $heads->[$i] = last_epoch_commit($self, $i);
1005 # returns a revision range for git-log(1)
1006 sub log_range ($$$) {
1007 my ($sync, $unit, $tip) = @_;
1008 my $opt = $sync->{-opt};
1009 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1010 my $i = $unit->{epoch};
1011 my $cur = $sync->{ranges}->[$i] or do {
1012 $pr->("$i.git indexing all of $tip\n") if $pr;
1013 return $tip; # all of it
1016 # fast equality check to avoid (v)fork+execve overhead
1018 $sync->{ranges}->[$i] = undef;
1022 my $range = "$cur..$tip";
1023 $pr->("$i.git checking contiguity... ") if $pr;
1024 my $git = $unit->{git};
1025 if (is_ancestor($sync->{self}->git, $cur, $tip)) { # common case
1026 $pr->("OK\n") if $pr;
1027 my $n = $git->qx(qw(rev-list --count), $range);
1030 $sync->{ranges}->[$i] = undef;
1031 $pr->("$i.git has nothing new\n") if $pr;
1032 return; # nothing to do
1034 $pr->("$i.git has $n changes since $cur\n") if $pr;
1036 $pr->("FAIL\n") if $pr;
1038 discontiguous range: $range
1039 Rewritten history? (in $git->{git_dir})
1041 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1043 $range = "$base..$tip";
1044 warn "found merge-base: $base\n"
1047 warn "discarding history at $cur\n";
1050 reindexing $git->{git_dir}
1053 # $cur^0 may no longer exist if pruned by git
1054 if ($git->qx(qw(rev-parse -q --verify), "$cur^0")) {
1055 $unit->{unindex_range} = "$base..$cur";
1056 } elsif ($base && $git->qx(qw(rev-parse -q --verify), $base)) {
1057 $unit->{unindex_range} = "$base..";
1059 warn "W: unable to unindex before $range\n";
1065 # overridden by ExtSearchIdx
1066 sub artnum_max { $_[0]->{mm}->num_highwater }
1068 sub sync_prepare ($$) {
1069 my ($self, $sync) = @_;
1070 $sync->{ranges} = sync_ranges($self, $sync);
1071 my $pr = $sync->{-opt}->{-progress};
1073 my $head = $sync->{ibx}->{ref_head} || 'HEAD';
1076 ($pfx) = ($sync->{ibx}->{inboxdir} =~ m!([^/]+)\z!g);
1077 $pfx //= $sync->{ibx}->{inboxdir};
1081 if ($self->{ibx_map}) {
1082 # ExtSearchIdx won't index messages unless they're in
1083 # over.sqlite3 for a given inbox, so don't read beyond
1084 # what's in the per-inbox index.
1085 $reindex_heads = [];
1086 my $v = PublicInbox::Search::SCHEMA_VERSION;
1087 my $mm = $sync->{ibx}->mm;
1088 for my $i (0..$sync->{epoch_max}) {
1089 $reindex_heads->[$i] = $mm->last_commit_xap($v, $i);
1091 } elsif ($sync->{reindex}) { # V2 inbox
1092 # reindex stops at the current heads and we later
1093 # rerun index_sync without {reindex}
1094 $reindex_heads = $self->last_commits($sync);
1096 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1097 $sync->{index_oid} = $self->can('index_oid');
1099 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1100 my $git_dir = $sync->{ibx}->git_dir_n($i);
1101 -d $git_dir or next; # missing epochs are fine
1102 my $git = PublicInbox::Git->new($git_dir);
1103 my $unit = { git => $git, epoch => $i };
1104 if ($reindex_heads) {
1105 $head = $reindex_heads->[$i] or next;
1107 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1108 next if $?; # new repo
1110 my $range = log_range($sync, $unit, $tip) or next;
1111 # can't use 'rev-list --count' if we use --diff-filter
1112 $pr->("$pfx $i.git counting $range ... ") if $pr;
1113 # Don't bump num_highwater on --reindex by using {D}.
1114 # We intentionally do NOT use {D} in the non-reindex case
1115 # because we want NNTP article number gaps from unindexed
1116 # messages to show up in mirrors, too.
1117 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1118 my $stk = log2stack($sync, $git, $range);
1119 return 0 if $sync->{quit};
1120 my $nr = $stk ? $stk->num_records : 0;
1121 $pr->("$nr\n") if $pr;
1122 $unit->{stack} = $stk; # may be undef
1123 unshift @{$sync->{todo}}, $unit;
1126 return 0 if $sync->{quit};
1128 # XXX this should not happen unless somebody bypasses checks in
1129 # our code and blindly injects "d" file history into git repos
1130 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1131 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1132 local $self->{current_info} = 'leftover ';
1133 my $unindex_oid = $self->can('unindex_oid');
1134 for my $oid (@leftovers) {
1135 last if $sync->{quit};
1136 $oid = unpack('H*', $oid);
1137 my $req = { %$sync, oid => $oid };
1138 $self->git->cat_async($oid, $unindex_oid, $req);
1140 $self->git->cat_async_wait;
1142 return 0 if $sync->{quit};
1144 $sync->{-regen_fmt} = "%u/?\n";
1148 # reindex should NOT see new commits anymore, if we do,
1149 # it's a problem and we need to notice it via die()
1150 my $pad = length($regen_max) + 1;
1151 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1152 $sync->{nr} = \(my $nr = 0);
1153 return -1 if $sync->{reindex};
1154 $regen_max + $self->artnum_max || 0;
1157 sub unindex_oid_aux ($$$) {
1158 my ($self, $oid, $mid) = @_;
1159 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1160 for my $num (@removed) {
1161 my $idx = idx_shard($self, $num);
1162 $idx->shard_remove($num);
1166 sub unindex_oid ($$;$) { # git->cat_async callback
1167 my ($bref, $oid, $type, $size, $sync) = @_;
1168 return if is_bad_blob($oid, $type, $size, $sync->{oid});
1169 my $self = $sync->{self};
1170 local $self->{current_info} = "$self->{current_info} $oid";
1171 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1172 my $mm = $self->{mm};
1173 my $mids = mids(PublicInbox::Eml->new($bref));
1175 my $oidx = $self->{oidx};
1176 foreach my $mid (@$mids) {
1179 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1180 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1182 my $n = scalar(keys(%gone)) or next;
1184 warn "BUG: multiple articles linked to $oid\n",
1185 join(',',sort keys %gone), "\n";
1187 foreach my $num (keys %gone) {
1189 my $mid0 = $mm->mid_for($num);
1190 $unindexed->{$mid0} = $num;
1192 $mm->num_delete($num);
1194 unindex_oid_aux($self, $oid, $mid);
1198 sub git { $_[0]->{ibx}->git }
1200 # this is rare, it only happens when we get discontiguous history in
1201 # a mirror because the source used -purge or -edit
1202 sub unindex_todo ($$$) {
1203 my ($self, $sync, $unit) = @_;
1204 my $unindex_range = delete($unit->{unindex_range}) // return;
1205 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1206 my $before = scalar keys %$unindexed;
1207 # order does not matter, here:
1208 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1209 --no-abbrev --no-renames), $unindex_range);
1210 local $sync->{in_unindex} = 1;
1211 my $unindex_oid = $self->can('unindex_oid');
1213 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1214 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1216 close $fh or die "git log failed: \$?=$?";
1217 $self->git->cat_async_wait;
1219 return unless $sync->{-opt}->{prune};
1220 my $after = scalar keys %$unindexed;
1221 return if $before == $after;
1223 # ensure any blob can not longer be accessed via dumb HTTP
1224 PublicInbox::Import::run_die(['git',
1225 "--git-dir=$unit->{git}->{git_dir}",
1226 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1229 sub sync_ranges ($$) {
1230 my ($self, $sync) = @_;
1231 my $reindex = $sync->{reindex};
1232 return $self->last_commits($sync) unless $reindex;
1233 return [] if ref($reindex) ne 'HASH';
1235 my $ranges = $reindex->{from}; # arrayref;
1236 if (ref($ranges) ne 'ARRAY') {
1237 die 'BUG: $reindex->{from} not an ARRAY';
1242 sub index_xap_only { # git->cat_async callback
1243 my ($bref, $oid, $type, $size, $smsg) = @_;
1244 my $self = $smsg->{self};
1245 my $idx = idx_shard($self, $smsg->{num});
1246 $smsg->{raw_bytes} = $size;
1247 $idx->index_raw($bref, undef, $smsg);
1248 $self->{transact_bytes} += $size;
1251 sub index_xap_step ($$$;$) {
1252 my ($self, $sync, $beg, $step) = @_;
1253 my $end = $sync->{art_end};
1254 return if $beg > $end; # nothing to do
1256 $step //= $self->{shards};
1257 my $ibx = $self->{ibx};
1258 if (my $pr = $sync->{-opt}->{-progress}) {
1259 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1260 "$beg..$end (% $step)\n");
1262 for (my $num = $beg; $num <= $end; $num += $step) {
1263 last if $sync->{quit};
1264 my $smsg = $ibx->over->get_art($num) or next;
1265 $smsg->{self} = $self;
1266 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1267 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1268 ${$sync->{nr}} = $num;
1269 reindex_checkpoint($self, $sync);
1274 sub index_todo ($$$) {
1275 my ($self, $sync, $unit) = @_;
1276 return if $sync->{quit};
1277 unindex_todo($self, $sync, $unit);
1278 my $stk = delete($unit->{stack}) or return;
1279 my $all = $self->git;
1280 my $index_oid = $self->can('index_oid');
1281 my $unindex_oid = $self->can('unindex_oid');
1283 if ($unit->{git}->{git_dir} =~ m!/([^/]+)/git/([0-9]+\.git)\z!) {
1284 $pfx = "$1 $2"; # v2
1286 ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1287 $pfx //= $unit->{git}->{git_dir};
1289 local $self->{current_info} = "$pfx ";
1290 local $sync->{latest_cmt} = \(my $latest_cmt);
1291 local $sync->{unit} = $unit;
1292 while (my ($f, $at, $ct, $oid, $cmt) = $stk->pop_rec) {
1293 if ($sync->{quit}) {
1294 warn "waiting to quit...\n";
1295 $all->async_wait_all;
1296 $self->update_last_commit($sync);
1307 if ($sync->{max_size}) {
1308 $all->check_async($oid, \&check_size, $req);
1310 $all->cat_async($oid, $index_oid, $req);
1312 } elsif ($f eq 'd') {
1313 $all->cat_async($oid, $unindex_oid, $req);
1315 if (${$sync->{need_checkpoint}}) {
1316 reindex_checkpoint($self, $sync);
1319 $all->async_wait_all;
1320 $self->update_last_commit($sync, $stk);
1324 my ($self, $opt, $sync, $art_beg) = @_;
1325 my $seq = $opt->{sequential_shard};
1327 local $self->{parallel} = 0 if $seq;
1328 $self->idx_init($opt); # acquire lock
1329 if (my $art_end = $self->{ibx}->mm->max) {
1331 need_checkpoint => \(my $bool = 0),
1334 nr => \(my $nr = 0),
1335 -regen_fmt => "%u/?\n",
1337 $sync->{art_end} = $art_end;
1338 if ($seq || !$self->{parallel}) {
1339 my $shard_end = $self->{shards} - 1;
1340 for my $i (0..$shard_end) {
1341 last if $sync->{quit};
1342 index_xap_step($self, $sync, $art_beg + $i);
1343 if ($i != $shard_end) {
1344 reindex_checkpoint($self, $sync);
1347 } else { # parallel (maybe)
1348 index_xap_step($self, $sync, $art_beg, 1);
1351 $self->git->cat_async_wait;
1355 # public, called by public-inbox-index
1357 my ($self, $opt) = @_;
1359 return xapian_only($self, $opt) if $opt->{xapian_only};
1361 my $pr = $opt->{-progress};
1363 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1364 return unless defined $latest;
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