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');
335 # because too many Message-IDs are prefixed with
337 if ($mid =~ /\w{12,}/) {
338 my @long = ($mid =~ /(\w{3,}+)/g);
339 $tg->index_text(join(' ', @long), 1, 'XM');
341 $tg->increase_termpos;
343 $smsg->{to} = $smsg->{cc} = '';
344 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
345 my $data = $smsg->to_doc_data($oid, $mid0);
346 $doc->set_data($data);
347 if (my $altid = $self->{-altid}) {
348 foreach my $alt (@$altid) {
349 my $pfx = $alt->{xprefix};
350 foreach my $mid (@$mids) {
351 my $id = $alt->mid2alt($mid);
352 next unless defined $id;
353 $doc->add_boolean_term($pfx . $id);
358 if (my $over = $self->{over}) {
359 $over->add_overview($mime, $bytes, $num, $oid, $mid0);
361 $doc->add_boolean_term('Q' . $_) foreach @$mids;
362 $self->{xdb}->replace_document($doc_id = $num, $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);
399 my $over = $self->{over};
402 batch_do($self, 'Q' . $mid, sub {
404 $db->delete_document($_) for @$ids;
405 $over->delete_articles($ids) if $over;
410 warn "failed to remove message <$mid>: $@\n";
412 warn "cannot remove non-existent <$mid>\n";
416 # MID is a hint in V2
418 my ($self, $oid, $mid) = @_;
419 my $db = $self->{xdb};
421 $self->{over}->remove_oid($oid, $mid) if $self->{over};
423 # XXX careful, we cannot use batch_do here since we conditionally
424 # delete documents based on other factors, so we cannot call
425 # find_doc_ids twice.
426 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
427 return if $head == $tail;
429 # there is only ONE element in @delete unless we
430 # have bugs in our v2writable deduplication check
432 for (; $head != $tail; $head->inc) {
433 my $docid = $head->get_docid;
434 my $doc = $db->get_document($docid);
435 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
437 if ($smsg->{blob} eq $oid) {
438 push(@delete, $docid);
441 $db->delete_document($_) foreach @delete;
445 sub term_generator { # write-only
448 my $tg = $self->{term_generator};
451 $tg = Search::Xapian::TermGenerator->new;
452 $tg->set_stemmer($self->stemmer);
454 $self->{term_generator} = $tg;
457 sub index_git_blob_id {
458 my ($doc, $pfx, $objid) = @_;
460 my $len = length($objid);
461 for (my $len = length($objid); $len >= 7; ) {
462 $doc->add_term($pfx.$objid);
463 $objid = substr($objid, 0, --$len);
468 my ($self, $mime) = @_;
469 my $mid = eval { mid_clean(mid_mime($mime)) };
470 $self->remove_message($mid) if defined $mid;
474 my ($self, $mime) = @_;
475 my $mid = mid_clean(mid_mime($mime));
476 my $mm = $self->{mm};
479 if (defined $self->{regen_down}) {
480 $num = $mm->num_for($mid) and return $num;
482 while (($num = $self->{regen_down}--) > 0) {
483 if ($mm->mid_set($num, $mid) != 0) {
487 } elsif (defined $self->{regen_up}) {
488 $num = $mm->num_for($mid) and return $num;
490 # this is to fixup old bugs due to add-remove-add
491 while (($num = ++$self->{regen_up})) {
492 if ($mm->mid_set($num, $mid) != 0) {
498 $num = $mm->mid_insert($mid) and return $num;
500 # fallback to num_for since filters like RubyLang set the number
505 my ($self, $mime) = @_;
506 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
510 my ($self, $mime, $bytes, $blob) = @_;
511 my $num = index_mm($self, $mime);
512 add_message($self, $mime, $bytes, $num, $blob);
516 my ($self, $mime) = @_;
517 unindex_blob($self, $mime);
518 unindex_mm($self, $mime);
522 my ($git, $blob, $sizeref) = @_;
524 my $str = $git->cat_file($blob, $sizeref);
525 # fixup bugs from import:
526 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
527 PublicInbox::MIME->new($str);
533 my ($self, $opts) = @_;
534 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
537 sub batch_adjust ($$$$) {
538 my ($max, $bytes, $batch_cb, $latest) = @_;
542 $batch_cb->($latest);
548 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
549 my $hex = '[a-f0-9]';
550 my $h40 = $hex .'{40}';
551 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
552 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
553 my $git = $self->{git};
556 my $max = BATCH_BYTES;
561 while (defined($line = <$log>)) {
562 if ($line =~ /$addmsg/o) {
564 delete $D{$blob} and next;
565 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
566 batch_adjust(\$max, $bytes, $batch_cb, $latest);
567 $add_cb->($self, $mime, $bytes, $blob);
568 } elsif ($line =~ /$delmsg/o) {
571 } elsif ($line =~ /^commit ($h40)/o) {
577 foreach my $blob (keys %D) {
578 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
579 $del_cb->($self, $mime);
581 $batch_cb->($latest, $newest);
586 die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
587 $self->{mm} ||= eval {
588 require PublicInbox::Msgmap;
589 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
594 my ($self, $range) = @_;
595 my $git = $self->{git};
597 if (index($range, '..') < 0) {
599 # can't use 'rev-list --count' if we use --diff-filter
600 my $fh = $git->popen(qw(log --pretty=tformat:%h
601 --no-notes --no-color --no-renames
602 --diff-filter=AM), $range);
603 ++$regen_max while <$fh>;
604 my (undef, $max) = $self->{mm}->minmax;
606 if ($max && $max == $regen_max) {
607 # fix up old bugs in full indexes which caused messages to
608 # not appear in Msgmap
609 $self->{regen_up} = $max;
611 # normal regen is for for fresh data
612 $self->{regen_down} = $regen_max;
616 $git->popen(qw/log --no-notes --no-color --no-renames
617 --raw -r --no-abbrev/, $range);
620 sub is_ancestor ($$$) {
621 my ($git, $cur, $tip) = @_;
622 return 0 unless $git->check($cur);
623 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
624 qw(merge-base --is-ancestor), $cur, $tip ];
625 my $pid = spawn($cmd);
626 defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
627 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
631 sub need_update ($$$) {
632 my ($self, $cur, $new) = @_;
633 my $git = $self->{git};
634 return 1 if $cur && !is_ancestor($git, $cur, $new);
635 my $range = $cur eq '' ? $new : "$cur..$new";
636 chomp(my $n = $git->qx(qw(rev-list --count), $range));
637 ($n eq '' || $n > 0);
640 # indexes all unindexed messages (v1 only)
642 my ($self, $opts) = @_;
643 my $tip = $opts->{ref} || 'HEAD';
644 my $reindex = $opts->{reindex};
645 my ($mkey, $last_commit, $lx, $xlog);
646 my $git = $self->{git};
649 my $xdb = $self->begin_txn_lazy;
650 my $mm = _msgmap_init($self);
653 $mkey = 'last_commit';
654 $last_commit = $xdb->get_metadata('last_commit');
658 $mkey = undef if $last_commit ne '';
661 # use last_commit from msgmap if it is older or unset
662 my $lm = $mm->last_commit || '';
663 if (!$lm || ($lm && $lx && is_ancestor($git, $lm, $lx))) {
667 $self->{over}->rollback_lazy;
668 $self->{over}->disconnect;
671 $xdb->cancel_transaction;
672 $xdb = _xdb_release($self);
674 # ensure we leak no FDs to "git log" with Xapian <= 1.2
675 my $range = $lx eq '' ? $tip : "$lx..$tip";
676 $xlog = _git_log($self, $range);
678 $xdb = $self->begin_txn_lazy;
679 } while ($xdb->get_metadata('last_commit') ne $last_commit);
681 my $dbh = $mm->{dbh} if $mm;
683 my ($commit, $newest) = @_;
686 my $cur = $mm->last_commit || '';
687 if (need_update($self, $cur, $newest)) {
688 $mm->last_commit($newest);
693 if ($mkey && $newest) {
694 my $cur = $xdb->get_metadata($mkey);
695 if (need_update($self, $cur, $newest)) {
696 $xdb->set_metadata($mkey, $newest);
699 $self->commit_txn_lazy;
701 $xdb = _xdb_release($self);
702 # let another process do some work... <
704 $xdb = $self->begin_txn_lazy;
705 $dbh->begin_work if $dbh;
710 read_log($self, $xlog, *index_both, *unindex_both, $cb);
714 # order matters for unlocking
715 $_[0]->{xdb} = undef;
716 $_[0]->{lockfh} = undef;
719 # remote_* subs are only used by SearchIdxPart
722 if (my $w = $self->{w}) {
723 print $w "commit\n" or die "failed to write commit: $!";
725 $self->commit_txn_lazy;
731 if (my $w = delete $self->{w}) {
732 my $pid = delete $self->{pid} or die "no process to wait on\n";
733 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
734 close $w or die "failed to close pipe for pid:$pid: $!\n";
735 waitpid($pid, 0) == $pid or die "remote process did not finish";
736 $? == 0 or die ref($self)." pid:$pid exited with: $?";
738 die "transaction in progress $self\n" if $self->{txn};
739 $self->_xdb_release if $self->{xdb};
744 my ($self, $oid, $mid) = @_;
745 if (my $w = $self->{w}) {
746 # triggers remove_by_oid in a partition
747 print $w "D $oid $mid\n" or die "failed to write remove $!";
749 $self->begin_txn_lazy;
750 $self->remove_by_oid($oid, $mid);
756 return if $self->{txn};
758 $self->{-inbox}->with_umask(sub {
759 my $xdb = $self->{xdb} || $self->_xdb_acquire;
760 $self->{over}->begin_lazy if $self->{over};
761 $xdb->begin_transaction;
767 sub commit_txn_lazy {
769 delete $self->{txn} or return;
770 $self->{-inbox}->with_umask(sub {
771 $self->{xdb}->commit_transaction;
772 $self->{over}->commit_lazy if $self->{over};
778 die "$$ $0 xdb not released\n" if $self->{xdb};
779 die "$$ $0 still in transaction\n" if $self->{txn};