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);
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 my $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 ($) {
69 # always load existing shards in case core count changes:
70 # Also, shard count may change while -watch is running
71 my $srch = $self->{ibx}->search or return 0;
72 delete $self->{ibx}->{search};
74 } : $self->{nshard}; # self->{nshard} is for ExtSearchIdx
78 # $creat may be any true value, or 0/undef. A hashref is true,
79 # and $creat->{nproc} may be set to an integer
80 my ($class, $v2ibx, $creat) = @_;
81 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
82 my $dir = $v2ibx->assert_usable_dir;
86 File::Path::mkpath($dir);
88 die "$dir does not exist\n";
91 $v2ibx->umask_prepare;
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;
123 $self->{ibx}->git_dir_latest(\$epoch_max);
124 if (defined $skip_epoch && $epoch_max == -1) {
125 $epoch_max = $skip_epoch;
127 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
131 # returns undef on duplicate or spam
132 # mimics Import::add and wraps it for v2
134 my ($self, $eml, $check_cb) = @_;
135 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
139 my ($self, $num) = @_;
140 $self->{idx_shards}->[$num % scalar(@{$self->{idx_shards}})];
143 # indexes a message, returns true if checkpointing is needed
145 my ($self, $msgref, $mime, $smsg) = @_;
146 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
147 $self->{oidx}->add_overview($mime, $smsg);
148 my $idx = idx_shard($self, $smsg->{num});
149 $idx->index_raw($msgref, $mime, $smsg);
150 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
151 $n >= $self->{batch_bytes};
155 my ($self, $mime, $check_cb) = @_;
159 $mime = $check_cb->($mime, $self->{ibx}) or return;
162 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
163 # as does SQLite 3.4.1+ (released in 2007-07-20), and
164 # Xapian 1.3.2+ (released 2015-03-15).
165 # For the most part, we can spawn git-fast-import without
166 # leaking FDs to it...
169 my ($num, $mid0) = v2_num_for($self, $mime);
170 defined $num or return; # duplicate
171 defined $mid0 or die "BUG: \$mid0 undefined\n";
172 my $im = $self->importer;
173 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
174 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
175 $cmt = $im->get_mark($cmt);
176 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
178 my $msgref = delete $smsg->{-raw_email};
179 if (do_idx($self, $msgref, $mime, $smsg)) {
187 my ($self, $mime) = @_;
188 my $mids = mids($mime);
190 my $mid = $mids->[0];
191 my $num = $self->{mm}->mid_insert($mid);
192 if (defined $num) { # common case
196 # crap, Message-ID is already known, hope somebody just resent:
197 foreach my $m (@$mids) {
198 # read-only lookup now safe to do after above barrier
199 # easy, don't store duplicates
200 # note: do not add more diagnostic info here since
201 # it gets noisy on public-inbox-watch restarts
202 return () if content_exists($self, $mime, $m);
205 # AltId may pre-populate article numbers (e.g. X-Mail-Count
206 # or NNTP article number), use that article number if it's
208 my $altid = $self->{ibx}->{altid};
209 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
210 my $num = $self->{mm}->num_for($mid);
212 if (defined $num && !$self->{oidx}->get_art($num)) {
218 warn "<$mid> reused for mismatched content\n";
220 # try the rest of the mids
221 for(my $i = $#$mids; $i >= 1; $i--) {
223 $num = $self->{mm}->mid_insert($m);
225 warn "alternative <$m> for <$mid> found\n";
230 # none of the existing Message-IDs are good, generate a new one:
231 v2_num_for_harder($self, $mime);
234 sub v2_num_for_harder {
235 my ($self, $eml) = @_;
237 my $dig = content_digest($eml);
238 my $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
239 my $num = $self->{mm}->mid_insert($mid0);
240 unless (defined $num) {
241 # it's hard to spoof the last Received: header
242 my @recvd = $eml->header_raw('Received');
243 $dig->add("Received: $_") foreach (@recvd);
244 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
245 $num = $self->{mm}->mid_insert($mid0);
247 # fall back to a random Message-ID and give up determinism:
248 until (defined($num)) {
250 $mid0 = PublicInbox::Import::digest2mid($dig, $eml);
251 warn "using random Message-ID <$mid0> as fallback\n";
252 $num = $self->{mm}->mid_insert($mid0);
255 PublicInbox::Import::append_mid($eml, $mid0);
259 sub _idx_init { # with_umask callback
260 my ($self, $opt) = @_;
261 $self->lock_acquire unless $opt && $opt->{-skip_lock};
262 $self->{oidx}->create;
264 # xcpdb can change shard count while -watch is idle
265 my $nshards = count_shards($self);
266 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
267 $self->{batch_bytes} = $opt->{batch_size} //
268 $PublicInbox::SearchIdx::BATCH_BYTES;
269 $self->{batch_bytes} *= $self->{shards} if $self->{parallel};
271 # need to create all shards before initializing msgmap FD
272 # idx_shards must be visible to all forked processes
273 my $max = $self->{shards} - 1;
274 my $idx = $self->{idx_shards} = [];
275 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
276 my $ibx = $self->{ibx} or return; # ExtIdxSearch
278 # Now that all subprocesses are up, we can open the FDs
280 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
281 "$ibx->{inboxdir}/msgmap.sqlite3",
282 $ibx->{-no_fsync} ? 2 : 1);
283 $mm->{dbh}->begin_work;
286 sub parallel_init ($$) {
287 my ($self, $indexlevel) = @_;
288 if (($indexlevel // 'full') eq 'basic') {
289 $self->{parallel} = 0;
291 pipe(my ($r, $w)) or die "pipe failed: $!";
292 # pipe for barrier notifications doesn't need to be big,
294 fcntl($w, 1031, 4096) if $^O eq 'linux';
295 $self->{bnote} = [ $r, $w ];
302 my ($self, $opt) = @_;
303 return if $self->{idx_shards};
304 my $ibx = $self->{ibx};
306 # do not leak read-only FDs to child processes, we only have these
307 # FDs for duplicate detection so they should not be
308 # frequently activated.
309 delete @$ibx{qw(mm search)};
312 parallel_init($self, $ibx->{indexlevel});
314 $ibx->with_umask(\&_idx_init, $self, $opt);
317 # returns an array mapping [ epoch => latest_commit ]
318 # latest_commit may be undef if nothing was done to that epoch
319 # $replace_map = { $object_id => $strref, ... }
320 sub _replace_oids ($$$) {
321 my ($self, $mime, $replace_map) = @_;
323 my $ibx = $self->{ibx};
324 my $pfx = "$ibx->{inboxdir}/git";
325 my $rewrites = []; # epoch => commit
326 my $max = $self->{epoch_max};
328 unless (defined($max)) {
329 defined(my $latest = $ibx->git_dir_latest(\$max)) or return;
330 $self->{epoch_max} = $max;
333 foreach my $i (0..$max) {
334 my $git_dir = "$pfx/$i.git";
336 my $git = PublicInbox::Git->new($git_dir);
337 my $im = $self->import_init($git, 0, 1);
338 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
344 sub content_hashes ($) {
346 my @chashes = ( content_hash($mime) );
348 # We still support Email::MIME, here, and
349 # Email::MIME->as_string doesn't always round-trip, so we may
350 # use a second content_hash
351 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
352 push @chashes, $rt if $chashes[0] ne $rt;
356 sub content_matches ($$) {
357 my ($chashes, $existing) = @_;
358 my $chash = content_hash($existing);
359 foreach (@$chashes) {
360 return 1 if $_ eq $chash
365 # used for removing or replacing (purging)
366 sub rewrite_internal ($$;$$$) {
367 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
369 my ($im, $need_reindex, $replace_map);
371 $replace_map = {}; # oid => sref
372 $need_reindex = [] if $new_eml;
374 $im = $self->importer;
376 my $oidx = $self->{oidx};
377 my $chashes = content_hashes($old_eml);
379 my $mids = mids($old_eml);
381 # We avoid introducing new blobs into git since the raw content
382 # can be slightly different, so we do not need the user-supplied
383 # message now that we have the mids and content_hash
387 foreach my $mid (@$mids) {
388 my %gone; # num => [ smsg, $mime, raw ]
390 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
391 my $msg = get_blob($self, $smsg);
392 if (!defined($msg)) {
393 warn "broken smsg for $mid\n";
397 my $cur = PublicInbox::Eml->new($msg);
398 if (content_matches($chashes, $cur)) {
399 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
402 my $n = scalar keys %gone;
405 warn "BUG: multiple articles linked to <$mid>\n",
406 join(',', sort keys %gone), "\n";
408 foreach my $num (keys %gone) {
409 my ($smsg, $mime, $orig) = @{$gone{$num}};
410 # $removed should only be set once assuming
411 # no bugs in our deduplication code:
412 $removed = [ undef, $mime, $smsg ];
413 my $oid = $smsg->{blob};
415 $replace_map->{$oid} = $sref;
417 ($mark, undef) = $im->remove($orig, $cmt_msg);
418 $removed->[0] = $mark;
421 if ($need_reindex) { # ->replace
422 push @$need_reindex, $smsg;
423 } else { # ->purge or ->remove
424 $self->{mm}->num_delete($num);
426 unindex_oid_aux($self, $oid, $mid);
431 my $cmt = $im->get_mark($mark);
432 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
434 if ($replace_map && scalar keys %$replace_map) {
435 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
436 return { rewrites => $rewrites, need_reindex => $need_reindex };
438 defined($mark) ? $removed : undef;
441 # public (see PublicInbox::Import->remove), but note the 3rd element
442 # (retval[2]) is not part of the stable API shared with Import->remove
444 my ($self, $eml, $cmt_msg) = @_;
445 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
446 $self, $eml, $cmt_msg);
447 defined($r) && defined($r->[0]) ? @$r: undef;
450 sub _replace ($$;$$) {
451 my ($self, $old_eml, $new_eml, $sref) = @_;
452 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
453 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
454 $self, $old_eml, undef, $new_eml, $sref) or return;
456 my $rewrites = $rewritten->{rewrites};
457 # ->done is called if there are rewrites since we gc+prune from git
458 $self->idx_init if @$rewrites;
460 for my $i (0..$#$rewrites) {
461 defined(my $cmt = $rewrites->[$i]) or next;
462 $self->{last_commit}->[$i] = $cmt;
469 my ($self, $mime) = @_;
470 my $rewritten = _replace($self, $mime, undef, \'') or return;
471 $rewritten->{rewrites}
474 # returns the git object_id of $fh, does not write the object to FS
475 sub git_hash_raw ($$) {
476 my ($self, $raw) = @_;
477 # grab the expected OID we have to reindex:
478 pipe(my($in, $w)) or die "pipe: $!";
479 my $git_dir = $self->git->{git_dir};
480 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
481 my $r = popen_rd($cmd, undef, { 0 => $in });
482 print $w $$raw or die "print \$w: $!";
483 close $w or die "close \$w: $!";
485 chomp(my $oid = <$r>);
486 close $r or die "git hash-object failed: $?";
487 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
491 sub _check_mids_match ($$$) {
492 my ($old_list, $new_list, $hdrs) = @_;
493 my %old_mids = map { $_ => 1 } @$old_list;
494 my %new_mids = map { $_ => 1 } @$new_list;
495 my @old = keys %old_mids;
496 my @new = keys %new_mids;
497 my $err = "$hdrs may not be changed when replacing\n";
498 die $err if scalar(@old) != scalar(@new);
499 delete @new_mids{@old};
500 delete @old_mids{@new};
501 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
504 # Changing Message-IDs or References with ->replace isn't supported.
505 # The rules for dealing with messages with multiple or conflicting
506 # Message-IDs are pretty complex and rethreading hasn't been fully
508 sub check_mids_match ($$) {
509 my ($old, $new) = @_;
510 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
511 _check_mids_match(references($old), references($new),
512 'References/In-Reply-To');
517 my ($self, $old_mime, $new_mime) = @_;
519 check_mids_match($old_mime, $new_mime);
521 # mutt will always add Content-Length:, Status:, Lines: when editing
522 PublicInbox::Import::drop_unwanted_headers($new_mime);
524 my $raw = $new_mime->as_string;
525 my $expect_oid = git_hash_raw($self, \$raw);
526 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
527 my $need_reindex = $rewritten->{need_reindex};
529 # just in case we have bugs in deduplication code:
530 my $n = scalar(@$need_reindex);
532 my $list = join(', ', map {
533 "$_->{num}: <$_->{mid}>"
536 W: rewritten $n messages matching content of original message (expected: 1).
537 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
542 # make sure we really got the OID:
543 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
544 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
546 # don't leak FDs to Xapian:
549 # reindex modified messages:
550 for my $smsg (@$need_reindex) {
551 my $new_smsg = bless {
556 }, 'PublicInbox::Smsg';
557 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
558 $new_smsg->populate($new_mime, $sync);
559 do_idx($self, \$raw, $new_mime, $new_smsg);
561 $rewritten->{rewrites};
564 sub last_epoch_commit ($$;$) {
565 my ($self, $i, $cmt) = @_;
566 my $v = PublicInbox::Search::SCHEMA_VERSION();
567 $self->{mm}->last_commit_xap($v, $i, $cmt);
570 sub set_last_commits ($) { # this is NOT for ExtSearchIdx
572 defined(my $epoch_max = $self->{epoch_max}) or return;
573 my $last_commit = $self->{last_commit};
574 foreach my $i (0..$epoch_max) {
575 defined(my $cmt = $last_commit->[$i]) or next;
576 $last_commit->[$i] = undef;
577 last_epoch_commit($self, $i, $cmt);
583 $self->{bnote} or return;
585 my $barrier = { map { $_ => 1 } (0..$n) };
589 my ($self, $barrier) = @_;
590 my $bnote = $self->{bnote} or return;
592 while (scalar keys %$barrier) {
593 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
594 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
595 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
600 sub checkpoint ($;$) {
601 my ($self, $wait) = @_;
603 if (my $im = $self->{im}) {
610 my $shards = $self->{idx_shards};
612 my $mm = $self->{mm};
613 my $dbh = $mm->{dbh} if $mm;
615 # SQLite msgmap data is second in importance
616 $dbh->commit if $dbh;
618 # SQLite overview is third
619 $self->{oidx}->commit_lazy;
621 # Now deal with Xapian
623 my $barrier = $self->barrier_init(scalar @$shards);
625 # each shard needs to issue a barrier command
626 $_->shard_barrier for @$shards;
628 # wait for each Xapian shard
629 $self->barrier_wait($barrier);
631 $_->shard_commit for @$shards;
634 # last_commit is special, don't commit these until
635 # Xapian shards are done:
636 $dbh->begin_work if $dbh;
637 set_last_commits($self);
643 $self->{total_bytes} += $self->{transact_bytes};
644 $self->{transact_bytes} = 0;
647 # issue a write barrier to ensure all data is visible to other processes
648 # and read-only ops. Order of data importance is: git > SQLite > Xapian
650 sub barrier { checkpoint($_[0], 1) };
652 # true if locked and active
653 sub active { !!$_[0]->{im} }
659 if (my $im = delete $self->{im}) {
660 eval { $im->done }; # PublicInbox::Import::done
661 $err .= "import done: $@\n" if $@;
664 eval { checkpoint($self) };
665 $err .= "checkpoint: $@\n" if $@;
667 if (my $mm = delete $self->{mm}) {
668 my $m = $err ? 'rollback' : 'commit';
669 eval { $mm->{dbh}->$m };
670 $err .= "msgmap $m: $@\n" if $@;
672 my $shards = delete $self->{idx_shards};
675 eval { $_->shard_close };
676 $err .= "shard close: $@\n" if $@;
679 eval { $self->{oidx}->dbh_close };
680 $err .= "over close: $@\n" if $@;
681 delete $self->{bnote};
682 my $nbytes = $self->{total_bytes};
683 $self->{total_bytes} = 0;
684 $self->lock_release(!!$nbytes) if $shards;
689 sub write_alternates ($$$) {
690 my ($info_dir, $mode, $out) = @_;
691 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
692 my $tmp = $fh->filename;
693 print $fh @$out or die "print $tmp: $!\n";
694 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
695 close $fh or die "close $tmp $!\n";
696 my $alt = "$info_dir/alternates";
697 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
698 $fh->unlink_on_destroy(0);
701 sub fill_alternates ($$) {
702 my ($self, $epoch) = @_;
704 my $pfx = "$self->{ibx}->{inboxdir}/git";
705 my $all = "$self->{ibx}->{inboxdir}/all.git";
706 PublicInbox::Import::init_bare($all) unless -d $all;
707 my $info_dir = "$all/objects/info";
708 my $alt = "$info_dir/alternates";
712 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
713 $mode = (stat($fh))[2] & 07777;
715 # we assign a sort score to every alternate and favor
716 # the newest (highest numbered) one because loose objects
717 # require scanning epochs and only the latest epoch is
718 # expected to see loose objects
720 my $other = 0; # in case admin adds non-epoch repos
722 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
728 } split(/\n+/, do { local $/; <$fh> });
731 foreach my $i (0..$epoch) {
732 my $dir = "../../git/$i.git/objects";
733 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
739 write_alternates($info_dir, $mode,
740 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
744 my ($self, $epoch) = @_;
745 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
746 PublicInbox::Import::init_bare($git_dir);
747 my @cmd = (qw/git config/, "--file=$git_dir/config",
748 'include.path', '../../all.git/config');
749 PublicInbox::Import::run_die(\@cmd);
750 fill_alternates($self, $epoch);
756 my $im = $self->{im};
758 if ($im->{bytes_added} < $self->{rotate_bytes}) {
765 my $git_dir = $self->git_init(++$self->{epoch_max});
766 my $git = PublicInbox::Git->new($git_dir);
767 return $self->import_init($git, 0);
772 my $latest = $self->{ibx}->git_dir_latest(\$max);
773 if (defined $latest) {
774 my $git = PublicInbox::Git->new($latest);
775 my $packed_bytes = $git->packed_bytes;
776 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
778 if ($unpacked_bytes >= $self->{rotate_bytes}) {
781 $self->{epoch_max} = $max;
782 return $self->import_init($git, $packed_bytes);
785 $self->{epoch_max} = $epoch;
786 $latest = $self->git_init($epoch);
787 $self->import_init(PublicInbox::Git->new($latest), 0);
791 my ($self, $git, $packed_bytes, $tmp) = @_;
792 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
793 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
794 $im->{lock_path} = undef;
795 $im->{path_type} = 'v2';
796 $self->{im} = $im unless $tmp;
802 my ($mid, $cur, $new) = @_;
804 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
805 print $ah $cur->as_string or die "print: $!";
806 $ah->flush or die "flush: $!";
807 PublicInbox::Import::drop_unwanted_headers($new);
808 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
809 print $bh $new->as_string or die "print: $!";
810 $bh->flush or die "flush: $!";
811 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
812 print STDERR "# MID conflict <$mid>\n";
813 my $pid = spawn($cmd, undef, { 1 => 2 });
814 waitpid($pid, 0) == $pid or die "diff did not finish";
818 my ($self, $smsg) = @_;
819 if (my $im = $self->{im}) {
820 my $msg = $im->cat_blob($smsg->{blob});
823 # older message, should be in alternates
824 $self->{ibx}->msg_by_smsg($smsg);
827 sub content_exists ($$$) {
828 my ($self, $mime, $mid) = @_;
829 my $oidx = $self->{oidx};
830 my $chashes = content_hashes($mime);
832 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
833 my $msg = get_blob($self, $smsg);
834 if (!defined($msg)) {
835 warn "broken smsg for $mid\n";
838 my $cur = PublicInbox::Eml->new($msg);
839 return 1 if content_matches($chashes, $cur);
841 # XXX DEBUG_DIFF is experimental and may be removed
842 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
849 if (my $shards = $self->{idx_shards}) {
850 $_->atfork_child foreach @$shards;
852 if (my $im = $self->{im}) {
855 die "unexpected mm" if $self->{mm};
856 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
860 sub reindex_checkpoint ($$) {
861 my ($self, $sync) = @_;
863 $self->git->cleanup; # *async_wait
864 ${$sync->{need_checkpoint}} = 0;
865 my $mm_tmp = $sync->{mm_tmp};
866 $mm_tmp->atfork_prepare if $mm_tmp;
867 $self->done; # release lock
869 if (my $pr = $sync->{-opt}->{-progress}) {
870 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
873 # allow -watch or -mda to write...
874 $self->idx_init($sync->{-opt}); # reacquire lock
875 $mm_tmp->atfork_parent if $mm_tmp;
878 sub index_oid { # cat_async callback
879 my ($bref, $oid, $type, $size, $arg) = @_;
880 return if $size == 0; # purged
882 my $eml = PublicInbox::Eml->new($$bref);
883 my $mids = mids($eml);
884 my $chash = content_hash($eml);
885 my $self = $arg->{self};
887 if (scalar(@$mids) == 0) {
888 warn "E: $oid has no Message-ID, skipping\n";
892 # {unindexed} is unlikely
893 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
894 $num = delete($unindexed->{$mids->[0]});
897 $self->{mm}->mid_set($num, $mid0);
898 delete($arg->{unindexed}) if !keys(%$unindexed);
901 if (!defined($num)) { # reuse if reindexing (or duplicates)
902 my $oidx = $self->{oidx};
903 for my $mid (@$mids) {
904 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
905 last if defined $num;
908 $mid0 //= do { # is this a number we got before?
909 $num = $arg->{mm_tmp}->num_for($mids->[0]);
910 defined($num) ? $mids->[0] : undef;
912 if (!defined($num)) {
913 for (my $i = $#$mids; $i >= 1; $i--) {
914 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
922 $arg->{mm_tmp}->num_delete($num);
923 } else { # never seen
924 $num = $self->{mm}->mid_insert($mids->[0]);
927 } else { # rare, try the rest of them, backwards
928 for (my $i = $#$mids; $i >= 1; $i--) {
929 $num = $self->{mm}->mid_insert($mids->[$i]);
937 if (!defined($num)) {
938 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
947 }, 'PublicInbox::Smsg';
948 $smsg->populate($eml, $arg);
949 if (do_idx($self, $bref, $eml, $smsg)) {
950 ${$arg->{need_checkpoint}} = 1;
954 # only update last_commit for $i on reindex iff newer than current
955 # $sync will be used by subclasses
956 sub update_last_commit {
957 my ($self, $sync, $unit, $cmt) = @_;
958 my $last = last_epoch_commit($self, $unit->{epoch});
959 if (defined $last && is_ancestor($unit->{git}, $last, $cmt)) {
960 my @cmd = (qw(rev-list --count), "$last..$cmt");
961 chomp(my $n = $unit->{git}->qx(@cmd));
962 return if $n ne '' && $n == 0;
964 last_epoch_commit($self, $unit->{epoch}, $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($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';
1046 # reindex stops at the current heads and we later rerun index_sync
1048 my $reindex_heads = $self->last_commits($sync) if $sync->{reindex};
1050 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
1051 $sync->{index_oid} = $self->can('index_oid');
1053 for (my $i = $sync->{epoch_max}; $i >= 0; $i--) {
1054 my $git_dir = $sync->{ibx}->git_dir_n($i);
1055 -d $git_dir or next; # missing epochs are fine
1056 my $git = PublicInbox::Git->new($git_dir);
1057 my $unit = { git => $git, epoch => $i };
1058 if ($reindex_heads) {
1059 $head = $reindex_heads->[$i] or next;
1061 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1062 next if $?; # new repo
1064 my $range = log_range($sync, $unit, $tip) or next;
1065 # can't use 'rev-list --count' if we use --diff-filter
1066 $pr->("$i.git counting $range ... ") if $pr;
1067 # Don't bump num_highwater on --reindex by using {D}.
1068 # We intentionally do NOT use {D} in the non-reindex case
1069 # because we want NNTP article number gaps from unindexed
1070 # messages to show up in mirrors, too.
1071 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1072 my $stk = log2stack($sync, $git, $range);
1073 my $nr = $stk ? $stk->num_records : 0;
1074 $pr->("$nr\n") if $pr;
1075 $unit->{stack} = $stk; # may be undef
1076 unshift @{$sync->{todo}}, $unit;
1080 # XXX this should not happen unless somebody bypasses checks in
1081 # our code and blindly injects "d" file history into git repos
1082 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1083 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1084 my $unindex_oid = $self->can('unindex_oid');
1085 for my $oid (@leftovers) {
1086 $oid = unpack('H*', $oid);
1087 $self->{current_info} = "leftover $oid";
1088 my $req = { %$sync, oid => $oid };
1089 $self->git->cat_async($oid, $unindex_oid, $req);
1091 $self->git->cat_async_wait;
1094 $sync->{-regen_fmt} = "%u/?\n";
1098 # reindex should NOT see new commits anymore, if we do,
1099 # it's a problem and we need to notice it via die()
1100 my $pad = length($regen_max) + 1;
1101 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1102 $sync->{nr} = \(my $nr = 0);
1103 return -1 if $sync->{reindex};
1104 $regen_max + $self->artnum_max || 0;
1107 sub unindex_oid_aux ($$$) {
1108 my ($self, $oid, $mid) = @_;
1109 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1110 for my $num (@removed) {
1111 my $idx = idx_shard($self, $num);
1112 $idx->shard_remove($oid, $num);
1116 sub unindex_oid ($$;$) { # git->cat_async callback
1117 my ($bref, $oid, $type, $size, $sync) = @_;
1118 my $self = $sync->{self};
1119 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1120 my $mm = $self->{mm};
1121 my $mids = mids(PublicInbox::Eml->new($bref));
1123 my $oidx = $self->{oidx};
1124 foreach my $mid (@$mids) {
1127 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1128 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1130 my $n = scalar(keys(%gone)) or next;
1132 warn "BUG: multiple articles linked to $oid\n",
1133 join(',',sort keys %gone), "\n";
1135 foreach my $num (keys %gone) {
1137 my $mid0 = $mm->mid_for($num);
1138 $unindexed->{$mid0} = $num;
1140 $mm->num_delete($num);
1142 unindex_oid_aux($self, $oid, $mid);
1146 sub git { $_[0]->{ibx}->git }
1148 # this is rare, it only happens when we get discontiguous history in
1149 # a mirror because the source used -purge or -edit
1150 sub unindex_todo ($$$) {
1151 my ($self, $sync, $unit) = @_;
1152 my $unindex_range = delete($unit->{unindex_range}) // return;
1153 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1154 my $before = scalar keys %$unindexed;
1155 # order does not matter, here:
1156 my $fh = $unit->{git}->popen(qw(log --raw -r --no-notes --no-color
1157 --no-abbrev --no-renames), $unindex_range);
1158 local $sync->{in_unindex} = 1;
1159 my $unindex_oid = $self->can('unindex_oid');
1161 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1162 $self->git->cat_async($1, $unindex_oid, { %$sync, oid => $1 });
1164 close $fh or die "git log failed: \$?=$?";
1165 $self->git->cat_async_wait;
1167 return unless $sync->{-opt}->{prune};
1168 my $after = scalar keys %$unindexed;
1169 return if $before == $after;
1171 # ensure any blob can not longer be accessed via dumb HTTP
1172 PublicInbox::Import::run_die(['git',
1173 "--git-dir=$unit->{git}->{git_dir}",
1174 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1177 sub sync_ranges ($$) {
1178 my ($self, $sync) = @_;
1179 my $reindex = $sync->{reindex};
1180 return $self->last_commits($sync) unless $reindex;
1181 return [] if ref($reindex) ne 'HASH';
1183 my $ranges = $reindex->{from}; # arrayref;
1184 if (ref($ranges) ne 'ARRAY') {
1185 die 'BUG: $reindex->{from} not an ARRAY';
1190 sub index_xap_only { # git->cat_async callback
1191 my ($bref, $oid, $type, $size, $smsg) = @_;
1192 my $self = $smsg->{self};
1193 my $idx = idx_shard($self, $smsg->{num});
1194 $smsg->{raw_bytes} = $size;
1195 $idx->index_raw($bref, undef, $smsg);
1196 $self->{transact_bytes} += $size;
1199 sub index_xap_step ($$$;$) {
1200 my ($self, $sync, $beg, $step) = @_;
1201 my $end = $sync->{art_end};
1202 return if $beg > $end; # nothing to do
1204 $step //= $self->{shards};
1205 my $ibx = $self->{ibx};
1206 if (my $pr = $sync->{-opt}->{-progress}) {
1207 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1208 "$beg..$end (% $step)\n");
1210 for (my $num = $beg; $num <= $end; $num += $step) {
1211 my $smsg = $ibx->over->get_art($num) or next;
1212 $smsg->{self} = $self;
1213 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1214 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1215 ${$sync->{nr}} = $num;
1216 reindex_checkpoint($self, $sync);
1221 sub index_todo ($$$) {
1222 my ($self, $sync, $unit) = @_;
1223 unindex_todo($self, $sync, $unit);
1224 my $stk = delete($unit->{stack}) or return;
1225 my $all = $self->git;
1226 my $index_oid = $self->can('index_oid');
1227 my $unindex_oid = $self->can('unindex_oid');
1228 my ($pfx) = ($unit->{git}->{git_dir} =~ m!/([^/]+)\z!g);
1229 $pfx //= $unit->{git}->{git_dir};
1230 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1231 $self->{current_info} = "$pfx $oid";
1232 my $req = { %$sync, autime => $at, cotime => $ct, oid => $oid };
1234 if ($sync->{max_size}) {
1235 $all->check_async($oid, \&check_size, $req);
1237 $all->cat_async($oid, $index_oid, $req);
1239 } elsif ($f eq 'd') {
1240 $all->cat_async($oid, $unindex_oid, $req);
1242 if (${$sync->{need_checkpoint}}) {
1243 reindex_checkpoint($self, $sync);
1246 $all->async_wait_all;
1247 $self->update_last_commit($sync, $unit, $stk->{latest_cmt});
1251 my ($self, $opt, $sync, $art_beg) = @_;
1252 my $seq = $opt->{sequential_shard};
1254 local $self->{parallel} = 0 if $seq;
1255 $self->idx_init($opt); # acquire lock
1256 if (my $art_end = $self->{ibx}->mm->max) {
1258 need_checkpoint => \(my $bool = 0),
1261 nr => \(my $nr = 0),
1262 -regen_fmt => "%u/?\n",
1264 $sync->{art_end} = $art_end;
1265 if ($seq || !$self->{parallel}) {
1266 my $shard_end = $self->{shards} - 1;
1267 for my $i (0..$shard_end) {
1268 index_xap_step($self, $sync, $art_beg + $i);
1269 if ($i != $shard_end) {
1270 reindex_checkpoint($self, $sync);
1273 } else { # parallel (maybe)
1274 index_xap_step($self, $sync, $art_beg, 1);
1277 $self->git->cat_async_wait;
1281 # public, called by public-inbox-index
1283 my ($self, $opt) = @_;
1285 return xapian_only($self, $opt) if $opt->{xapian_only};
1287 my $pr = $opt->{-progress};
1289 my $latest = $self->{ibx}->git_dir_latest(\$epoch_max);
1290 return unless defined $latest;
1292 my $seq = $opt->{sequential_shard};
1293 my $art_beg; # the NNTP article number we start xapian_only at
1294 my $idxlevel = $self->{ibx}->{indexlevel};
1295 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1297 $self->idx_init($opt); # acquire lock
1298 fill_alternates($self, $epoch_max);
1299 $self->{oidx}->rethread_prepare($opt);
1301 need_checkpoint => \(my $bool = 0),
1302 reindex => $opt->{reindex},
1305 ibx => $self->{ibx},
1306 epoch_max => $epoch_max,
1308 if (sync_prepare($self, $sync)) {
1309 # tmp_clone seems to fail if inside a transaction, so
1310 # we rollback here (because we opened {mm} for reading)
1311 # Note: we do NOT rely on DBI transactions for atomicity;
1312 # only for batch performance.
1313 $self->{mm}->{dbh}->rollback;
1314 $self->{mm}->{dbh}->begin_work;
1316 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1318 # xapian_only works incrementally w/o --reindex
1319 if ($seq && !$opt->{reindex}) {
1320 $art_beg = $sync->{mm_tmp}->max;
1321 $art_beg++ if defined($art_beg);
1324 # work forwards through history
1325 index_todo($self, $sync, $_) for @{$sync->{todo}};
1326 $self->{oidx}->rethread_done($opt);
1329 if (my $nr = $sync->{nr}) {
1330 my $pr = $sync->{-opt}->{-progress};
1331 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1334 # deal with Xapian shards sequentially
1335 if ($seq && delete($sync->{mm_tmp})) {
1336 $self->{ibx}->{indexlevel} = $idxlevel;
1337 xapian_only($self, $opt, $sync, $art_beg);
1340 # --reindex on the command-line
1341 if ($opt->{reindex} && !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1342 $self->lock_acquire;
1343 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1344 if (my $xdb = $s0->idx_acquire) {
1345 my $n = $xdb->get_metadata('has_threadid');
1346 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1349 $self->lock_release;
1352 # reindex does not pick up new changes, so we rerun w/o it:
1353 if ($opt->{reindex}) {
1356 delete @again{qw(rethread reindex -skip_lock)};
1357 index_sync($self, \%again);