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
16 # REPLYCNT => 4, # IMAP ANSWERED
19 use PublicInbox::Smsg;
20 use PublicInbox::Over;
22 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
23 NumberValueRangeProcessor QueryParser Stem);
24 our $Xap; # 'Search::Xapian' or 'Xapian'
28 return 1 if defined $Xap;
29 for my $x (qw(Search::Xapian Xapian)) {
33 $x->import(qw(:standard));
35 $X{$_} = $Xap.'::'.$_ for (keys %X);
37 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
38 # so lets hope this part of the ABI is stable because it's
40 $ENQ_ASCENDING = $x eq 'Xapian' ?
41 1 : Search::Xapian::ENQ_ASCENDING();
44 *PublicInbox::Smsg::sortable_unserialise =
45 $Xap.'::sortable_unserialise';
46 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
47 # website as it could become a denial-of-service vector
48 # FLAG_PHRASE also seems to cause performance problems chert
49 # (and probably earlier Xapian DBs). glass seems fine...
50 # TODO: make this an option, maybe?
51 # or make indexlevel=medium as default
52 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
59 # This is English-only, everything else is non-standard and may be confused as
60 # a prefix common in patch emails
61 our $LANG = 'english';
64 # SCHEMA_VERSION history
66 # 1 - subject_path is lower-cased
67 # 2 - subject_path is id_compress in the index, only
68 # 3 - message-ID is compressed if it includes '%' (hack!)
69 # 4 - change "Re: " normalization, avoid circular Reference ghosts
70 # 5 - subject_path drops trailing '.'
71 # 6 - preserve References: order in document data
72 # 7 - remove references and inreplyto terms
73 # 8 - remove redundant/unneeded document data
74 # 9 - disable Message-ID compression (SHA-1)
75 # 10 - optimize doc for NNTP overviews
76 # 11 - merge threads when vivifying ghosts
77 # 12 - change YYYYMMDD value column to numeric
78 # 13 - fix threading for empty References/In-Reply-To
79 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
80 # 14 - fix ghost root vivification
81 # 15 - see public-inbox-v2-format(5)
82 # further bumps likely unnecessary, we'll suggest in-place
83 # "--reindex" use for further fixes and tweaks
85 # public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
86 # * "lid:" and "l:" for List-Id searches
90 # note: the non-X term prefix allocations are shared with
91 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
92 my %bool_pfx_external = (
93 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
94 lid => 'G', # newsGroup (or similar entity), just inside <>
97 dfblob => 'XDFPRE XDFPOST',
100 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
102 # for mairix compatibility
104 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
105 l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
112 b => $non_quoted_body . ' XQUOT',
113 bs => $non_quoted_body . ' XQUOT S',
117 nq => $non_quoted_body,
125 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
128 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
129 # not documenting lid: for now, either, it is probably redundant with l:,
130 # especially since we don't offer boolean searches for To/Cc/From
133 's:' => 'match within Subject e.g. s:"a quick brown fox"',
135 date range as YYYYMMDD e.g. d:19931002..20101002
136 Open-ended ranges such as d:19931002.. and d:..20101002
140 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
142 'b:' => 'match within message body, including text attachments',
143 'nq:' => 'match non-quoted text within message body',
144 'q:' => 'match quoted text within message body',
145 'n:' => 'match filename of attachment(s)',
146 't:' => 'match within the To header',
147 'c:' => 'match within the Cc header',
148 'f:' => 'match within the From header',
149 'a:' => 'match within the To, Cc, and From headers',
150 'tc:' => 'match within the To and Cc headers',
151 'l:' => 'match contents of the List-Id header',
152 'bs:' => 'match within the Subject and body',
153 'dfn:' => 'match filename from diff',
154 'dfa:' => 'match diff removed (-) lines',
155 'dfb:' => 'match diff added (+) lines',
156 'dfhh:' => 'match diff hunk header context (usually a function name)',
157 'dfctx:' => 'match diff context lines',
158 'dfpre:' => 'match pre-image git blob ID',
159 'dfpost:' => 'match post-image git blob ID',
160 'dfblob:' => 'match either pre or post-image git blob ID',
165 my ($self, $rdonly) = @_;
166 if ($self->{ibx_ver} == 1) {
167 "$self->{inboxdir}/public-inbox/xapian" . SCHEMA_VERSION;
169 my $dir = "$self->{inboxdir}/xap" . SCHEMA_VERSION;
170 return $dir if $rdonly;
172 my $shard = $self->{shard};
173 defined $shard or die "shard not given";
180 my $dir = xdir($self, 1);
181 my ($xdb, $slow_phrase);
182 my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
183 if ($self->{ibx_ver} >= 2) {
184 foreach my $shard (<$dir/*>) {
185 -d $shard && $shard =~ m!/[0-9]+\z! or next;
186 my $sub = $X{Database}->new($shard);
188 $xdb->add_database($sub);
192 $slow_phrase ||= -f "$shard/iamchert";
195 $slow_phrase = -f "$dir/iamchert";
196 $xdb = $X{Database}->new($dir);
198 $$qpf |= FLAG_PHRASE() unless $slow_phrase;
204 $self->{xdb} ||= do {
211 my ($class, $ibx) = @_;
212 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
214 inboxdir => $ibx->{inboxdir},
215 altid => $ibx->{altid},
216 ibx_ver => $ibx->version,
218 my $dir = xdir($self, 1);
219 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
225 if (my $xdb = $self->{xdb}) {
228 $self; # make chaining easier
233 my ($self, $query_string, $opts) = @_;
235 if ($query_string eq '' && !$opts->{mset}) {
236 $self->{over_ro}->recent($opts);
239 my $qp_flags = $self->{qp_flags};
240 my $query = $qp->parse_query($query_string, $qp_flags);
241 $opts->{relevance} = 1 unless exists $opts->{relevance};
242 _do_enquire($self, $query, $opts);
247 my ($self, $cb, $arg) = @_;
251 eval { @ret = $cb->($arg) };
252 return @ret unless $@;
255 eval { $ret = $cb->($arg) };
256 return $ret unless $@;
258 # Exception: The revision being read has been discarded -
259 # you should call Xapian::Database::reopen()
260 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
261 warn "reopen try #$i on $@\n";
264 # let caller decide how to spew, because ExtMsg queries
265 # get wonky and trigger:
266 # "something terrible happened at .../Xapian/Enquire.pm"
270 die "Too many Xapian database modifications in progress\n";
274 my ($self, $query, $opts) = @_;
275 retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
278 sub _enquire_once { # retry_reopen callback
279 my ($self, $query, $opts) = @{$_[0]};
280 my $xdb = xdb($self);
281 my $enquire = $X{Enquire}->new($xdb);
282 $enquire->set_query($query);
284 my $desc = !$opts->{asc};
285 if (($opts->{mset} || 0) == 2) {
286 $enquire->set_docid_order($ENQ_ASCENDING);
287 $enquire->set_weighting_scheme($X{BoolWeight}->new);
288 } elsif ($opts->{relevance}) {
289 $enquire->set_sort_by_relevance_then_value(TS, $desc);
291 $enquire->set_sort_by_value_then_relevance(TS, $desc);
293 my $offset = $opts->{offset} || 0;
294 my $limit = $opts->{limit} || 50;
295 my $mset = $enquire->get_mset($offset, $limit);
296 return $mset if $opts->{mset};
297 my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
298 return \@msgs unless wantarray;
300 ($mset->get_matches_estimated, \@msgs)
304 sub stemmer { $X{Stem}->new($LANG) }
310 my $qp = $self->{query_parser};
312 my $xdb = xdb($self);
314 $qp = $X{QueryParser}->new;
315 $qp->set_default_op(OP_AND());
316 $qp->set_database($xdb);
317 $qp->set_stemmer($self->stemmer);
318 $qp->set_stemming_strategy(STEM_SOME());
319 $qp->set_max_wildcard_expansion(100);
320 my $nvrp = $X{NumberValueRangeProcessor};
321 $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
322 $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
324 while (my ($name, $prefix) = each %bool_pfx_external) {
325 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
328 # we do not actually create AltId objects,
329 # just parse the spec to avoid the extra DB handles for now.
330 if (my $altid = $self->{altid}) {
331 my $user_pfx = $self->{-user_pfx} = [];
333 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
334 # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
335 # and '_' with prefixes matching \w+
336 /\Aserial:(\w+):/ or next;
338 push @$user_pfx, "$pfx:", <<EOF;
339 alternate serial number e.g. $pfx:12345 (boolean)
342 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
347 while (my ($name, $prefix) = each %prob_prefix) {
348 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
351 $self->{query_parser} = $qp;
356 $self->qp; # parse altids
358 if (my $user_pfx = $self->{-user_pfx}) {
359 push @ret, @$user_pfx;