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 references/;
16 use PublicInbox::MsgIter;
18 use POSIX qw(strftime);
19 use PublicInbox::OverIdx;
20 require PublicInbox::Git;
21 use Compress::Zlib qw(compress);
24 BATCH_BYTES => 10_000_000,
25 DEBUG => !!$ENV{DEBUG},
40 return $s unless ($s =~ /\A"(.*)"\z/);
42 $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
43 $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
48 my ($class, $ibx, $creat, $part) = @_;
49 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
50 my $git_dir = $mainrepo;
54 $mainrepo = $ibx->{mainrepo};
55 $altid = $ibx->{altid};
56 $version = $ibx->{version} || 1;
58 require PublicInbox::AltId;
60 PublicInbox::AltId->new($ibx, $_);
64 $ibx = { mainrepo => $git_dir, version => 1 };
66 $ibx = PublicInbox::InboxWritable->new($ibx);
67 require Search::Xapian::WritableDatabase;
69 mainrepo => $mainrepo,
77 $self->{lock_path} = "$mainrepo/ssoma.lock";
78 my $dir = $self->xdir;
79 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
80 } elsif ($version == 2) {
81 defined $part or die "partition is required for v2\n";
82 # partition is a number
83 $self->{partition} = $part;
84 $self->{lock_path} = undef;
86 die "unsupported inbox version=$version\n";
88 $self->{creat} = ($creat || 0) == 1;
94 my $xdb = delete $self->{xdb} or croak 'not acquired';
96 $self->lock_release if $self->{creat};
102 croak 'already acquired' if $self->{xdb};
103 my $dir = $self->xdir;
104 my $flag = Search::Xapian::DB_OPEN;
105 if ($self->{creat}) {
108 File::Path::mkpath($dir);
109 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
111 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
115 my ($doc, $col, $num) = @_;
116 $num = Search::Xapian::sortable_serialise($num);
117 $doc->add_value($col, $num);
120 sub index_users ($$) {
121 my ($tg, $smsg) = @_;
123 my $from = $smsg->from;
127 $tg->index_text($from, 1, 'A'); # A - author
128 $tg->increase_termpos;
129 $tg->index_text($to, 1, 'XTO') if $to ne '';
130 $tg->increase_termpos;
131 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
132 $tg->increase_termpos;
135 sub index_diff_inc ($$$$) {
136 my ($tg, $text, $pfx, $xnq) = @_;
138 $tg->index_text(join("\n", @$xnq), 1, 'XNQ');
139 $tg->increase_termpos;
142 $tg->index_text($text, 1, $pfx);
143 $tg->increase_termpos;
146 sub index_old_diff_fn {
147 my ($tg, $seen, $fa, $fb, $xnq) = @_;
149 # no renames or space support for traditional diffs,
150 # find the number of leading common paths to strip:
151 my @fa = split('/', $fa);
152 my @fb = split('/', $fb);
153 while (scalar(@fa) && scalar(@fb)) {
154 $fa = join('/', @fa);
155 $fb = join('/', @fb);
157 unless ($seen->{$fa}++) {
158 index_diff_inc($tg, $fa, 'XDFN', $xnq);
168 sub index_diff ($$$) {
169 my ($tg, $lines, $doc) = @_;
175 if ($in_diff && s/^ //) { # diff context
176 index_diff_inc($tg, $_, 'XDFCTX', $xnq);
177 } elsif (/^-- $/) { # email signature begins
179 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
180 my ($fa, $fb) = ($1, $2);
181 my $fn = (split('/', git_unquote($fa), 2))[1];
182 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
183 $fn = (split('/', git_unquote($fb), 2))[1];
184 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
187 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
188 my ($opt, $fa, $fb) = ($1, $2, $3);
190 # only support unified:
191 next unless $opt =~ /[uU]/;
192 $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb,
194 } elsif (m!^--- ("?a/.+)!) {
195 my $fn = (split('/', git_unquote($1), 2))[1];
196 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
198 } elsif (m!^\+\+\+ ("?b/.+)!) {
199 my $fn = (split('/', git_unquote($1), 2))[1];
200 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
202 } elsif (/^--- (\S+)/) {
205 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
206 $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1,
208 } elsif ($in_diff && s/^\+//) { # diff added
209 index_diff_inc($tg, $_, 'XDFB', $xnq);
210 } elsif ($in_diff && s/^-//) { # diff removed
211 index_diff_inc($tg, $_, 'XDFA', $xnq);
212 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
213 my ($ba, $bb) = ($1, $2);
214 index_git_blob_id($doc, 'XDFPRE', $ba);
215 index_git_blob_id($doc, 'XDFPOST', $bb);
217 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
218 # traditional diff w/o -p
219 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
220 # hunk header context
221 index_diff_inc($tg, $1, 'XDFHH', $xnq);
222 # ignore the following lines:
223 } elsif (/^(?:dis)similarity index/ ||
224 /^(?:old|new) mode/ ||
225 /^(?:deleted|new) file mode/ ||
226 /^(?:copy|rename) (?:from|to) / ||
227 /^(?:dis)?similarity index / ||
228 /^\\ No newline at end of file/ ||
229 /^Binary files .* differ/) {
235 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
240 $tg->index_text(join("\n", @xnq), 1, 'XNQ');
241 $tg->increase_termpos;
244 sub index_body ($$$) {
245 my ($tg, $lines, $doc) = @_;
246 my $txt = join("\n", @$lines);
248 # does it look like a diff?
249 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
251 index_diff($tg, $lines, $doc);
253 $tg->index_text($txt, 1, 'XNQ');
256 $tg->index_text($txt, 0, 'XQUOT');
258 $tg->increase_termpos;
263 # mime = Email::MIME object
264 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
266 my $mids = mids($mime->header_obj);
267 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
268 unless (defined $num) { # v1
269 my $mm = $self->_msgmap_init;
270 $num = $mm->mid_insert($mid0) || $mm->num_for($mid0);
273 my $smsg = PublicInbox::SearchMsg->new($mime);
274 my $doc = $smsg->{doc};
275 my $subj = $smsg->subject;
278 $xpath = $self->subject_path($subj);
279 $xpath = id_compress($xpath);
282 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
283 defined $bytes or $bytes = length($mime->as_string);
284 $smsg->{bytes} = $bytes;
286 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
287 my @ds = gmtime($smsg->ds);
288 my $yyyymmdd = strftime('%Y%m%d', @ds);
289 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
290 my $dt = strftime('%Y%m%d%H%M%S', @ds);
291 add_val($doc, PublicInbox::Search::DT(), $dt);
292 my @vals = ($smsg->{ts}, $smsg->{ds});
294 my $tg = $self->term_generator;
296 $tg->set_document($doc);
297 $tg->index_text($subj, 1, 'S') if $subj;
298 $tg->increase_termpos;
300 index_users($tg, $smsg);
302 msg_iter($mime, sub {
303 my ($part, $depth, @idx) = @{$_[0]};
304 my $ct = $part->content_type || 'text/plain';
305 my $fn = $part->filename;
306 if (defined $fn && $fn ne '') {
307 $tg->index_text($fn, 1, 'XFN');
310 return if $ct =~ m!\btext/x?html\b!i;
312 my $s = eval { $part->body_str };
314 if ($ct =~ m!\btext/plain\b!i) {
315 # Try to assume UTF-8 because Alpine
316 # seems to do wacky things and set
318 $part->charset_set('UTF-8');
319 $s = eval { $part->body_str };
320 $s = $part->body if $@;
323 defined $s or return;
326 my $body = $part->body;
327 my @lines = split(/\n/, $body);
328 while (defined(my $l = shift @lines)) {
330 index_body($tg, \@orig, $doc) if @orig;
333 index_body($tg, \@quot, 0) if @quot;
337 index_body($tg, \@quot, 0) if @quot;
338 index_body($tg, \@orig, $doc) if @orig;
341 # populates smsg->references for smsg->to_doc_data
342 my $refs = parse_references($smsg, $mid0, $mids);
343 my $data = $smsg->to_doc_data($oid, $mid0);
344 foreach my $mid (@$mids) {
345 $tg->index_text($mid, 1, 'XM');
347 $doc->set_data($data);
348 if (my $altid = $self->{-altid}) {
349 foreach my $alt (@$altid) {
350 my $pfx = $alt->{xprefix};
351 foreach my $mid (@$mids) {
352 my $id = $alt->mid2alt($mid);
353 next unless defined $id;
354 $doc->add_boolean_term($pfx . $id);
359 $self->delete_article($num) if defined $num; # for reindexing
362 $data = compress($data);
363 push @vals, $num, $mids, $refs, $xpath, $data;
364 $self->{over}->add_over(\@vals);
365 $doc->add_boolean_term('Q' . $_) foreach @$mids;
366 $doc->add_boolean_term('XNUM' . $num) if defined $num;
367 $doc_id = $self->{xdb}->add_document($doc);
371 warn "failed to index message <".join('> <',@$mids).">: $@\n";
377 # returns begin and end PostingIterator
379 my ($self, $termval) = @_;
380 my $db = $self->{xdb};
382 ($db->postlist_begin($termval), $db->postlist_end($termval));
386 my ($self, $termval, $cb) = @_;
387 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
389 my ($head, $tail) = $self->find_doc_ids($termval);
390 return if $head == $tail;
392 for (; $head != $tail && @ids < $batch_size; $head->inc) {
393 push @ids, $head->get_docid;
400 my ($self, $mid) = @_;
401 my $db = $self->{xdb};
403 $mid = mid_clean($mid);
406 batch_do($self, 'Q' . $mid, sub {
408 $db->delete_document($_) for @$ids;
413 warn "failed to remove message <$mid>: $@\n";
415 warn "cannot remove non-existent <$mid>\n";
420 my ($self, $num) = @_;
422 batch_do($self, 'XNUM' . $num, sub {
424 $ndel += scalar @$ids;
425 $self->{xdb}->delete_document($_) for @$ids;
429 # MID is a hint in V2
431 my ($self, $oid, $mid) = @_;
432 my $db = $self->{xdb};
434 # XXX careful, we cannot use batch_do here since we conditionally
435 # delete documents based on other factors, so we cannot call
436 # find_doc_ids twice.
437 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
438 return if $head == $tail;
440 # there is only ONE element in @delete unless we
441 # have bugs in our v2writable deduplication check
444 for (; $head != $tail; $head->inc) {
445 my $docid = $head->get_docid;
446 my $doc = $db->get_document($docid);
447 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
449 if ($smsg->{blob} eq $oid) {
450 push(@delete, $docid);
451 push(@over_del, $smsg->num);
454 $db->delete_document($_) foreach @delete;
455 $self->{over}->remove_oid($oid, $mid);
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 parse_references ($$$) {
472 my ($smsg, $mid0, $mids) = @_;
473 my $mime = $smsg->{mime};
474 my $hdr = $mime->header_obj;
475 my $refs = references($hdr);
476 push(@$refs, @$mids) if scalar(@$mids) > 1;
477 return $refs if scalar(@$refs) == 0;
479 # prevent circular references here:
480 my %seen = ( $mid0 => 1 );
482 foreach my $ref (@$refs) {
483 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
484 warn "References: <$ref> too long, ignoring\n";
487 next if $seen{$ref}++;
490 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
494 sub index_git_blob_id {
495 my ($doc, $pfx, $objid) = @_;
497 my $len = length($objid);
498 for (my $len = length($objid); $len >= 7; ) {
499 $doc->add_term($pfx.$objid);
500 $objid = substr($objid, 0, --$len);
505 my ($self, $mime) = @_;
506 my $mid = eval { mid_clean(mid_mime($mime)) };
507 $self->remove_message($mid) if defined $mid;
511 my ($self, $mime) = @_;
512 my $mid = mid_clean(mid_mime($mime));
513 my $mm = $self->{mm};
514 my $num = $mm->mid_insert($mid);
515 return $num if defined $num;
517 # fallback to num_for since filters like RubyLang set the number
522 my ($self, $mime) = @_;
523 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
527 my ($self, $mime, $bytes, $blob) = @_;
528 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
529 add_message($self, $mime, $bytes, $num, $blob);
533 my ($self, $mime) = @_;
534 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
535 unindex_blob($self, $mime);
539 my ($self, $mime, $bytes, $blob) = @_;
540 my $num = index_mm($self, $mime);
541 add_message($self, $mime, $bytes, $num, $blob);
545 my ($self, $mime) = @_;
546 unindex_blob($self, $mime);
547 unindex_mm($self, $mime);
551 my ($git, $blob, $sizeref) = @_;
553 my $str = $git->cat_file($blob, $sizeref);
554 # fixup bugs from import:
555 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
556 PublicInbox::MIME->new($str);
562 my ($self, $opts) = @_;
563 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
566 sub batch_adjust ($$$$) {
567 my ($max, $bytes, $batch_cb, $latest) = @_;
571 $batch_cb->($latest, 1);
577 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
578 my $hex = '[a-f0-9]';
579 my $h40 = $hex .'{40}';
580 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
581 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
582 my $git = $self->{git};
585 my $max = BATCH_BYTES;
588 while (defined($line = <$log>)) {
589 if ($line =~ /$addmsg/o) {
591 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
592 batch_adjust(\$max, $bytes, $batch_cb, $latest);
593 $add_cb->($self, $mime, $bytes, $blob);
594 } elsif ($line =~ /$delmsg/o) {
596 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
597 batch_adjust(\$max, $bytes, $batch_cb, $latest);
598 $del_cb->($self, $mime);
599 } elsif ($line =~ /^commit ($h40)/o) {
603 $batch_cb->($latest, 0);
608 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
609 $self->{mm} ||= eval {
610 require PublicInbox::Msgmap;
611 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
616 my ($self, $range) = @_;
617 $self->{git}->popen(qw/log --reverse --no-notes --no-color
618 --raw -r --no-abbrev/, $range);
621 # indexes all unindexed messages
623 my ($self, $opts) = @_;
624 my $tip = $opts->{ref} || 'HEAD';
625 my $reindex = $opts->{reindex};
626 my ($mkey, $last_commit, $lx, $xlog);
627 $self->{git}->batch_prepare;
628 my $xdb = $self->begin_txn_lazy;
631 $mkey = 'last_commit';
632 $last_commit = $xdb->get_metadata('last_commit');
636 $mkey = undef if $last_commit ne '';
638 $self->{over}->rollback_lazy;
639 $self->{over}->disconnect;
641 $xdb->cancel_transaction;
642 $xdb = _xdb_release($self);
644 # ensure we leak no FDs to "git log"
645 my $range = $lx eq '' ? $tip : "$lx..$tip";
646 $xlog = _git_log($self, $range);
648 $xdb = $self->begin_txn_lazy;
649 } while ($xdb->get_metadata('last_commit') ne $last_commit);
651 my $mm = _msgmap_init($self);
652 my $dbh = $mm->{dbh} if $mm;
655 my ($commit, $more) = @_;
657 $mm->last_commit($commit) if $commit;
661 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
662 $self->commit_txn_lazy;
664 # let another process do some work... <
667 $xdb = $self->begin_txn_lazy;
669 $dbh->begin_work if $dbh;
675 my $lm = $mm->last_commit || '';
677 # Common case is the indexes are synced,
678 # we only need to run git-log once:
679 rlog($self, $xlog, *index_both, *unindex_both, $cb);
681 # Uncommon case, msgmap and xapian are out-of-sync
682 # do not care for performance (but git is fast :>)
683 # This happens if we have to reindex Xapian since
684 # msgmap is a frozen format and our Xapian format
686 my $r = $lm eq '' ? $tip : "$lm..$tip";
688 # first, ensure msgmap is up-to-date:
689 my $mkey_prev = $mkey;
690 $mkey = undef; # ignore xapian, for now
691 my $mlog = _git_log($self, $r);
693 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
694 $mm_only = $mlog = undef;
696 # now deal with Xapian
699 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
702 # user didn't install DBD::SQLite and DBI
703 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
708 # order matters for unlocking
709 $_[0]->{xdb} = undef;
710 $_[0]->{lockfh} = undef;
713 # remote_* subs are only used by SearchIdxPart
716 if (my $w = $self->{w}) {
717 print $w "commit\n" or die "failed to write commit: $!";
719 $self->commit_txn_lazy;
725 if (my $w = delete $self->{w}) {
726 my $pid = delete $self->{pid} or die "no process to wait on\n";
727 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
728 close $w or die "failed to close pipe for pid:$pid: $!\n";
729 waitpid($pid, 0) == $pid or die "remote process did not finish";
730 $? == 0 or die ref($self)." pid:$pid exited with: $?";
732 die "transaction in progress $self\n" if $self->{txn};
733 $self->_xdb_release if $self->{xdb};
738 my ($self, $oid, $mid) = @_;
739 if (my $w = $self->{w}) {
740 # triggers remove_by_oid in a partition
741 print $w "D $oid $mid\n" or die "failed to write remove $!";
743 $self->begin_txn_lazy;
744 $self->remove_by_oid($oid, $mid);
750 return if $self->{txn};
751 my $xdb = $self->{xdb} || $self->_xdb_acquire;
752 $self->{over}->begin_lazy;
753 $xdb->begin_transaction;
758 sub commit_txn_lazy {
760 delete $self->{txn} or return;
761 $self->{xdb}->commit_transaction;
762 $self->{over}->commit_lazy;
767 die "$$ $0 xdb not released\n" if $self->{xdb};
768 die "$$ $0 still in transaction\n" if $self->{txn};