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_ro} = $self->{over} =
80 PublicInbox::OverIdx->new("$dir/over.sqlite3");
81 } elsif ($version == 2) {
82 defined $part or die "partition is required for v2\n";
83 # partition is a number
84 $self->{partition} = $part;
85 $self->{lock_path} = undef;
87 die "unsupported inbox version=$version\n";
89 $self->{creat} = ($creat || 0) == 1;
95 my $xdb = delete $self->{xdb} or croak 'not acquired';
97 $self->lock_release if $self->{creat};
103 croak 'already acquired' if $self->{xdb};
104 my $dir = $self->xdir;
105 my $flag = Search::Xapian::DB_OPEN;
106 if ($self->{creat}) {
109 File::Path::mkpath($dir);
110 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
112 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
116 my ($doc, $col, $num) = @_;
117 $num = Search::Xapian::sortable_serialise($num);
118 $doc->add_value($col, $num);
121 sub index_users ($$) {
122 my ($tg, $smsg) = @_;
124 my $from = $smsg->from;
128 $tg->index_text($from, 1, 'A'); # A - author
129 $tg->increase_termpos;
130 $tg->index_text($to, 1, 'XTO') if $to ne '';
131 $tg->increase_termpos;
132 $tg->index_text($cc, 1, 'XCC') if $cc ne '';
133 $tg->increase_termpos;
136 sub index_diff_inc ($$$$) {
137 my ($tg, $text, $pfx, $xnq) = @_;
139 $tg->index_text(join("\n", @$xnq), 1, 'XNQ');
140 $tg->increase_termpos;
143 $tg->index_text($text, 1, $pfx);
144 $tg->increase_termpos;
147 sub index_old_diff_fn {
148 my ($tg, $seen, $fa, $fb, $xnq) = @_;
150 # no renames or space support for traditional diffs,
151 # find the number of leading common paths to strip:
152 my @fa = split('/', $fa);
153 my @fb = split('/', $fb);
154 while (scalar(@fa) && scalar(@fb)) {
155 $fa = join('/', @fa);
156 $fb = join('/', @fb);
158 unless ($seen->{$fa}++) {
159 index_diff_inc($tg, $fa, 'XDFN', $xnq);
169 sub index_diff ($$$) {
170 my ($tg, $lines, $doc) = @_;
176 if ($in_diff && s/^ //) { # diff context
177 index_diff_inc($tg, $_, 'XDFCTX', $xnq);
178 } elsif (/^-- $/) { # email signature begins
180 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
181 my ($fa, $fb) = ($1, $2);
182 my $fn = (split('/', git_unquote($fa), 2))[1];
183 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
184 $fn = (split('/', git_unquote($fb), 2))[1];
185 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
188 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
189 my ($opt, $fa, $fb) = ($1, $2, $3);
191 # only support unified:
192 next unless $opt =~ /[uU]/;
193 $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb,
195 } elsif (m!^--- ("?a/.+)!) {
196 my $fn = (split('/', git_unquote($1), 2))[1];
197 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
199 } elsif (m!^\+\+\+ ("?b/.+)!) {
200 my $fn = (split('/', git_unquote($1), 2))[1];
201 $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
203 } elsif (/^--- (\S+)/) {
206 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
207 $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1,
209 } elsif ($in_diff && s/^\+//) { # diff added
210 index_diff_inc($tg, $_, 'XDFB', $xnq);
211 } elsif ($in_diff && s/^-//) { # diff removed
212 index_diff_inc($tg, $_, 'XDFA', $xnq);
213 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
214 my ($ba, $bb) = ($1, $2);
215 index_git_blob_id($doc, 'XDFPRE', $ba);
216 index_git_blob_id($doc, 'XDFPOST', $bb);
218 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
219 # traditional diff w/o -p
220 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
221 # hunk header context
222 index_diff_inc($tg, $1, 'XDFHH', $xnq);
223 # ignore the following lines:
224 } elsif (/^(?:dis)similarity index/ ||
225 /^(?:old|new) mode/ ||
226 /^(?:deleted|new) file mode/ ||
227 /^(?:copy|rename) (?:from|to) / ||
228 /^(?:dis)?similarity index / ||
229 /^\\ No newline at end of file/ ||
230 /^Binary files .* differ/) {
236 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
241 $tg->index_text(join("\n", @xnq), 1, 'XNQ');
242 $tg->increase_termpos;
245 sub index_body ($$$) {
246 my ($tg, $lines, $doc) = @_;
247 my $txt = join("\n", @$lines);
249 # does it look like a diff?
250 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
252 index_diff($tg, $lines, $doc);
254 $tg->index_text($txt, 1, 'XNQ');
257 $tg->index_text($txt, 0, 'XQUOT');
259 $tg->increase_termpos;
264 # mime = Email::MIME object
265 my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
267 my $mids = mids($mime->header_obj);
268 $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
269 unless (defined $num) { # v1
270 my $mm = $self->_msgmap_init;
271 $num = $mm->mid_insert($mid0) || $mm->num_for($mid0);
274 my $smsg = PublicInbox::SearchMsg->new($mime);
275 my $doc = $smsg->{doc};
276 my $subj = $smsg->subject;
279 $xpath = $self->subject_path($subj);
280 $xpath = id_compress($xpath);
283 $smsg->{lines} = $mime->body_raw =~ tr!\n!\n!;
284 defined $bytes or $bytes = length($mime->as_string);
285 $smsg->{bytes} = $bytes;
287 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
288 my @ds = gmtime($smsg->ds);
289 my $yyyymmdd = strftime('%Y%m%d', @ds);
290 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
291 my $dt = strftime('%Y%m%d%H%M%S', @ds);
292 add_val($doc, PublicInbox::Search::DT(), $dt);
293 my @vals = ($smsg->{ts}, $smsg->{ds});
295 my $tg = $self->term_generator;
297 $tg->set_document($doc);
298 $tg->index_text($subj, 1, 'S') if $subj;
299 $tg->increase_termpos;
301 index_users($tg, $smsg);
303 msg_iter($mime, sub {
304 my ($part, $depth, @idx) = @{$_[0]};
305 my $ct = $part->content_type || 'text/plain';
306 my $fn = $part->filename;
307 if (defined $fn && $fn ne '') {
308 $tg->index_text($fn, 1, 'XFN');
311 return if $ct =~ m!\btext/x?html\b!i;
313 my $s = eval { $part->body_str };
315 if ($ct =~ m!\btext/plain\b!i) {
316 # Try to assume UTF-8 because Alpine
317 # seems to do wacky things and set
319 $part->charset_set('UTF-8');
320 $s = eval { $part->body_str };
321 $s = $part->body if $@;
324 defined $s or return;
327 my $body = $part->body;
328 my @lines = split(/\n/, $body);
329 while (defined(my $l = shift @lines)) {
331 index_body($tg, \@orig, $doc) if @orig;
334 index_body($tg, \@quot, 0) if @quot;
338 index_body($tg, \@quot, 0) if @quot;
339 index_body($tg, \@orig, $doc) if @orig;
342 # populates smsg->references for smsg->to_doc_data
343 my $refs = parse_references($smsg, $mid0, $mids);
344 my $data = $smsg->to_doc_data($oid, $mid0);
345 foreach my $mid (@$mids) {
346 $tg->index_text($mid, 1, 'XM');
348 $doc->set_data($data);
349 if (my $altid = $self->{-altid}) {
350 foreach my $alt (@$altid) {
351 my $pfx = $alt->{xprefix};
352 foreach my $mid (@$mids) {
353 my $id = $alt->mid2alt($mid);
354 next unless defined $id;
355 $doc->add_boolean_term($pfx . $id);
360 $self->delete_article($num) if defined $num; # for reindexing
363 $data = compress($data);
364 push @vals, $num, $mids, $refs, $xpath, $data;
365 $self->{over}->add_over(\@vals);
366 $doc->add_boolean_term('Q' . $_) foreach @$mids;
367 $doc->add_boolean_term('XNUM' . $num) if defined $num;
368 $doc_id = $self->{xdb}->add_document($doc);
372 warn "failed to index message <".join('> <',@$mids).">: $@\n";
378 # returns begin and end PostingIterator
380 my ($self, $termval) = @_;
381 my $db = $self->{xdb};
383 ($db->postlist_begin($termval), $db->postlist_end($termval));
387 my ($self, $termval, $cb) = @_;
388 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
390 my ($head, $tail) = $self->find_doc_ids($termval);
391 return if $head == $tail;
393 for (; $head != $tail && @ids < $batch_size; $head->inc) {
394 push @ids, $head->get_docid;
401 my ($self, $mid) = @_;
402 my $db = $self->{xdb};
404 $mid = mid_clean($mid);
407 batch_do($self, 'Q' . $mid, sub {
409 $db->delete_document($_) for @$ids;
414 warn "failed to remove message <$mid>: $@\n";
416 warn "cannot remove non-existent <$mid>\n";
421 my ($self, $num) = @_;
423 batch_do($self, 'XNUM' . $num, sub {
425 $ndel += scalar @$ids;
426 $self->{xdb}->delete_document($_) for @$ids;
430 # MID is a hint in V2
432 my ($self, $oid, $mid) = @_;
433 my $db = $self->{xdb};
435 # XXX careful, we cannot use batch_do here since we conditionally
436 # delete documents based on other factors, so we cannot call
437 # find_doc_ids twice.
438 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
439 return if $head == $tail;
441 # there is only ONE element in @delete unless we
442 # 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($doc, $mid);
450 if ($smsg->{blob} eq $oid) {
451 push(@delete, $docid);
452 push(@over_del, $smsg->num);
455 $db->delete_document($_) foreach @delete;
456 $self->{over}->remove_oid($oid, $mid);
460 sub term_generator { # write-only
463 my $tg = $self->{term_generator};
466 $tg = Search::Xapian::TermGenerator->new;
467 $tg->set_stemmer($self->stemmer);
469 $self->{term_generator} = $tg;
472 sub parse_references ($$$) {
473 my ($smsg, $mid0, $mids) = @_;
474 my $mime = $smsg->{mime};
475 my $hdr = $mime->header_obj;
476 my $refs = references($hdr);
477 push(@$refs, @$mids) if scalar(@$mids) > 1;
478 return $refs if scalar(@$refs) == 0;
480 # prevent circular references here:
481 my %seen = ( $mid0 => 1 );
483 foreach my $ref (@$refs) {
484 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
485 warn "References: <$ref> too long, ignoring\n";
488 next if $seen{$ref}++;
491 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
495 sub index_git_blob_id {
496 my ($doc, $pfx, $objid) = @_;
498 my $len = length($objid);
499 for (my $len = length($objid); $len >= 7; ) {
500 $doc->add_term($pfx.$objid);
501 $objid = substr($objid, 0, --$len);
506 my ($self, $mime) = @_;
507 my $mid = eval { mid_clean(mid_mime($mime)) };
508 $self->remove_message($mid) if defined $mid;
512 my ($self, $mime) = @_;
513 my $mid = mid_clean(mid_mime($mime));
514 my $mm = $self->{mm};
515 my $num = $mm->mid_insert($mid);
516 return $num if defined $num;
518 # fallback to num_for since filters like RubyLang set the number
523 my ($self, $mime) = @_;
524 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
528 my ($self, $mime, $bytes, $blob) = @_;
529 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
530 add_message($self, $mime, $bytes, $num, $blob);
534 my ($self, $mime) = @_;
535 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
536 unindex_blob($self, $mime);
540 my ($self, $mime, $bytes, $blob) = @_;
541 my $num = index_mm($self, $mime);
542 add_message($self, $mime, $bytes, $num, $blob);
546 my ($self, $mime) = @_;
547 unindex_blob($self, $mime);
548 unindex_mm($self, $mime);
552 my ($git, $blob, $sizeref) = @_;
554 my $str = $git->cat_file($blob, $sizeref);
555 # fixup bugs from import:
556 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
557 PublicInbox::MIME->new($str);
563 my ($self, $opts) = @_;
564 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
567 sub batch_adjust ($$$$) {
568 my ($max, $bytes, $batch_cb, $latest) = @_;
572 $batch_cb->($latest, 1);
578 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
579 my $hex = '[a-f0-9]';
580 my $h40 = $hex .'{40}';
581 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
582 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
583 my $git = $self->{git};
586 my $max = BATCH_BYTES;
589 while (defined($line = <$log>)) {
590 if ($line =~ /$addmsg/o) {
592 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
593 batch_adjust(\$max, $bytes, $batch_cb, $latest);
594 $add_cb->($self, $mime, $bytes, $blob);
595 } elsif ($line =~ /$delmsg/o) {
597 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
598 batch_adjust(\$max, $bytes, $batch_cb, $latest);
599 $del_cb->($self, $mime);
600 } elsif ($line =~ /^commit ($h40)/o) {
604 $batch_cb->($latest, 0);
609 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
610 $self->{mm} ||= eval {
611 require PublicInbox::Msgmap;
612 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
617 my ($self, $range) = @_;
618 $self->{git}->popen(qw/log --reverse --no-notes --no-color
619 --raw -r --no-abbrev/, $range);
622 # indexes all unindexed messages
624 my ($self, $opts) = @_;
625 my $tip = $opts->{ref} || 'HEAD';
626 my $reindex = $opts->{reindex};
627 my ($mkey, $last_commit, $lx, $xlog);
628 $self->{git}->batch_prepare;
629 my $xdb = $self->begin_txn_lazy;
632 $mkey = 'last_commit';
633 $last_commit = $xdb->get_metadata('last_commit');
637 $mkey = undef if $last_commit ne '';
639 $self->{over}->rollback_lazy;
640 $self->{over}->disconnect;
642 $xdb->cancel_transaction;
643 $xdb = _xdb_release($self);
645 # ensure we leak no FDs to "git log"
646 my $range = $lx eq '' ? $tip : "$lx..$tip";
647 $xlog = _git_log($self, $range);
649 $xdb = $self->begin_txn_lazy;
650 } while ($xdb->get_metadata('last_commit') ne $last_commit);
652 my $mm = _msgmap_init($self);
653 my $dbh = $mm->{dbh} if $mm;
656 my ($commit, $more) = @_;
658 $mm->last_commit($commit) if $commit;
662 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
663 $self->commit_txn_lazy;
665 # let another process do some work... <
668 $xdb = $self->begin_txn_lazy;
670 $dbh->begin_work if $dbh;
676 my $lm = $mm->last_commit || '';
678 # Common case is the indexes are synced,
679 # we only need to run git-log once:
680 rlog($self, $xlog, *index_both, *unindex_both, $cb);
682 # Uncommon case, msgmap and xapian are out-of-sync
683 # do not care for performance (but git is fast :>)
684 # This happens if we have to reindex Xapian since
685 # msgmap is a frozen format and our Xapian format
687 my $r = $lm eq '' ? $tip : "$lm..$tip";
689 # first, ensure msgmap is up-to-date:
690 my $mkey_prev = $mkey;
691 $mkey = undef; # ignore xapian, for now
692 my $mlog = _git_log($self, $r);
694 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
695 $mm_only = $mlog = undef;
697 # now deal with Xapian
700 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
703 # user didn't install DBD::SQLite and DBI
704 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
709 # order matters for unlocking
710 $_[0]->{xdb} = undef;
711 $_[0]->{lockfh} = undef;
714 # remote_* subs are only used by SearchIdxPart
717 if (my $w = $self->{w}) {
718 print $w "commit\n" or die "failed to write commit: $!";
720 $self->commit_txn_lazy;
726 if (my $w = delete $self->{w}) {
727 my $pid = delete $self->{pid} or die "no process to wait on\n";
728 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
729 close $w or die "failed to close pipe for pid:$pid: $!\n";
730 waitpid($pid, 0) == $pid or die "remote process did not finish";
731 $? == 0 or die ref($self)." pid:$pid exited with: $?";
733 die "transaction in progress $self\n" if $self->{txn};
734 $self->_xdb_release if $self->{xdb};
739 my ($self, $oid, $mid) = @_;
740 if (my $w = $self->{w}) {
741 # triggers remove_by_oid in a partition
742 print $w "D $oid $mid\n" or die "failed to write remove $!";
744 $self->begin_txn_lazy;
745 $self->remove_by_oid($oid, $mid);
751 return if $self->{txn};
752 my $xdb = $self->{xdb} || $self->_xdb_acquire;
753 $self->{over}->begin_lazy;
754 $xdb->begin_transaction;
759 sub commit_txn_lazy {
761 delete $self->{txn} or return;
762 $self->{xdb}->commit_transaction;
763 $self->{over}->commit_lazy;
768 die "$$ $0 xdb not released\n" if $self->{xdb};
769 die "$$ $0 still in transaction\n" if $self->{txn};