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 require PublicInbox::Git;
22 use Compress::Zlib qw(compress);
25 BATCH_BYTES => 1_000_000,
26 DEBUG => !!$ENV{DEBUG},
41 return $s unless ($s =~ /\A"(.*)"\z/);
43 $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
44 $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
49 my ($class, $ibx, $creat, $part) = @_;
50 my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
51 my $git_dir = $mainrepo;
55 $mainrepo = $ibx->{mainrepo};
56 $altid = $ibx->{altid};
57 $version = $ibx->{version} || 1;
59 require PublicInbox::AltId;
61 PublicInbox::AltId->new($ibx, $_);
65 $ibx = { mainrepo => $git_dir, version => 1 };
67 $ibx = PublicInbox::InboxWritable->new($ibx);
68 require Search::Xapian::WritableDatabase;
70 mainrepo => $mainrepo,
78 $self->{lock_path} = "$mainrepo/ssoma.lock";
79 my $dir = $self->xdir;
80 $self->{over} = 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
271 $num = index_mm($self, $mime);
274 my $smsg = PublicInbox::SearchMsg->new($mime);
275 my $doc = $smsg->{doc};
276 my $subj = $smsg->subject;
277 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
278 my @ds = gmtime($smsg->ds);
279 my $yyyymmdd = strftime('%Y%m%d', @ds);
280 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
281 my $dt = strftime('%Y%m%d%H%M%S', @ds);
282 add_val($doc, PublicInbox::Search::DT(), $dt);
284 my $tg = $self->term_generator;
286 $tg->set_document($doc);
287 $tg->index_text($subj, 1, 'S') if $subj;
288 $tg->increase_termpos;
290 index_users($tg, $smsg);
292 msg_iter($mime, sub {
293 my ($part, $depth, @idx) = @{$_[0]};
294 my $ct = $part->content_type || 'text/plain';
295 my $fn = $part->filename;
296 if (defined $fn && $fn ne '') {
297 $tg->index_text($fn, 1, 'XFN');
298 $tg->increase_termpos;
301 return if $ct =~ m!\btext/x?html\b!i;
303 my $s = eval { $part->body_str };
305 if ($ct =~ m!\btext/plain\b!i) {
306 # Try to assume UTF-8 because Alpine
307 # seems to do wacky things and set
309 $part->charset_set('UTF-8');
310 $s = eval { $part->body_str };
311 $s = $part->body if $@;
314 defined $s or return;
317 my $body = $part->body;
318 my @lines = split(/\n/, $body);
319 while (defined(my $l = shift @lines)) {
321 index_body($tg, \@orig, $doc) if @orig;
324 index_body($tg, \@quot, 0) if @quot;
328 index_body($tg, \@quot, 0) if @quot;
329 index_body($tg, \@orig, $doc) if @orig;
332 foreach my $mid (@$mids) {
333 $tg->index_text($mid, 1, 'XM');
334 $tg->increase_termpos;
336 $smsg->{to} = $smsg->{cc} = '';
337 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
338 my $data = $smsg->to_doc_data($oid, $mid0);
339 $doc->set_data($data);
340 if (my $altid = $self->{-altid}) {
341 foreach my $alt (@$altid) {
342 my $pfx = $alt->{xprefix};
343 foreach my $mid (@$mids) {
344 my $id = $alt->mid2alt($mid);
345 next unless defined $id;
346 $doc->add_boolean_term($pfx . $id);
351 if (my $over = $self->{over}) {
352 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
354 $doc->add_boolean_term('Q' . $_) foreach @$mids;
355 $self->{xdb}->replace_document($doc_id = $num, $doc);
359 warn "failed to index message <".join('> <',@$mids).">: $@\n";
365 # returns begin and end PostingIterator
367 my ($self, $termval) = @_;
368 my $db = $self->{xdb};
370 ($db->postlist_begin($termval), $db->postlist_end($termval));
374 my ($self, $termval, $cb) = @_;
375 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
377 my ($head, $tail) = $self->find_doc_ids($termval);
378 return if $head == $tail;
380 for (; $head != $tail && @ids < $batch_size; $head->inc) {
381 push @ids, $head->get_docid;
388 my ($self, $mid) = @_;
389 my $db = $self->{xdb};
391 $mid = mid_clean($mid);
392 my $over = $self->{over};
395 batch_do($self, 'Q' . $mid, sub {
397 $db->delete_document($_) for @$ids;
398 $over->delete_articles($ids) if $over;
403 warn "failed to remove message <$mid>: $@\n";
405 warn "cannot remove non-existent <$mid>\n";
409 # MID is a hint in V2
411 my ($self, $oid, $mid) = @_;
412 my $db = $self->{xdb};
414 $self->{over}->remove_oid($oid, $mid) if $self->{over};
416 # XXX careful, we cannot use batch_do here since we conditionally
417 # delete documents based on other factors, so we cannot call
418 # find_doc_ids twice.
419 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
420 return if $head == $tail;
422 # there is only ONE element in @delete unless we
423 # have bugs in our v2writable deduplication check
425 for (; $head != $tail; $head->inc) {
426 my $docid = $head->get_docid;
427 my $doc = $db->get_document($docid);
428 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
430 if ($smsg->{blob} eq $oid) {
431 push(@delete, $docid);
434 $db->delete_document($_) foreach @delete;
438 sub term_generator { # write-only
441 my $tg = $self->{term_generator};
444 $tg = Search::Xapian::TermGenerator->new;
445 $tg->set_stemmer($self->stemmer);
447 $self->{term_generator} = $tg;
450 sub index_git_blob_id {
451 my ($doc, $pfx, $objid) = @_;
453 my $len = length($objid);
454 for (my $len = length($objid); $len >= 7; ) {
455 $doc->add_term($pfx.$objid);
456 $objid = substr($objid, 0, --$len);
461 my ($self, $mime) = @_;
462 my $mid = eval { mid_clean(mid_mime($mime)) };
463 $self->remove_message($mid) if defined $mid;
467 my ($self, $mime) = @_;
468 my $mid = mid_clean(mid_mime($mime));
469 my $mm = $self->{mm};
472 if (defined $self->{regen_down}) {
473 $num = $mm->num_for($mid) and return $num;
475 while (($num = $self->{regen_down}--) > 0) {
476 if ($mm->mid_set($num, $mid) != 0) {
480 } elsif (defined $self->{regen_up}) {
481 $num = $mm->num_for($mid) and return $num;
483 # this is to fixup old bugs due to add-remove-add
484 while (($num = ++$self->{regen_up})) {
485 if ($mm->mid_set($num, $mid) != 0) {
491 $num = $mm->mid_insert($mid) and return $num;
493 # fallback to num_for since filters like RubyLang set the number
498 my ($self, $mime) = @_;
499 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
503 my ($self, $mime, $bytes, $blob) = @_;
504 my $num = index_mm($self, $mime);
505 add_message($self, $mime, $bytes, $num, $blob);
509 my ($self, $mime) = @_;
510 unindex_blob($self, $mime);
511 unindex_mm($self, $mime);
515 my ($git, $blob, $sizeref) = @_;
517 my $str = $git->cat_file($blob, $sizeref);
518 # fixup bugs from import:
519 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
520 PublicInbox::MIME->new($str);
526 my ($self, $opts) = @_;
527 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
530 sub batch_adjust ($$$$) {
531 my ($max, $bytes, $batch_cb, $latest) = @_;
535 $batch_cb->($latest);
541 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
542 my $hex = '[a-f0-9]';
543 my $h40 = $hex .'{40}';
544 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
545 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
546 my $git = $self->{git};
549 my $max = BATCH_BYTES;
554 my $mid = '20170114215743.5igbjup6qpsh3jfg@genre.crustytoothpaste.net';
555 while (defined($line = <$log>)) {
556 if ($line =~ /$addmsg/o) {
558 delete $D{$blob} and next;
559 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
560 my $mids = mids($mime->header_obj);
562 warn "ADD $mid\n" if ($_ eq $mid);
564 batch_adjust(\$max, $bytes, $batch_cb, $latest);
565 $add_cb->($self, $mime, $bytes, $blob);
566 } elsif ($line =~ /$delmsg/o) {
569 } elsif ($line =~ /^commit ($h40)/o) {
575 foreach my $blob (keys %D) {
576 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
577 my $mids = mids($mime->header_obj);
579 warn "DEL $mid\n" if ($_ eq $mid);
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) {
601 # can't use 'rev-list --count' if we use --diff-filter
602 my $fh = $git->popen(qw(log --pretty=tformat:%h
603 --no-notes --no-color --no-renames
604 --diff-filter=AM), $range);
605 ++$regen_max while <$fh>;
606 my (undef, $max) = $self->{mm}->minmax;
608 if ($max && $max == $regen_max) {
609 # fix up old bugs in full indexes which caused messages to
610 # not appear in Msgmap
611 $self->{regen_up} = $max;
613 # normal regen is for for fresh data
614 $self->{regen_down} = $regen_max;
618 $git->popen(qw/log --no-notes --no-color --no-renames
619 --raw -r --no-abbrev/, $range);
622 sub is_ancestor ($$$) {
623 my ($git, $cur, $tip) = @_;
624 return 0 unless $git->check($cur);
625 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
626 qw(merge-base --is-ancestor), $cur, $tip ];
627 my $pid = spawn($cmd);
628 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
629 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
633 sub need_update ($$$) {
634 my ($self, $cur, $new) = @_;
635 my $git = $self->{git};
636 return 1 if $cur && !is_ancestor($git, $cur, $new);
637 my $range = $cur eq '' ? $new : "$cur..$new";
638 chomp(my $n = $git->qx(qw(rev-list --count), $range));
639 ($n eq '' || $n > 0);
642 # indexes all unindexed messages (v1 only)
644 my ($self, $opts) = @_;
645 my $tip = $opts->{ref} || 'HEAD';
646 my $reindex = $opts->{reindex};
647 my ($mkey, $last_commit, $lx, $xlog);
648 my $git = $self->{git};
651 my $xdb = $self->begin_txn_lazy;
652 my $mm = _msgmap_init($self);
655 $mkey = 'last_commit';
656 $last_commit = $xdb->get_metadata('last_commit');
660 $mkey = undef if $last_commit ne '';
663 # use last_commit from msgmap if it is older or unset
664 my $lm = $mm->last_commit || '';
665 if (!$lm || ($lm && $lx && is_ancestor($git, $lm, $lx))) {
669 $self->{over}->rollback_lazy;
670 $self->{over}->disconnect;
672 $xdb->cancel_transaction;
673 $xdb = _xdb_release($self);
675 # ensure we leak no FDs to "git log" with Xapian <= 1.2
676 my $range = $lx eq '' ? $tip : "$lx..$tip";
677 $xlog = _git_log($self, $range);
679 $xdb = $self->begin_txn_lazy;
680 } while ($xdb->get_metadata('last_commit') ne $last_commit);
682 my $dbh = $mm->{dbh} if $mm;
684 my ($commit, $newest) = @_;
687 my $cur = $mm->last_commit || '';
688 if (need_update($self, $cur, $newest)) {
689 $mm->last_commit($newest);
694 if ($mkey && $newest) {
695 my $cur = $xdb->get_metadata($mkey);
696 if (need_update($self, $cur, $newest)) {
697 $xdb->set_metadata($mkey, $newest);
700 $self->commit_txn_lazy;
701 # let another process do some work... <
703 $xdb = $self->begin_txn_lazy;
704 $dbh->begin_work if $dbh;
709 read_log($self, $xlog, *index_both, *unindex_both, $cb);
713 # order matters for unlocking
714 $_[0]->{xdb} = undef;
715 $_[0]->{lockfh} = undef;
718 # remote_* subs are only used by SearchIdxPart
721 if (my $w = $self->{w}) {
722 print $w "commit\n" or die "failed to write commit: $!";
724 $self->commit_txn_lazy;
730 if (my $w = delete $self->{w}) {
731 my $pid = delete $self->{pid} or die "no process to wait on\n";
732 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
733 close $w or die "failed to close pipe for pid:$pid: $!\n";
734 waitpid($pid, 0) == $pid or die "remote process did not finish";
735 $? == 0 or die ref($self)." pid:$pid exited with: $?";
737 die "transaction in progress $self\n" if $self->{txn};
738 $self->_xdb_release if $self->{xdb};
743 my ($self, $oid, $mid) = @_;
744 if (my $w = $self->{w}) {
745 # triggers remove_by_oid in a partition
746 print $w "D $oid $mid\n" or die "failed to write remove $!";
748 $self->begin_txn_lazy;
749 $self->remove_by_oid($oid, $mid);
755 return if $self->{txn};
756 my $xdb = $self->{xdb} || $self->_xdb_acquire;
757 $self->{over}->begin_lazy if $self->{over};
758 $xdb->begin_transaction;
763 sub commit_txn_lazy {
765 delete $self->{txn} or return;
766 $self->{xdb}->commit_transaction;
767 $self->{over}->commit_lazy if $self->{over};
772 die "$$ $0 xdb not released\n" if $self->{xdb};
773 die "$$ $0 still in transaction\n" if $self->{txn};