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
13 use constant NUM => 2; # NNTP article number
15 use Search::Xapian qw/:standard/;
16 use PublicInbox::SearchMsg;
17 use PublicInbox::MIME;
18 use PublicInbox::MID qw/id_compress/;
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,
51 my %bool_pfx_internal = (
52 type => 'T', # "mail" or "ghost"
53 thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
56 my %bool_pfx_external = (
57 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
60 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
62 # for mairix compatibility
64 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
71 b => $non_quoted_body . ' XQUOT',
72 bs => $non_quoted_body . ' XQUOT S',
76 nq => $non_quoted_body,
84 dfblob => 'XDFPRE XDFPOST',
87 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
90 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
92 's:' => 'match within Subject e.g. s:"a quick brown fox"',
94 date range as YYYYMMDD e.g. d:19931002..20101002
95 Open-ended ranges such as d:19931002.. and d:..20101002
98 'b:' => 'match within message body, including text attachments',
99 'nq:' => 'match non-quoted text within message body',
100 'q:' => 'match quoted text within message body',
101 'n:' => 'match filename of attachment(s)',
102 't:' => 'match within the To header',
103 'c:' => 'match within the Cc header',
104 'f:' => 'match within the From header',
105 'a:' => 'match within the To, Cc, and From headers',
106 'tc:' => 'match within the To and Cc headers',
107 'bs:' => 'match within the Subject and body',
108 'dfn:' => 'match filename from diff',
109 'dfa:' => 'match diff removed (-) lines',
110 'dfb:' => 'match diff added (+) lines',
111 'dfhh:' => 'match diff hunk header context (usually a function name)',
112 'dfctx:' => 'match diff context lines',
113 'dfpre:' => 'match pre-image git blob ID',
114 'dfpost:' => 'match post-image git blob ID',
115 'dfblob:' => 'match either pre or post-image git blob ID',
119 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
123 if ($self->{version} == 1) {
124 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
126 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
127 my $part = $self->{partition};
128 defined $part or die "partition not given";
134 my ($class, $mainrepo, $altid) = @_;
138 $version = $ibx->{version} || 1;
139 $mainrepo = $ibx->{mainrepo};
142 mainrepo => $mainrepo,
147 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
150 foreach my $part (<$dir/*>) {
151 -d $part && $part =~ m!/\d+\z! or next;
153 my $sub = Search::Xapian::Database->new($part);
155 $xdb->add_database($sub);
161 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
163 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
170 $self->{xdb}->reopen;
171 if (my $skel = $self->{skel}) {
174 $self; # make chaining easier
179 my ($self, $query_string, $opts) = @_;
183 unless ($query_string eq '') {
184 $query = $self->qp->parse_query($query_string, QP_FLAGS);
185 $opts->{relevance} = 1 unless exists $opts->{relevance};
188 _do_enquire($self, $query, $opts);
192 my ($self, $mid, $opts) = @_;
193 my $smsg = first_smsg_by_mid($self, $mid) or
194 return { total => 0, msgs => [] };
195 my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
196 my $path = $smsg->path;
197 if (defined $path && $path ne '') {
198 my $path = id_compress($smsg->path);
199 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
200 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
203 $opts->{limit} ||= 1000;
205 # always sort threads by timestamp, this makes life easier
206 # for the threading algorithm (in SearchThread.pm)
208 $opts->{enquire} = enquire_skel($self);
209 _do_enquire($self, $qtid, $opts);
213 my ($self, $cb) = @_;
216 eval { $ret = $cb->() };
217 return $ret unless $@;
218 # Exception: The revision being read has been discarded -
219 # you should call Xapian::Database::reopen()
220 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
221 warn "reopen try #$i on $@\n";
224 warn "ref: ", ref($@), "\n";
228 die "Too many Xapian database modifications in progress\n";
232 my ($self, $query, $opts) = @_;
233 retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
237 my ($self, $query, $opts) = @_;
238 my $enquire = $opts->{enquire} || enquire($self);
239 if (defined $query) {
240 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
242 $query = $mail_query;
244 $enquire->set_query($query);
246 my $desc = !$opts->{asc};
247 if ($opts->{relevance}) {
248 $enquire->set_sort_by_relevance_then_value(TS, $desc);
249 } elsif ($opts->{num}) {
250 $enquire->set_sort_by_value(NUM, 0);
252 $enquire->set_sort_by_value_then_relevance(TS, $desc);
254 my $offset = $opts->{offset} || 0;
255 my $limit = $opts->{limit} || 50;
256 my $mset = $enquire->get_mset($offset, $limit);
257 return $mset if $opts->{mset};
259 PublicInbox::SearchMsg->load_doc($_->get_document);
262 { total => $mset->get_matches_estimated, msgs => \@msgs }
266 sub stemmer { Search::Xapian::Stem->new($LANG) }
272 my $qp = $self->{query_parser};
276 $qp = Search::Xapian::QueryParser->new;
277 $qp->set_default_op(OP_AND);
278 $qp->set_database($self->{xdb});
279 $qp->set_stemmer($self->stemmer);
280 $qp->set_stemming_strategy(STEM_SOME);
281 $qp->add_valuerangeprocessor(
282 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
284 while (my ($name, $prefix) = each %bool_pfx_external) {
285 $qp->add_boolean_prefix($name, $prefix);
288 # we do not actually create AltId objects,
289 # just parse the spec to avoid the extra DB handles for now.
290 if (my $altid = $self->{altid}) {
291 my $user_pfx = $self->{-user_pfx} ||= [];
293 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
294 /\Aserial:(\w+):/ or next;
296 push @$user_pfx, "$pfx:", <<EOF;
297 alternate serial number e.g. $pfx:12345 (boolean)
300 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
305 while (my ($name, $prefix) = each %prob_prefix) {
306 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
309 $self->{query_parser} = $qp;
312 sub num_range_processor {
313 $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
316 # only used for NNTP server
318 my ($self, $beg, $end, $offset) = @_;
319 my $qp = Search::Xapian::QueryParser->new;
320 $qp->set_database($self->{skel} || $self->{xdb});
321 $qp->add_valuerangeprocessor($self->num_range_processor);
322 my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
325 enquire => enquire_skel($self),
330 _do_enquire($self, $query, $opts);
334 my ($self, $ts, $opts) = @_;
335 my $qp = $self->{qp_ts} ||= eval {
336 my $q = Search::Xapian::QueryParser->new;
337 $q->set_database($self->{skel} || $self->{xdb});
338 $q->add_valuerangeprocessor(
339 Search::Xapian::NumberValueRangeProcessor->new(TS));
342 my $query = $qp->parse_query($ts, QP_FLAGS);
343 $opts->{enquire} = enquire_skel($self);
344 _do_enquire($self, $query, $opts);
347 sub first_smsg_by_mid {
348 my ($self, $mid) = @_;
350 retry_reopen($self, sub {
351 each_smsg_by_mid($self, $mid, sub { $smsg = $_[0]; undef });
357 my ($self, $num) = @_;
358 my $term = 'XNUM'.$num;
359 my $db = $self->{skel} || $self->{xdb};
360 retry_reopen($self, sub {
361 my $head = $db->postlist_begin($term);
362 my $tail = $db->postlist_end($term);
363 return if $head->equal($tail);
364 my $doc_id = $head->get_docid;
365 return unless defined $doc_id;
367 if ($head->nequal($tail)) {
368 my $loc= $self->{mainrepo} .
369 ($self->{skel} ? 'skel' : 'xdb');
370 warn "article #$num is not unique in $loc\n";
373 my $doc = $db->get_document($doc_id);
374 my $smsg = PublicInbox::SearchMsg->wrap($doc);
375 $smsg->{doc_id} = $doc_id;
380 sub each_smsg_by_mid {
381 my ($self, $mid, $cb) = @_;
382 # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
383 # interface will need it...
384 my $db = $self->{skel} || $self->{xdb};
385 my $term = 'Q' . $mid;
386 my $head = $db->postlist_begin($term);
387 my $tail = $db->postlist_end($term);
388 if ($head == $tail) {
390 $head = $db->postlist_begin($term);
391 $tail = $db->postlist_end($term);
393 return ($head, $tail, $db) if wantarray;
394 for (; $head->nequal($tail); $head->inc) {
395 my $doc_id = $head->get_docid;
396 my $doc = $db->get_document($doc_id);
397 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
398 $smsg->{doc_id} = $doc_id;
399 $cb->($smsg) or return;
403 # normalize subjects so they are suitable as pathnames for URLs
404 # XXX: consider for removal
407 $subj = subject_normalized($subj);
408 $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
412 sub subject_normalized {
414 $subj =~ s/\A\s+//s; # no leading space
415 $subj =~ s/\s+\z//s; # no trailing space
416 $subj =~ s/\s+/ /gs; # no redundant spaces
417 $subj =~ s/\.+\z//; # no trailing '.'
418 $subj =~ s/$REPLY_RE//igo; # remove reply prefix
424 $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
429 if (my $skel = $self->{skel}) {
430 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
438 $self->qp; # parse altids
440 if (my $user_pfx = $self->{-user_pfx}) {
441 push @ret, @$user_pfx;