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;
11 use PublicInbox::IdxStack;
14 use PublicInbox::Import;
15 use PublicInbox::MID qw(mids references);
16 use PublicInbox::ContentHash qw(content_hash content_digest);
17 use PublicInbox::InboxWritable;
18 use PublicInbox::OverIdx;
19 use PublicInbox::Msgmap;
20 use PublicInbox::Spawn qw(spawn popen_rd);
21 use PublicInbox::SearchIdx qw(log2stack crlf_adjust is_ancestor check_size);
22 use IO::Handle; # ->autoflush
23 use File::Temp qw(tempfile);
25 my $OID = qr/[a-f0-9]{40,}/;
26 # an estimate of the post-packed size to the raw uncompressed size
27 my $PACKING_FACTOR = 0.4;
29 # SATA storage lags behind what CPUs are capable of, so relying on
30 # nproc(1) can be misleading and having extra Xapian shards is a
31 # waste of FDs and space. It can also lead to excessive IO latency
32 # and slow things down. Users on NVME or other fast storage can
33 # use the NPROC env or switches in our script/public-inbox-* programs
34 # to increase Xapian shards
35 our $NPROC_MAX_DEFAULT = 4;
38 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"),
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 epoch -> commit
125 $self->{over}->{-no_sync} = 1 if $v2ibx->{-no_sync};
126 $self->{shards} = count_shards($self) || nproc_shards($creat);
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, $eml, $check_cb) = @_;
152 $self->{ibx}->with_umask(\&_add, $self, $eml, $check_cb);
155 # indexes a message, returns true if checkpointing is needed
157 my ($self, $msgref, $mime, $smsg) = @_;
158 $smsg->{bytes} = $smsg->{raw_bytes} + crlf_adjust($$msgref);
159 $self->{over}->add_overview($mime, $smsg);
160 my $idx = idx_shard($self, $smsg->{num} % $self->{shards});
161 $idx->index_raw($msgref, $mime, $smsg);
162 my $n = $self->{transact_bytes} += $smsg->{raw_bytes};
163 $n >= ($PublicInbox::SearchIdx::BATCH_BYTES * $self->{shards});
167 my ($self, $mime, $check_cb) = @_;
171 $mime = $check_cb->($mime, $self->{ibx}) or return;
174 # All pipes (> $^F) known to Perl 5.6+ have FD_CLOEXEC set,
175 # as does SQLite 3.4.1+ (released in 2007-07-20), and
176 # Xapian 1.3.2+ (released 2015-03-15).
177 # For the most part, we can spawn git-fast-import without
178 # leaking FDs to it...
181 my ($num, $mid0) = v2_num_for($self, $mime);
182 defined $num or return; # duplicate
183 defined $mid0 or die "BUG: \$mid0 undefined\n";
184 my $im = $self->importer;
185 my $smsg = bless { mid => $mid0, num => $num }, 'PublicInbox::Smsg';
186 my $cmt = $im->add($mime, undef, $smsg); # sets $smsg->{ds|ts|blob}
187 $cmt = $im->get_mark($cmt);
188 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
190 my $msgref = delete $smsg->{-raw_email};
191 if (do_idx($self, $msgref, $mime, $smsg)) {
199 my ($self, $mime) = @_;
200 my $mids = mids($mime->header_obj);
202 my $mid = $mids->[0];
203 my $num = $self->{mm}->mid_insert($mid);
204 if (defined $num) { # common case
208 # crap, Message-ID is already known, hope somebody just resent:
209 foreach my $m (@$mids) {
210 # read-only lookup now safe to do after above barrier
211 # easy, don't store duplicates
212 # note: do not add more diagnostic info here since
213 # it gets noisy on public-inbox-watch restarts
214 return () if content_exists($self, $mime, $m);
217 # AltId may pre-populate article numbers (e.g. X-Mail-Count
218 # or NNTP article number), use that article number if it's
220 my $altid = $self->{ibx}->{altid};
221 if ($altid && grep(/:file=msgmap\.sqlite3\z/, @$altid)) {
222 my $num = $self->{mm}->num_for($mid);
224 if (defined $num && !$self->{over}->get_art($num)) {
230 warn "<$mid> reused for mismatched content\n";
232 # try the rest of the mids
233 for(my $i = $#$mids; $i >= 1; $i--) {
235 $num = $self->{mm}->mid_insert($m);
237 warn "alternative <$m> for <$mid> found\n";
242 # none of the existing Message-IDs are good, generate a new one:
243 v2_num_for_harder($self, $mime);
246 sub v2_num_for_harder {
247 my ($self, $mime) = @_;
249 my $hdr = $mime->header_obj;
250 my $dig = content_digest($mime);
251 my $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
252 my $num = $self->{mm}->mid_insert($mid0);
253 unless (defined $num) {
254 # it's hard to spoof the last Received: header
255 my @recvd = $hdr->header_raw('Received');
256 $dig->add("Received: $_") foreach (@recvd);
257 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
258 $num = $self->{mm}->mid_insert($mid0);
260 # fall back to a random Message-ID and give up determinism:
261 until (defined($num)) {
263 $mid0 = PublicInbox::Import::digest2mid($dig, $hdr);
264 warn "using random Message-ID <$mid0> as fallback\n";
265 $num = $self->{mm}->mid_insert($mid0);
268 PublicInbox::Import::append_mid($hdr, $mid0);
273 my ($self, $shard_i) = @_;
274 $self->{idx_shards}->[$shard_i];
277 sub _idx_init { # with_umask callback
278 my ($self, $opt) = @_;
279 $self->lock_acquire unless $opt && $opt->{-skip_lock};
280 $self->{over}->create;
282 # xcpdb can change shard count while -watch is idle
283 my $nshards = count_shards($self);
284 $self->{shards} = $nshards if $nshards && $nshards != $self->{shards};
286 # need to create all shards before initializing msgmap FD
287 # idx_shards must be visible to all forked processes
288 my $max = $self->{shards} - 1;
289 my $idx = $self->{idx_shards} = [];
290 push @$idx, PublicInbox::SearchIdxShard->new($self, $_) for (0..$max);
292 # Now that all subprocesses are up, we can open the FDs
294 my $mm = $self->{mm} = PublicInbox::Msgmap->new_file(
295 "$self->{ibx}->{inboxdir}/msgmap.sqlite3",
296 $self->{ibx}->{-no_sync} ? 2 : 1);
297 $mm->{dbh}->begin_work;
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 $self->{parallel} = 0 if ($ibx->{indexlevel}//'') eq 'basic';
313 if ($self->{parallel}) {
314 pipe(my ($r, $w)) or die "pipe failed: $!";
315 # pipe for barrier notifications doesn't need to be big,
317 fcntl($w, 1031, 4096) if $^O eq 'linux';
318 $self->{bnote} = [ $r, $w ];
323 $ibx->with_umask(\&_idx_init, $self, $opt);
326 # returns an array mapping [ epoch => latest_commit ]
327 # latest_commit may be undef if nothing was done to that epoch
328 # $replace_map = { $object_id => $strref, ... }
329 sub _replace_oids ($$$) {
330 my ($self, $mime, $replace_map) = @_;
332 my $pfx = "$self->{ibx}->{inboxdir}/git";
333 my $rewrites = []; # epoch => commit
334 my $max = $self->{epoch_max};
336 unless (defined($max)) {
337 defined(my $latest = git_dir_latest($self, \$max)) or return;
338 $self->{epoch_max} = $max;
341 foreach my $i (0..$max) {
342 my $git_dir = "$pfx/$i.git";
344 my $git = PublicInbox::Git->new($git_dir);
345 my $im = $self->import_init($git, 0, 1);
346 $rewrites->[$i] = $im->replace_oids($mime, $replace_map);
352 sub content_hashes ($) {
354 my @chashes = ( content_hash($mime) );
356 # We still support Email::MIME, here, and
357 # Email::MIME->as_string doesn't always round-trip, so we may
358 # use a second content_hash
359 my $rt = content_hash(PublicInbox::Eml->new(\($mime->as_string)));
360 push @chashes, $rt if $chashes[0] ne $rt;
364 sub content_matches ($$) {
365 my ($chashes, $existing) = @_;
366 my $chash = content_hash($existing);
367 foreach (@$chashes) {
368 return 1 if $_ eq $chash
373 # used for removing or replacing (purging)
374 sub rewrite_internal ($$;$$$) {
375 my ($self, $old_eml, $cmt_msg, $new_eml, $sref) = @_;
377 my ($im, $need_reindex, $replace_map);
379 $replace_map = {}; # oid => sref
380 $need_reindex = [] if $new_eml;
382 $im = $self->importer;
384 my $over = $self->{over};
385 my $chashes = content_hashes($old_eml);
387 my $mids = mids($old_eml->header_obj);
389 # We avoid introducing new blobs into git since the raw content
390 # can be slightly different, so we do not need the user-supplied
391 # message now that we have the mids and content_hash
395 foreach my $mid (@$mids) {
396 my %gone; # num => [ smsg, $mime, raw ]
398 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
399 my $msg = get_blob($self, $smsg);
400 if (!defined($msg)) {
401 warn "broken smsg for $mid\n";
405 my $cur = PublicInbox::Eml->new($msg);
406 if (content_matches($chashes, $cur)) {
407 $gone{$smsg->{num}} = [ $smsg, $cur, \$orig ];
410 my $n = scalar keys %gone;
413 warn "BUG: multiple articles linked to <$mid>\n",
414 join(',', sort keys %gone), "\n";
416 foreach my $num (keys %gone) {
417 my ($smsg, $mime, $orig) = @{$gone{$num}};
418 # $removed should only be set once assuming
419 # no bugs in our deduplication code:
420 $removed = [ undef, $mime, $smsg ];
421 my $oid = $smsg->{blob};
423 $replace_map->{$oid} = $sref;
425 ($mark, undef) = $im->remove($orig, $cmt_msg);
426 $removed->[0] = $mark;
429 if ($need_reindex) { # ->replace
430 push @$need_reindex, $smsg;
431 } else { # ->purge or ->remove
432 $self->{mm}->num_delete($num);
434 unindex_oid_remote($self, $oid, $mid);
439 my $cmt = $im->get_mark($mark);
440 $self->{last_commit}->[$self->{epoch_max}] = $cmt;
442 if ($replace_map && scalar keys %$replace_map) {
443 my $rewrites = _replace_oids($self, $new_eml, $replace_map);
444 return { rewrites => $rewrites, need_reindex => $need_reindex };
446 defined($mark) ? $removed : undef;
449 # public (see PublicInbox::Import->remove), but note the 3rd element
450 # (retval[2]) is not part of the stable API shared with Import->remove
452 my ($self, $eml, $cmt_msg) = @_;
453 my $r = $self->{ibx}->with_umask(\&rewrite_internal,
454 $self, $eml, $cmt_msg);
455 defined($r) && defined($r->[0]) ? @$r: undef;
458 sub _replace ($$;$$) {
459 my ($self, $old_eml, $new_eml, $sref) = @_;
460 my $arg = [ $self, $old_eml, undef, $new_eml, $sref ];
461 my $rewritten = $self->{ibx}->with_umask(\&rewrite_internal,
462 $self, $old_eml, undef, $new_eml, $sref) or return;
464 my $rewrites = $rewritten->{rewrites};
465 # ->done is called if there are rewrites since we gc+prune from git
466 $self->idx_init if @$rewrites;
468 for my $i (0..$#$rewrites) {
469 defined(my $cmt = $rewrites->[$i]) or next;
470 $self->{last_commit}->[$i] = $cmt;
477 my ($self, $mime) = @_;
478 my $rewritten = _replace($self, $mime, undef, \'') or return;
479 $rewritten->{rewrites}
482 # returns the git object_id of $fh, does not write the object to FS
483 sub git_hash_raw ($$) {
484 my ($self, $raw) = @_;
485 # grab the expected OID we have to reindex:
486 pipe(my($in, $w)) or die "pipe: $!";
487 my $git_dir = $self->{ibx}->git->{git_dir};
488 my $cmd = ['git', "--git-dir=$git_dir", qw(hash-object --stdin)];
489 my $r = popen_rd($cmd, undef, { 0 => $in });
490 print $w $$raw or die "print \$w: $!";
491 close $w or die "close \$w: $!";
493 chomp(my $oid = <$r>);
494 close $r or die "git hash-object failed: $?";
495 $oid =~ /\A$OID\z/ or die "OID not expected: $oid";
499 sub _check_mids_match ($$$) {
500 my ($old_list, $new_list, $hdrs) = @_;
501 my %old_mids = map { $_ => 1 } @$old_list;
502 my %new_mids = map { $_ => 1 } @$new_list;
503 my @old = keys %old_mids;
504 my @new = keys %new_mids;
505 my $err = "$hdrs may not be changed when replacing\n";
506 die $err if scalar(@old) != scalar(@new);
507 delete @new_mids{@old};
508 delete @old_mids{@new};
509 die $err if (scalar(keys %old_mids) || scalar(keys %new_mids));
512 # Changing Message-IDs or References with ->replace isn't supported.
513 # The rules for dealing with messages with multiple or conflicting
514 # Message-IDs are pretty complex and rethreading hasn't been fully
516 sub check_mids_match ($$) {
517 my ($old_mime, $new_mime) = @_;
518 my $old = $old_mime->header_obj;
519 my $new = $new_mime->header_obj;
520 _check_mids_match(mids($old), mids($new), 'Message-ID(s)');
521 _check_mids_match(references($old), references($new),
522 'References/In-Reply-To');
527 my ($self, $old_mime, $new_mime) = @_;
529 check_mids_match($old_mime, $new_mime);
531 # mutt will always add Content-Length:, Status:, Lines: when editing
532 PublicInbox::Import::drop_unwanted_headers($new_mime);
534 my $raw = $new_mime->as_string;
535 my $expect_oid = git_hash_raw($self, \$raw);
536 my $rewritten = _replace($self, $old_mime, $new_mime, \$raw) or return;
537 my $need_reindex = $rewritten->{need_reindex};
539 # just in case we have bugs in deduplication code:
540 my $n = scalar(@$need_reindex);
542 my $list = join(', ', map {
543 "$_->{num}: <$_->{mid}>"
546 W: rewritten $n messages matching content of original message (expected: 1).
547 W: possible bug in public-inbox, NNTP article IDs and Message-IDs follow:
552 # make sure we really got the OID:
553 my ($blob, $type, $bytes) = $self->{ibx}->git->check($expect_oid);
554 $blob eq $expect_oid or die "BUG: $expect_oid not found after replace";
556 # don't leak FDs to Xapian:
557 $self->{ibx}->git->cleanup;
559 # reindex modified messages:
560 for my $smsg (@$need_reindex) {
561 my $new_smsg = bless {
566 }, 'PublicInbox::Smsg';
567 my $sync = { autime => $smsg->{ds}, cotime => $smsg->{ts} };
568 $new_smsg->populate($new_mime, $sync);
569 do_idx($self, \$raw, $new_mime, $new_smsg);
571 $rewritten->{rewrites};
574 sub last_epoch_commit ($$;$) {
575 my ($self, $i, $cmt) = @_;
576 my $v = PublicInbox::Search::SCHEMA_VERSION();
577 $self->{mm}->last_commit_xap($v, $i, $cmt);
580 sub set_last_commits ($) {
582 defined(my $epoch_max = $self->{epoch_max}) or return;
583 my $last_commit = $self->{last_commit};
584 foreach my $i (0..$epoch_max) {
585 defined(my $cmt = $last_commit->[$i]) or next;
586 $last_commit->[$i] = undef;
587 last_epoch_commit($self, $i, $cmt);
593 $self->{bnote} or return;
595 my $barrier = { map { $_ => 1 } (0..$n) };
599 my ($self, $barrier) = @_;
600 my $bnote = $self->{bnote} or return;
602 while (scalar keys %$barrier) {
603 defined(my $l = readline($r)) or die "EOF on barrier_wait: $!";
604 $l =~ /\Abarrier (\d+)/ or die "bad line on barrier_wait: $l";
605 delete $barrier->{$1} or die "bad shard[$1] on barrier wait";
610 sub checkpoint ($;$) {
611 my ($self, $wait) = @_;
613 if (my $im = $self->{im}) {
620 my $shards = $self->{idx_shards};
622 my $dbh = $self->{mm}->{dbh};
624 # SQLite msgmap data is second in importance
627 # SQLite overview is third
628 $self->{over}->commit_lazy;
630 # Now deal with Xapian
632 my $barrier = $self->barrier_init(scalar @$shards);
634 # each shard needs to issue a barrier command
635 $_->remote_barrier for @$shards;
637 # wait for each Xapian shard
638 $self->barrier_wait($barrier);
640 $_->remote_commit for @$shards;
643 # last_commit is special, don't commit these until
644 # remote shards are done:
646 set_last_commits($self);
651 $self->{total_bytes} += $self->{transact_bytes};
652 $self->{transact_bytes} = 0;
655 # issue a write barrier to ensure all data is visible to other processes
656 # and read-only ops. Order of data importance is: git > SQLite > Xapian
658 sub barrier { checkpoint($_[0], 1) };
663 my $im = delete $self->{im};
664 $im->done if $im; # PublicInbox::Import::done
666 my $mm = delete $self->{mm};
667 $mm->{dbh}->commit if $mm;
668 my $shards = delete $self->{idx_shards};
670 $_->remote_close for @$shards;
672 $self->{over}->disconnect;
673 delete $self->{bnote};
674 my $nbytes = $self->{total_bytes};
675 $self->{total_bytes} = 0;
676 $self->lock_release(!!$nbytes) if $shards;
677 $self->{ibx}->git->cleanup;
680 sub fill_alternates ($$) {
681 my ($self, $epoch) = @_;
683 my $pfx = "$self->{ibx}->{inboxdir}/git";
684 my $all = "$self->{ibx}->{inboxdir}/all.git";
685 PublicInbox::Import::init_bare($all) unless -d $all;
686 my $info_dir = "$all/objects/info";
687 my $alt = "$info_dir/alternates";
691 open(my $fh, '<', $alt) or die "open < $alt: $!\n";
692 $mode = (stat($fh))[2] & 07777;
694 # we assign a sort score to every alternate and favor
695 # the newest (highest numbered) one because loose objects
696 # require scanning epochs and only the latest epoch is
697 # expected to see loose objects
699 my $other = 0; # in case admin adds non-epoch repos
701 if (m!\A\Q../../\E([0-9]+)\.git/objects\z!) {
707 } split(/\n+/, do { local $/; <$fh> });
710 foreach my $i (0..$epoch) {
711 my $dir = "../../git/$i.git/objects";
712 if (!exists($alt{$dir}) && -d "$pfx/$i.git") {
719 my ($fh, $tmp) = tempfile('alt-XXXXXXXX', DIR => $info_dir);
720 print $fh join("\n", sort { $alt{$b} <=> $alt{$a} } keys %alt), "\n"
721 or die "print $tmp: $!\n";
722 chmod($mode, $fh) or die "fchmod $tmp: $!\n";
723 close $fh or die "close $tmp $!\n";
724 rename($tmp, $alt) or die "rename $tmp => $alt: $!\n";
728 my ($self, $epoch) = @_;
729 my $git_dir = "$self->{ibx}->{inboxdir}/git/$epoch.git";
730 PublicInbox::Import::init_bare($git_dir);
731 my @cmd = (qw/git config/, "--file=$git_dir/config",
732 'include.path', '../../all.git/config');
733 PublicInbox::Import::run_die(\@cmd);
734 fill_alternates($self, $epoch);
739 my ($self, $max) = @_;
741 my $pfx = "$self->{ibx}->{inboxdir}/git";
742 return unless -d $pfx;
744 opendir my $dh, $pfx or die "opendir $pfx: $!\n";
745 while (defined(my $git_dir = readdir($dh))) {
746 $git_dir =~ m!\A([0-9]+)\.git\z! or next;
749 $latest = "$pfx/$git_dir";
757 my $im = $self->{im};
759 if ($im->{bytes_added} < $self->{rotate_bytes}) {
766 my $git_dir = $self->git_init(++$self->{epoch_max});
767 my $git = PublicInbox::Git->new($git_dir);
768 return $self->import_init($git, 0);
773 my $latest = git_dir_latest($self, \$max);
774 if (defined $latest) {
775 my $git = PublicInbox::Git->new($latest);
776 my $packed_bytes = $git->packed_bytes;
777 my $unpacked_bytes = $packed_bytes / $PACKING_FACTOR;
779 if ($unpacked_bytes >= $self->{rotate_bytes}) {
782 $self->{epoch_max} = $max;
783 return $self->import_init($git, $packed_bytes);
786 $self->{epoch_max} = $epoch;
787 $latest = $self->git_init($epoch);
788 $self->import_init(PublicInbox::Git->new($latest), 0);
792 my ($self, $git, $packed_bytes, $tmp) = @_;
793 my $im = PublicInbox::Import->new($git, undef, undef, $self->{ibx});
794 $im->{bytes_added} = int($packed_bytes / $PACKING_FACTOR);
795 $im->{lock_path} = undef;
796 $im->{path_type} = 'v2';
797 $self->{im} = $im unless $tmp;
803 my ($mid, $cur, $new) = @_;
805 my ($ah, $an) = tempfile('email-cur-XXXXXXXX', TMPDIR => 1);
806 print $ah $cur->as_string or die "print: $!";
807 close $ah or die "close: $!";
808 my ($bh, $bn) = tempfile('email-new-XXXXXXXX', TMPDIR => 1);
809 PublicInbox::Import::drop_unwanted_headers($new);
810 print $bh $new->as_string or die "print: $!";
811 close $bh or die "close: $!";
812 my $cmd = [ qw(diff -u), $an, $bn ];
813 print STDERR "# MID conflict <$mid>\n";
814 my $pid = spawn($cmd, undef, { 1 => 2 });
815 waitpid($pid, 0) == $pid or die "diff did not finish";
820 my ($self, $smsg) = @_;
821 if (my $im = $self->{im}) {
822 my $msg = $im->cat_blob($smsg->{blob});
825 # older message, should be in alternates
826 $self->{ibx}->msg_by_smsg($smsg);
829 sub content_exists ($$$) {
830 my ($self, $mime, $mid) = @_;
831 my $over = $self->{over};
832 my $chashes = content_hashes($mime);
834 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
835 my $msg = get_blob($self, $smsg);
836 if (!defined($msg)) {
837 warn "broken smsg for $mid\n";
840 my $cur = PublicInbox::Eml->new($msg);
841 return 1 if content_matches($chashes, $cur);
843 # XXX DEBUG_DIFF is experimental and may be removed
844 diff($mid, $cur, $mime) if $ENV{DEBUG_DIFF};
851 if (my $shards = $self->{idx_shards}) {
852 $_->atfork_child foreach @$shards;
854 if (my $im = $self->{im}) {
857 die "unexpected mm" if $self->{mm};
858 close $self->{bnote}->[0] or die "close bnote[0]: $!\n";
862 sub reindex_checkpoint ($$) {
863 my ($self, $sync) = @_;
865 $self->{ibx}->git->cleanup; # *async_wait
866 ${$sync->{need_checkpoint}} = 0;
867 $sync->{mm_tmp}->atfork_prepare;
868 $self->done; # release lock
870 if (my $pr = $sync->{-opt}->{-progress}) {
871 $pr->(sprintf($sync->{-regen_fmt}, ${$sync->{nr}}));
874 # allow -watch or -mda to write...
875 $self->idx_init; # reacquire lock
876 $sync->{mm_tmp}->atfork_parent;
879 sub index_oid { # cat_async callback
880 my ($bref, $oid, $type, $size, $arg) = @_;
881 return if $size == 0; # purged
883 my $mime = PublicInbox::Eml->new($$bref);
884 my $mids = mids($mime->header_obj);
885 my $chash = content_hash($mime);
886 my $self = $arg->{v2w};
888 if (scalar(@$mids) == 0) {
889 warn "E: $oid has no Message-ID, skipping\n";
893 # {unindexed} is unlikely
894 if ((my $unindexed = $arg->{unindexed}) && scalar(@$mids) == 1) {
895 $num = delete($unindexed->{$mids->[0]});
898 $self->{mm}->mid_set($num, $mid0);
899 delete($arg->{unindexed}) if !keys(%$unindexed);
902 if (!defined($num)) { # reuse if reindexing (or duplicates)
903 my $over = $self->{over};
904 for my $mid (@$mids) {
905 ($num, $mid0) = $over->num_mid0_for_oid($oid, $mid);
906 last if defined $num;
909 $mid0 //= do { # is this a number we got before?
910 $num = $arg->{mm_tmp}->num_for($mids->[0]);
911 defined($num) ? $mids->[0] : undef;
913 if (!defined($num)) {
914 for (my $i = $#$mids; $i >= 1; $i--) {
915 $num = $arg->{mm_tmp}->num_for($mids->[$i]);
923 $arg->{mm_tmp}->num_delete($num);
924 } else { # never seen
925 $num = $self->{mm}->mid_insert($mids->[0]);
928 } else { # rare, try the rest of them, backwards
929 for (my $i = $#$mids; $i >= 1; $i--) {
930 $num = $self->{mm}->mid_insert($mids->[$i]);
938 if (!defined($num)) {
939 warn "E: $oid <", join('> <', @$mids), "> is a duplicate\n";
948 }, 'PublicInbox::Smsg';
949 $smsg->populate($mime, $arg);
950 if (do_idx($self, $bref, $mime, $smsg)) {
951 ${$arg->{need_checkpoint}} = 1;
955 # only update last_commit for $i on reindex iff newer than current
956 sub update_last_commit ($$$$) {
957 my ($self, $git, $i, $cmt) = @_;
958 my $last = last_epoch_commit($self, $i);
959 if (defined $last && is_ancestor($git, $last, $cmt)) {
960 my @cmd = (qw(rev-list --count), "$last..$cmt");
961 chomp(my $n = $git->qx(@cmd));
962 return if $n ne '' && $n == 0;
964 last_epoch_commit($self, $i, $cmt);
967 sub git_dir_n ($$) { "$_[0]->{ibx}->{inboxdir}/git/$_[1].git" }
969 sub last_commits ($$) {
970 my ($self, $epoch_max) = @_;
972 for (my $i = $epoch_max; $i >= 0; $i--) {
973 $heads->[$i] = last_epoch_commit($self, $i);
978 # returns a revision range for git-log(1)
979 sub log_range ($$$$$) {
980 my ($self, $sync, $git, $i, $tip) = @_;
981 my $opt = $sync->{-opt};
982 my $pr = $opt->{-progress} if (($opt->{verbose} || 0) > 1);
983 my $cur = $sync->{ranges}->[$i] or do {
984 $pr->("$i.git indexing all of $tip") if $pr;
985 return $tip; # all of it
988 # fast equality check to avoid (v)fork+execve overhead
990 $sync->{ranges}->[$i] = undef;
994 my $range = "$cur..$tip";
995 $pr->("$i.git checking contiguity... ") if $pr;
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} starting at
1024 $sync->{unindex_range}->{$i} = "$base..$cur";
1029 sub sync_prepare ($$$) {
1030 my ($self, $sync, $epoch_max) = @_;
1031 my $pr = $sync->{-opt}->{-progress};
1033 my $head = $self->{ibx}->{ref_head} || 'refs/heads/master';
1035 # reindex stops at the current heads and we later rerun index_sync
1037 my $reindex_heads = last_commits($self, $epoch_max) if $sync->{reindex};
1039 for (my $i = $epoch_max; $i >= 0; $i--) {
1040 my $git_dir = git_dir_n($self, $i);
1041 -d $git_dir or next; # missing epochs are fine
1042 my $git = PublicInbox::Git->new($git_dir);
1043 if ($reindex_heads) {
1044 $head = $reindex_heads->[$i] or next;
1046 chomp(my $tip = $git->qx(qw(rev-parse -q --verify), $head));
1048 next if $?; # new repo
1049 my $range = log_range($self, $sync, $git, $i, $tip) or next;
1050 # can't use 'rev-list --count' if we use --diff-filter
1051 $pr->("$i.git counting $range ... ") if $pr;
1052 # Don't bump num_highwater on --reindex by using {D}.
1053 # We intentionally do NOT use {D} in the non-reindex case
1054 # because we want NNTP article number gaps from unindexed
1055 # messages to show up in mirrors, too.
1056 $sync->{D} //= $sync->{reindex} ? {} : undef; # OID_BIN => NR
1057 my $stk = log2stack($sync, $git, $range, $self->{ibx});
1058 my $nr = $stk ? $stk->num_records : 0;
1059 $pr->("$nr\n") if $pr;
1060 $sync->{stacks}->[$i] = $stk if $stk;
1064 # XXX this should not happen unless somebody bypasses checks in
1065 # our code and blindly injects "d" file history into git repos
1066 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
1067 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
1068 my $arg = { v2w => $self };
1069 my $all = $self->{ibx}->git;
1070 for my $oid (@leftovers) {
1071 $oid = unpack('H*', $oid);
1072 $self->{current_info} = "leftover $oid";
1073 $all->cat_async($oid, \&unindex_oid, $arg);
1075 $all->cat_async_wait;
1077 return 0 if (!$regen_max && !keys(%{$self->{unindex_range}}));
1079 # reindex should NOT see new commits anymore, if we do,
1080 # it's a problem and we need to notice it via die()
1081 my $pad = length($regen_max) + 1;
1082 $sync->{-regen_fmt} = "% ${pad}u/$regen_max\n";
1083 $sync->{nr} = \(my $nr = 0);
1084 return -1 if $sync->{reindex};
1085 $regen_max + $self->{mm}->num_highwater() || 0;
1088 sub unindex_oid_remote ($$$) {
1089 my ($self, $oid, $mid) = @_;
1090 my @removed = $self->{over}->remove_oid($oid, $mid);
1091 for my $num (@removed) {
1092 my $idx = idx_shard($self, $num % $self->{shards});
1093 $idx->remote_remove($oid, $num);
1097 sub unindex_oid ($$;$) { # git->cat_async callback
1098 my ($bref, $oid, $type, $size, $sync) = @_;
1099 my $self = $sync->{v2w};
1100 my $unindexed = $sync->{in_unindex} ? $sync->{unindexed} : undef;
1101 my $mm = $self->{mm};
1102 my $mids = mids(PublicInbox::Eml->new($bref)->header_obj);
1104 my $over = $self->{over};
1105 foreach my $mid (@$mids) {
1108 while (my $smsg = $over->next_by_mid($mid, \$id, \$prev)) {
1109 $gone{$smsg->{num}} = 1 if $oid eq $smsg->{blob};
1111 my $n = scalar(keys(%gone)) or next;
1113 warn "BUG: multiple articles linked to $oid\n",
1114 join(',',sort keys %gone), "\n";
1116 foreach my $num (keys %gone) {
1118 my $mid0 = $mm->mid_for($num);
1119 $unindexed->{$mid0} = $num;
1121 $mm->num_delete($num);
1123 unindex_oid_remote($self, $oid, $mid);
1127 # this is rare, it only happens when we get discontiguous history in
1128 # a mirror because the source used -purge or -edit
1129 sub unindex ($$$$) {
1130 my ($self, $sync, $git, $unindex_range) = @_;
1131 my $unindexed = $sync->{unindexed} //= {}; # $mid0 => $num
1132 my $before = scalar keys %$unindexed;
1133 # order does not matter, here:
1134 my @cmd = qw(log --raw -r
1135 --no-notes --no-color --no-abbrev --no-renames);
1136 my $fh = $git->popen(@cmd, $unindex_range);
1137 my $all = $self->{ibx}->git;
1138 local $sync->{in_unindex} = 1;
1140 /\A:\d{6} 100644 $OID ($OID) [AM]\tm$/o or next;
1141 $all->cat_async($1, \&unindex_oid, $sync);
1143 close $fh or die "git log failed: \$?=$?";
1144 $all->cat_async_wait;
1146 return unless $sync->{-opt}->{prune};
1147 my $after = scalar keys %$unindexed;
1148 return if $before == $after;
1150 # ensure any blob can not longer be accessed via dumb HTTP
1151 PublicInbox::Import::run_die(['git', "--git-dir=$git->{git_dir}",
1152 qw(-c gc.reflogExpire=now gc --prune=all --quiet)]);
1155 sub sync_ranges ($$$) {
1156 my ($self, $sync, $epoch_max) = @_;
1157 my $reindex = $sync->{reindex};
1159 return last_commits($self, $epoch_max) unless $reindex;
1160 return [] if ref($reindex) ne 'HASH';
1162 my $ranges = $reindex->{from}; # arrayref;
1163 if (ref($ranges) ne 'ARRAY') {
1164 die 'BUG: $reindex->{from} not an ARRAY';
1169 sub index_epoch ($$$) {
1170 my ($self, $sync, $i) = @_;
1172 my $git_dir = git_dir_n($self, $i);
1173 -d $git_dir or return; # missing epochs are fine
1174 my $git = PublicInbox::Git->new($git_dir);
1175 if (my $unindex_range = delete $sync->{unindex_range}->{$i}) { # rare
1176 unindex($self, $sync, $git, $unindex_range);
1178 defined(my $stk = $sync->{stacks}->[$i]) or return;
1179 $sync->{stacks}->[$i] = undef;
1180 my $all = $self->{ibx}->git;
1181 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
1182 $self->{current_info} = "$i.git $oid";
1184 my $arg = { %$sync, autime => $at, cotime => $ct };
1185 if ($sync->{index_max_size}) {
1186 $all->check_async($oid, \&check_size, $arg);
1188 $all->cat_async($oid, \&index_oid, $arg);
1190 } elsif ($f eq 'd') {
1191 $all->cat_async($oid, \&unindex_oid, $sync);
1193 if (${$sync->{need_checkpoint}}) {
1194 reindex_checkpoint($self, $sync);
1197 $all->check_async_wait;
1198 $all->cat_async_wait;
1199 update_last_commit($self, $git, $i, $stk->{latest_cmt});
1202 # public, called by public-inbox-index
1204 my ($self, $opt) = @_;
1206 my $pr = $opt->{-progress};
1208 my $latest = git_dir_latest($self, \$epoch_max);
1209 return unless defined $latest;
1210 $self->idx_init($opt); # acquire lock
1211 fill_alternates($self, $epoch_max);
1212 $self->{over}->rethread_prepare($opt);
1214 need_checkpoint => \(my $bool = 0),
1215 unindex_range => {}, # EPOCH => oid_old..oid_new
1216 reindex => $opt->{reindex},
1220 $sync->{ranges} = sync_ranges($self, $sync, $epoch_max);
1221 if (sync_prepare($self, $sync, $epoch_max)) {
1222 # tmp_clone seems to fail if inside a transaction, so
1223 # we rollback here (because we opened {mm} for reading)
1224 # Note: we do NOT rely on DBI transactions for atomicity;
1225 # only for batch performance.
1226 $self->{mm}->{dbh}->rollback;
1227 $self->{mm}->{dbh}->begin_work;
1229 $self->{mm}->tmp_clone($self->{ibx}->{inboxdir});
1231 if ($sync->{index_max_size} = $self->{ibx}->{index_max_size}) {
1232 $sync->{index_oid} = \&index_oid;
1234 # work forwards through history
1235 index_epoch($self, $sync, $_) for (0..$epoch_max);
1238 if (my $nr = $sync->{nr}) {
1239 my $pr = $sync->{-opt}->{-progress};
1240 $pr->('all.git '.sprintf($sync->{-regen_fmt}, $$nr)) if $pr;
1242 $self->{over}->rethread_done($opt);
1244 # reindex does not pick up new changes, so we rerun w/o it:
1245 if ($opt->{reindex}) {
1248 delete @again{qw(rethread reindex -skip_lock)};
1249 index_sync($self, \%again);