1 # Copyright (C) 2015-2020 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;
11 TS => 0, # Received: header in Unix time (IMAP INTERNALDATE)
12 YYYYMMDD => 1, # Date: header for searching in the WWW UI
13 DT => 2, # Date: YYYYMMDDHHMMSS
14 BYTES => 3, # IMAP RFC822.SIZE
15 UID => 4, # IMAP UID == NNTP article number == Xapian docid
17 # REPLYCNT => 4, # IMAP ANSWERED
20 use PublicInbox::Smsg;
21 use PublicInbox::Over;
23 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
24 NumberValueRangeProcessor QueryParser Stem);
25 our $Xap; # 'Search::Xapian' or 'Xapian'
29 return 1 if defined $Xap;
30 for my $x (qw(Search::Xapian Xapian)) {
34 $x->import(qw(:standard));
36 $X{$_} = $Xap.'::'.$_ for (keys %X);
38 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
39 # so lets hope this part of the ABI is stable because it's
41 $ENQ_ASCENDING = $x eq 'Xapian' ?
42 1 : Search::Xapian::ENQ_ASCENDING();
45 *PublicInbox::Smsg::sortable_unserialise =
46 $Xap.'::sortable_unserialise';
47 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
48 # website as it could become a denial-of-service vector
49 # FLAG_PHRASE also seems to cause performance problems chert
50 # (and probably earlier Xapian DBs). glass seems fine...
51 # TODO: make this an option, maybe?
52 # or make indexlevel=medium as default
53 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
60 # This is English-only, everything else is non-standard and may be confused as
61 # a prefix common in patch emails
62 our $LANG = 'english';
65 # SCHEMA_VERSION history
67 # 1 - subject_path is lower-cased
68 # 2 - subject_path is id_compress in the index, only
69 # 3 - message-ID is compressed if it includes '%' (hack!)
70 # 4 - change "Re: " normalization, avoid circular Reference ghosts
71 # 5 - subject_path drops trailing '.'
72 # 6 - preserve References: order in document data
73 # 7 - remove references and inreplyto terms
74 # 8 - remove redundant/unneeded document data
75 # 9 - disable Message-ID compression (SHA-1)
76 # 10 - optimize doc for NNTP overviews
77 # 11 - merge threads when vivifying ghosts
78 # 12 - change YYYYMMDD value column to numeric
79 # 13 - fix threading for empty References/In-Reply-To
80 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
81 # 14 - fix ghost root vivification
82 # 15 - see public-inbox-v2-format(5)
83 # further bumps likely unnecessary, we'll suggest in-place
84 # "--reindex" use for further fixes and tweaks
86 # public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
87 # * "lid:" and "l:" for List-Id searches
91 # note: the non-X term prefix allocations are shared with
92 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
93 my %bool_pfx_external = (
94 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
95 lid => 'G', # newsGroup (or similar entity), just inside <>
98 dfblob => 'XDFPRE XDFPOST',
101 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
103 # for mairix compatibility
105 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
106 l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
113 b => $non_quoted_body . ' XQUOT',
114 bs => $non_quoted_body . ' XQUOT S',
118 nq => $non_quoted_body,
126 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
129 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
130 # not documenting lid: for now, either, it is probably redundant with l:,
131 # especially since we don't offer boolean searches for To/Cc/From
134 's:' => 'match within Subject e.g. s:"a quick brown fox"',
136 date range as YYYYMMDD e.g. d:19931002..20101002
137 Open-ended ranges such as d:19931002.. and d:..20101002
141 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
143 'b:' => 'match within message body, including text attachments',
144 'nq:' => 'match non-quoted text within message body',
145 'q:' => 'match quoted text within message body',
146 'n:' => 'match filename of attachment(s)',
147 't:' => 'match within the To header',
148 'c:' => 'match within the Cc header',
149 'f:' => 'match within the From header',
150 'a:' => 'match within the To, Cc, and From headers',
151 'tc:' => 'match within the To and Cc headers',
152 'l:' => 'match contents of the List-Id header',
153 'bs:' => 'match within the Subject and body',
154 'dfn:' => 'match filename from diff',
155 'dfa:' => 'match diff removed (-) lines',
156 'dfb:' => 'match diff added (+) lines',
157 'dfhh:' => 'match diff hunk header context (usually a function name)',
158 'dfctx:' => 'match diff context lines',
159 'dfpre:' => 'match pre-image git blob ID',
160 'dfpost:' => 'match post-image git blob ID',
161 'dfblob:' => 'match either pre or post-image git blob ID',
166 my ($self, $rdonly) = @_;
167 if ($self->{ibx_ver} == 1) {
168 "$self->{inboxdir}/public-inbox/xapian" . SCHEMA_VERSION;
170 my $dir = "$self->{inboxdir}/xap" . SCHEMA_VERSION;
171 return $dir if $rdonly;
173 my $shard = $self->{shard};
174 defined $shard or die "shard not given";
181 my $dir = xdir($self, 1);
182 my ($xdb, $slow_phrase);
183 my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
184 if ($self->{ibx_ver} >= 2) {
186 foreach my $shard (<$dir/*>) {
187 -d $shard && $shard =~ m!/[0-9]+\z! or next;
188 my $sub = $X{Database}->new($shard);
190 $xdb->add_database($sub);
194 $slow_phrase ||= -f "$shard/iamchert";
197 $self->{nshard} = $n;
199 $slow_phrase = -f "$dir/iamchert";
200 $xdb = $X{Database}->new($dir);
202 $$qpf |= FLAG_PHRASE() unless $slow_phrase;
206 # v2 Xapian docids don't conflict, so they're identical to
207 # NNTP article numbers and IMAP UIDs.
208 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
210 my ($nshard, $mitem) = @_;
211 my $docid = $mitem->get_docid;
212 int(($docid - 1) / $nshard) + 1;
217 $self->{xdb} ||= do {
224 my ($class, $ibx) = @_;
225 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
227 inboxdir => $ibx->{inboxdir},
228 altid => $ibx->{altid},
229 ibx_ver => $ibx->version,
231 my $dir = xdir($self, 1);
232 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
238 if (my $xdb = $self->{xdb}) {
241 $self; # make chaining easier
246 my ($self, $query_string, $opts) = @_;
248 if ($query_string eq '' && !$opts->{mset}) {
249 $self->{over_ro}->recent($opts);
252 my $qp_flags = $self->{qp_flags};
253 my $query = $qp->parse_query($query_string, $qp_flags);
254 $opts->{relevance} = 1 unless exists $opts->{relevance};
255 _do_enquire($self, $query, $opts);
260 my ($self, $cb, $arg) = @_;
264 eval { @ret = $cb->($arg) };
265 return @ret unless $@;
268 eval { $ret = $cb->($arg) };
269 return $ret unless $@;
271 # Exception: The revision being read has been discarded -
272 # you should call Xapian::Database::reopen()
273 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
274 warn "reopen try #$i on $@\n";
277 # let caller decide how to spew, because ExtMsg queries
278 # get wonky and trigger:
279 # "something terrible happened at .../Xapian/Enquire.pm"
283 die "Too many Xapian database modifications in progress\n";
287 my ($self, $query, $opts) = @_;
288 retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
291 sub _enquire_once { # retry_reopen callback
292 my ($self, $query, $opts) = @{$_[0]};
293 my $xdb = xdb($self);
294 my $enquire = $X{Enquire}->new($xdb);
295 $enquire->set_query($query);
297 my $desc = !$opts->{asc};
298 if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
299 $enquire->set_docid_order($ENQ_ASCENDING);
300 $enquire->set_weighting_scheme($X{BoolWeight}->new);
301 } elsif ($opts->{relevance}) {
302 $enquire->set_sort_by_relevance_then_value(TS, $desc);
304 $enquire->set_sort_by_value_then_relevance(TS, $desc);
306 my $offset = $opts->{offset} || 0;
307 my $limit = $opts->{limit} || 50;
308 my $mset = $enquire->get_mset($offset, $limit);
309 return $mset if $opts->{mset};
310 my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
311 return \@msgs unless wantarray;
313 ($mset->get_matches_estimated, \@msgs)
317 sub stemmer { $X{Stem}->new($LANG) }
323 my $qp = $self->{query_parser};
325 my $xdb = xdb($self);
327 $qp = $X{QueryParser}->new;
328 $qp->set_default_op(OP_AND());
329 $qp->set_database($xdb);
330 $qp->set_stemmer($self->stemmer);
331 $qp->set_stemming_strategy(STEM_SOME());
332 $qp->set_max_wildcard_expansion(100);
333 my $nvrp = $X{NumberValueRangeProcessor};
334 $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
335 $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
337 # for IMAP, undocumented for WWW and may be split off go away
338 $qp->add_valuerangeprocessor($nvrp->new(BYTES, 'bytes:'));
339 $qp->add_valuerangeprocessor($nvrp->new(TS, 'ts:'));
340 $qp->add_valuerangeprocessor($nvrp->new(UID, 'uid:'));
342 while (my ($name, $prefix) = each %bool_pfx_external) {
343 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
346 # we do not actually create AltId objects,
347 # just parse the spec to avoid the extra DB handles for now.
348 if (my $altid = $self->{altid}) {
349 my $user_pfx = $self->{-user_pfx} = [];
351 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
352 # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
353 # and '_' with prefixes matching \w+
354 /\Aserial:(\w+):/ or next;
356 push @$user_pfx, "$pfx:", <<EOF;
357 alternate serial number e.g. $pfx:12345 (boolean)
360 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
365 while (my ($name, $prefix) = each %prob_prefix) {
366 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
369 $self->{query_parser} = $qp;
374 $self->qp; # parse altids
376 if (my $user_pfx = $self->{-user_pfx}) {
377 push @ret, @$user_pfx;