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");
57 $ibx = { mainrepo => $git_dir, version => 1 };
59 $ibx = PublicInbox::InboxWritable->new($ibx);
60 require Search::Xapian::WritableDatabase;
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;
88 my $xdb = delete $self->{xdb} or croak 'not acquired';
90 $self->lock_release if $self->{creat};
96 croak 'already acquired' if $self->{xdb};
97 my $dir = $self->xdir;
98 my $flag = Search::Xapian::DB_OPEN;
102 File::Path::mkpath($dir);
103 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
105 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
109 my ($doc, $col, $num) = @_;
110 $num = Search::Xapian::sortable_serialise($num);
111 $doc->add_value($col, $num);
114 sub index_text ($$$$)
116 my ($self, $field, $n, $text) = @_;
117 my $tg = $self->term_generator;
119 if ($self->{indexlevel} eq 'full') {
120 $tg->index_text($field, $n, $text);
121 $tg->increase_termpos;
123 $tg->index_text_without_positions($field, $n, $text);
127 sub index_users ($$) {
128 my ($self, $smsg) = @_;
130 my $from = $smsg->from;
134 $self->index_text($from, 1, 'A'); # A - author
135 $self->index_text($to, 1, 'XTO') if $to ne '';
136 $self->index_text($cc, 1, 'XCC') if $cc ne '';
139 sub index_diff_inc ($$$$) {
140 my ($self, $text, $pfx, $xnq) = @_;
142 $self->index_text(join("\n", @$xnq), 1, 'XNQ');
145 $self->index_text($text, 1, $pfx);
148 sub index_old_diff_fn {
149 my ($self, $seen, $fa, $fb, $xnq) = @_;
151 # no renames or space support for traditional diffs,
152 # find the number of leading common paths to strip:
153 my @fa = split('/', $fa);
154 my @fb = split('/', $fb);
155 while (scalar(@fa) && scalar(@fb)) {
156 $fa = join('/', @fa);
157 $fb = join('/', @fb);
159 unless ($seen->{$fa}++) {
160 $self->index_diff_inc($fa, 'XDFN', $xnq);
170 sub index_diff ($$$) {
171 my ($self, $lines, $doc) = @_;
177 if ($in_diff && s/^ //) { # diff context
178 $self->index_diff_inc($_, 'XDFCTX', $xnq);
179 } elsif (/^-- $/) { # email signature begins
181 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
182 my ($fa, $fb) = ($1, $2);
183 my $fn = (split('/', git_unquote($fa), 2))[1];
184 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
185 $fn = (split('/', git_unquote($fb), 2))[1];
186 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
189 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
190 my ($opt, $fa, $fb) = ($1, $2, $3);
192 # only support unified:
193 next unless $opt =~ /[uU]/;
194 $in_diff = $self->index_old_diff_fn(\%seen, $fa, $fb,
196 } elsif (m!^--- ("?a/.+)!) {
197 my $fn = (split('/', git_unquote($1), 2))[1];
198 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
200 } elsif (m!^\+\+\+ ("?b/.+)!) {
201 my $fn = (split('/', git_unquote($1), 2))[1];
202 $seen{$fn}++ or $self->index_diff_inc($fn, 'XDFN', $xnq);
204 } elsif (/^--- (\S+)/) {
207 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
208 $in_diff = $self->index_old_diff_fn(\%seen, $in_diff, $1,
210 } elsif ($in_diff && s/^\+//) { # diff added
211 $self->index_diff_inc($_, 'XDFB', $xnq);
212 } elsif ($in_diff && s/^-//) { # diff removed
213 $self->index_diff_inc($_, 'XDFA', $xnq);
214 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
215 my ($ba, $bb) = ($1, $2);
216 index_git_blob_id($doc, 'XDFPRE', $ba);
217 index_git_blob_id($doc, 'XDFPOST', $bb);
219 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
220 # traditional diff w/o -p
221 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
222 # hunk header context
223 $self->index_diff_inc($1, 'XDFHH', $xnq);
224 # ignore the following lines:
225 } elsif (/^(?:dis)similarity index/ ||
226 /^(?:old|new) mode/ ||
227 /^(?:deleted|new) file mode/ ||
228 /^(?:copy|rename) (?:from|to) / ||
229 /^(?:dis)?similarity index / ||
230 /^\\ No newline at end of file/ ||
231 /^Binary files .* differ/) {
237 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
242 $self->index_text(join("\n", @xnq), 1, 'XNQ');
245 sub index_body ($$$) {
246 my ($self, $lines, $doc) = @_;
247 my $txt = join("\n", @$lines);
249 # does it look like a diff?
250 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
252 $self->index_diff($lines, $doc);
254 $self->index_text($txt, 1, 'XNQ');
257 $self->index_text($txt, 0, 'XQUOT');
262 sub add_xapian ($$$$$) {
263 my ($self, $mime, $num, $oid, $mids, $mid0) = @_;
264 my $smsg = PublicInbox::SearchMsg->new($mime);
265 my $doc = Search::Xapian::Document->new;
266 my $subj = $smsg->subject;
267 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
268 my @ds = gmtime($smsg->ds);
269 my $yyyymmdd = strftime('%Y%m%d', @ds);
270 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
271 my $dt = strftime('%Y%m%d%H%M%S', @ds);
272 add_val($doc, PublicInbox::Search::DT(), $dt);
274 my $tg = $self->term_generator;
276 $tg->set_document($doc);
277 $self->index_text($subj, 1, 'S') if $subj;
278 $self->index_users($smsg);
280 msg_iter($mime, sub {
281 my ($part, $depth, @idx) = @{$_[0]};
282 my $ct = $part->content_type || 'text/plain';
283 my $fn = $part->filename;
284 if (defined $fn && $fn ne '') {
285 $self->index_text($fn, 1, 'XFN');
288 my ($s, undef) = msg_part_text($part, $ct);
289 defined $s or return;
292 my @lines = split(/\n/, $s);
293 while (defined(my $l = shift @lines)) {
295 $self->index_body(\@orig, $doc) if @orig;
298 $self->index_body(\@quot, 0) if @quot;
302 $self->index_body(\@quot, 0) if @quot;
303 $self->index_body(\@orig, $doc) if @orig;
306 foreach my $mid (@$mids) {
307 $self->index_text($mid, 1, 'XM');
309 # because too many Message-IDs are prefixed with
311 if ($mid =~ /\w{12,}/) {
312 my @long = ($mid =~ /(\w{3,}+)/g);
313 $self->index_text(join(' ', @long), 1, 'XM');
316 $smsg->{to} = $smsg->{cc} = '';
317 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
318 my $data = $smsg->to_doc_data($oid, $mid0);
319 $doc->set_data($data);
320 if (my $altid = $self->{-altid}) {
321 foreach my $alt (@$altid) {
322 my $pfx = $alt->{xprefix};
323 foreach my $mid (@$mids) {
324 my $id = $alt->mid2alt($mid);
325 next unless defined $id;
326 $doc->add_boolean_term($pfx . $id);
330 $doc->add_boolean_term('Q' . $_) foreach @$mids;
331 $self->{xdb}->replace_document($num, $doc);
335 # mime = Email::MIME object
336 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
337 my $mids = mids($mime->header_obj);
338 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
339 unless (defined $num) { # v1
341 $num = index_mm($self, $mime);
344 if ($self->{indexlevel} =~ $xapianlevels) {
345 $self->add_xapian($mime, $num, $oid, $mids, $mid0)
347 if (my $over = $self->{over}) {
348 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
353 warn "failed to index message <".join('> <',@$mids).">: $@\n";
359 # returns begin and end PostingIterator
361 my ($self, $termval) = @_;
362 my $db = $self->{xdb};
364 ($db->postlist_begin($termval), $db->postlist_end($termval));
369 my ($self, $termval, $cb) = @_;
370 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
372 my ($head, $tail) = $self->find_doc_ids($termval);
373 return if $head == $tail;
375 for (; $head != $tail && @ids < $batch_size; $head->inc) {
376 push @ids, $head->get_docid;
382 # v1 only, where $mid is unique
384 my ($self, $mid) = @_;
385 my $db = $self->{xdb};
386 $mid = mid_clean($mid);
388 if (my $over = $self->{over}) {
389 my $nr = eval { $over->remove_oid(undef, $mid) };
391 warn "failed to remove <$mid> from overview: $@\n";
393 warn "<$mid> missing for removal from overview\n";
396 return if $self->{indexlevel} !~ $xapianlevels;
399 batch_do($self, 'Q' . $mid, sub {
401 $db->delete_document($_) for @$ids;
406 warn "failed to remove <$mid> from Xapian: $@\n";
408 warn "<$mid> missing for removal from Xapian\n";
412 # MID is a hint in V2
414 my ($self, $oid, $mid) = @_;
415 my $db = $self->{xdb};
417 $self->{over}->remove_oid($oid, $mid) if $self->{over};
419 # XXX careful, we cannot use batch_do here since we conditionally
420 # delete documents based on other factors, so we cannot call
421 # find_doc_ids twice.
422 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
423 return if $head == $tail;
425 # there is only ONE element in @delete unless we
426 # have bugs in our v2writable deduplication check
428 for (; $head != $tail; $head->inc) {
429 my $docid = $head->get_docid;
430 my $doc = $db->get_document($docid);
431 my $smsg = PublicInbox::SearchMsg->wrap($mid);
432 $smsg->load_expand($doc);
433 if ($smsg->{blob} eq $oid) {
434 push(@delete, $docid);
437 $db->delete_document($_) foreach @delete;
441 sub term_generator { # write-only
444 my $tg = $self->{term_generator};
447 $tg = Search::Xapian::TermGenerator->new;
448 $tg->set_stemmer($self->stemmer);
450 $self->{term_generator} = $tg;
453 sub index_git_blob_id {
454 my ($doc, $pfx, $objid) = @_;
456 my $len = length($objid);
457 for (my $len = length($objid); $len >= 7; ) {
458 $doc->add_term($pfx.$objid);
459 $objid = substr($objid, 0, --$len);
464 my ($self, $mime) = @_;
465 my $mid = eval { mid_clean(mid_mime($mime)) };
466 $self->remove_message($mid) if defined $mid;
470 my ($self, $mime) = @_;
471 my $mid = mid_clean(mid_mime($mime));
472 my $mm = $self->{mm};
475 if (defined $self->{regen_down}) {
476 $num = $mm->num_for($mid) and return $num;
478 while (($num = $self->{regen_down}--) > 0) {
479 if ($mm->mid_set($num, $mid) != 0) {
483 } elsif (defined $self->{regen_up}) {
484 $num = $mm->num_for($mid) and return $num;
486 # this is to fixup old bugs due to add-remove-add
487 while (($num = ++$self->{regen_up})) {
488 if ($mm->mid_set($num, $mid) != 0) {
494 $num = $mm->mid_insert($mid) and return $num;
496 # fallback to num_for since filters like RubyLang set the number
501 my ($self, $mime) = @_;
502 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
506 my ($self, $mime, $bytes, $blob) = @_;
507 my $num = index_mm($self, $mime);
508 add_message($self, $mime, $bytes, $num, $blob);
512 my ($self, $mime) = @_;
513 unindex_blob($self, $mime);
514 unindex_mm($self, $mime);
518 my ($git, $blob, $sizeref) = @_;
520 my $str = $git->cat_file($blob, $sizeref);
521 # fixup bugs from import:
522 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
523 PublicInbox::MIME->new($str);
529 my ($self, $opts) = @_;
530 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
533 sub batch_adjust ($$$$) {
534 my ($max, $bytes, $batch_cb, $latest) = @_;
538 $batch_cb->($latest);
544 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
545 my $hex = '[a-f0-9]';
546 my $h40 = $hex .'{40}';
547 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
548 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
549 my $git = $self->{git};
552 my $max = BATCH_BYTES;
557 while (defined($line = <$log>)) {
558 if ($line =~ /$addmsg/o) {
560 if (delete $D{$blob}) {
561 if (defined $self->{regen_down}) {
562 my $num = $self->{regen_down}--;
563 $self->{mm}->num_highwater($num);
567 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
568 batch_adjust(\$max, $bytes, $batch_cb, $latest);
569 $add_cb->($self, $mime, $bytes, $blob);
570 } elsif ($line =~ /$delmsg/o) {
573 } elsif ($line =~ /^commit ($h40)/o) {
579 foreach my $blob (keys %D) {
580 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
581 $del_cb->($self, $mime);
583 $batch_cb->($latest, $newest);
588 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
589 $self->{mm} ||= eval {
590 require PublicInbox::Msgmap;
591 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
596 my ($self, $range) = @_;
597 my $git = $self->{git};
599 if (index($range, '..') < 0) {
600 # don't show annoying git errrors to users who run -index
602 $git->qx(qw(rev-parse -q --verify), "$range^0");
604 open my $fh, '<', '/dev/null' or
605 die "failed to open /dev/null: $!\n";
610 # Count the new files so they can be added newest to oldest
611 # and still have numbers increasing from oldest to newest
613 # can't use 'rev-list --count' if we use --diff-filter
614 my $fh = $git->popen(qw(log --pretty=tformat:%h
615 --no-notes --no-color --no-renames
616 --diff-filter=AM), $range);
617 ++$fcount while <$fh>;
618 my $high = $self->{mm}->num_highwater;
620 if (index($range, '..') < 0) {
621 if ($high && $high == $fcount) {
622 # fix up old bugs in full indexes which caused messages to
623 # not appear in Msgmap
624 $self->{regen_up} = $high;
626 # normal regen is for for fresh data
627 $self->{regen_down} = $fcount;
630 # Give oldest messages the smallest numbers
631 $self->{regen_down} = $high + $fcount;
634 $git->popen(qw/log --no-notes --no-color --no-renames
635 --raw -r --no-abbrev/, $range);
638 # --is-ancestor requires git 1.8.0+
639 sub is_ancestor ($$$) {
640 my ($git, $cur, $tip) = @_;
641 return 0 unless $git->check($cur);
642 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
643 qw(merge-base --is-ancestor), $cur, $tip ];
644 my $pid = spawn($cmd);
645 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
646 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
650 sub need_update ($$$) {
651 my ($self, $cur, $new) = @_;
652 my $git = $self->{git};
653 return 1 if $cur && !is_ancestor($git, $cur, $new);
654 my $range = $cur eq '' ? $new : "$cur..$new";
655 chomp(my $n = $git->qx(qw(rev-list --count), $range));
656 ($n eq '' || $n > 0);
659 # The last git commit we indexed with Xapian or SQLite (msgmap)
660 # This needs to account for cases where Xapian or SQLite is
661 # out-of-date with respect to the other.
663 my ($self, $mm) = @_;
664 my $lm = $mm->last_commit || '';
666 if ($self->{indexlevel} =~ $xapianlevels) {
667 $lx = $self->{xdb}->get_metadata('last_commit') || '';
671 # Use last_commit from msgmap if it is older or unset
672 if (!$lm || ($lx && $lx && is_ancestor($self->{git}, $lm, $lx))) {
678 # indexes all unindexed messages (v1 only)
680 my ($self, $opts) = @_;
681 my $tip = $opts->{ref} || 'HEAD';
682 my ($last_commit, $lx, $xlog);
683 my $git = $self->{git};
686 my $xdb = $self->begin_txn_lazy;
687 my $mm = _msgmap_init($self);
690 $last_commit = _last_x_commit($self, $mm);
691 $lx = $opts->{reindex} ? '' : $last_commit;
693 $self->{over}->rollback_lazy;
694 $self->{over}->disconnect;
697 $xdb->cancel_transaction;
698 $xdb = _xdb_release($self);
700 # ensure we leak no FDs to "git log" with Xapian <= 1.2
701 my $range = $lx eq '' ? $tip : "$lx..$tip";
702 $xlog = _git_log($self, $range);
704 $xdb = $self->begin_txn_lazy;
705 } while (_last_x_commit($self, $mm) ne $last_commit);
707 my $dbh = $mm->{dbh} if $mm;
709 my ($commit, $newest) = @_;
712 my $cur = $mm->last_commit || '';
713 if (need_update($self, $cur, $newest)) {
714 $mm->last_commit($newest);
719 if ($newest && $self->{indexlevel} =~ $xapianlevels) {
720 my $cur = $xdb->get_metadata('last_commit');
721 if (need_update($self, $cur, $newest)) {
722 $xdb->set_metadata('last_commit', $newest);
725 $self->commit_txn_lazy;
727 $xdb = _xdb_release($self);
728 # let another process do some work... <
730 $xdb = $self->begin_txn_lazy;
731 $dbh->begin_work if $dbh;
736 read_log($self, $xlog, *index_both, *unindex_both, $cb);
740 # order matters for unlocking
741 $_[0]->{xdb} = undef;
742 $_[0]->{lockfh} = undef;
745 # remote_* subs are only used by SearchIdxPart
748 if (my $w = $self->{w}) {
749 print $w "commit\n" or die "failed to write commit: $!";
751 $self->commit_txn_lazy;
757 if (my $w = delete $self->{w}) {
758 my $pid = delete $self->{pid} or die "no process to wait on\n";
759 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
760 close $w or die "failed to close pipe for pid:$pid: $!\n";
761 waitpid($pid, 0) == $pid or die "remote process did not finish";
762 $? == 0 or die ref($self)." pid:$pid exited with: $?";
764 die "transaction in progress $self\n" if $self->{txn};
765 $self->_xdb_release if $self->{xdb};
770 my ($self, $oid, $mid) = @_;
771 if (my $w = $self->{w}) {
772 # triggers remove_by_oid in a partition
773 print $w "D $oid $mid\n" or die "failed to write remove $!";
775 $self->begin_txn_lazy;
776 $self->remove_by_oid($oid, $mid);
782 return if $self->{txn};
784 $self->{-inbox}->with_umask(sub {
785 my $xdb = $self->{xdb} || $self->_xdb_acquire;
786 $self->{over}->begin_lazy if $self->{over};
787 $xdb->begin_transaction;
793 sub commit_txn_lazy {
795 delete $self->{txn} or return;
796 $self->{-inbox}->with_umask(sub {
797 $self->{xdb}->commit_transaction;
798 $self->{over}->commit_lazy if $self->{over};
804 die "$$ $0 xdb not released\n" if $self->{xdb};
805 die "$$ $0 still in transaction\n" if $self->{txn};