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 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
10 # values for searching
11 use constant TS => 0; # Received: header in Unix time
12 use constant YYYYMMDD => 1; # for searching in the WWW UI
14 use Search::Xapian qw/:standard/;
15 use PublicInbox::SearchMsg;
16 use PublicInbox::MIME;
17 use PublicInbox::MID qw/id_compress/;
18 use PublicInbox::Over;
20 # This is English-only, everything else is non-standard and may be confused as
21 # a prefix common in patch emails
22 our $REPLY_RE = qr/^re:\s+/i;
23 our $LANG = 'english';
26 # SCHEMA_VERSION history
28 # 1 - subject_path is lower-cased
29 # 2 - subject_path is id_compress in the index, only
30 # 3 - message-ID is compressed if it includes '%' (hack!)
31 # 4 - change "Re: " normalization, avoid circular Reference ghosts
32 # 5 - subject_path drops trailing '.'
33 # 6 - preserve References: order in document data
34 # 7 - remove references and inreplyto terms
35 # 8 - remove redundant/unneeded document data
36 # 9 - disable Message-ID compression (SHA-1)
37 # 10 - optimize doc for NNTP overviews
38 # 11 - merge threads when vivifying ghosts
39 # 12 - change YYYYMMDD value column to numeric
40 # 13 - fix threading for empty References/In-Reply-To
41 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
42 # 14 - fix ghost root vivification
45 # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
46 # as it could become a denial-of-service vector
47 QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
50 my %bool_pfx_external = (
51 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
54 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
56 # for mairix compatibility
58 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
65 b => $non_quoted_body . ' XQUOT',
66 bs => $non_quoted_body . ' XQUOT S',
70 nq => $non_quoted_body,
78 dfblob => 'XDFPRE XDFPOST',
81 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
84 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
86 's:' => 'match within Subject e.g. s:"a quick brown fox"',
88 date range as YYYYMMDD e.g. d:19931002..20101002
89 Open-ended ranges such as d:19931002.. and d:..20101002
92 'b:' => 'match within message body, including text attachments',
93 'nq:' => 'match non-quoted text within message body',
94 'q:' => 'match quoted text within message body',
95 'n:' => 'match filename of attachment(s)',
96 't:' => 'match within the To header',
97 'c:' => 'match within the Cc header',
98 'f:' => 'match within the From header',
99 'a:' => 'match within the To, Cc, and From headers',
100 'tc:' => 'match within the To and Cc headers',
101 'bs:' => 'match within the Subject and body',
102 'dfn:' => 'match filename from diff',
103 'dfa:' => 'match diff removed (-) lines',
104 'dfb:' => 'match diff added (+) lines',
105 'dfhh:' => 'match diff hunk header context (usually a function name)',
106 'dfctx:' => 'match diff context lines',
107 'dfpre:' => 'match pre-image git blob ID',
108 'dfpost:' => 'match post-image git blob ID',
109 'dfblob:' => 'match either pre or post-image git blob ID',
115 if ($self->{version} == 1) {
116 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
118 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
119 my $part = $self->{partition};
120 defined $part or die "partition not given";
126 my ($class, $mainrepo, $altid) = @_;
130 $version = $ibx->{version} || 1;
131 $mainrepo = $ibx->{mainrepo};
134 mainrepo => $mainrepo,
140 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
143 foreach my $part (<$dir/*>) {
144 -d $part && $part =~ m!/\d+\z! or next;
146 my $sub = Search::Xapian::Database->new($part);
148 $xdb->add_database($sub);
156 $self->{xdb} = Search::Xapian::Database->new($dir);
158 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
164 $self->{xdb}->reopen;
165 $self; # make chaining easier
170 my ($self, $query_string, $opts) = @_;
172 if ($query_string eq '' && !$opts->{mset}) {
173 $self->{over_ro}->recent($opts);
175 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
176 $opts->{relevance} = 1 unless exists $opts->{relevance};
177 _do_enquire($self, $query, $opts);
182 my ($self, $mid, $prev) = @_;
183 $self->{over_ro}->get_thread($mid, $prev);
187 my ($self, $cb) = @_;
191 eval { @ret = $cb->() };
192 return @ret unless $@;
195 eval { $ret = $cb->() };
196 return $ret unless $@;
198 # Exception: The revision being read has been discarded -
199 # you should call Xapian::Database::reopen()
200 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
201 warn "reopen try #$i on $@\n";
204 warn "ref: ", ref($@), "\n";
208 die "Too many Xapian database modifications in progress\n";
212 my ($self, $query, $opts) = @_;
213 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
217 my ($self, $query, $opts) = @_;
218 my $enquire = enquire($self);
219 $enquire->set_query($query);
221 my $desc = !$opts->{asc};
222 if (($opts->{mset} || 0) == 2) {
223 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
224 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
225 delete $self->{enquire};
226 } elsif ($opts->{relevance}) {
227 $enquire->set_sort_by_relevance_then_value(TS, $desc);
229 $enquire->set_sort_by_value_then_relevance(TS, $desc);
231 my $offset = $opts->{offset} || 0;
232 my $limit = $opts->{limit} || 50;
233 my $mset = $enquire->get_mset($offset, $limit);
234 return $mset if $opts->{mset};
236 PublicInbox::SearchMsg->load_doc($_->get_document);
238 return \@msgs unless wantarray;
240 ($mset->get_matches_estimated, \@msgs)
244 sub stemmer { Search::Xapian::Stem->new($LANG) }
250 my $qp = $self->{query_parser};
254 $qp = Search::Xapian::QueryParser->new;
255 $qp->set_default_op(OP_AND);
256 $qp->set_database($self->{xdb});
257 $qp->set_stemmer($self->stemmer);
258 $qp->set_stemming_strategy(STEM_SOME);
259 $qp->add_valuerangeprocessor(
260 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
262 while (my ($name, $prefix) = each %bool_pfx_external) {
263 $qp->add_boolean_prefix($name, $prefix);
266 # we do not actually create AltId objects,
267 # just parse the spec to avoid the extra DB handles for now.
268 if (my $altid = $self->{altid}) {
269 my $user_pfx = $self->{-user_pfx} ||= [];
271 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
272 /\Aserial:(\w+):/ or next;
274 push @$user_pfx, "$pfx:", <<EOF;
275 alternate serial number e.g. $pfx:12345 (boolean)
278 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
283 while (my ($name, $prefix) = each %prob_prefix) {
284 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
287 $self->{query_parser} = $qp;
290 # only used for NNTP server
292 my ($self, $beg, $end, $offset) = @_;
293 $self->{over_ro}->query_xover($beg, $end, $offset);
297 my ($self, $ts, $prev) = @_;
298 $self->{over_ro}->query_ts($ts, $prev);
301 sub first_smsg_by_mid {
302 my ($self, $mid) = @_;
304 retry_reopen($self, sub {
305 each_smsg_by_mid($self, $mid, sub { $smsg = $_[0]; undef });
311 my ($self, $num) = @_;
312 my $term = 'XNUM'.$num;
313 my $db = $self->{xdb};
314 retry_reopen($self, sub {
315 my $head = $db->postlist_begin($term);
316 my $tail = $db->postlist_end($term);
317 return if $head->equal($tail);
318 my $doc_id = $head->get_docid;
319 return unless defined $doc_id;
321 if ($head->nequal($tail)) {
322 warn "article #$num is not unique\n";
325 my $doc = $db->get_document($doc_id);
326 my $smsg = PublicInbox::SearchMsg->wrap($doc);
327 $smsg->{doc_id} = $doc_id;
332 sub each_smsg_by_mid {
333 my ($self, $mid, $cb) = @_;
334 # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
335 # interface will need it...
336 my $db = $self->{xdb};
337 my $term = 'Q' . $mid;
338 my $head = $db->postlist_begin($term);
339 my $tail = $db->postlist_end($term);
340 if ($head == $tail) {
342 $head = $db->postlist_begin($term);
343 $tail = $db->postlist_end($term);
345 return ($head, $tail, $db) if wantarray;
346 for (; $head->nequal($tail); $head->inc) {
347 my $doc_id = $head->get_docid;
348 my $doc = $db->get_document($doc_id);
349 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
350 $smsg->{doc_id} = $doc_id;
351 $cb->($smsg) or return;
355 # normalize subjects so they are suitable as pathnames for URLs
356 # XXX: consider for removal
359 $subj = subject_normalized($subj);
360 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
364 sub subject_normalized {
366 $subj =~ s/\A\s+//s; # no leading space
367 $subj =~ s/\s+\z//s; # no trailing space
368 $subj =~ s/\s+/ /gs; # no redundant spaces
369 $subj =~ s/\.+\z//; # no trailing '.'
370 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
376 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
381 $self->qp; # parse altids
383 if (my $user_pfx = $self->{-user_pfx}) {
384 push @ret, @$user_pfx;