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 git_dir_latest($self, \$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 $pfx = "$self->{ibx}->{inboxdir}/git";
324 my $rewrites = []; # epoch => commit
325 my $max = $self->{epoch_max};
327 unless (defined($max)) {
328 defined(my $latest = git_dir_latest($self, \$max)) or return;
329 $self->{epoch_max} = $max;
332 foreach my $i (0..$max) {
333 my $git_dir = "$pfx/$i.git";
335 my $git = PublicInbox::Git->new($git_dir);
336 my $im = $self->import_init($git, 0, 1);
337 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
343 sub content_hashes ($) {
345 my @chashes = ( content_hash($mime) );
347 # We still support Email::MIME, here, and
348 # Email::MIME->as_string doesn't always round-trip, so we may
349 # use a second content_hash
350 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
351 push @chashes, $rt if $chashes[0] ne $rt;
355 sub content_matches ($$) {
356 my ($chashes, $existing) = @_;
357 my $chash = content_hash($existing);
358 foreach (@$chashes) {
359 return 1 if $_ eq $chash
364 # used for removing or replacing (purging)
365 sub rewrite_internal ($$;$$$) {
366 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
368 my ($im, $need_reindex, $replace_map);
370 $replace_map = {}; # oid => sref
371 $need_reindex = [] if $new_eml;
373 $im = $self->importer;
375 my $oidx = $self->{oidx};
376 my $chashes = content_hashes($old_eml);
378 my $mids = mids($old_eml);
380 # We avoid introducing new blobs into git since the raw content
381 # can be slightly different, so we do not need the user-supplied
382 # message now that we have the mids and content_hash
386 foreach my $mid (@$mids) {
387 my %gone; # num => [ smsg, $mime, raw ]
389 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
390 my $msg = get_blob($self, $smsg);
391 if (!defined($msg)) {
392 warn "broken smsg for $mid\n";
396 my $cur = PublicInbox::Eml->new($msg);
397 if (content_matches($chashes, $cur)) {
398 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
401 my $n = scalar keys %gone;
404 warn "BUG: multiple articles linked to <$mid>\n",
405 join(',', sort keys %gone), "\n";
407 foreach my $num (keys %gone) {
408 my ($smsg, $mime, $orig) = @{$gone{$num}};
409 # $removed should only be set once assuming
410 # no bugs in our deduplication code:
411 $removed = [ undef, $mime, $smsg ];
412 my $oid = $smsg->{blob};
414 $replace_map->{$oid} = $sref;
416 ($mark, undef) = $im->remove($orig, $cmt_msg);
417 $removed->[0] = $mark;
420 if ($need_reindex) { # ->replace
421 push @$need_reindex, $smsg;
422 } else { # ->purge or ->remove
423 $self->{mm}->num_delete($num);
425 unindex_oid_remote($self, $oid, $mid);
430 my $cmt = $im->get_mark($mark);
431 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
433 if ($replace_map && scalar keys %$replace_map) {
434 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
435 return { rewrites => $rewrites, need_reindex => $need_reindex };
437 defined($mark) ? $removed : undef;
440 # public (see PublicInbox::Import->remove), but note the 3rd element
441 # (retval[2]) is not part of the stable API shared with Import->remove
443 my ($self, $eml, $cmt_msg) = @_;
444 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
445 $self, $eml, $cmt_msg);
446 defined($r) && defined($r->[0]) ? @$r: undef;
449 sub _replace ($$;$$) {
450 my ($self, $old_eml, $new_eml, $sref) = @_;
451 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
452 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
453 $self, $old_eml, undef, $new_eml, $sref) or return;
455 my $rewrites = $rewritten->{rewrites};
456 # ->done is called if there are rewrites since we gc+prune from git
457 $self->idx_init if @$rewrites;
459 for my $i (0..$#$rewrites) {
460 defined(my $cmt = $rewrites->[$i]) or next;
461 $self->{last_commit}->[$i] = $cmt;
468 my ($self, $mime) = @_;
469 my $rewritten = _replace($self, $mime, undef, \'') or return;
470 $rewritten->{rewrites}
473 # returns the git object_id of $fh, does not write the object to FS
474 sub git_hash_raw ($$) {
475 my ($self, $raw) = @_;
476 # grab the expected OID we have to reindex:
477 pipe(my($in, $w)) or die "pipe: $!";
478 my $git_dir = $self->git->{git_dir};
479 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
480 my $r = popen_rd($cmd, undef, { 0 => $in });
481 print $w $$raw or die "print \$w: $!";
482 close $w or die "close \$w: $!";
484 chomp(my $oid = <$r>);
485 close $r or die "git hash-object failed: $?";
486 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
490 sub _check_mids_match ($$$) {
491 my ($old_list, $new_list, $hdrs) = @_;
492 my %old_mids = map { $_ => 1 } @$old_list;
493 my %new_mids = map { $_ => 1 } @$new_list;
494 my @old = keys %old_mids;
495 my @new = keys %new_mids;
496 my $err = "$hdrs may not be changed when replacing\n";
497 die $err if scalar(@old) != scalar(@new);
498 delete @new_mids{@old};
499 delete @old_mids{@new};
500 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
503 # Changing Message-IDs or References with ->replace isn't supported.
504 # The rules for dealing with messages with multiple or conflicting
505 # Message-IDs are pretty complex and rethreading hasn't been fully
507 sub check_mids_match ($$) {
508 my ($old, $new) = @_;
509 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
510 _check_mids_match(references($old), references($new),
511 'References/In-Reply-To');
516 my ($self, $old_mime, $new_mime) = @_;
518 check_mids_match($old_mime, $new_mime);
520 # mutt will always add Content-Length:, Status:, Lines: when editing
521 PublicInbox::Import::drop_unwanted_headers($new_mime);
523 my $raw = $new_mime->as_string;
524 my $expect_oid = git_hash_raw($self, \$raw);
525 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
526 my $need_reindex = $rewritten->{need_reindex};
528 # just in case we have bugs in deduplication code:
529 my $n = scalar(@$need_reindex);
531 my $list = join(', ', map {
532 "$_->{num}: <$_->{mid}>"
535 W: rewritten $n messages matching content of original message (expected: 1).
536 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
541 # make sure we really got the OID:
542 my ($blob, $type, $bytes) = $self->git->check($expect_oid);
543 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
545 # don't leak FDs to Xapian:
548 # reindex modified messages:
549 for my $smsg (@$need_reindex) {
550 my $new_smsg = bless {
555 }, 'PublicInbox::Smsg';
556 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
557 $new_smsg->populate($new_mime, $sync);
558 do_idx($self, \$raw, $new_mime, $new_smsg);
560 $rewritten->{rewrites};
563 sub last_epoch_commit ($$;$) {
564 my ($self, $i, $cmt) = @_;
565 my $v = PublicInbox::Search::SCHEMA_VERSION();
566 $self->{mm}->last_commit_xap($v, $i, $cmt);
569 sub set_last_commits ($) {
571 defined(my $epoch_max = $self->{epoch_max}) or return;
572 my $last_commit = $self->{last_commit};
573 foreach my $i (0..$epoch_max) {
574 defined(my $cmt = $last_commit->[$i]) or next;
575 $last_commit->[$i] = undef;
576 last_epoch_commit($self, $i, $cmt);
582 $self->{bnote} or return;
584 my $barrier = { map { $_ => 1 } (0..$n) };
588 my ($self, $barrier) = @_;
589 my $bnote = $self->{bnote} or return;
591 while (scalar keys %$barrier) {
592 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
593 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
594 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
599 sub checkpoint ($;$) {
600 my ($self, $wait) = @_;
602 if (my $im = $self->{im}) {
609 my $shards = $self->{idx_shards};
611 my $dbh = $self->{mm}->{dbh};
613 # SQLite msgmap data is second in importance
616 # SQLite overview is third
617 $self->{oidx}->commit_lazy;
619 # Now deal with Xapian
621 my $barrier = $self->barrier_init(scalar @$shards);
623 # each shard needs to issue a barrier command
624 $_->shard_barrier for @$shards;
626 # wait for each Xapian shard
627 $self->barrier_wait($barrier);
629 $_->shard_commit for @$shards;
632 # last_commit is special, don't commit these until
633 # remote shards are done:
635 set_last_commits($self);
640 $self->{total_bytes} += $self->{transact_bytes};
641 $self->{transact_bytes} = 0;
644 # issue a write barrier to ensure all data is visible to other processes
645 # and read-only ops. Order of data importance is: git > SQLite > Xapian
647 sub barrier { checkpoint($_[0], 1) };
649 # true if locked and active
650 sub active { !!$_[0]->{im} }
656 if (my $im = delete $self->{im}) {
657 eval { $im->done }; # PublicInbox::Import::done
658 $err .= "import done: $@\n" if $@;
661 eval { checkpoint($self) };
662 $err .= "checkpoint: $@\n" if $@;
664 if (my $mm = delete $self->{mm}) {
665 my $m = $err ? 'rollback' : 'commit';
666 eval { $mm->{dbh}->$m };
667 $err .= "msgmap $m: $@\n" if $@;
669 my $shards = delete $self->{idx_shards};
672 eval { $_->shard_close };
673 $err .= "shard close: $@\n" if $@;
676 eval { $self->{oidx}->dbh_close };
677 $err .= "over close: $@\n" if $@;
678 delete $self->{bnote};
679 my $nbytes = $self->{total_bytes};
680 $self->{total_bytes} = 0;
681 $self->lock_release(!!$nbytes) if $shards;
686 sub write_alternates ($$$) {
687 my ($info_dir, $mode, $out) = @_;
688 my $fh = File::Temp->new(TEMPLATE => 'alt-XXXXXXXX', DIR => $info_dir);
689 my $tmp = $fh->filename;
690 print $fh @$out or die "print $tmp: $!\n";
691 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
692 close $fh or die "close $tmp $!\n";
693 my $alt = "$info_dir/alternates";
694 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
695 $fh->unlink_on_destroy(0);
698 sub fill_alternates ($$) {
699 my ($self, $epoch) = @_;
701 my $pfx = "$self->{ibx}->{inboxdir}/git";
702 my $all = "$self->{ibx}->{inboxdir}/all.git";
703 PublicInbox::Import::init_bare($all) unless -d $all;
704 my $info_dir = "$all/objects/info";
705 my $alt = "$info_dir/alternates";
709 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
710 $mode = (stat($fh))[2] & 07777;
712 # we assign a sort score to every alternate and favor
713 # the newest (highest numbered) one because loose objects
714 # require scanning epochs and only the latest epoch is
715 # expected to see loose objects
717 my $other = 0; # in case admin adds non-epoch repos
719 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
725 } split(/\n+/, do { local $/; <$fh> });
728 foreach my $i (0..$epoch) {
729 my $dir = "../../git/$i.git/objects";
730 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
736 write_alternates($info_dir, $mode,
737 [join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"]);
741 my ($self, $epoch) = @_;
742 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
743 PublicInbox::Import::init_bare($git_dir);
744 my @cmd = (qw/git config/, "--file=$git_dir/config",
745 'include.path', '../../all.git/config');
746 PublicInbox::Import::run_die(\@cmd);
747 fill_alternates($self, $epoch);
752 my ($self, $max) = @_;
754 my $pfx = "$self->{ibx}->{inboxdir}/git";
755 return unless -d $pfx;
757 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
758 while (defined(my $git_dir = readdir($dh))) {
759 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
762 $latest = "$pfx/$git_dir";
770 my $im = $self->{im};
772 if ($im->{bytes_added} < $self->{rotate_bytes}) {
779 my $git_dir = $self->git_init(++$self->{epoch_max});
780 my $git = PublicInbox::Git->new($git_dir);
781 return $self->import_init($git, 0);
786 my $latest = git_dir_latest($self, \$max);
787 if (defined $latest) {
788 my $git = PublicInbox::Git->new($latest);
789 my $packed_bytes = $git->packed_bytes;
790 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
792 if ($unpacked_bytes >= $self->{rotate_bytes}) {
795 $self->{epoch_max} = $max;
796 return $self->import_init($git, $packed_bytes);
799 $self->{epoch_max} = $epoch;
800 $latest = $self->git_init($epoch);
801 $self->import_init(PublicInbox::Git->new($latest), 0);
805 my ($self, $git, $packed_bytes, $tmp) = @_;
806 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
807 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
808 $im->{lock_path} = undef;
809 $im->{path_type} = 'v2';
810 $self->{im} = $im unless $tmp;
816 my ($mid, $cur, $new) = @_;
818 my $ah = File::Temp->new(TEMPLATE => 'email-cur-XXXXXXXX', TMPDIR => 1);
819 print $ah $cur->as_string or die "print: $!";
820 $ah->flush or die "flush: $!";
821 PublicInbox::Import::drop_unwanted_headers($new);
822 my $bh = File::Temp->new(TEMPLATE => 'email-new-XXXXXXXX', TMPDIR => 1);
823 print $bh $new->as_string or die "print: $!";
824 $bh->flush or die "flush: $!";
825 my $cmd = [ qw(diff -u), $ah->filename, $bh->filename ];
826 print STDERR "# MID conflict <$mid>\n";
827 my $pid = spawn($cmd, undef, { 1 => 2 });
828 waitpid($pid, 0) == $pid or die "diff did not finish";
832 my ($self, $smsg) = @_;
833 if (my $im = $self->{im}) {
834 my $msg = $im->cat_blob($smsg->{blob});
837 # older message, should be in alternates
838 $self->{ibx}->msg_by_smsg($smsg);
841 sub content_exists ($$$) {
842 my ($self, $mime, $mid) = @_;
843 my $oidx = $self->{oidx};
844 my $chashes = content_hashes($mime);
846 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
847 my $msg = get_blob($self, $smsg);
848 if (!defined($msg)) {
849 warn "broken smsg for $mid\n";
852 my $cur = PublicInbox::Eml->new($msg);
853 return 1 if content_matches($chashes, $cur);
855 # XXX DEBUG_DIFF is experimental and may be removed
856 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
863 if (my $shards = $self->{idx_shards}) {
864 $_->atfork_child foreach @$shards;
866 if (my $im = $self->{im}) {
869 die "unexpected mm" if $self->{mm};
870 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
874 sub reindex_checkpoint ($$) {
875 my ($self, $sync) = @_;
877 $self->git->cleanup; # *async_wait
878 ${$sync->{need_checkpoint}} = 0;
879 my $mm_tmp = $sync->{mm_tmp};
880 $mm_tmp->atfork_prepare if $mm_tmp;
881 $self->done; # release lock
883 if (my $pr = $sync->{-opt}->{-progress}) {
884 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
887 # allow -watch or -mda to write...
888 $self->idx_init($sync->{-opt}); # reacquire lock
889 $mm_tmp->atfork_parent if $mm_tmp;
892 sub index_oid { # cat_async callback
893 my ($bref, $oid, $type, $size, $arg) = @_;
894 return if $size == 0; # purged
896 my $eml = PublicInbox::Eml->new($$bref);
897 my $mids = mids($eml);
898 my $chash = content_hash($eml);
899 my $self = $arg->{v2w};
901 if (scalar(@$mids) == 0) {
902 warn "E: $oid has no Message-ID, skipping\n";
906 # {unindexed} is unlikely
907 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
908 $num = delete($unindexed->{$mids->[0]});
911 $self->{mm}->mid_set($num, $mid0);
912 delete($arg->{unindexed}) if !keys(%$unindexed);
915 if (!defined($num)) { # reuse if reindexing (or duplicates)
916 my $oidx = $self->{oidx};
917 for my $mid (@$mids) {
918 ($num, $mid0) = $oidx->num_mid0_for_oid($oid, $mid);
919 last if defined $num;
922 $mid0 //= do { # is this a number we got before?
923 $num = $arg->{mm_tmp}->num_for($mids->[0]);
924 defined($num) ? $mids->[0] : undef;
926 if (!defined($num)) {
927 for (my $i = $#$mids; $i >= 1; $i--) {
928 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
936 $arg->{mm_tmp}->num_delete($num);
937 } else { # never seen
938 $num = $self->{mm}->mid_insert($mids->[0]);
941 } else { # rare, try the rest of them, backwards
942 for (my $i = $#$mids; $i >= 1; $i--) {
943 $num = $self->{mm}->mid_insert($mids->[$i]);
951 if (!defined($num)) {
952 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
961 }, 'PublicInbox::Smsg';
962 $smsg->populate($eml, $arg);
963 if (do_idx($self, $bref, $eml, $smsg)) {
964 ${$arg->{need_checkpoint}} = 1;
968 # only update last_commit for $i on reindex iff newer than current
969 sub update_last_commit {
970 my ($self, $git, $i, $cmt) = @_;
971 my $last = last_epoch_commit($self, $i);
972 if (defined $last && is_ancestor($git, $last, $cmt)) {
973 my @cmd = (qw(rev-list --count), "$last..$cmt");
974 chomp(my $n = $git->qx(@cmd));
975 return if $n ne '' && $n == 0;
977 last_epoch_commit($self, $i, $cmt);
980 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
982 sub last_commits ($$) {
983 my ($self, $epoch_max) = @_;
985 for (my $i = $epoch_max; $i >= 0; $i--) {
986 $heads->[$i] = last_epoch_commit($self, $i);
991 # returns a revision range for git-log(1)
992 sub log_range ($$$$$) {
993 my ($self, $sync, $git, $i, $tip) = @_;
994 my $opt = $sync->{-opt};
995 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
996 my $cur = $sync->{ranges}->[$i] or do {
997 $pr->("$i.git indexing all of $tip\n") if $pr;
998 return $tip; # all of it
1001 # fast equality check to avoid (v)fork+execve overhead
1003 $sync->{ranges}->[$i] = undef;
1007 my $range = "$cur..$tip";
1008 $pr->("$i.git checking contiguity... ") if $pr;
1009 if (is_ancestor($git, $cur, $tip)) { # common case
1010 $pr->("OK\n") if $pr;
1011 my $n = $git->qx(qw(rev-list --count), $range);
1014 $sync->{ranges}->[$i] = undef;
1015 $pr->("$i.git has nothing new\n") if $pr;
1016 return; # nothing to do
1018 $pr->("$i.git has $n changes since $cur\n") if $pr;
1020 $pr->("FAIL\n") if $pr;
1022 discontiguous range: $range
1023 Rewritten history? (in $git->{git_dir})
1025 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1027 $range = "$base..$tip";
1028 warn "found merge-base: $base\n"
1031 warn "discarding history at $cur\n";
1034 reindexing $git->{git_dir} starting at
1037 $sync->{unindex_range}->{$i} = "$base..$cur";
1042 sub sync_prepare ($$$) {
1043 my ($self, $sync, $epoch_max) = @_;
1044 my $pr = $sync->{-opt}->{-progress};
1046 my $head = $self->{ibx}->{ref_head} || 'HEAD';
1048 # reindex stops at the current heads and we later rerun index_sync
1050 my $reindex_heads = $self->last_commits($epoch_max) if $sync->{reindex};
1052 for (my $i = $epoch_max; $i >= 0; $i--) {
1053 my $git_dir = git_dir_n($self, $i);
1054 -d $git_dir or next; # missing epochs are fine
1055 my $git = PublicInbox::Git->new($git_dir);
1056 if ($reindex_heads) {
1057 $head = $reindex_heads->[$i] or next;
1059 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1061 next if $?; # new repo
1062 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1063 # can't use 'rev-list --count' if we use --diff-filter
1064 $pr->("$i.git counting $range ... ") if $pr;
1065 # Don't bump num_highwater on --reindex by using {D}.
1066 # We intentionally do NOT use {D} in the non-reindex case
1067 # because we want NNTP article number gaps from unindexed
1068 # messages to show up in mirrors, too.
1069 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1070 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1071 my $nr = $stk ? $stk->num_records : 0;
1072 $pr->("$nr\n") if $pr;
1073 $sync->{stacks}->[$i] = $stk if $stk;
1077 # XXX this should not happen unless somebody bypasses checks in
1078 # our code and blindly injects "d" file history into git repos
1079 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1080 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1081 my $arg = { v2w => $self };
1082 for my $oid (@leftovers) {
1083 $oid = unpack('H*', $oid);
1084 $self->{current_info} = "leftover $oid";
1085 $self->git->cat_async($oid, \&unindex_oid, $arg);
1087 $self->git->cat_async_wait;
1090 $sync->{-regen_fmt} = "%u/?\n";
1094 # reindex should NOT see new commits anymore, if we do,
1095 # it's a problem and we need to notice it via die()
1096 my $pad = length($regen_max) + 1;
1097 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1098 $sync->{nr} = \(my $nr = 0);
1099 return -1 if $sync->{reindex};
1100 $regen_max + $self->{mm}->num_highwater() || 0;
1103 sub unindex_oid_remote ($$$) {
1104 my ($self, $oid, $mid) = @_;
1105 my @removed = $self->{oidx}->remove_oid($oid, $mid);
1106 for my $num (@removed) {
1107 my $idx = idx_shard($self, $num);
1108 $idx->shard_remove($oid, $num);
1112 sub unindex_oid ($$;$) { # git->cat_async callback
1113 my ($bref, $oid, $type, $size, $sync) = @_;
1114 my $self = $sync->{v2w};
1115 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1116 my $mm = $self->{mm};
1117 my $mids = mids(PublicInbox::Eml->new($bref));
1119 my $oidx = $self->{oidx};
1120 foreach my $mid (@$mids) {
1123 while (my $smsg = $oidx->next_by_mid($mid, \$id, \$prev)) {
1124 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1126 my $n = scalar(keys(%gone)) or next;
1128 warn "BUG: multiple articles linked to $oid\n",
1129 join(',',sort keys %gone), "\n";
1131 foreach my $num (keys %gone) {
1133 my $mid0 = $mm->mid_for($num);
1134 $unindexed->{$mid0} = $num;
1136 $mm->num_delete($num);
1138 unindex_oid_remote($self, $oid, $mid);
1142 sub git { $_[0]->{ibx}->git }
1144 # this is rare, it only happens when we get discontiguous history in
1145 # a mirror because the source used -purge or -edit
1146 sub unindex ($$$$) {
1147 my ($self, $sync, $git, $unindex_range) = @_;
1148 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1149 my $before = scalar keys %$unindexed;
1150 # order does not matter, here:
1151 my @cmd = qw(log --raw -r
1152 --no-notes --no-color --no-abbrev --no-renames);
1153 my $fh = $git->popen(@cmd, $unindex_range);
1154 local $sync->{in_unindex} = 1;
1156 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1157 $self->git->cat_async($1, \&unindex_oid, $sync);
1159 close $fh or die "git log failed: \$?=$?";
1160 $self->git->cat_async_wait;
1162 return unless $sync->{-opt}->{prune};
1163 my $after = scalar keys %$unindexed;
1164 return if $before == $after;
1166 # ensure any blob can not longer be accessed via dumb HTTP
1167 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1168 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1171 sub sync_ranges ($$$) {
1172 my ($self, $sync, $epoch_max) = @_;
1173 my $reindex = $sync->{reindex};
1175 return last_commits($self, $epoch_max) unless $reindex;
1176 return [] if ref($reindex) ne 'HASH';
1178 my $ranges = $reindex->{from}; # arrayref;
1179 if (ref($ranges) ne 'ARRAY') {
1180 die 'BUG: $reindex->{from} not an ARRAY';
1185 sub index_xap_only { # git->cat_async callback
1186 my ($bref, $oid, $type, $size, $smsg) = @_;
1187 my $self = $smsg->{v2w};
1188 my $idx = idx_shard($self, $smsg->{num});
1189 $smsg->{raw_bytes} = $size;
1190 $idx->index_raw($bref, undef, $smsg);
1191 $self->{transact_bytes} += $size;
1194 sub index_xap_step ($$$;$) {
1195 my ($self, $sync, $beg, $step) = @_;
1196 my $end = $sync->{art_end};
1197 return if $beg > $end; # nothing to do
1199 $step //= $self->{shards};
1200 my $ibx = $self->{ibx};
1201 if (my $pr = $sync->{-opt}->{-progress}) {
1202 $pr->("Xapian indexlevel=$ibx->{indexlevel} ".
1203 "$beg..$end (% $step)\n");
1205 for (my $num = $beg; $num <= $end; $num += $step) {
1206 my $smsg = $ibx->over->get_art($num) or next;
1207 $smsg->{v2w} = $self;
1208 $ibx->git->cat_async($smsg->{blob}, \&index_xap_only, $smsg);
1209 if ($self->{transact_bytes} >= $self->{batch_bytes}) {
1210 ${$sync->{nr}} = $num;
1211 reindex_checkpoint($self, $sync);
1216 sub index_epoch ($$$) {
1217 my ($self, $sync, $i) = @_;
1219 my $git_dir = git_dir_n($self, $i);
1220 -d $git_dir or return; # missing epochs are fine
1221 my $git = PublicInbox::Git->new($git_dir);
1222 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1223 unindex($self, $sync, $git, $unindex_range);
1225 defined(my $stk = $sync->{stacks}->[$i]) or return;
1226 $sync->{stacks}->[$i] = undef;
1227 my $all = $self->git;
1228 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1229 $self->{current_info} = "$i.git $oid";
1231 my $arg = { %$sync, autime => $at, cotime => $ct };
1232 if ($sync->{max_size}) {
1233 $all->check_async($oid, \&check_size, $arg);
1235 $all->cat_async($oid, \&index_oid, $arg);
1237 } elsif ($f eq 'd') {
1238 $all->cat_async($oid, \&unindex_oid, $sync);
1240 if (${$sync->{need_checkpoint}}) {
1241 reindex_checkpoint($self, $sync);
1244 $all->async_wait_all;
1245 $self->update_last_commit($git, $i, $stk->{latest_cmt});
1249 my ($self, $opt, $sync, $art_beg) = @_;
1250 my $seq = $opt->{sequential_shard};
1252 local $self->{parallel} = 0 if $seq;
1253 $self->idx_init($opt); # acquire lock
1254 if (my $art_end = $self->{ibx}->mm->max) {
1256 need_checkpoint => \(my $bool = 0),
1259 nr => \(my $nr = 0),
1260 -regen_fmt => "%u/?\n",
1262 $sync->{art_end} = $art_end;
1263 if ($seq || !$self->{parallel}) {
1264 my $shard_end = $self->{shards} - 1;
1265 for my $i (0..$shard_end) {
1266 index_xap_step($self, $sync, $art_beg + $i);
1267 if ($i != $shard_end) {
1268 reindex_checkpoint($self, $sync);
1271 } else { # parallel (maybe)
1272 index_xap_step($self, $sync, $art_beg, 1);
1275 $self->git->cat_async_wait;
1279 # public, called by public-inbox-index
1281 my ($self, $opt) = @_;
1283 return xapian_only($self, $opt) if $opt->{xapian_only};
1285 my $pr = $opt->{-progress};
1287 my $latest = git_dir_latest($self, \$epoch_max);
1288 return unless defined $latest;
1290 my $seq = $opt->{sequential_shard};
1291 my $art_beg; # the NNTP article number we start xapian_only at
1292 my $idxlevel = $self->{ibx}->{indexlevel};
1293 local $self->{ibx}->{indexlevel} = 'basic' if $seq;
1295 $self->idx_init($opt); # acquire lock
1296 fill_alternates($self, $epoch_max);
1297 $self->{oidx}->rethread_prepare($opt);
1299 need_checkpoint => \(my $bool = 0),
1300 unindex_range => {}, # EPOCH => oid_old..oid_new
1301 reindex => $opt->{reindex},
1305 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1306 if (sync_prepare($self, $sync, $epoch_max)) {
1307 # tmp_clone seems to fail if inside a transaction, so
1308 # we rollback here (because we opened {mm} for reading)
1309 # Note: we do NOT rely on DBI transactions for atomicity;
1310 # only for batch performance.
1311 $self->{mm}->{dbh}->rollback;
1312 $self->{mm}->{dbh}->begin_work;
1314 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1316 # xapian_only works incrementally w/o --reindex
1317 if ($seq && !$opt->{reindex}) {
1318 $art_beg = $sync->{mm_tmp}->max;
1319 $art_beg++ if defined($art_beg);
1322 if ($sync->{max_size} = $opt->{max_size}) {
1323 $sync->{index_oid} = \&index_oid;
1325 # work forwards through history
1326 index_epoch($self, $sync, $_) for (0..$epoch_max);
1327 $self->{oidx}->rethread_done($opt);
1330 if (my $nr = $sync->{nr}) {
1331 my $pr = $sync->{-opt}->{-progress};
1332 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1335 # deal with Xapian shards sequentially
1336 if ($seq && delete($sync->{mm_tmp})) {
1337 $self->{ibx}->{indexlevel} = $idxlevel;
1338 xapian_only($self, $opt, $sync, $art_beg);
1341 # --reindex on the command-line
1342 if ($opt->{reindex} && !ref($opt->{reindex}) && $idxlevel ne 'basic') {
1343 $self->lock_acquire;
1344 my $s0 = PublicInbox::SearchIdx->new($self->{ibx}, 0, 0);
1345 if (my $xdb = $s0->idx_acquire) {
1346 my $n = $xdb->get_metadata('has_threadid');
1347 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
1350 $self->lock_release;
1353 # reindex does not pick up new changes, so we rerun w/o it:
1354 if ($opt->{reindex}) {
1357 delete @again{qw(rethread reindex -skip_lock)};
1358 index_sync($self, \%again);