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 base qw(PublicInbox::Lock);
11 use PublicInbox::SearchIdxShard;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentHash qw(content_hash content_digest);
17 use PublicInbox::Inbox;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd);
21 use PublicInbox::SearchIdx;
22 use PublicInbox::MultiMidQueue;
23 use IO::Handle; # ->autoflush
24 use File::Temp qw(tempfile);
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 for my $nproc (qw(nproc gnproc)) { # GNU coreutils nproc
39 `$nproc 2>/dev/null` =~ /^(\d+)$/ and return $1;
42 # getconf(1) is POSIX, but *NPROCESSORS* vars are not
43 for (qw(_NPROCESSORS_ONLN NPROCESSORS_ONLN)) {
44 `getconf $_ 2>/dev/null` =~ /^(\d+)$/ and return $1;
47 # should we bother with `sysctl hw.ncpu`? Those only give
48 # us total processor count, not online processor count.
52 sub nproc_shards ($) {
54 my $n = $creat_opt->{nproc} if ref($creat_opt) eq 'HASH';
57 # assume 2 cores if not detectable or zero
58 state $NPROC_DETECTED = detect_nproc() || 2;
60 $n = $NPROC_MAX_DEFAULT if $n > $NPROC_MAX_DEFAULT;
63 # subtract for the main process and git-fast-import
68 sub count_shards ($) {
71 my $xpfx = $self->{xpfx};
73 # always load existing shards in case core count changes:
74 # Also, shard count may change while -watch is running
75 # due to "xcpdb --reshard"
78 foreach my $shard (<$xpfx/*>) {
79 -d $shard && $shard =~ m!/[0-9]+\z! or next;
80 $XapianDatabase //= do {
81 require PublicInbox::Search;
82 PublicInbox::Search::load_xapian();
83 $PublicInbox::Search::X{Database};
86 $XapianDatabase->new($shard)->close;
95 # $creat may be any true value, or 0/undef. A hashref is true,
96 # and $creat->{nproc} may be set to an integer
97 my ($class, $v2ibx, $creat) = @_;
98 $v2ibx = PublicInbox::InboxWritable->new($v2ibx);
99 my $dir = $v2ibx->assert_usable_dir;
103 File::Path::mkpath($dir);
105 die "$dir does not exist\n";
108 $v2ibx->umask_prepare;
110 my $xpfx = "$dir/xap" . PublicInbox::Search::SCHEMA_VERSION;
113 im => undef, # PublicInbox::Import
119 over => PublicInbox::OverIdx->new("$xpfx/over.sqlite3", 1),
120 lock_path => "$dir/inbox.lock",
121 # limit each git repo (epoch) to 1GB or so
122 rotate_bytes => int((1024 * 1024 * 1024) / $PACKING_FACTOR),
123 last_commit => [], # git repo -> commit
125 $self->{shards} = count_shards($self) || nproc_shards($creat);
126 $self->{index_max_size} = $v2ibx->{index_max_size};
132 my ($self, $shards, $skip_epoch, $skip_artnum) = @_;
133 if (defined $shards) {
134 $self->{parallel} = 0 if $shards == 0;
135 $self->{shards} = $shards if $shards > 0;
138 $self->{mm}->skip_artnum($skip_artnum) if defined $skip_artnum;
140 git_dir_latest($self, \$epoch_max);
141 if (defined $skip_epoch && $epoch_max == -1) {
142 $epoch_max = $skip_epoch;
144 $self->git_init($epoch_max >= 0 ? $epoch_max : 0);
148 # returns undef on duplicate or spam
149 # mimics Import::add and wraps it for v2
151 my ($self, $mime, $check_cb) = @_;
152 $self->{-inbox}->with_umask(sub {
153 _add($self, $mime, $check_cb)
157 # indexes a message, returns true if checkpointing is needed
159 my ($self, $msgref, $mime, $smsg) = @_;
160 $smsg->{bytes} = $smsg->{raw_bytes} +
161 PublicInbox::SearchIdx::crlf_adjust($$msgref);
162 $self->{over}->add_overview($mime, $smsg);
163 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
164 $idx->index_raw($msgref, $mime, $smsg);
165 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
166 $n >= ($PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
170 my ($self, $mime, $check_cb) = @_;
174 $mime = $check_cb->($mime) or return;
177 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
178 # as does SQLite 3.4.1+ (released in 2007-07-20), and
179 # Xapian 1.3.2+ (released 2015-03-15).
180 # For the most part, we can spawn git-fast-import without
181 # leaking FDs to it...
184 my ($num, $mid0) = v2_num_for($self, $mime);
185 defined $num or return; # duplicate
186 defined $mid0 or die "BUG: \$mid0 undefined\n";
187 my $im = $self->importer;
188 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
189 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
190 $cmt = $im->get_mark($cmt);
191 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
193 my $msgref = delete $smsg->{-raw_email};
194 if (do_idx($self, $msgref, $mime, $smsg)) {
202 my ($self, $mime) = @_;
203 my $mids = mids($mime->header_obj);
205 my $mid = $mids->[0];
206 my $num = $self->{mm}->mid_insert($mid);
207 if (defined $num) { # common case
211 # crap, Message-ID is already known, hope somebody just resent:
212 foreach my $m (@$mids) {
213 # read-only lookup now safe to do after above barrier
214 # easy, don't store duplicates
215 # note: do not add more diagnostic info here since
216 # it gets noisy on public-inbox-watch restarts
217 return () if content_exists($self, $mime, $m);
220 # AltId may pre-populate article numbers (e.g. X-Mail-Count
221 # or NNTP article number), use that article number if it's
223 my $altid = $self->{-inbox}->{altid};
224 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
225 my $num = $self->{mm}->num_for($mid);
227 if (defined $num && !$self->{over}->get_art($num)) {
233 warn "<$mid> reused for mismatched content\n";
235 # try the rest of the mids
236 for(my $i = $#$mids; $i >= 1; $i--) {
238 $num = $self->{mm}->mid_insert($m);
240 warn "alternative <$m> for <$mid> found\n";
245 # none of the existing Message-IDs are good, generate a new one:
246 v2_num_for_harder($self, $mime);
249 sub v2_num_for_harder {
250 my ($self, $mime) = @_;
252 my $hdr = $mime->header_obj;
253 my $dig = content_digest($mime);
254 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
255 my $num = $self->{mm}->mid_insert($mid0);
256 unless (defined $num) {
257 # it's hard to spoof the last Received: header
258 my @recvd = $hdr->header_raw('Received');
259 $dig->add("Received: $_") foreach (@recvd);
260 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
261 $num = $self->{mm}->mid_insert($mid0);
263 # fall back to a random Message-ID and give up determinism:
264 until (defined($num)) {
266 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
267 warn "using random Message-ID <$mid0> as fallback\n";
268 $num = $self->{mm}->mid_insert($mid0);
271 PublicInbox::Import::append_mid($hdr, $mid0);
276 my ($self, $shard_i) = @_;
277 $self->{idx_shards}->[$shard_i];
282 my ($self, $opt) = @_;
283 return if $self->{idx_shards};
284 my $ibx = $self->{-inbox};
286 # do not leak read-only FDs to child processes, we only have these
287 # FDs for duplicate detection so they should not be
288 # frequently activated.
289 delete $ibx->{$_} foreach (qw(git mm search));
291 my $indexlevel = $ibx->{indexlevel};
292 if ($indexlevel && $indexlevel eq 'basic') {
293 $self->{parallel} = 0;
296 if ($self->{parallel}) {
297 pipe(my ($r, $w)) or die "pipe failed: $!";
298 # pipe for barrier notifications doesn't need to be big,
300 fcntl($w, 1031, 4096) if $^O eq 'linux';
301 $self->{bnote} = [ $r, $w ];
305 my $over = $self->{over};
307 $ibx->with_umask(sub {
308 $self->lock_acquire unless ($opt && $opt->{-skip_lock});
311 # xcpdb can change shard count while -watch is idle
312 my $nshards = count_shards($self);
313 if ($nshards && $nshards != $self->{shards}) {
314 $self->{shards} = $nshards;
317 # need to create all shards before initializing msgmap FD
318 my $max = $self->{shards} - 1;
320 # idx_shards must be visible to all forked processes
321 my $idx = $self->{idx_shards} = [];
322 for my $i (0..$max) {
323 push @$idx, PublicInbox::SearchIdxShard->new($self, $i);
326 # Now that all subprocesses are up, we can open the FDs
328 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
329 "$self->{-inbox}->{inboxdir}/msgmap.sqlite3", 1);
330 $mm->{dbh}->begin_work;
334 # returns an array mapping [ epoch => latest_commit ]
335 # latest_commit may be undef if nothing was done to that epoch
336 # $replace_map = { $object_id => $strref, ... }
337 sub _replace_oids ($$$) {
338 my ($self, $mime, $replace_map) = @_;
340 my $pfx = "$self->{-inbox}->{inboxdir}/git";
341 my $rewrites = []; # epoch => commit
342 my $max = $self->{epoch_max};
344 unless (defined($max)) {
345 defined(my $latest = git_dir_latest($self, \$max)) or return;
346 $self->{epoch_max} = $max;
349 foreach my $i (0..$max) {
350 my $git_dir = "$pfx/$i.git";
352 my $git = PublicInbox::Git->new($git_dir);
353 my $im = $self->import_init($git, 0, 1);
354 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
360 sub content_hashes ($) {
362 my @chashes = ( content_hash($mime) );
364 # We still support Email::MIME, here, and
365 # Email::MIME->as_string doesn't always round-trip, so we may
366 # use a second content_hash
367 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
368 push @chashes, $rt if $chashes[0] ne $rt;
372 sub content_matches ($$) {
373 my ($chashes, $existing) = @_;
374 my $chash = content_hash($existing);
375 foreach (@$chashes) {
376 return 1 if $_ eq $chash
381 # used for removing or replacing (purging)
382 sub rewrite_internal ($$;$$$) {
383 my ($self, $old_mime, $cmt_msg, $new_mime, $sref) = @_;
385 my ($im, $need_reindex, $replace_map);
387 $replace_map = {}; # oid => sref
388 $need_reindex = [] if $new_mime;
390 $im = $self->importer;
392 my $over = $self->{over};
393 my $chashes = content_hashes($old_mime);
395 my $mids = mids($old_mime->header_obj);
397 # We avoid introducing new blobs into git since the raw content
398 # can be slightly different, so we do not need the user-supplied
399 # message now that we have the mids and content_hash
403 foreach my $mid (@$mids) {
404 my %gone; # num => [ smsg, $mime, raw ]
406 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
407 my $msg = get_blob($self, $smsg);
408 if (!defined($msg)) {
409 warn "broken smsg for $mid\n";
413 my $cur = PublicInbox::Eml->new($msg);
414 if (content_matches($chashes, $cur)) {
415 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
418 my $n = scalar keys %gone;
421 warn "BUG: multiple articles linked to <$mid>\n",
422 join(',', sort keys %gone), "\n";
424 foreach my $num (keys %gone) {
425 my ($smsg, $mime, $orig) = @{$gone{$num}};
426 # @removed should only be set once assuming
427 # no bugs in our deduplication code:
428 @removed = (undef, $mime, $smsg);
429 my $oid = $smsg->{blob};
431 $replace_map->{$oid} = $sref;
433 ($mark, undef) = $im->remove($orig, $cmt_msg);
437 if ($need_reindex) { # ->replace
438 push @$need_reindex, $smsg;
439 } else { # ->purge or ->remove
440 $self->{mm}->num_delete($num);
442 unindex_oid_remote($self, $oid, $mid);
447 my $cmt = $im->get_mark($mark);
448 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
450 if ($replace_map && scalar keys %$replace_map) {
451 my $rewrites = _replace_oids($self, $new_mime, $replace_map);
452 return { rewrites => $rewrites, need_reindex => $need_reindex };
454 defined($mark) ? @removed : undef;
457 # public (see PublicInbox::Import->remove), but note the 3rd element
458 # (retval[2]) is not part of the stable API shared with Import->remove
460 my ($self, $mime, $cmt_msg) = @_;
462 $self->{-inbox}->with_umask(sub {
463 @ret = rewrite_internal($self, $mime, $cmt_msg);
465 defined($ret[0]) ? @ret : undef;
468 sub _replace ($$;$$) {
469 my ($self, $old_mime, $new_mime, $sref) = @_;
470 my $rewritten = $self->{-inbox}->with_umask(sub {
471 rewrite_internal($self, $old_mime, undef, $new_mime, $sref);
474 my $rewrites = $rewritten->{rewrites};
475 # ->done is called if there are rewrites since we gc+prune from git
476 $self->idx_init if @$rewrites;
478 for my $i (0..$#$rewrites) {
479 defined(my $cmt = $rewrites->[$i]) or next;
480 $self->{last_commit}->[$i] = $cmt;
487 my ($self, $mime) = @_;
488 my $rewritten = _replace($self, $mime, undef, \'') or return;
489 $rewritten->{rewrites}
492 # returns the git object_id of $fh, does not write the object to FS
493 sub git_hash_raw ($$) {
494 my ($self, $raw) = @_;
495 # grab the expected OID we have to reindex:
496 open my $tmp_fh, '+>', undef or die "failed to open tmp: $!";
497 $tmp_fh->autoflush(1);
498 print $tmp_fh $$raw or die "print \$tmp_fh: $!";
499 sysseek($tmp_fh, 0, 0) or die "seek failed: $!";
501 my $git_dir = $self->{-inbox}->git->{git_dir};
502 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
503 my $r = popen_rd($cmd, undef, { 0 => $tmp_fh });
505 chomp(my $oid = <$r>);
506 close $r or die "git hash-object failed: $?";
507 $oid =~ /\A[a-f0-9]{40}\z/ or die "OID not expected: $oid";
511 sub _check_mids_match ($$$) {
512 my ($old_list, $new_list, $hdrs) = @_;
513 my %old_mids = map { $_ => 1 } @$old_list;
514 my %new_mids = map { $_ => 1 } @$new_list;
515 my @old = keys %old_mids;
516 my @new = keys %new_mids;
517 my $err = "$hdrs may not be changed when replacing\n";
518 die $err if scalar(@old) != scalar(@new);
519 delete @new_mids{@old};
520 delete @old_mids{@new};
521 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
524 # Changing Message-IDs or References with ->replace isn't supported.
525 # The rules for dealing with messages with multiple or conflicting
526 # Message-IDs are pretty complex and rethreading hasn't been fully
528 sub check_mids_match ($$) {
529 my ($old_mime, $new_mime) = @_;
530 my $old = $old_mime->header_obj;
531 my $new = $new_mime->header_obj;
532 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
533 _check_mids_match(references($old), references($new),
534 'References/In-Reply-To');
539 my ($self, $old_mime, $new_mime) = @_;
541 check_mids_match($old_mime, $new_mime);
543 # mutt will always add Content-Length:, Status:, Lines: when editing
544 PublicInbox::Import::drop_unwanted_headers($new_mime);
546 my $raw = $new_mime->as_string;
547 my $expect_oid = git_hash_raw($self, \$raw);
548 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
549 my $need_reindex = $rewritten->{need_reindex};
551 # just in case we have bugs in deduplication code:
552 my $n = scalar(@$need_reindex);
554 my $list = join(', ', map {
555 "$_->{num}: <$_->{mid}>"
558 W: rewritten $n messages matching content of original message (expected: 1).
559 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
564 # make sure we really got the OID:
565 my ($blob, $type, $bytes) = $self->{-inbox}->git->check($expect_oid);
566 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
568 # don't leak FDs to Xapian:
569 $self->{-inbox}->git->cleanup;
571 # reindex modified messages:
572 for my $smsg (@$need_reindex) {
573 my $new_smsg = bless {
578 }, 'PublicInbox::Smsg';
579 my $v2w = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
580 $new_smsg->populate($new_mime, $v2w);
581 do_idx($self, \$raw, $new_mime, $new_smsg);
583 $rewritten->{rewrites};
586 sub last_epoch_commit ($$;$) {
587 my ($self, $i, $cmt) = @_;
588 my $v = PublicInbox::Search::SCHEMA_VERSION();
589 $self->{mm}->last_commit_xap($v, $i, $cmt);
592 sub set_last_commits ($) {
594 defined(my $epoch_max = $self->{epoch_max}) or return;
595 my $last_commit = $self->{last_commit};
596 foreach my $i (0..$epoch_max) {
597 defined(my $cmt = $last_commit->[$i]) or next;
598 $last_commit->[$i] = undef;
599 last_epoch_commit($self, $i, $cmt);
605 $self->{bnote} or return;
607 my $barrier = { map { $_ => 1 } (0..$n) };
611 my ($self, $barrier) = @_;
612 my $bnote = $self->{bnote} or return;
614 while (scalar keys %$barrier) {
615 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
616 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
617 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
622 sub checkpoint ($;$) {
623 my ($self, $wait) = @_;
625 if (my $im = $self->{im}) {
632 my $shards = $self->{idx_shards};
634 my $dbh = $self->{mm}->{dbh};
636 # SQLite msgmap data is second in importance
639 # SQLite overview is third
640 $self->{over}->commit_lazy;
642 # Now deal with Xapian
644 my $barrier = $self->barrier_init(scalar @$shards);
646 # each shard needs to issue a barrier command
647 $_->remote_barrier for @$shards;
649 # wait for each Xapian shard
650 $self->barrier_wait($barrier);
652 $_->remote_commit for @$shards;
655 # last_commit is special, don't commit these until
656 # remote shards are done:
658 set_last_commits($self);
663 $self->{total_bytes} += $self->{transact_bytes};
664 $self->{transact_bytes} = 0;
667 # issue a write barrier to ensure all data is visible to other processes
668 # and read-only ops. Order of data importance is: git > SQLite > Xapian
670 sub barrier { checkpoint($_[0], 1) };
675 my $im = delete $self->{im};
676 $im->done if $im; # PublicInbox::Import::done
678 my $mm = delete $self->{mm};
679 $mm->{dbh}->commit if $mm;
680 my $shards = delete $self->{idx_shards};
682 $_->remote_close for @$shards;
684 $self->{over}->disconnect;
685 delete $self->{bnote};
686 my $nbytes = $self->{total_bytes};
687 $self->{total_bytes} = 0;
688 $self->lock_release(!!$nbytes) if $shards;
689 $self->{-inbox}->git->cleanup;
692 sub fill_alternates ($$) {
693 my ($self, $epoch) = @_;
695 my $pfx = "$self->{-inbox}->{inboxdir}/git";
696 my $all = "$self->{-inbox}->{inboxdir}/all.git";
699 PublicInbox::Import::init_bare($all);
701 my $info_dir = "$all/objects/info";
702 my $alt = "$info_dir/alternates";
706 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
707 $mode = (stat($fh))[2] & 07777;
709 # we assign a sort score to every alternate and favor
710 # the newest (highest numbered) one when we
712 my $other = 0; # in case admin adds non-epoch repos
714 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
720 } split(/\n+/, do { local $/; <$fh> });
723 foreach my $i (0..$epoch) {
724 my $dir = "../../git/$i.git/objects";
725 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
732 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
733 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
734 or die "print $tmp: $!\n";
735 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
736 close $fh or die "close $tmp $!\n";
737 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
741 my ($self, $epoch) = @_;
742 my $git_dir = "$self->{-inbox}->{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->{-inbox}->{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->{-inbox});
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, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
819 print $ah $cur->as_string or die "print: $!";
820 close $ah or die "close: $!";
821 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
822 PublicInbox::Import::drop_unwanted_headers($new);
823 print $bh $new->as_string or die "print: $!";
824 close $bh or die "close: $!";
825 my $cmd = [ qw(diff -u), $an, $bn ];
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";
833 my ($self, $smsg) = @_;
834 if (my $im = $self->{im}) {
835 my $msg = $im->cat_blob($smsg->{blob});
838 # older message, should be in alternates
839 my $ibx = $self->{-inbox};
840 $ibx->msg_by_smsg($smsg);
843 sub content_exists ($$$) {
844 my ($self, $mime, $mid) = @_;
845 my $over = $self->{over};
846 my $chashes = content_hashes($mime);
848 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
849 my $msg = get_blob($self, $smsg);
850 if (!defined($msg)) {
851 warn "broken smsg for $mid\n";
854 my $cur = PublicInbox::Eml->new($msg);
855 return 1 if content_matches($chashes, $cur);
857 # XXX DEBUG_DIFF is experimental and may be removed
858 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
865 my $fh = delete $self->{reindex_pipe};
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 mark_deleted ($$$$) {
879 my ($self, $sync, $git, $oid) = @_;
880 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
881 my $msgref = $git->cat_file($oid);
882 my $mime = PublicInbox::Eml->new($$msgref);
883 my $mids = mids($mime->header_obj);
884 my $chash = content_hash($mime);
885 foreach my $mid (@$mids) {
886 $sync->{D}->{"$mid\0$chash"} = $oid;
890 sub reindex_checkpoint ($$$) {
891 my ($self, $sync, $git) = @_;
894 $sync->{mm_tmp}->atfork_prepare;
895 $self->done; # release lock
897 if (my $pr = $sync->{-opt}->{-progress}) {
898 my ($bn) = (split('/', $git->{git_dir}))[-1];
899 $pr->("$bn ".sprintf($sync->{-regen_fmt}, $sync->{nr}));
902 # allow -watch or -mda to write...
903 $self->idx_init; # reacquire lock
904 $sync->{mm_tmp}->atfork_parent;
907 # only for a few odd messages with multiple Message-IDs
908 sub reindex_oid_m ($$$$;$) {
909 my ($self, $sync, $git, $oid, $regen_num) = @_;
910 $self->{current_info} = "multi_mid $oid";
911 my ($num, $mid0, $len);
912 my $msgref = $git->cat_file($oid, \$len);
913 my $mime = PublicInbox::Eml->new($$msgref);
914 my $mids = mids($mime->header_obj);
915 my $chash = content_hash($mime);
916 die "BUG: reindex_oid_m called for <=1 mids" if scalar(@$mids) <= 1;
918 for my $mid (reverse @$mids) {
919 delete($sync->{D}->{"$mid\0$chash"}) and
920 die "BUG: reindex_oid should handle <$mid> delete";
922 my $over = $self->{over};
923 for my $mid (reverse @$mids) {
924 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
925 next unless defined $num;
926 if (defined($regen_num) && $regen_num != $num) {
927 die "BUG: regen(#$regen_num) != over(#$num)";
930 unless (defined($num)) {
931 for my $mid (reverse @$mids) {
932 # is this a number we got before?
933 my $n = $sync->{mm_tmp}->num_for($mid);
934 next unless defined $n;
935 next if defined($regen_num) && $regen_num != $n;
936 ($num, $mid0) = ($n, $mid);
941 $sync->{mm_tmp}->num_delete($num);
942 } elsif (defined $regen_num) {
944 for my $mid (reverse @$mids) {
945 $self->{mm}->mid_set($num, $mid) == 1 or next;
949 unless (defined $mid0) {
950 warn "E: cannot regen #$num\n";
953 } else { # fixup bugs in old mirrors on reindex
954 for my $mid (reverse @$mids) {
955 $num = $self->{mm}->mid_insert($mid);
956 next unless defined $num;
961 if ($sync->{reindex}) {
962 warn "reindex added #$num <$mid0>\n";
965 warn "E: cannot find article #\n";
975 }, 'PublicInbox::Smsg';
976 $smsg->populate($mime, $self);
977 if (do_idx($self, $msgref, $mime, $smsg)) {
978 reindex_checkpoint($self, $sync, $git);
982 sub check_unindexed ($$$) {
983 my ($self, $num, $mid0) = @_;
984 my $unindexed = $self->{unindexed} // {};
985 my $n = delete($unindexed->{$mid0});
986 defined $n or return;
988 die "BUG: unindexed $n != $num <$mid0>\n";
990 $self->{mm}->mid_set($num, $mid0);
994 sub multi_mid_q_push ($$$) {
995 my ($self, $sync, $oid) = @_;
996 my $multi_mid = $sync->{multi_mid} //= PublicInbox::MultiMidQueue->new;
997 if ($sync->{reindex}) { # no regen on reindex
998 $multi_mid->push_oid($oid, $self);
1000 my $num = $sync->{regen}--;
1001 die "BUG: ran out of article numbers" if $num <= 0;
1002 $multi_mid->set_oid($num, $oid, $self);
1006 sub reindex_oid ($$$$) {
1007 my ($self, $sync, $git, $oid) = @_;
1008 return if PublicInbox::SearchIdx::too_big($self, $git, $oid);
1009 my ($num, $mid0, $len);
1010 my $msgref = $git->cat_file($oid, \$len);
1011 return if $len == 0; # purged
1012 my $mime = PublicInbox::Eml->new($$msgref);
1013 my $mids = mids($mime->header_obj);
1014 my $chash = content_hash($mime);
1016 if (scalar(@$mids) == 0) {
1017 warn "E: $oid has no Message-ID, skipping\n";
1019 } elsif (scalar(@$mids) == 1) {
1020 my $mid = $mids->[0];
1022 # was the file previously marked as deleted?, skip if so
1023 if (delete($sync->{D}->{"$mid\0$chash"})) {
1024 if (!$sync->{reindex}) {
1025 $num = $sync->{regen}--;
1026 $self->{mm}->num_highwater($num);
1031 # is this a number we got before?
1032 $num = $sync->{mm_tmp}->num_for($mid);
1035 check_unindexed($self, $num, $mid0);
1037 $num = $sync->{regen}--;
1038 die "BUG: ran out of article numbers" if $num <= 0;
1039 if ($self->{mm}->mid_set($num, $mid) != 1) {
1040 warn "E: unable to assign $num => <$mid>\n";
1045 } else { # multiple MIDs are a weird case:
1048 $del += delete($sync->{D}->{"$_\0$chash"}) // 0;
1051 unindex_oid_remote($self, $oid, $_) for @$mids;
1052 # do not delete from {mm_tmp}, since another
1053 # single-MID message may use it.
1054 } else { # handle them at the end:
1055 multi_mid_q_push($self, $sync, $oid);
1059 $sync->{mm_tmp}->mid_delete($mid0) or
1060 die "failed to delete <$mid0> for article #$num\n";
1067 }, 'PublicInbox::Smsg';
1068 $smsg->populate($mime, $self);
1069 if (do_idx($self, $msgref, $mime, $smsg)) {
1070 reindex_checkpoint($self, $sync, $git);
1074 # only update last_commit for $i on reindex iff newer than current
1075 sub update_last_commit ($$$$) {
1076 my ($self, $git, $i, $cmt) = @_;
1077 my $last = last_epoch_commit($self, $i);
1078 if (defined $last && is_ancestor($git, $last, $cmt)) {
1079 my @cmd = (qw(rev-list --count), "$last..$cmt");
1080 chomp(my $n = $git->qx(@cmd));
1081 return if $n ne '' && $n == 0;
1083 last_epoch_commit($self, $i, $cmt);
1086 sub git_dir_n ($$) { "$_[0]->{-inbox}->{inboxdir}/git/$_[1].git" }
1088 sub last_commits ($$) {
1089 my ($self, $epoch_max) = @_;
1091 for (my $i = $epoch_max; $i >= 0; $i--) {
1092 $heads->[$i] = last_epoch_commit($self, $i);
1097 *is_ancestor = *PublicInbox::SearchIdx::is_ancestor;
1099 # returns a revision range for git-log(1)
1100 sub log_range ($$$$$) {
1101 my ($self, $sync, $git, $i, $tip) = @_;
1102 my $opt = $sync->{-opt};
1103 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
1104 my $cur = $sync->{ranges}->[$i] or do {
1105 $pr->("$i.git indexing all of $tip") if $pr;
1106 return $tip; # all of it
1109 # fast equality check to avoid (v)fork+execve overhead
1111 $sync->{ranges}->[$i] = undef;
1115 my $range = "$cur..$tip";
1116 $pr->("$i.git checking contiguity... ") if $pr;
1117 if (is_ancestor($git, $cur, $tip)) { # common case
1118 $pr->("OK\n") if $pr;
1119 my $n = $git->qx(qw(rev-list --count), $range);
1122 $sync->{ranges}->[$i] = undef;
1123 $pr->("$i.git has nothing new\n") if $pr;
1124 return; # nothing to do
1126 $pr->("$i.git has $n changes since $cur\n") if $pr;
1128 $pr->("FAIL\n") if $pr;
1130 discontiguous range: $range
1131 Rewritten history? (in $git->{git_dir})
1133 chomp(my $base = $git->qx('merge-base', $tip, $cur));
1135 $range = "$base..$tip";
1136 warn "found merge-base: $base\n"
1139 warn "discarding history at $cur\n";
1142 reindexing $git->{git_dir} starting at
1145 $sync->{unindex_range}->{$i} = "$base..$cur";
1150 sub sync_prepare ($$$) {
1151 my ($self, $sync, $epoch_max) = @_;
1152 my $pr = $sync->{-opt}->{-progress};
1154 my $head = $self->{-inbox}->{ref_head} || 'refs/heads/master';
1156 # reindex stops at the current heads and we later rerun index_sync
1158 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1160 for (my $i = $epoch_max; $i >= 0; $i--) {
1161 die 'BUG: already indexing!' if $self->{reindex_pipe};
1162 my $git_dir = git_dir_n($self, $i);
1163 -d $git_dir or next; # missing epochs are fine
1164 my $git = PublicInbox::Git->new($git_dir);
1165 if ($reindex_heads) {
1166 $head = $reindex_heads->[$i] or next;
1168 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1170 next if $?; # new repo
1171 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1172 $sync->{ranges}->[$i] = $range;
1174 # can't use 'rev-list --count' if we use --diff-filter
1175 $pr->("$i.git counting $range ... ") if $pr;
1177 my $fh = $git->popen(qw(log --pretty=tformat:%H
1178 --no-notes --no-color --no-renames
1179 --diff-filter=AM), $range, '--', 'm');
1181 close $fh or die "git log failed: \$?=$?";
1182 $pr->("$n\n") if $pr;
1186 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1188 # reindex should NOT see new commits anymore, if we do,
1189 # it's a problem and we need to notice it via die()
1190 my $pad = length($regen_max) + 1;
1191 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1193 return -1 if $sync->{reindex};
1194 $regen_max + $self->{mm}->num_highwater() || 0;
1197 sub unindex_oid_remote ($$$) {
1198 my ($self, $oid, $mid) = @_;
1199 $_->remote_remove($oid, $mid) foreach @{$self->{idx_shards}};
1200 $self->{over}->remove_oid($oid, $mid);
1203 sub unindex_oid ($$$;$) {
1204 my ($self, $git, $oid, $unindexed) = @_;
1205 my $mm = $self->{mm};
1206 my $msgref = $git->cat_file($oid);
1207 my $mime = PublicInbox::Eml->new($msgref);
1208 my $mids = mids($mime->header_obj);
1209 $mime = $msgref = undef;
1210 my $over = $self->{over};
1211 foreach my $mid (@$mids) {
1214 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1215 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1218 my $n = scalar keys %gone;
1221 warn "BUG: multiple articles linked to $oid\n",
1222 join(',',sort keys %gone), "\n";
1224 foreach my $num (keys %gone) {
1226 my $mid0 = $mm->mid_for($num);
1227 $unindexed->{$mid0} = $num;
1229 $mm->num_delete($num);
1231 unindex_oid_remote($self, $oid, $mid);
1235 my $x40 = qr/[a-f0-9]{40}/;
1236 sub unindex ($$$$) {
1237 my ($self, $sync, $git, $unindex_range) = @_;
1238 my $unindexed = $self->{unindexed} ||= {}; # $mid0 => $num
1239 my $before = scalar keys %$unindexed;
1240 # order does not matter, here:
1241 my @cmd = qw(log --raw -r
1242 --no-notes --no-color --no-abbrev --no-renames);
1243 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $unindex_range);
1245 /\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o or next;
1246 unindex_oid($self, $git, $1, $unindexed);
1248 delete $self->{reindex_pipe};
1249 close $fh or die "git log failed: \$?=$?";
1251 return unless $sync->{-opt}->{prune};
1252 my $after = scalar keys %$unindexed;
1253 return if $before == $after;
1255 # ensure any blob can not longer be accessed via dumb HTTP
1256 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1257 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1260 sub sync_ranges ($$$) {
1261 my ($self, $sync, $epoch_max) = @_;
1262 my $reindex = $sync->{reindex};
1264 return last_commits($self, $epoch_max) unless $reindex;
1265 return [] if ref($reindex) ne 'HASH';
1267 my $ranges = $reindex->{from}; # arrayref;
1268 if (ref($ranges) ne 'ARRAY') {
1269 die 'BUG: $reindex->{from} not an ARRAY';
1274 sub index_epoch ($$$) {
1275 my ($self, $sync, $i) = @_;
1277 my $git_dir = git_dir_n($self, $i);
1278 die 'BUG: already reindexing!' if $self->{reindex_pipe};
1279 -d $git_dir or return; # missing epochs are fine
1280 fill_alternates($self, $i);
1281 my $git = PublicInbox::Git->new($git_dir);
1282 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) {
1283 unindex($self, $sync, $git, $unindex_range);
1285 defined(my $range = $sync->{ranges}->[$i]) or return;
1286 if (my $pr = $sync->{-opt}->{-progress}) {
1287 $pr->("$i.git indexing $range\n");
1290 my @cmd = qw(log --raw -r --pretty=tformat:%H.%at.%ct
1291 --no-notes --no-color --no-abbrev --no-renames);
1292 my $fh = $self->{reindex_pipe} = $git->popen(@cmd, $range);
1296 $self->{current_info} = "$i.git $_";
1297 if (/\A($x40)\.([0-9]+)\.([0-9]+)$/o) {
1299 $self->{autime} = $2;
1300 $self->{cotime} = $3;
1301 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\tm$/o) {
1302 reindex_oid($self, $sync, $git, $1);
1303 } elsif (/\A:\d{6} 100644 $x40 ($x40) [AM]\td$/o) {
1304 mark_deleted($self, $sync, $git, $1);
1307 close $fh or die "git log failed: \$?=$?";
1308 delete @$self{qw(reindex_pipe autime cotime)};
1309 update_last_commit($self, $git, $i, $cmt) if defined $cmt;
1312 # public, called by public-inbox-index
1314 my ($self, $opt) = @_;
1316 my $pr = $opt->{-progress};
1318 my $latest = git_dir_latest($self, \$epoch_max);
1319 return unless defined $latest;
1320 $self->idx_init($opt); # acquire lock
1322 D => {}, # "$mid\0$chash" => $oid
1323 unindex_range => {}, # EPOCH => oid_old..oid_new
1324 reindex => $opt->{reindex},
1327 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1328 $sync->{regen} = sync_prepare($self, $sync, $epoch_max);
1330 if ($sync->{regen}) {
1331 # tmp_clone seems to fail if inside a transaction, so
1332 # we rollback here (because we opened {mm} for reading)
1333 # Note: we do NOT rely on DBI transactions for atomicity;
1334 # only for batch performance.
1335 $self->{mm}->{dbh}->rollback;
1336 $self->{mm}->{dbh}->begin_work;
1337 $sync->{mm_tmp} = $self->{mm}->tmp_clone;
1340 # work backwards through history
1341 for (my $i = $epoch_max; $i >= 0; $i--) {
1342 index_epoch($self, $sync, $i);
1345 # unindex is required for leftovers if "deletes" affect messages
1346 # in a previous fetch+index window:
1348 if (my @leftovers = values %{delete $sync->{D}}) {
1349 $git = $self->{-inbox}->git;
1350 for my $oid (@leftovers) {
1351 $self->{current_info} = "leftover $oid";
1352 unindex_oid($self, $git, $oid);
1355 if (my $multi_mid = delete $sync->{multi_mid}) {
1356 $git //= $self->{-inbox}->git;
1357 my $min = $multi_mid->{min};
1358 my $max = $multi_mid->{max};
1359 if ($sync->{reindex}) {
1360 # we may need to create new Message-IDs if mirrors
1361 # were initially indexed with old versions
1362 for (my $i = $max; $i >= $min; $i--) {
1364 $oid = $multi_mid->get_oid($i, $self) or next;
1365 next unless defined $oid;
1366 reindex_oid_m($self, $sync, $git, $oid);
1368 } else { # regen on initial index
1369 for my $num ($min..$max) {
1371 $oid = $multi_mid->get_oid($num, $self) or next;
1372 reindex_oid_m($self, $sync, $git, $oid, $num);
1376 $git->cleanup if $git;
1379 if (my $nr = $sync->{nr}) {
1380 my $pr = $sync->{-opt}->{-progress};
1381 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $nr)) if $pr;
1384 # reindex does not pick up new changes, so we rerun w/o it:
1385 if ($opt->{reindex}) {
1388 delete @again{qw(reindex -skip_lock)};
1389 index_sync($self, \%again);