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);
24 BATCH_BYTES => defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
25 0x7fffffff : 1_000_000,
26 DEBUG => !!$ENV{DEBUG},
29 my $xapianlevels = qr/\A(?:full|medium)\z/;
32 my ($class, $ibx, $creat, $part) = @_;
33 my $levels = qr/\A(?:full|medium|basic)\z/;
34 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
35 my $git_dir = $mainrepo;
38 my $indexlevel = 'full';
40 $mainrepo = $ibx->{mainrepo};
41 $altid = $ibx->{altid};
42 $version = $ibx->{version} || 1;
44 require PublicInbox::AltId;
46 PublicInbox::AltId->new($ibx, $_);
49 if ($ibx->{indexlevel}) {
50 if ($ibx->{indexlevel} =~ $levels) {
51 $indexlevel = $ibx->{indexlevel};
53 die("Invalid indexlevel $ibx->{indexlevel}\n");
56 } else { # FIXME: old tests: old tests
57 $ibx = { mainrepo => $git_dir, version => 1 };
59 $ibx = PublicInbox::InboxWritable->new($ibx);
61 mainrepo => $mainrepo,
66 indexlevel => $indexlevel,
70 $self->{lock_path} = "$mainrepo/ssoma.lock";
71 my $dir = $self->xdir;
72 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
73 } elsif ($version == 2) {
74 defined $part or die "partition is required for v2\n";
75 # partition is a number
76 $self->{partition} = $part;
77 $self->{lock_path} = undef;
79 die "unsupported inbox version=$version\n";
81 $self->{creat} = ($creat || 0) == 1;
85 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
89 if (need_xapian($self)) {
90 my $xdb = delete $self->{xdb} or croak 'not acquired';
93 $self->lock_release if $self->{creat};
100 my $dir = $self->xdir;
101 if (need_xapian($self)) {
102 croak 'already acquired' if $self->{xdb};
103 PublicInbox::Search::load_xapian();
104 require Search::Xapian::WritableDatabase;
105 $flag = $self->{creat} ?
106 Search::Xapian::DB_CREATE_OR_OPEN() :
107 Search::Xapian::DB_OPEN();
109 if ($self->{creat}) {
113 # don't create empty Xapian directories if we don't need Xapian
114 my $is_part = defined($self->{partition});
115 if (!$is_part || ($is_part && need_xapian($self))) {
116 File::Path::mkpath($dir);
119 return unless defined $flag;
120 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
124 my ($doc, $col, $num) = @_;
125 $num = Search::Xapian::sortable_serialise($num);
126 $doc->add_value($col, $num);
129 sub index_text ($$$$)
131 my ($self, $field, $n, $text) = @_;
132 my $tg = $self->term_generator;
134 if ($self->{indexlevel} eq 'full') {
135 $tg->index_text($field, $n, $text);
136 $tg->increase_termpos;
138 $tg->index_text_without_positions($field, $n, $text);
142 sub index_users ($$) {
143 my ($self, $smsg) = @_;
145 my $from = $smsg->from;
149 $self->index_text($from, 1, 'A'); # A - author
150 $self->index_text($to, 1, 'XTO') if $to ne '';
151 $self->index_text($cc, 1, 'XCC') if $cc ne '';
154 sub index_diff_inc ($$$$) {
155 my ($self, $text, $pfx, $xnq) = @_;
157 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
160 $self->index_text($text, 1, $pfx);
163 sub index_old_diff_fn {
164 my ($self, $seen, $fa, $fb, $xnq) = @_;
166 # no renames or space support for traditional diffs,
167 # find the number of leading common paths to strip:
168 my @fa = split('/', $fa);
169 my @fb = split('/', $fb);
170 while (scalar(@fa) && scalar(@fb)) {
171 $fa = join('/', @fa);
172 $fb = join('/', @fb);
174 unless ($seen->{$fa}++) {
175 $self->index_diff_inc($fa, 'XDFN', $xnq);
185 sub index_diff ($$$) {
186 my ($self, $lines, $doc) = @_;
192 if ($in_diff && s/^ //) { # diff context
193 $self->index_diff_inc($_, 'XDFCTX', $xnq);
194 } elsif (/^-- $/) { # email signature begins
196 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
197 my ($fa, $fb) = ($1, $2);
198 my $fn = (split('/', git_unquote($fa), 2))[1];
199 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
200 $fn = (split('/', git_unquote($fb), 2))[1];
201 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
204 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
205 my ($opt, $fa, $fb) = ($1, $2, $3);
207 # only support unified:
208 next unless $opt =~ /[uU]/;
209 $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
211 } elsif (m!^--- ("?a/.+)!) {
212 my $fn = (split('/', git_unquote($1), 2))[1];
213 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
215 } elsif (m!^\+\+\+ ("?b/.+)!) {
216 my $fn = (split('/', git_unquote($1), 2))[1];
217 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
219 } elsif (/^--- (\S+)/) {
222 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
223 $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
225 } elsif ($in_diff && s/^\+//) { # diff added
226 $self->index_diff_inc($_, 'XDFB', $xnq);
227 } elsif ($in_diff && s/^-//) { # diff removed
228 $self->index_diff_inc($_, 'XDFA', $xnq);
229 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
230 my ($ba, $bb) = ($1, $2);
231 index_git_blob_id($doc, 'XDFPRE', $ba);
232 index_git_blob_id($doc, 'XDFPOST', $bb);
234 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
235 # traditional diff w/o -p
236 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
237 # hunk header context
238 $self->index_diff_inc($1, 'XDFHH', $xnq);
239 # ignore the following lines:
240 } elsif (/^(?:dis)similarity index/ ||
241 /^(?:old|new) mode/ ||
242 /^(?:deleted|new) file mode/ ||
243 /^(?:copy|rename) (?:from|to) / ||
244 /^(?:dis)?similarity index / ||
245 /^\\ No newline at end of file/ ||
246 /^Binary files .* differ/) {
252 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
257 $self->index_text(join("\n", @xnq), 1, 'XNQ');
260 sub index_body ($$$) {
261 my ($self, $lines, $doc) = @_;
262 my $txt = join("\n", @$lines);
264 # does it look like a diff?
265 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
267 $self->index_diff($lines, $doc);
269 $self->index_text($txt, 1, 'XNQ');
272 $self->index_text($txt, 0, 'XQUOT');
277 sub add_xapian ($$$$$) {
278 my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
279 my $smsg = PublicInbox::SearchMsg->new($mime);
280 my $doc = Search::Xapian::Document->new;
281 my $subj = $smsg->subject;
282 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
283 my @ds = gmtime($smsg->ds);
284 my $yyyymmdd = strftime('%Y%m%d', @ds);
285 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
286 my $dt = strftime('%Y%m%d%H%M%S', @ds);
287 add_val($doc, PublicInbox::Search::DT(), $dt);
289 my $tg = $self->term_generator;
291 $tg->set_document($doc);
292 $self->index_text($subj, 1, 'S') if $subj;
293 $self->index_users($smsg);
295 msg_iter($mime, sub {
296 my ($part, $depth, @idx) = @{$_[0]};
297 my $ct = $part->content_type || 'text/plain';
298 my $fn = $part->filename;
299 if (defined $fn && $fn ne '') {
300 $self->index_text($fn, 1, 'XFN');
303 my ($s, undef) = msg_part_text($part, $ct);
304 defined $s or return;
307 my @lines = split(/\n/, $s);
308 while (defined(my $l = shift @lines)) {
310 $self->index_body(\@orig, $doc) if @orig;
313 $self->index_body(\@quot, 0) if @quot;
317 $self->index_body(\@quot, 0) if @quot;
318 $self->index_body(\@orig, $doc) if @orig;
321 foreach my $mid (@$mids) {
322 $self->index_text($mid, 1, 'XM');
324 # because too many Message-IDs are prefixed with
326 if ($mid =~ /\w{12,}/) {
327 my @long = ($mid =~ /(\w{3,}+)/g);
328 $self->index_text(join(' ', @long), 1, 'XM');
331 $smsg->{to} = $smsg->{cc} = '';
332 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
333 my $data = $smsg->to_doc_data($oid, $mid0);
334 $doc->set_data($data);
335 if (my $altid = $self->{-altid}) {
336 foreach my $alt (@$altid) {
337 my $pfx = $alt->{xprefix};
338 foreach my $mid (@$mids) {
339 my $id = $alt->mid2alt($mid);
340 next unless defined $id;
341 $doc->add_boolean_term($pfx . $id);
345 $doc->add_boolean_term('Q' . $_) foreach @$mids;
346 $self->{xdb}->replace_document($num, $doc);
350 # mime = Email::MIME object
351 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
352 my $mids = mids($mime->header_obj);
353 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
354 unless (defined $num) { # v1
356 $num = index_mm($self, $mime);
359 if (need_xapian($self)) {
360 $self->add_xapian($mime, $num, $oid, $mids, $mid0)
362 if (my $over = $self->{over}) {
363 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
368 warn "failed to index message <".join('> <',@$mids).">: $@\n";
374 # returns begin and end PostingIterator
376 my ($self, $termval) = @_;
377 my $db = $self->{xdb};
379 ($db->postlist_begin($termval), $db->postlist_end($termval));
384 my ($self, $termval, $cb) = @_;
385 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
387 my ($head, $tail) = $self->find_doc_ids($termval);
388 return if $head == $tail;
390 for (; $head != $tail && @ids < $batch_size; $head->inc) {
391 push @ids, $head->get_docid;
397 # v1 only, where $mid is unique
399 my ($self, $mid) = @_;
400 $mid = mid_clean($mid);
402 if (my $over = $self->{over}) {
403 my $nr = eval { $over->remove_oid(undef, $mid) };
405 warn "failed to remove <$mid> from overview: $@\n";
407 warn "<$mid> missing for removal from overview\n";
410 return unless need_xapian($self);
411 my $db = $self->{xdb};
414 batch_do($self, 'Q' . $mid, sub {
416 $db->delete_document($_) for @$ids;
421 warn "failed to remove <$mid> from Xapian: $@\n";
423 warn "<$mid> missing for removal from Xapian\n";
427 # MID is a hint in V2
429 my ($self, $oid, $mid) = @_;
431 $self->{over}->remove_oid($oid, $mid) if $self->{over};
433 return unless need_xapian($self);
434 my $db = $self->{xdb};
436 # XXX careful, we cannot use batch_do here since we conditionally
437 # delete documents based on other factors, so we cannot call
438 # find_doc_ids twice.
439 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
440 return if $head == $tail;
442 # there is only ONE element in @delete unless we
443 # have bugs in our v2writable deduplication check
445 for (; $head != $tail; $head->inc) {
446 my $docid = $head->get_docid;
447 my $doc = $db->get_document($docid);
448 my $smsg = PublicInbox::SearchMsg->wrap($mid);
449 $smsg->load_expand($doc);
450 if ($smsg->{blob} eq $oid) {
451 push(@delete, $docid);
454 $db->delete_document($_) foreach @delete;
458 sub term_generator { # write-only
461 my $tg = $self->{term_generator};
464 $tg = Search::Xapian::TermGenerator->new;
465 $tg->set_stemmer($self->stemmer);
467 $self->{term_generator} = $tg;
470 sub index_git_blob_id {
471 my ($doc, $pfx, $objid) = @_;
473 my $len = length($objid);
474 for (my $len = length($objid); $len >= 7; ) {
475 $doc->add_term($pfx.$objid);
476 $objid = substr($objid, 0, --$len);
481 my ($self, $mime) = @_;
482 my $mid = eval { mid_clean(mid_mime($mime)) };
483 $self->remove_message($mid) if defined $mid;
487 my ($self, $mime) = @_;
488 my $mid = mid_clean(mid_mime($mime));
489 my $mm = $self->{mm};
492 if (defined $self->{regen_down}) {
493 $num = $mm->num_for($mid) and return $num;
495 while (($num = $self->{regen_down}--) > 0) {
496 if ($mm->mid_set($num, $mid) != 0) {
500 } elsif (defined $self->{regen_up}) {
501 $num = $mm->num_for($mid) and return $num;
503 # this is to fixup old bugs due to add-remove-add
504 while (($num = ++$self->{regen_up})) {
505 if ($mm->mid_set($num, $mid) != 0) {
511 $num = $mm->mid_insert($mid) and return $num;
513 # fallback to num_for since filters like RubyLang set the number
518 my ($self, $mime) = @_;
519 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
523 my ($self, $mime, $bytes, $blob) = @_;
524 my $num = index_mm($self, $mime);
525 add_message($self, $mime, $bytes, $num, $blob);
529 my ($self, $mime) = @_;
530 unindex_blob($self, $mime);
531 unindex_mm($self, $mime);
535 my ($git, $blob, $sizeref) = @_;
537 my $str = $git->cat_file($blob, $sizeref);
538 # fixup bugs from import:
539 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
540 PublicInbox::MIME->new($str);
546 my ($self, $opts) = @_;
547 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
550 sub batch_adjust ($$$$) {
551 my ($max, $bytes, $batch_cb, $latest) = @_;
555 $batch_cb->($latest);
561 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
562 my $hex = '[a-f0-9]';
563 my $h40 = $hex .'{40}';
564 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
565 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
566 my $git = $self->{git};
569 my $max = BATCH_BYTES;
574 while (defined($line = <$log>)) {
575 if ($line =~ /$addmsg/o) {
577 if (delete $D{$blob}) {
578 if (defined $self->{regen_down}) {
579 my $num = $self->{regen_down}--;
580 $self->{mm}->num_highwater($num);
584 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
585 batch_adjust(\$max, $bytes, $batch_cb, $latest);
586 $add_cb->($self, $mime, $bytes, $blob);
587 } elsif ($line =~ /$delmsg/o) {
590 } elsif ($line =~ /^commit ($h40)/o) {
596 foreach my $blob (keys %D) {
597 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
598 $del_cb->($self, $mime);
600 $batch_cb->($latest, $newest);
605 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
606 $self->{mm} ||= eval {
607 require PublicInbox::Msgmap;
608 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
613 my ($self, $range) = @_;
614 my $git = $self->{git};
616 if (index($range, '..') < 0) {
617 # don't show annoying git errrors to users who run -index
619 $git->qx(qw(rev-parse -q --verify), "$range^0");
621 open my $fh, '<', '/dev/null' or
622 die "failed to open /dev/null: $!\n";
627 # Count the new files so they can be added newest to oldest
628 # and still have numbers increasing from oldest to newest
630 # can't use 'rev-list --count' if we use --diff-filter
631 my $fh = $git->popen(qw(log --pretty=tformat:%h
632 --no-notes --no-color --no-renames
633 --diff-filter=AM), $range);
634 ++$fcount while <$fh>;
635 my $high = $self->{mm}->num_highwater;
637 if (index($range, '..') < 0) {
638 if ($high && $high == $fcount) {
639 # fix up old bugs in full indexes which caused messages to
640 # not appear in Msgmap
641 $self->{regen_up} = $high;
643 # normal regen is for for fresh data
644 $self->{regen_down} = $fcount;
647 # Give oldest messages the smallest numbers
648 $self->{regen_down} = $high + $fcount;
651 $git->popen(qw/log --no-notes --no-color --no-renames
652 --raw -r --no-abbrev/, $range);
655 # --is-ancestor requires git 1.8.0+
656 sub is_ancestor ($$$) {
657 my ($git, $cur, $tip) = @_;
658 return 0 unless $git->check($cur);
659 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
660 qw(merge-base --is-ancestor), $cur, $tip ];
661 my $pid = spawn($cmd);
662 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
663 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
667 sub need_update ($$$) {
668 my ($self, $cur, $new) = @_;
669 my $git = $self->{git};
670 return 1 if $cur && !is_ancestor($git, $cur, $new);
671 my $range = $cur eq '' ? $new : "$cur..$new";
672 chomp(my $n = $git->qx(qw(rev-list --count), $range));
673 ($n eq '' || $n > 0);
676 # The last git commit we indexed with Xapian or SQLite (msgmap)
677 # This needs to account for cases where Xapian or SQLite is
678 # out-of-date with respect to the other.
680 my ($self, $mm) = @_;
681 my $lm = $mm->last_commit || '';
683 if (need_xapian($self)) {
684 $lx = $self->{xdb}->get_metadata('last_commit') || '';
688 # Use last_commit from msgmap if it is older or unset
689 if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
695 # indexes all unindexed messages (v1 only)
697 my ($self, $opts) = @_;
698 my $tip = $opts->{ref} || 'HEAD';
699 my ($last_commit, $lx, $xlog);
700 my $git = $self->{git};
703 my $xdb = $self->begin_txn_lazy;
704 my $mm = _msgmap_init($self);
707 $last_commit = _last_x_commit($self, $mm);
708 $lx = $opts->{reindex} ? '' : $last_commit;
710 $self->{over}->rollback_lazy;
711 $self->{over}->disconnect;
714 $xdb->cancel_transaction if $xdb;
715 $xdb = _xdb_release($self);
717 # ensure we leak no FDs to "git log" with Xapian <= 1.2
718 my $range = $lx eq '' ? $tip : "$lx..$tip";
719 $xlog = _git_log($self, $range);
721 $xdb = $self->begin_txn_lazy;
722 } while (_last_x_commit($self, $mm) ne $last_commit);
724 my $dbh = $mm->{dbh} if $mm;
726 my ($commit, $newest) = @_;
729 my $cur = $mm->last_commit || '';
730 if (need_update($self, $cur, $newest)) {
731 $mm->last_commit($newest);
736 if ($newest && need_xapian($self)) {
737 my $cur = $xdb->get_metadata('last_commit');
738 if (need_update($self, $cur, $newest)) {
739 $xdb->set_metadata('last_commit', $newest);
742 $self->commit_txn_lazy;
744 $xdb = _xdb_release($self);
745 # let another process do some work... <
747 $xdb = $self->begin_txn_lazy;
748 $dbh->begin_work if $dbh;
753 read_log($self, $xlog, *index_both, *unindex_both, $cb);
757 # order matters for unlocking
758 $_[0]->{xdb} = undef;
759 $_[0]->{lockfh} = undef;
762 # remote_* subs are only used by SearchIdxPart
765 if (my $w = $self->{w}) {
766 print $w "commit\n" or die "failed to write commit: $!";
768 $self->commit_txn_lazy;
774 if (my $w = delete $self->{w}) {
775 my $pid = delete $self->{pid} or die "no process to wait on\n";
776 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
777 close $w or die "failed to close pipe for pid:$pid: $!\n";
778 waitpid($pid, 0) == $pid or die "remote process did not finish";
779 $? == 0 or die ref($self)." pid:$pid exited with: $?";
781 die "transaction in progress $self\n" if $self->{txn};
782 $self->_xdb_release if $self->{xdb};
787 my ($self, $oid, $mid) = @_;
788 if (my $w = $self->{w}) {
789 # triggers remove_by_oid in a partition
790 print $w "D $oid $mid\n" or die "failed to write remove $!";
792 $self->begin_txn_lazy;
793 $self->remove_by_oid($oid, $mid);
799 return if $self->{txn};
801 $self->{-inbox}->with_umask(sub {
802 my $xdb = $self->{xdb} || $self->_xdb_acquire;
803 $self->{over}->begin_lazy if $self->{over};
804 $xdb->begin_transaction if $xdb;
810 sub commit_txn_lazy {
812 delete $self->{txn} or return;
813 $self->{-inbox}->with_umask(sub {
814 if (my $xdb = $self->{xdb}) {
815 $xdb->commit_transaction;
817 $self->{over}->commit_lazy if $self->{over};
823 if (need_xapian($self)) {
824 die "$$ $0 xdb not released\n" if $self->{xdb};
826 die "$$ $0 still in transaction\n" if $self->{txn};