1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces. This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
12 use base qw(PublicInbox::Search PublicInbox::Lock);
13 use PublicInbox::MIME;
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime mids/;
16 use PublicInbox::MsgIter;
18 use POSIX qw(strftime);
19 use PublicInbox::OverIdx;
20 use PublicInbox::Spawn qw(spawn);
21 use PublicInbox::Git qw(git_unquote);
22 use Compress::Zlib qw(compress);
25 BATCH_BYTES => defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
26 0x7fffffff : 1_000_000,
27 DEBUG => !!$ENV{DEBUG},
30 my $xapianlevels = qr/\A(?:full|medium)\z/;
33 my ($class, $ibx, $creat, $part) = @_;
34 my $levels = qr/\A(?:full|medium|basic)\z/;
35 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
36 my $git_dir = $mainrepo;
39 my $indexlevel = 'full';
41 $mainrepo = $ibx->{mainrepo};
42 $altid = $ibx->{altid};
43 $version = $ibx->{version} || 1;
45 require PublicInbox::AltId;
47 PublicInbox::AltId->new($ibx, $_);
50 if ($ibx->{indexlevel}) {
51 if ($ibx->{indexlevel} =~ $levels) {
52 $indexlevel = $ibx->{indexlevel};
54 die("Invalid indexlevel $ibx->{indexlevel}\n");
57 } else { # FIXME: old tests: old tests
58 $ibx = { mainrepo => $git_dir, version => 1 };
60 $ibx = PublicInbox::InboxWritable->new($ibx);
62 mainrepo => $mainrepo,
67 indexlevel => $indexlevel,
71 $self->{lock_path} = "$mainrepo/ssoma.lock";
72 my $dir = $self->xdir;
73 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
74 } elsif ($version == 2) {
75 defined $part or die "partition is required for v2\n";
76 # partition is a number
77 $self->{partition} = $part;
78 $self->{lock_path} = undef;
80 die "unsupported inbox version=$version\n";
82 $self->{creat} = ($creat || 0) == 1;
86 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
90 if (need_xapian($self)) {
91 my $xdb = delete $self->{xdb} or croak 'not acquired';
94 $self->lock_release if $self->{creat};
101 my $dir = $self->xdir;
102 if (need_xapian($self)) {
103 croak 'already acquired' if $self->{xdb};
104 PublicInbox::Search::load_xapian();
105 require Search::Xapian::WritableDatabase;
106 $flag = $self->{creat} ?
107 Search::Xapian::DB_CREATE_OR_OPEN() :
108 Search::Xapian::DB_OPEN();
110 if ($self->{creat}) {
113 File::Path::mkpath($dir);
115 return unless defined $flag;
116 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
120 my ($doc, $col, $num) = @_;
121 $num = Search::Xapian::sortable_serialise($num);
122 $doc->add_value($col, $num);
125 sub index_text ($$$$)
127 my ($self, $field, $n, $text) = @_;
128 my $tg = $self->term_generator;
130 if ($self->{indexlevel} eq 'full') {
131 $tg->index_text($field, $n, $text);
132 $tg->increase_termpos;
134 $tg->index_text_without_positions($field, $n, $text);
138 sub index_users ($$) {
139 my ($self, $smsg) = @_;
141 my $from = $smsg->from;
145 $self->index_text($from, 1, 'A'); # A - author
146 $self->index_text($to, 1, 'XTO') if $to ne '';
147 $self->index_text($cc, 1, 'XCC') if $cc ne '';
150 sub index_diff_inc ($$$$) {
151 my ($self, $text, $pfx, $xnq) = @_;
153 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
156 $self->index_text($text, 1, $pfx);
159 sub index_old_diff_fn {
160 my ($self, $seen, $fa, $fb, $xnq) = @_;
162 # no renames or space support for traditional diffs,
163 # find the number of leading common paths to strip:
164 my @fa = split('/', $fa);
165 my @fb = split('/', $fb);
166 while (scalar(@fa) && scalar(@fb)) {
167 $fa = join('/', @fa);
168 $fb = join('/', @fb);
170 unless ($seen->{$fa}++) {
171 $self->index_diff_inc($fa, 'XDFN', $xnq);
181 sub index_diff ($$$) {
182 my ($self, $lines, $doc) = @_;
188 if ($in_diff && s/^ //) { # diff context
189 $self->index_diff_inc($_, 'XDFCTX', $xnq);
190 } elsif (/^-- $/) { # email signature begins
192 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
193 my ($fa, $fb) = ($1, $2);
194 my $fn = (split('/', git_unquote($fa), 2))[1];
195 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
196 $fn = (split('/', git_unquote($fb), 2))[1];
197 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
200 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
201 my ($opt, $fa, $fb) = ($1, $2, $3);
203 # only support unified:
204 next unless $opt =~ /[uU]/;
205 $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
207 } elsif (m!^--- ("?a/.+)!) {
208 my $fn = (split('/', git_unquote($1), 2))[1];
209 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
211 } elsif (m!^\+\+\+ ("?b/.+)!) {
212 my $fn = (split('/', git_unquote($1), 2))[1];
213 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
215 } elsif (/^--- (\S+)/) {
218 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
219 $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
221 } elsif ($in_diff && s/^\+//) { # diff added
222 $self->index_diff_inc($_, 'XDFB', $xnq);
223 } elsif ($in_diff && s/^-//) { # diff removed
224 $self->index_diff_inc($_, 'XDFA', $xnq);
225 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
226 my ($ba, $bb) = ($1, $2);
227 index_git_blob_id($doc, 'XDFPRE', $ba);
228 index_git_blob_id($doc, 'XDFPOST', $bb);
230 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
231 # traditional diff w/o -p
232 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
233 # hunk header context
234 $self->index_diff_inc($1, 'XDFHH', $xnq);
235 # ignore the following lines:
236 } elsif (/^(?:dis)similarity index/ ||
237 /^(?:old|new) mode/ ||
238 /^(?:deleted|new) file mode/ ||
239 /^(?:copy|rename) (?:from|to) / ||
240 /^(?:dis)?similarity index / ||
241 /^\\ No newline at end of file/ ||
242 /^Binary files .* differ/) {
248 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
253 $self->index_text(join("\n", @xnq), 1, 'XNQ');
256 sub index_body ($$$) {
257 my ($self, $lines, $doc) = @_;
258 my $txt = join("\n", @$lines);
260 # does it look like a diff?
261 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
263 $self->index_diff($lines, $doc);
265 $self->index_text($txt, 1, 'XNQ');
268 $self->index_text($txt, 0, 'XQUOT');
273 sub add_xapian ($$$$$) {
274 my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
275 my $smsg = PublicInbox::SearchMsg->new($mime);
276 my $doc = Search::Xapian::Document->new;
277 my $subj = $smsg->subject;
278 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
279 my @ds = gmtime($smsg->ds);
280 my $yyyymmdd = strftime('%Y%m%d', @ds);
281 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
282 my $dt = strftime('%Y%m%d%H%M%S', @ds);
283 add_val($doc, PublicInbox::Search::DT(), $dt);
285 my $tg = $self->term_generator;
287 $tg->set_document($doc);
288 $self->index_text($subj, 1, 'S') if $subj;
289 $self->index_users($smsg);
291 msg_iter($mime, sub {
292 my ($part, $depth, @idx) = @{$_[0]};
293 my $ct = $part->content_type || 'text/plain';
294 my $fn = $part->filename;
295 if (defined $fn && $fn ne '') {
296 $self->index_text($fn, 1, 'XFN');
299 my ($s, undef) = msg_part_text($part, $ct);
300 defined $s or return;
303 my @lines = split(/\n/, $s);
304 while (defined(my $l = shift @lines)) {
306 $self->index_body(\@orig, $doc) if @orig;
309 $self->index_body(\@quot, 0) if @quot;
313 $self->index_body(\@quot, 0) if @quot;
314 $self->index_body(\@orig, $doc) if @orig;
317 foreach my $mid (@$mids) {
318 $self->index_text($mid, 1, 'XM');
320 # because too many Message-IDs are prefixed with
322 if ($mid =~ /\w{12,}/) {
323 my @long = ($mid =~ /(\w{3,}+)/g);
324 $self->index_text(join(' ', @long), 1, 'XM');
327 $smsg->{to} = $smsg->{cc} = '';
328 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
329 my $data = $smsg->to_doc_data($oid, $mid0);
330 $doc->set_data($data);
331 if (my $altid = $self->{-altid}) {
332 foreach my $alt (@$altid) {
333 my $pfx = $alt->{xprefix};
334 foreach my $mid (@$mids) {
335 my $id = $alt->mid2alt($mid);
336 next unless defined $id;
337 $doc->add_boolean_term($pfx . $id);
341 $doc->add_boolean_term('Q' . $_) foreach @$mids;
342 $self->{xdb}->replace_document($num, $doc);
346 # mime = Email::MIME object
347 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
348 my $mids = mids($mime->header_obj);
349 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
350 unless (defined $num) { # v1
352 $num = index_mm($self, $mime);
355 if (need_xapian($self)) {
356 $self->add_xapian($mime, $num, $oid, $mids, $mid0)
358 if (my $over = $self->{over}) {
359 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
364 warn "failed to index message <".join('> <',@$mids).">: $@\n";
370 # returns begin and end PostingIterator
372 my ($self, $termval) = @_;
373 my $db = $self->{xdb};
375 ($db->postlist_begin($termval), $db->postlist_end($termval));
380 my ($self, $termval, $cb) = @_;
381 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
383 my ($head, $tail) = $self->find_doc_ids($termval);
384 return if $head == $tail;
386 for (; $head != $tail && @ids < $batch_size; $head->inc) {
387 push @ids, $head->get_docid;
393 # v1 only, where $mid is unique
395 my ($self, $mid) = @_;
396 $mid = mid_clean($mid);
398 if (my $over = $self->{over}) {
399 my $nr = eval { $over->remove_oid(undef, $mid) };
401 warn "failed to remove <$mid> from overview: $@\n";
403 warn "<$mid> missing for removal from overview\n";
406 return unless need_xapian($self);
407 my $db = $self->{xdb};
410 batch_do($self, 'Q' . $mid, sub {
412 $db->delete_document($_) for @$ids;
417 warn "failed to remove <$mid> from Xapian: $@\n";
419 warn "<$mid> missing for removal from Xapian\n";
423 # MID is a hint in V2
425 my ($self, $oid, $mid) = @_;
427 $self->{over}->remove_oid($oid, $mid) if $self->{over};
429 return unless need_xapian($self);
430 my $db = $self->{xdb};
432 # XXX careful, we cannot use batch_do here since we conditionally
433 # delete documents based on other factors, so we cannot call
434 # find_doc_ids twice.
435 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
436 return if $head == $tail;
438 # there is only ONE element in @delete unless we
439 # have bugs in our v2writable deduplication check
441 for (; $head != $tail; $head->inc) {
442 my $docid = $head->get_docid;
443 my $doc = $db->get_document($docid);
444 my $smsg = PublicInbox::SearchMsg->wrap($mid);
445 $smsg->load_expand($doc);
446 if ($smsg->{blob} eq $oid) {
447 push(@delete, $docid);
450 $db->delete_document($_) foreach @delete;
454 sub term_generator { # write-only
457 my $tg = $self->{term_generator};
460 $tg = Search::Xapian::TermGenerator->new;
461 $tg->set_stemmer($self->stemmer);
463 $self->{term_generator} = $tg;
466 sub index_git_blob_id {
467 my ($doc, $pfx, $objid) = @_;
469 my $len = length($objid);
470 for (my $len = length($objid); $len >= 7; ) {
471 $doc->add_term($pfx.$objid);
472 $objid = substr($objid, 0, --$len);
477 my ($self, $mime) = @_;
478 my $mid = eval { mid_clean(mid_mime($mime)) };
479 $self->remove_message($mid) if defined $mid;
483 my ($self, $mime) = @_;
484 my $mid = mid_clean(mid_mime($mime));
485 my $mm = $self->{mm};
488 if (defined $self->{regen_down}) {
489 $num = $mm->num_for($mid) and return $num;
491 while (($num = $self->{regen_down}--) > 0) {
492 if ($mm->mid_set($num, $mid) != 0) {
496 } elsif (defined $self->{regen_up}) {
497 $num = $mm->num_for($mid) and return $num;
499 # this is to fixup old bugs due to add-remove-add
500 while (($num = ++$self->{regen_up})) {
501 if ($mm->mid_set($num, $mid) != 0) {
507 $num = $mm->mid_insert($mid) and return $num;
509 # fallback to num_for since filters like RubyLang set the number
514 my ($self, $mime) = @_;
515 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
519 my ($self, $mime, $bytes, $blob) = @_;
520 my $num = index_mm($self, $mime);
521 add_message($self, $mime, $bytes, $num, $blob);
525 my ($self, $mime) = @_;
526 unindex_blob($self, $mime);
527 unindex_mm($self, $mime);
531 my ($git, $blob, $sizeref) = @_;
533 my $str = $git->cat_file($blob, $sizeref);
534 # fixup bugs from import:
535 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
536 PublicInbox::MIME->new($str);
542 my ($self, $opts) = @_;
543 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
546 sub batch_adjust ($$$$) {
547 my ($max, $bytes, $batch_cb, $latest) = @_;
551 $batch_cb->($latest);
557 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
558 my $hex = '[a-f0-9]';
559 my $h40 = $hex .'{40}';
560 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
561 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
562 my $git = $self->{git};
565 my $max = BATCH_BYTES;
570 while (defined($line = <$log>)) {
571 if ($line =~ /$addmsg/o) {
573 if (delete $D{$blob}) {
574 if (defined $self->{regen_down}) {
575 my $num = $self->{regen_down}--;
576 $self->{mm}->num_highwater($num);
580 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
581 batch_adjust(\$max, $bytes, $batch_cb, $latest);
582 $add_cb->($self, $mime, $bytes, $blob);
583 } elsif ($line =~ /$delmsg/o) {
586 } elsif ($line =~ /^commit ($h40)/o) {
592 foreach my $blob (keys %D) {
593 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
594 $del_cb->($self, $mime);
596 $batch_cb->($latest, $newest);
601 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
602 $self->{mm} ||= eval {
603 require PublicInbox::Msgmap;
604 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
609 my ($self, $range) = @_;
610 my $git = $self->{git};
612 if (index($range, '..') < 0) {
613 # don't show annoying git errrors to users who run -index
615 $git->qx(qw(rev-parse -q --verify), "$range^0");
617 open my $fh, '<', '/dev/null' or
618 die "failed to open /dev/null: $!\n";
623 # Count the new files so they can be added newest to oldest
624 # and still have numbers increasing from oldest to newest
626 # can't use 'rev-list --count' if we use --diff-filter
627 my $fh = $git->popen(qw(log --pretty=tformat:%h
628 --no-notes --no-color --no-renames
629 --diff-filter=AM), $range);
630 ++$fcount while <$fh>;
631 my $high = $self->{mm}->num_highwater;
633 if (index($range, '..') < 0) {
634 if ($high && $high == $fcount) {
635 # fix up old bugs in full indexes which caused messages to
636 # not appear in Msgmap
637 $self->{regen_up} = $high;
639 # normal regen is for for fresh data
640 $self->{regen_down} = $fcount;
643 # Give oldest messages the smallest numbers
644 $self->{regen_down} = $high + $fcount;
647 $git->popen(qw/log --no-notes --no-color --no-renames
648 --raw -r --no-abbrev/, $range);
651 # --is-ancestor requires git 1.8.0+
652 sub is_ancestor ($$$) {
653 my ($git, $cur, $tip) = @_;
654 return 0 unless $git->check($cur);
655 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
656 qw(merge-base --is-ancestor), $cur, $tip ];
657 my $pid = spawn($cmd);
658 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
659 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
663 sub need_update ($$$) {
664 my ($self, $cur, $new) = @_;
665 my $git = $self->{git};
666 return 1 if $cur && !is_ancestor($git, $cur, $new);
667 my $range = $cur eq '' ? $new : "$cur..$new";
668 chomp(my $n = $git->qx(qw(rev-list --count), $range));
669 ($n eq '' || $n > 0);
672 # The last git commit we indexed with Xapian or SQLite (msgmap)
673 # This needs to account for cases where Xapian or SQLite is
674 # out-of-date with respect to the other.
676 my ($self, $mm) = @_;
677 my $lm = $mm->last_commit || '';
679 if (need_xapian($self)) {
680 $lx = $self->{xdb}->get_metadata('last_commit') || '';
684 # Use last_commit from msgmap if it is older or unset
685 if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
691 # indexes all unindexed messages (v1 only)
693 my ($self, $opts) = @_;
694 my $tip = $opts->{ref} || 'HEAD';
695 my ($last_commit, $lx, $xlog);
696 my $git = $self->{git};
699 my $xdb = $self->begin_txn_lazy;
700 my $mm = _msgmap_init($self);
703 $last_commit = _last_x_commit($self, $mm);
704 $lx = $opts->{reindex} ? '' : $last_commit;
706 $self->{over}->rollback_lazy;
707 $self->{over}->disconnect;
710 $xdb->cancel_transaction if $xdb;
711 $xdb = _xdb_release($self);
713 # ensure we leak no FDs to "git log" with Xapian <= 1.2
714 my $range = $lx eq '' ? $tip : "$lx..$tip";
715 $xlog = _git_log($self, $range);
717 $xdb = $self->begin_txn_lazy;
718 } while (_last_x_commit($self, $mm) ne $last_commit);
720 my $dbh = $mm->{dbh} if $mm;
722 my ($commit, $newest) = @_;
725 my $cur = $mm->last_commit || '';
726 if (need_update($self, $cur, $newest)) {
727 $mm->last_commit($newest);
732 if ($newest && need_xapian($self)) {
733 my $cur = $xdb->get_metadata('last_commit');
734 if (need_update($self, $cur, $newest)) {
735 $xdb->set_metadata('last_commit', $newest);
738 $self->commit_txn_lazy;
740 $xdb = _xdb_release($self);
741 # let another process do some work... <
743 $xdb = $self->begin_txn_lazy;
744 $dbh->begin_work if $dbh;
749 read_log($self, $xlog, *index_both, *unindex_both, $cb);
753 # order matters for unlocking
754 $_[0]->{xdb} = undef;
755 $_[0]->{lockfh} = undef;
758 # remote_* subs are only used by SearchIdxPart
761 if (my $w = $self->{w}) {
762 print $w "commit\n" or die "failed to write commit: $!";
764 $self->commit_txn_lazy;
770 if (my $w = delete $self->{w}) {
771 my $pid = delete $self->{pid} or die "no process to wait on\n";
772 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
773 close $w or die "failed to close pipe for pid:$pid: $!\n";
774 waitpid($pid, 0) == $pid or die "remote process did not finish";
775 $? == 0 or die ref($self)." pid:$pid exited with: $?";
777 die "transaction in progress $self\n" if $self->{txn};
778 $self->_xdb_release if $self->{xdb};
783 my ($self, $oid, $mid) = @_;
784 if (my $w = $self->{w}) {
785 # triggers remove_by_oid in a partition
786 print $w "D $oid $mid\n" or die "failed to write remove $!";
788 $self->begin_txn_lazy;
789 $self->remove_by_oid($oid, $mid);
795 return if $self->{txn};
797 $self->{-inbox}->with_umask(sub {
798 my $xdb = $self->{xdb} || $self->_xdb_acquire;
799 $self->{over}->begin_lazy if $self->{over};
800 $xdb->begin_transaction if $xdb;
806 sub commit_txn_lazy {
808 delete $self->{txn} or return;
809 $self->{-inbox}->with_umask(sub {
810 if (my $xdb = $self->{xdb}) {
811 $xdb->commit_transaction;
813 $self->{over}->commit_lazy if $self->{over};
819 if (need_xapian($self)) {
820 die "$$ $0 xdb not released\n" if $self->{xdb};
822 die "$$ $0 still in transaction\n" if $self->{txn};