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");
58 $ibx = { mainrepo => $git_dir, version => 1 };
60 $ibx = PublicInbox::InboxWritable->new($ibx);
61 require Search::Xapian::WritableDatabase;
63 mainrepo => $mainrepo,
68 indexlevel => $indexlevel,
72 $self->{lock_path} = "$mainrepo/ssoma.lock";
73 my $dir = $self->xdir;
74 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
75 } elsif ($version == 2) {
76 defined $part or die "partition is required for v2\n";
77 # partition is a number
78 $self->{partition} = $part;
79 $self->{lock_path} = undef;
81 die "unsupported inbox version=$version\n";
83 $self->{creat} = ($creat || 0) == 1;
89 my $xdb = delete $self->{xdb} or croak 'not acquired';
91 $self->lock_release if $self->{creat};
97 croak 'already acquired' if $self->{xdb};
98 my $dir = $self->xdir;
99 my $flag = Search::Xapian::DB_OPEN;
100 if ($self->{creat}) {
103 File::Path::mkpath($dir);
104 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
106 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
110 my ($doc, $col, $num) = @_;
111 $num = Search::Xapian::sortable_serialise($num);
112 $doc->add_value($col, $num);
115 sub index_text ($$$$)
117 my ($self, $field, $n, $text) = @_;
118 my $tg = $self->term_generator;
120 if ($self->{indexlevel} eq 'full') {
121 $tg->index_text($field, $n, $text);
122 $tg->increase_termpos;
124 $tg->index_text_without_positions($field, $n, $text);
128 sub index_users ($$) {
129 my ($self, $smsg) = @_;
131 my $from = $smsg->from;
135 $self->index_text($from, 1, 'A'); # A - author
136 $self->index_text($to, 1, 'XTO') if $to ne '';
137 $self->index_text($cc, 1, 'XCC') if $cc ne '';
140 sub index_diff_inc ($$$$) {
141 my ($self, $text, $pfx, $xnq) = @_;
143 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
146 $self->index_text($text, 1, $pfx);
149 sub index_old_diff_fn {
150 my ($self, $seen, $fa, $fb, $xnq) = @_;
152 # no renames or space support for traditional diffs,
153 # find the number of leading common paths to strip:
154 my @fa = split('/', $fa);
155 my @fb = split('/', $fb);
156 while (scalar(@fa) && scalar(@fb)) {
157 $fa = join('/', @fa);
158 $fb = join('/', @fb);
160 unless ($seen->{$fa}++) {
161 $self->index_diff_inc($fa, 'XDFN', $xnq);
171 sub index_diff ($$$) {
172 my ($self, $lines, $doc) = @_;
178 if ($in_diff && s/^ //) { # diff context
179 $self->index_diff_inc($_, 'XDFCTX', $xnq);
180 } elsif (/^-- $/) { # email signature begins
182 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
183 my ($fa, $fb) = ($1, $2);
184 my $fn = (split('/', git_unquote($fa), 2))[1];
185 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
186 $fn = (split('/', git_unquote($fb), 2))[1];
187 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
190 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
191 my ($opt, $fa, $fb) = ($1, $2, $3);
193 # only support unified:
194 next unless $opt =~ /[uU]/;
195 $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
197 } elsif (m!^--- ("?a/.+)!) {
198 my $fn = (split('/', git_unquote($1), 2))[1];
199 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
201 } elsif (m!^\+\+\+ ("?b/.+)!) {
202 my $fn = (split('/', git_unquote($1), 2))[1];
203 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
205 } elsif (/^--- (\S+)/) {
208 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
209 $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
211 } elsif ($in_diff && s/^\+//) { # diff added
212 $self->index_diff_inc($_, 'XDFB', $xnq);
213 } elsif ($in_diff && s/^-//) { # diff removed
214 $self->index_diff_inc($_, 'XDFA', $xnq);
215 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
216 my ($ba, $bb) = ($1, $2);
217 index_git_blob_id($doc, 'XDFPRE', $ba);
218 index_git_blob_id($doc, 'XDFPOST', $bb);
220 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
221 # traditional diff w/o -p
222 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
223 # hunk header context
224 $self->index_diff_inc($1, 'XDFHH', $xnq);
225 # ignore the following lines:
226 } elsif (/^(?:dis)similarity index/ ||
227 /^(?:old|new) mode/ ||
228 /^(?:deleted|new) file mode/ ||
229 /^(?:copy|rename) (?:from|to) / ||
230 /^(?:dis)?similarity index / ||
231 /^\\ No newline at end of file/ ||
232 /^Binary files .* differ/) {
238 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
243 $self->index_text(join("\n", @xnq), 1, 'XNQ');
246 sub index_body ($$$) {
247 my ($self, $lines, $doc) = @_;
248 my $txt = join("\n", @$lines);
250 # does it look like a diff?
251 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
253 $self->index_diff($lines, $doc);
255 $self->index_text($txt, 1, 'XNQ');
258 $self->index_text($txt, 0, 'XQUOT');
263 sub add_xapian ($$$$$) {
264 my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
265 my $smsg = PublicInbox::SearchMsg->new($mime);
266 my $doc = Search::Xapian::Document->new;
267 my $subj = $smsg->subject;
268 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
269 my @ds = gmtime($smsg->ds);
270 my $yyyymmdd = strftime('%Y%m%d', @ds);
271 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
272 my $dt = strftime('%Y%m%d%H%M%S', @ds);
273 add_val($doc, PublicInbox::Search::DT(), $dt);
275 my $tg = $self->term_generator;
277 $tg->set_document($doc);
278 $self->index_text($subj, 1, 'S') if $subj;
279 $self->index_users($smsg);
281 msg_iter($mime, sub {
282 my ($part, $depth, @idx) = @{$_[0]};
283 my $ct = $part->content_type || 'text/plain';
284 my $fn = $part->filename;
285 if (defined $fn && $fn ne '') {
286 $self->index_text($fn, 1, 'XFN');
289 my ($s, undef) = msg_part_text($part, $ct);
290 defined $s or return;
293 my @lines = split(/\n/, $s);
294 while (defined(my $l = shift @lines)) {
296 $self->index_body(\@orig, $doc) if @orig;
299 $self->index_body(\@quot, 0) if @quot;
303 $self->index_body(\@quot, 0) if @quot;
304 $self->index_body(\@orig, $doc) if @orig;
307 foreach my $mid (@$mids) {
308 $self->index_text($mid, 1, 'XM');
310 # because too many Message-IDs are prefixed with
312 if ($mid =~ /\w{12,}/) {
313 my @long = ($mid =~ /(\w{3,}+)/g);
314 $self->index_text(join(' ', @long), 1, 'XM');
317 $smsg->{to} = $smsg->{cc} = '';
318 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
319 my $data = $smsg->to_doc_data($oid, $mid0);
320 $doc->set_data($data);
321 if (my $altid = $self->{-altid}) {
322 foreach my $alt (@$altid) {
323 my $pfx = $alt->{xprefix};
324 foreach my $mid (@$mids) {
325 my $id = $alt->mid2alt($mid);
326 next unless defined $id;
327 $doc->add_boolean_term($pfx . $id);
331 $doc->add_boolean_term('Q' . $_) foreach @$mids;
332 $self->{xdb}->replace_document($num, $doc);
336 # mime = Email::MIME object
337 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
338 my $mids = mids($mime->header_obj);
339 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
340 unless (defined $num) { # v1
342 $num = index_mm($self, $mime);
345 if ($self->{indexlevel} =~ $xapianlevels) {
346 $self->add_xapian($mime, $num, $oid, $mids, $mid0)
348 if (my $over = $self->{over}) {
349 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
354 warn "failed to index message <".join('> <',@$mids).">: $@\n";
360 # returns begin and end PostingIterator
362 my ($self, $termval) = @_;
363 my $db = $self->{xdb};
365 ($db->postlist_begin($termval), $db->postlist_end($termval));
370 my ($self, $termval, $cb) = @_;
371 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
373 my ($head, $tail) = $self->find_doc_ids($termval);
374 return if $head == $tail;
376 for (; $head != $tail && @ids < $batch_size; $head->inc) {
377 push @ids, $head->get_docid;
383 # v1 only, where $mid is unique
385 my ($self, $mid) = @_;
386 my $db = $self->{xdb};
387 $mid = mid_clean($mid);
389 if (my $over = $self->{over}) {
390 my $nr = eval { $over->remove_oid(undef, $mid) };
392 warn "failed to remove <$mid> from overview: $@\n";
394 warn "<$mid> missing for removal from overview\n";
397 return if $self->{indexlevel} !~ $xapianlevels;
400 batch_do($self, 'Q' . $mid, sub {
402 $db->delete_document($_) for @$ids;
407 warn "failed to remove <$mid> from Xapian: $@\n";
409 warn "<$mid> missing for removal from Xapian\n";
413 # MID is a hint in V2
415 my ($self, $oid, $mid) = @_;
416 my $db = $self->{xdb};
418 $self->{over}->remove_oid($oid, $mid) if $self->{over};
420 # XXX careful, we cannot use batch_do here since we conditionally
421 # delete documents based on other factors, so we cannot call
422 # find_doc_ids twice.
423 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
424 return if $head == $tail;
426 # there is only ONE element in @delete unless we
427 # have bugs in our v2writable deduplication check
429 for (; $head != $tail; $head->inc) {
430 my $docid = $head->get_docid;
431 my $doc = $db->get_document($docid);
432 my $smsg = PublicInbox::SearchMsg->wrap($mid);
433 $smsg->load_expand($doc);
434 if ($smsg->{blob} eq $oid) {
435 push(@delete, $docid);
438 $db->delete_document($_) foreach @delete;
442 sub term_generator { # write-only
445 my $tg = $self->{term_generator};
448 $tg = Search::Xapian::TermGenerator->new;
449 $tg->set_stemmer($self->stemmer);
451 $self->{term_generator} = $tg;
454 sub index_git_blob_id {
455 my ($doc, $pfx, $objid) = @_;
457 my $len = length($objid);
458 for (my $len = length($objid); $len >= 7; ) {
459 $doc->add_term($pfx.$objid);
460 $objid = substr($objid, 0, --$len);
465 my ($self, $mime) = @_;
466 my $mid = eval { mid_clean(mid_mime($mime)) };
467 $self->remove_message($mid) if defined $mid;
471 my ($self, $mime) = @_;
472 my $mid = mid_clean(mid_mime($mime));
473 my $mm = $self->{mm};
476 if (defined $self->{regen_down}) {
477 $num = $mm->num_for($mid) and return $num;
479 while (($num = $self->{regen_down}--) > 0) {
480 if ($mm->mid_set($num, $mid) != 0) {
484 } elsif (defined $self->{regen_up}) {
485 $num = $mm->num_for($mid) and return $num;
487 # this is to fixup old bugs due to add-remove-add
488 while (($num = ++$self->{regen_up})) {
489 if ($mm->mid_set($num, $mid) != 0) {
495 $num = $mm->mid_insert($mid) and return $num;
497 # fallback to num_for since filters like RubyLang set the number
502 my ($self, $mime) = @_;
503 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
507 my ($self, $mime, $bytes, $blob) = @_;
508 my $num = index_mm($self, $mime);
509 add_message($self, $mime, $bytes, $num, $blob);
513 my ($self, $mime) = @_;
514 unindex_blob($self, $mime);
515 unindex_mm($self, $mime);
519 my ($git, $blob, $sizeref) = @_;
521 my $str = $git->cat_file($blob, $sizeref);
522 # fixup bugs from import:
523 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
524 PublicInbox::MIME->new($str);
530 my ($self, $opts) = @_;
531 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
534 sub batch_adjust ($$$$) {
535 my ($max, $bytes, $batch_cb, $latest) = @_;
539 $batch_cb->($latest);
545 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
546 my $hex = '[a-f0-9]';
547 my $h40 = $hex .'{40}';
548 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
549 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
550 my $git = $self->{git};
553 my $max = BATCH_BYTES;
558 while (defined($line = <$log>)) {
559 if ($line =~ /$addmsg/o) {
561 if (delete $D{$blob}) {
562 if (defined $self->{regen_down}) {
563 my $num = $self->{regen_down}--;
564 $self->{mm}->num_highwater($num);
568 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
569 batch_adjust(\$max, $bytes, $batch_cb, $latest);
570 $add_cb->($self, $mime, $bytes, $blob);
571 } elsif ($line =~ /$delmsg/o) {
574 } elsif ($line =~ /^commit ($h40)/o) {
580 foreach my $blob (keys %D) {
581 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
582 $del_cb->($self, $mime);
584 $batch_cb->($latest, $newest);
589 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
590 $self->{mm} ||= eval {
591 require PublicInbox::Msgmap;
592 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
597 my ($self, $range) = @_;
598 my $git = $self->{git};
600 if (index($range, '..') < 0) {
601 # don't show annoying git errrors to users who run -index
603 $git->qx(qw(rev-parse -q --verify), "$range^0");
605 open my $fh, '<', '/dev/null' or
606 die "failed to open /dev/null: $!\n";
611 # Count the new files so they can be added newest to oldest
612 # and still have numbers increasing from oldest to newest
614 # can't use 'rev-list --count' if we use --diff-filter
615 my $fh = $git->popen(qw(log --pretty=tformat:%h
616 --no-notes --no-color --no-renames
617 --diff-filter=AM), $range);
618 ++$fcount while <$fh>;
619 my $high = $self->{mm}->num_highwater;
621 if (index($range, '..') < 0) {
622 if ($high && $high == $fcount) {
623 # fix up old bugs in full indexes which caused messages to
624 # not appear in Msgmap
625 $self->{regen_up} = $high;
627 # normal regen is for for fresh data
628 $self->{regen_down} = $fcount;
631 # Give oldest messages the smallest numbers
632 $self->{regen_down} = $high + $fcount;
635 $git->popen(qw/log --no-notes --no-color --no-renames
636 --raw -r --no-abbrev/, $range);
639 # --is-ancestor requires git 1.8.0+
640 sub is_ancestor ($$$) {
641 my ($git, $cur, $tip) = @_;
642 return 0 unless $git->check($cur);
643 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
644 qw(merge-base --is-ancestor), $cur, $tip ];
645 my $pid = spawn($cmd);
646 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
647 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
651 sub need_update ($$$) {
652 my ($self, $cur, $new) = @_;
653 my $git = $self->{git};
654 return 1 if $cur && !is_ancestor($git, $cur, $new);
655 my $range = $cur eq '' ? $new : "$cur..$new";
656 chomp(my $n = $git->qx(qw(rev-list --count), $range));
657 ($n eq '' || $n > 0);
660 # The last git commit we indexed with Xapian or SQLite (msgmap)
661 # This needs to account for cases where Xapian or SQLite is
662 # out-of-date with respect to the other.
664 my ($self, $mm) = @_;
665 my $lm = $mm->last_commit || '';
667 if ($self->{indexlevel} =~ $xapianlevels) {
668 $lx = $self->{xdb}->get_metadata('last_commit') || '';
672 # Use last_commit from msgmap if it is older or unset
673 if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
679 # indexes all unindexed messages (v1 only)
681 my ($self, $opts) = @_;
682 my $tip = $opts->{ref} || 'HEAD';
683 my ($last_commit, $lx, $xlog);
684 my $git = $self->{git};
687 my $xdb = $self->begin_txn_lazy;
688 my $mm = _msgmap_init($self);
691 $last_commit = _last_x_commit($self, $mm);
692 $lx = $opts->{reindex} ? '' : $last_commit;
694 $self->{over}->rollback_lazy;
695 $self->{over}->disconnect;
698 $xdb->cancel_transaction;
699 $xdb = _xdb_release($self);
701 # ensure we leak no FDs to "git log" with Xapian <= 1.2
702 my $range = $lx eq '' ? $tip : "$lx..$tip";
703 $xlog = _git_log($self, $range);
705 $xdb = $self->begin_txn_lazy;
706 } while (_last_x_commit($self, $mm) ne $last_commit);
708 my $dbh = $mm->{dbh} if $mm;
710 my ($commit, $newest) = @_;
713 my $cur = $mm->last_commit || '';
714 if (need_update($self, $cur, $newest)) {
715 $mm->last_commit($newest);
720 if ($newest && $self->{indexlevel} =~ $xapianlevels) {
721 my $cur = $xdb->get_metadata('last_commit');
722 if (need_update($self, $cur, $newest)) {
723 $xdb->set_metadata('last_commit', $newest);
726 $self->commit_txn_lazy;
728 $xdb = _xdb_release($self);
729 # let another process do some work... <
731 $xdb = $self->begin_txn_lazy;
732 $dbh->begin_work if $dbh;
737 read_log($self, $xlog, *index_both, *unindex_both, $cb);
741 # order matters for unlocking
742 $_[0]->{xdb} = undef;
743 $_[0]->{lockfh} = undef;
746 # remote_* subs are only used by SearchIdxPart
749 if (my $w = $self->{w}) {
750 print $w "commit\n" or die "failed to write commit: $!";
752 $self->commit_txn_lazy;
758 if (my $w = delete $self->{w}) {
759 my $pid = delete $self->{pid} or die "no process to wait on\n";
760 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
761 close $w or die "failed to close pipe for pid:$pid: $!\n";
762 waitpid($pid, 0) == $pid or die "remote process did not finish";
763 $? == 0 or die ref($self)." pid:$pid exited with: $?";
765 die "transaction in progress $self\n" if $self->{txn};
766 $self->_xdb_release if $self->{xdb};
771 my ($self, $oid, $mid) = @_;
772 if (my $w = $self->{w}) {
773 # triggers remove_by_oid in a partition
774 print $w "D $oid $mid\n" or die "failed to write remove $!";
776 $self->begin_txn_lazy;
777 $self->remove_by_oid($oid, $mid);
783 return if $self->{txn};
785 $self->{-inbox}->with_umask(sub {
786 my $xdb = $self->{xdb} || $self->_xdb_acquire;
787 $self->{over}->begin_lazy if $self->{over};
788 $xdb->begin_transaction;
794 sub commit_txn_lazy {
796 delete $self->{txn} or return;
797 $self->{-inbox}->with_umask(sub {
798 $self->{xdb}->commit_transaction;
799 $self->{over}->commit_lazy if $self->{over};
805 die "$$ $0 xdb not released\n" if $self->{xdb};
806 die "$$ $0 still in transaction\n" if $self->{txn};