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}) {
114 # don't create empty Xapian directories if we don't need Xapian
115 my $is_part = defined($self->{partition});
116 if (!$is_part || ($is_part && need_xapian($self))) {
117 File::Path::mkpath($dir);
120 return unless defined $flag;
121 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
125 my ($doc, $col, $num) = @_;
126 $num = Search::Xapian::sortable_serialise($num);
127 $doc->add_value($col, $num);
130 sub index_text ($$$$)
132 my ($self, $field, $n, $text) = @_;
133 my $tg = $self->term_generator;
135 if ($self->{indexlevel} eq 'full') {
136 $tg->index_text($field, $n, $text);
137 $tg->increase_termpos;
139 $tg->index_text_without_positions($field, $n, $text);
143 sub index_users ($$) {
144 my ($self, $smsg) = @_;
146 my $from = $smsg->from;
150 $self->index_text($from, 1, 'A'); # A - author
151 $self->index_text($to, 1, 'XTO') if $to ne '';
152 $self->index_text($cc, 1, 'XCC') if $cc ne '';
155 sub index_diff_inc ($$$$) {
156 my ($self, $text, $pfx, $xnq) = @_;
158 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
161 $self->index_text($text, 1, $pfx);
164 sub index_old_diff_fn {
165 my ($self, $seen, $fa, $fb, $xnq) = @_;
167 # no renames or space support for traditional diffs,
168 # find the number of leading common paths to strip:
169 my @fa = split('/', $fa);
170 my @fb = split('/', $fb);
171 while (scalar(@fa) && scalar(@fb)) {
172 $fa = join('/', @fa);
173 $fb = join('/', @fb);
175 unless ($seen->{$fa}++) {
176 $self->index_diff_inc($fa, 'XDFN', $xnq);
186 sub index_diff ($$$) {
187 my ($self, $lines, $doc) = @_;
193 if ($in_diff && s/^ //) { # diff context
194 $self->index_diff_inc($_, 'XDFCTX', $xnq);
195 } elsif (/^-- $/) { # email signature begins
197 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
198 my ($fa, $fb) = ($1, $2);
199 my $fn = (split('/', git_unquote($fa), 2))[1];
200 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
201 $fn = (split('/', git_unquote($fb), 2))[1];
202 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
205 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
206 my ($opt, $fa, $fb) = ($1, $2, $3);
208 # only support unified:
209 next unless $opt =~ /[uU]/;
210 $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
212 } elsif (m!^--- ("?a/.+)!) {
213 my $fn = (split('/', git_unquote($1), 2))[1];
214 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
216 } elsif (m!^\+\+\+ ("?b/.+)!) {
217 my $fn = (split('/', git_unquote($1), 2))[1];
218 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
220 } elsif (/^--- (\S+)/) {
223 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
224 $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
226 } elsif ($in_diff && s/^\+//) { # diff added
227 $self->index_diff_inc($_, 'XDFB', $xnq);
228 } elsif ($in_diff && s/^-//) { # diff removed
229 $self->index_diff_inc($_, 'XDFA', $xnq);
230 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
231 my ($ba, $bb) = ($1, $2);
232 index_git_blob_id($doc, 'XDFPRE', $ba);
233 index_git_blob_id($doc, 'XDFPOST', $bb);
235 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
236 # traditional diff w/o -p
237 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
238 # hunk header context
239 $self->index_diff_inc($1, 'XDFHH', $xnq);
240 # ignore the following lines:
241 } elsif (/^(?:dis)similarity index/ ||
242 /^(?:old|new) mode/ ||
243 /^(?:deleted|new) file mode/ ||
244 /^(?:copy|rename) (?:from|to) / ||
245 /^(?:dis)?similarity index / ||
246 /^\\ No newline at end of file/ ||
247 /^Binary files .* differ/) {
253 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
258 $self->index_text(join("\n", @xnq), 1, 'XNQ');
261 sub index_body ($$$) {
262 my ($self, $lines, $doc) = @_;
263 my $txt = join("\n", @$lines);
265 # does it look like a diff?
266 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
268 $self->index_diff($lines, $doc);
270 $self->index_text($txt, 1, 'XNQ');
273 $self->index_text($txt, 0, 'XQUOT');
278 sub add_xapian ($$$$$) {
279 my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
280 my $smsg = PublicInbox::SearchMsg->new($mime);
281 my $doc = Search::Xapian::Document->new;
282 my $subj = $smsg->subject;
283 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
284 my @ds = gmtime($smsg->ds);
285 my $yyyymmdd = strftime('%Y%m%d', @ds);
286 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
287 my $dt = strftime('%Y%m%d%H%M%S', @ds);
288 add_val($doc, PublicInbox::Search::DT(), $dt);
290 my $tg = $self->term_generator;
292 $tg->set_document($doc);
293 $self->index_text($subj, 1, 'S') if $subj;
294 $self->index_users($smsg);
296 msg_iter($mime, sub {
297 my ($part, $depth, @idx) = @{$_[0]};
298 my $ct = $part->content_type || 'text/plain';
299 my $fn = $part->filename;
300 if (defined $fn && $fn ne '') {
301 $self->index_text($fn, 1, 'XFN');
304 my ($s, undef) = msg_part_text($part, $ct);
305 defined $s or return;
308 my @lines = split(/\n/, $s);
309 while (defined(my $l = shift @lines)) {
311 $self->index_body(\@orig, $doc) if @orig;
314 $self->index_body(\@quot, 0) if @quot;
318 $self->index_body(\@quot, 0) if @quot;
319 $self->index_body(\@orig, $doc) if @orig;
322 foreach my $mid (@$mids) {
323 $self->index_text($mid, 1, 'XM');
325 # because too many Message-IDs are prefixed with
327 if ($mid =~ /\w{12,}/) {
328 my @long = ($mid =~ /(\w{3,}+)/g);
329 $self->index_text(join(' ', @long), 1, 'XM');
332 $smsg->{to} = $smsg->{cc} = '';
333 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
334 my $data = $smsg->to_doc_data($oid, $mid0);
335 $doc->set_data($data);
336 if (my $altid = $self->{-altid}) {
337 foreach my $alt (@$altid) {
338 my $pfx = $alt->{xprefix};
339 foreach my $mid (@$mids) {
340 my $id = $alt->mid2alt($mid);
341 next unless defined $id;
342 $doc->add_boolean_term($pfx . $id);
346 $doc->add_boolean_term('Q' . $_) foreach @$mids;
347 $self->{xdb}->replace_document($num, $doc);
351 # mime = Email::MIME object
352 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
353 my $mids = mids($mime->header_obj);
354 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
355 unless (defined $num) { # v1
357 $num = index_mm($self, $mime);
360 if (need_xapian($self)) {
361 $self->add_xapian($mime, $num, $oid, $mids, $mid0)
363 if (my $over = $self->{over}) {
364 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
369 warn "failed to index message <".join('> <',@$mids).">: $@\n";
375 # returns begin and end PostingIterator
377 my ($self, $termval) = @_;
378 my $db = $self->{xdb};
380 ($db->postlist_begin($termval), $db->postlist_end($termval));
385 my ($self, $termval, $cb) = @_;
386 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
388 my ($head, $tail) = $self->find_doc_ids($termval);
389 return if $head == $tail;
391 for (; $head != $tail && @ids < $batch_size; $head->inc) {
392 push @ids, $head->get_docid;
398 # v1 only, where $mid is unique
400 my ($self, $mid) = @_;
401 $mid = mid_clean($mid);
403 if (my $over = $self->{over}) {
404 my $nr = eval { $over->remove_oid(undef, $mid) };
406 warn "failed to remove <$mid> from overview: $@\n";
408 warn "<$mid> missing for removal from overview\n";
411 return unless need_xapian($self);
412 my $db = $self->{xdb};
415 batch_do($self, 'Q' . $mid, sub {
417 $db->delete_document($_) for @$ids;
422 warn "failed to remove <$mid> from Xapian: $@\n";
424 warn "<$mid> missing for removal from Xapian\n";
428 # MID is a hint in V2
430 my ($self, $oid, $mid) = @_;
432 $self->{over}->remove_oid($oid, $mid) if $self->{over};
434 return unless need_xapian($self);
435 my $db = $self->{xdb};
437 # XXX careful, we cannot use batch_do here since we conditionally
438 # delete documents based on other factors, so we cannot call
439 # find_doc_ids twice.
440 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
441 return if $head == $tail;
443 # there is only ONE element in @delete unless we
444 # have bugs in our v2writable deduplication check
446 for (; $head != $tail; $head->inc) {
447 my $docid = $head->get_docid;
448 my $doc = $db->get_document($docid);
449 my $smsg = PublicInbox::SearchMsg->wrap($mid);
450 $smsg->load_expand($doc);
451 if ($smsg->{blob} eq $oid) {
452 push(@delete, $docid);
455 $db->delete_document($_) foreach @delete;
459 sub term_generator { # write-only
462 my $tg = $self->{term_generator};
465 $tg = Search::Xapian::TermGenerator->new;
466 $tg->set_stemmer($self->stemmer);
468 $self->{term_generator} = $tg;
471 sub index_git_blob_id {
472 my ($doc, $pfx, $objid) = @_;
474 my $len = length($objid);
475 for (my $len = length($objid); $len >= 7; ) {
476 $doc->add_term($pfx.$objid);
477 $objid = substr($objid, 0, --$len);
482 my ($self, $mime) = @_;
483 my $mid = eval { mid_clean(mid_mime($mime)) };
484 $self->remove_message($mid) if defined $mid;
488 my ($self, $mime) = @_;
489 my $mid = mid_clean(mid_mime($mime));
490 my $mm = $self->{mm};
493 if (defined $self->{regen_down}) {
494 $num = $mm->num_for($mid) and return $num;
496 while (($num = $self->{regen_down}--) > 0) {
497 if ($mm->mid_set($num, $mid) != 0) {
501 } elsif (defined $self->{regen_up}) {
502 $num = $mm->num_for($mid) and return $num;
504 # this is to fixup old bugs due to add-remove-add
505 while (($num = ++$self->{regen_up})) {
506 if ($mm->mid_set($num, $mid) != 0) {
512 $num = $mm->mid_insert($mid) and return $num;
514 # fallback to num_for since filters like RubyLang set the number
519 my ($self, $mime) = @_;
520 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
524 my ($self, $mime, $bytes, $blob) = @_;
525 my $num = index_mm($self, $mime);
526 add_message($self, $mime, $bytes, $num, $blob);
530 my ($self, $mime) = @_;
531 unindex_blob($self, $mime);
532 unindex_mm($self, $mime);
536 my ($git, $blob, $sizeref) = @_;
538 my $str = $git->cat_file($blob, $sizeref);
539 # fixup bugs from import:
540 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
541 PublicInbox::MIME->new($str);
547 my ($self, $opts) = @_;
548 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
551 sub batch_adjust ($$$$) {
552 my ($max, $bytes, $batch_cb, $latest) = @_;
556 $batch_cb->($latest);
562 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
563 my $hex = '[a-f0-9]';
564 my $h40 = $hex .'{40}';
565 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
566 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
567 my $git = $self->{git};
570 my $max = BATCH_BYTES;
575 while (defined($line = <$log>)) {
576 if ($line =~ /$addmsg/o) {
578 if (delete $D{$blob}) {
579 if (defined $self->{regen_down}) {
580 my $num = $self->{regen_down}--;
581 $self->{mm}->num_highwater($num);
585 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
586 batch_adjust(\$max, $bytes, $batch_cb, $latest);
587 $add_cb->($self, $mime, $bytes, $blob);
588 } elsif ($line =~ /$delmsg/o) {
591 } elsif ($line =~ /^commit ($h40)/o) {
597 foreach my $blob (keys %D) {
598 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
599 $del_cb->($self, $mime);
601 $batch_cb->($latest, $newest);
606 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
607 $self->{mm} ||= eval {
608 require PublicInbox::Msgmap;
609 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
614 my ($self, $range) = @_;
615 my $git = $self->{git};
617 if (index($range, '..') < 0) {
618 # don't show annoying git errrors to users who run -index
620 $git->qx(qw(rev-parse -q --verify), "$range^0");
622 open my $fh, '<', '/dev/null' or
623 die "failed to open /dev/null: $!\n";
628 # Count the new files so they can be added newest to oldest
629 # and still have numbers increasing from oldest to newest
631 # can't use 'rev-list --count' if we use --diff-filter
632 my $fh = $git->popen(qw(log --pretty=tformat:%h
633 --no-notes --no-color --no-renames
634 --diff-filter=AM), $range);
635 ++$fcount while <$fh>;
636 my $high = $self->{mm}->num_highwater;
638 if (index($range, '..') < 0) {
639 if ($high && $high == $fcount) {
640 # fix up old bugs in full indexes which caused messages to
641 # not appear in Msgmap
642 $self->{regen_up} = $high;
644 # normal regen is for for fresh data
645 $self->{regen_down} = $fcount;
648 # Give oldest messages the smallest numbers
649 $self->{regen_down} = $high + $fcount;
652 $git->popen(qw/log --no-notes --no-color --no-renames
653 --raw -r --no-abbrev/, $range);
656 # --is-ancestor requires git 1.8.0+
657 sub is_ancestor ($$$) {
658 my ($git, $cur, $tip) = @_;
659 return 0 unless $git->check($cur);
660 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
661 qw(merge-base --is-ancestor), $cur, $tip ];
662 my $pid = spawn($cmd);
663 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
664 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
668 sub need_update ($$$) {
669 my ($self, $cur, $new) = @_;
670 my $git = $self->{git};
671 return 1 if $cur && !is_ancestor($git, $cur, $new);
672 my $range = $cur eq '' ? $new : "$cur..$new";
673 chomp(my $n = $git->qx(qw(rev-list --count), $range));
674 ($n eq '' || $n > 0);
677 # The last git commit we indexed with Xapian or SQLite (msgmap)
678 # This needs to account for cases where Xapian or SQLite is
679 # out-of-date with respect to the other.
681 my ($self, $mm) = @_;
682 my $lm = $mm->last_commit || '';
684 if (need_xapian($self)) {
685 $lx = $self->{xdb}->get_metadata('last_commit') || '';
689 # Use last_commit from msgmap if it is older or unset
690 if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
696 # indexes all unindexed messages (v1 only)
698 my ($self, $opts) = @_;
699 my $tip = $opts->{ref} || 'HEAD';
700 my ($last_commit, $lx, $xlog);
701 my $git = $self->{git};
704 my $xdb = $self->begin_txn_lazy;
705 my $mm = _msgmap_init($self);
708 $last_commit = _last_x_commit($self, $mm);
709 $lx = $opts->{reindex} ? '' : $last_commit;
711 $self->{over}->rollback_lazy;
712 $self->{over}->disconnect;
715 $xdb->cancel_transaction if $xdb;
716 $xdb = _xdb_release($self);
718 # ensure we leak no FDs to "git log" with Xapian <= 1.2
719 my $range = $lx eq '' ? $tip : "$lx..$tip";
720 $xlog = _git_log($self, $range);
722 $xdb = $self->begin_txn_lazy;
723 } while (_last_x_commit($self, $mm) ne $last_commit);
725 my $dbh = $mm->{dbh} if $mm;
727 my ($commit, $newest) = @_;
730 my $cur = $mm->last_commit || '';
731 if (need_update($self, $cur, $newest)) {
732 $mm->last_commit($newest);
737 if ($newest && need_xapian($self)) {
738 my $cur = $xdb->get_metadata('last_commit');
739 if (need_update($self, $cur, $newest)) {
740 $xdb->set_metadata('last_commit', $newest);
743 $self->commit_txn_lazy;
745 $xdb = _xdb_release($self);
746 # let another process do some work... <
748 $xdb = $self->begin_txn_lazy;
749 $dbh->begin_work if $dbh;
754 read_log($self, $xlog, *index_both, *unindex_both, $cb);
758 # order matters for unlocking
759 $_[0]->{xdb} = undef;
760 $_[0]->{lockfh} = undef;
763 # remote_* subs are only used by SearchIdxPart
766 if (my $w = $self->{w}) {
767 print $w "commit\n" or die "failed to write commit: $!";
769 $self->commit_txn_lazy;
775 if (my $w = delete $self->{w}) {
776 my $pid = delete $self->{pid} or die "no process to wait on\n";
777 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
778 close $w or die "failed to close pipe for pid:$pid: $!\n";
779 waitpid($pid, 0) == $pid or die "remote process did not finish";
780 $? == 0 or die ref($self)." pid:$pid exited with: $?";
782 die "transaction in progress $self\n" if $self->{txn};
783 $self->_xdb_release if $self->{xdb};
788 my ($self, $oid, $mid) = @_;
789 if (my $w = $self->{w}) {
790 # triggers remove_by_oid in a partition
791 print $w "D $oid $mid\n" or die "failed to write remove $!";
793 $self->begin_txn_lazy;
794 $self->remove_by_oid($oid, $mid);
800 return if $self->{txn};
802 $self->{-inbox}->with_umask(sub {
803 my $xdb = $self->{xdb} || $self->_xdb_acquire;
804 $self->{over}->begin_lazy if $self->{over};
805 $xdb->begin_transaction if $xdb;
811 sub commit_txn_lazy {
813 delete $self->{txn} or return;
814 $self->{-inbox}->with_umask(sub {
815 if (my $xdb = $self->{xdb}) {
816 $xdb->commit_transaction;
818 $self->{over}->commit_lazy if $self->{over};
824 if (need_xapian($self)) {
825 die "$$ $0 xdb not released\n" if $self->{xdb};
827 die "$$ $0 still in transaction\n" if $self->{txn};