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;
285 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
286 my $yyyymmdd = strftime('%Y%m%d', gmtime($smsg->ds));
287 add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
289 my $tg = $self->term_generator;
291 $tg->set_document($doc);
292 $tg->index_text($subj, 1, 'S') if $subj;
293 $tg->increase_termpos;
295 index_users($tg, $smsg);
297 msg_iter($mime, sub {
298 my ($part, $depth, @idx) = @{$_[0]};
299 my $ct = $part->content_type || 'text/plain';
300 my $fn = $part->filename;
301 if (defined $fn && $fn ne '') {
302 $tg->index_text($fn, 1, 'XFN');
305 return if $ct =~ m!\btext/x?html\b!i;
307 my $s = eval { $part->body_str };
309 if ($ct =~ m!\btext/plain\b!i) {
310 # Try to assume UTF-8 because Alpine
311 # seems to do wacky things and set
313 $part->charset_set('UTF-8');
314 $s = eval { $part->body_str };
315 $s = $part->body if $@;
318 defined $s or return;
321 my $body = $part->body;
322 my @lines = split(/\n/, $body);
323 while (defined(my $l = shift @lines)) {
325 index_body($tg, \@orig, $doc) if @orig;
328 index_body($tg, \@quot, 0) if @quot;
332 index_body($tg, \@quot, 0) if @quot;
333 index_body($tg, \@orig, $doc) if @orig;
336 # populates smsg->references for smsg->to_doc_data
337 my $refs = parse_references($smsg, $mid0, $mids);
338 my $data = $smsg->to_doc_data($oid, $mid0);
339 foreach my $mid (@$mids) {
340 $tg->index_text($mid, 1, 'XM');
342 $doc->set_data($data);
343 if (my $altid = $self->{-altid}) {
344 foreach my $alt (@$altid) {
345 my $pfx = $alt->{xprefix};
346 foreach my $mid (@$mids) {
347 my $id = $alt->mid2alt($mid);
348 next unless defined $id;
349 $doc->add_boolean_term($pfx . $id);
354 $self->delete_article($num) if defined $num; # for reindexing
357 $data = compress($data);
358 my @vals = ($smsg->ts, $num, $mids, $refs, $xpath, $data);
359 $self->{over}->add_over(\@vals);
360 $doc->add_boolean_term('Q' . $_) foreach @$mids;
361 $doc->add_boolean_term('XNUM' . $num) if defined $num;
362 $doc_id = $self->{xdb}->add_document($doc);
366 warn "failed to index message <".join('> <',@$mids).">: $@\n";
372 # returns begin and end PostingIterator
374 my ($self, $termval) = @_;
375 my $db = $self->{xdb};
377 ($db->postlist_begin($termval), $db->postlist_end($termval));
381 my ($self, $termval, $cb) = @_;
382 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
384 my ($head, $tail) = $self->find_doc_ids($termval);
385 return if $head == $tail;
387 for (; $head != $tail && @ids < $batch_size; $head->inc) {
388 push @ids, $head->get_docid;
395 my ($self, $mid) = @_;
396 my $db = $self->{xdb};
398 $mid = mid_clean($mid);
401 batch_do($self, 'Q' . $mid, sub {
403 $db->delete_document($_) for @$ids;
408 warn "failed to remove message <$mid>: $@\n";
410 warn "cannot remove non-existent <$mid>\n";
415 my ($self, $num) = @_;
417 batch_do($self, 'XNUM' . $num, sub {
419 $ndel += scalar @$ids;
420 $self->{xdb}->delete_document($_) for @$ids;
424 # MID is a hint in V2
426 my ($self, $oid, $mid) = @_;
427 my $db = $self->{xdb};
429 # XXX careful, we cannot use batch_do here since we conditionally
430 # delete documents based on other factors, so we cannot call
431 # find_doc_ids twice.
432 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
433 return if $head == $tail;
435 # there is only ONE element in @delete unless we
436 # have bugs in our v2writable deduplication check
439 for (; $head != $tail; $head->inc) {
440 my $docid = $head->get_docid;
441 my $doc = $db->get_document($docid);
442 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
444 if ($smsg->{blob} eq $oid) {
445 push(@delete, $docid);
446 push(@over_del, $smsg->num);
449 $db->delete_document($_) foreach @delete;
450 $self->{over}->remove_oid($oid, $mid);
454 sub term_generator { # write-only
457 my $tg = $self->{term_generator};
460 $tg = Search::Xapian::TermGenerator->new;
461 $tg->set_stemmer($self->stemmer);
463 $self->{term_generator} = $tg;
466 sub parse_references ($$$) {
467 my ($smsg, $mid0, $mids) = @_;
468 my $mime = $smsg->{mime};
469 my $hdr = $mime->header_obj;
470 my $refs = references($hdr);
471 push(@$refs, @$mids) if scalar(@$mids) > 1;
472 return $refs if scalar(@$refs) == 0;
474 # prevent circular references here:
475 my %seen = ( $mid0 => 1 );
477 foreach my $ref (@$refs) {
478 if (length($ref) > PublicInbox::MID::MAX_MID_SIZE) {
479 warn "References: <$ref> too long, ignoring\n";
482 next if $seen{$ref}++;
485 $smsg->{references} = '<'.join('> <', @keep).'>' if @keep;
489 sub index_git_blob_id {
490 my ($doc, $pfx, $objid) = @_;
492 my $len = length($objid);
493 for (my $len = length($objid); $len >= 7; ) {
494 $doc->add_term($pfx.$objid);
495 $objid = substr($objid, 0, --$len);
500 my ($self, $mime) = @_;
501 my $mid = eval { mid_clean(mid_mime($mime)) };
502 $self->remove_message($mid) if defined $mid;
506 my ($self, $mime) = @_;
507 my $mid = mid_clean(mid_mime($mime));
508 my $mm = $self->{mm};
509 my $num = $mm->mid_insert($mid);
510 return $num if defined $num;
512 # fallback to num_for since filters like RubyLang set the number
517 my ($self, $mime) = @_;
518 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
522 my ($self, $mime, $bytes, $blob) = @_;
523 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
524 add_message($self, $mime, $bytes, $num, $blob);
528 my ($self, $mime) = @_;
529 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
530 unindex_blob($self, $mime);
534 my ($self, $mime, $bytes, $blob) = @_;
535 my $num = index_mm($self, $mime);
536 add_message($self, $mime, $bytes, $num, $blob);
540 my ($self, $mime) = @_;
541 unindex_blob($self, $mime);
542 unindex_mm($self, $mime);
546 my ($git, $blob, $sizeref) = @_;
548 my $str = $git->cat_file($blob, $sizeref);
549 # fixup bugs from import:
550 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
551 PublicInbox::MIME->new($str);
557 my ($self, $opts) = @_;
558 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
561 sub batch_adjust ($$$$) {
562 my ($max, $bytes, $batch_cb, $latest) = @_;
566 $batch_cb->($latest, 1);
572 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
573 my $hex = '[a-f0-9]';
574 my $h40 = $hex .'{40}';
575 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
576 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
577 my $git = $self->{git};
580 my $max = BATCH_BYTES;
583 while (defined($line = <$log>)) {
584 if ($line =~ /$addmsg/o) {
586 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
587 batch_adjust(\$max, $bytes, $batch_cb, $latest);
588 $add_cb->($self, $mime, $bytes, $blob);
589 } elsif ($line =~ /$delmsg/o) {
591 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
592 batch_adjust(\$max, $bytes, $batch_cb, $latest);
593 $del_cb->($self, $mime);
594 } elsif ($line =~ /^commit ($h40)/o) {
598 $batch_cb->($latest, 0);
603 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
604 $self->{mm} ||= eval {
605 require PublicInbox::Msgmap;
606 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
611 my ($self, $range) = @_;
612 $self->{git}->popen(qw/log --reverse --no-notes --no-color
613 --raw -r --no-abbrev/, $range);
616 # indexes all unindexed messages
618 my ($self, $opts) = @_;
619 my $tip = $opts->{ref} || 'HEAD';
620 my $reindex = $opts->{reindex};
621 my ($mkey, $last_commit, $lx, $xlog);
622 $self->{git}->batch_prepare;
623 my $xdb = $self->begin_txn_lazy;
626 $mkey = 'last_commit';
627 $last_commit = $xdb->get_metadata('last_commit');
631 $mkey = undef if $last_commit ne '';
633 $self->{over}->rollback_lazy;
634 $self->{over}->disconnect;
636 $xdb->cancel_transaction;
637 $xdb = _xdb_release($self);
639 # ensure we leak no FDs to "git log"
640 my $range = $lx eq '' ? $tip : "$lx..$tip";
641 $xlog = _git_log($self, $range);
643 $xdb = $self->begin_txn_lazy;
644 } while ($xdb->get_metadata('last_commit') ne $last_commit);
646 my $mm = _msgmap_init($self);
647 my $dbh = $mm->{dbh} if $mm;
650 my ($commit, $more) = @_;
652 $mm->last_commit($commit) if $commit;
656 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
657 $self->commit_txn_lazy;
659 # let another process do some work... <
662 $xdb = $self->begin_txn_lazy;
664 $dbh->begin_work if $dbh;
670 my $lm = $mm->last_commit || '';
672 # Common case is the indexes are synced,
673 # we only need to run git-log once:
674 rlog($self, $xlog, *index_both, *unindex_both, $cb);
676 # Uncommon case, msgmap and xapian are out-of-sync
677 # do not care for performance (but git is fast :>)
678 # This happens if we have to reindex Xapian since
679 # msgmap is a frozen format and our Xapian format
681 my $r = $lm eq '' ? $tip : "$lm..$tip";
683 # first, ensure msgmap is up-to-date:
684 my $mkey_prev = $mkey;
685 $mkey = undef; # ignore xapian, for now
686 my $mlog = _git_log($self, $r);
688 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
689 $mm_only = $mlog = undef;
691 # now deal with Xapian
694 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
697 # user didn't install DBD::SQLite and DBI
698 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
703 # order matters for unlocking
704 $_[0]->{xdb} = undef;
705 $_[0]->{lockfh} = undef;
708 # remote_* subs are only used by SearchIdxPart
711 if (my $w = $self->{w}) {
712 print $w "commit\n" or die "failed to write commit: $!";
714 $self->commit_txn_lazy;
720 if (my $w = delete $self->{w}) {
721 my $pid = delete $self->{pid} or die "no process to wait on\n";
722 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
723 close $w or die "failed to close pipe for pid:$pid: $!\n";
724 waitpid($pid, 0) == $pid or die "remote process did not finish";
725 $? == 0 or die ref($self)." pid:$pid exited with: $?";
727 die "transaction in progress $self\n" if $self->{txn};
728 $self->_xdb_release if $self->{xdb};
733 my ($self, $oid, $mid) = @_;
734 if (my $w = $self->{w}) {
735 # triggers remove_by_oid in a partition
736 print $w "D $oid $mid\n" or die "failed to write remove $!";
738 $self->begin_txn_lazy;
739 $self->remove_by_oid($oid, $mid);
745 return if $self->{txn};
746 my $xdb = $self->{xdb} || $self->_xdb_acquire;
747 $self->{over}->begin_lazy;
748 $xdb->begin_transaction;
753 sub commit_txn_lazy {
755 delete $self->{txn} or return;
756 $self->{xdb}->commit_transaction;
757 $self->{over}->commit_lazy;
762 die "$$ $0 xdb not released\n" if $self->{xdb};
763 die "$$ $0 still in transaction\n" if $self->{txn};