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;
8 use parent qw(Exporter);
9 our @EXPORT_OK = qw(mdocid);
11 # values for searching, changing the numeric value breaks
12 # compatibility with old indices (so don't change them it)
14 TS => 0, # Received: header in Unix time (IMAP INTERNALDATE)
15 YYYYMMDD => 1, # Date: header for searching in the WWW UI
16 DT => 2, # Date: YYYYMMDDHHMMSS
18 # added for public-inbox 1.6.0+
19 BYTES => 3, # IMAP RFC822.SIZE
20 UID => 4, # IMAP UID == NNTP article number == Xapian docid
24 # REPLYCNT => ?, # IMAP ANSWERED
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
43 # 15 - see public-inbox-v2-format(5)
44 # further bumps likely unnecessary, we'll suggest in-place
45 # "--reindex" use for further fixes and tweaks:
47 # public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
48 # * "lid:" and "l:" for List-Id searches
50 # v1.6.0 adds BYTES and UID values
54 use PublicInbox::Smsg;
55 use PublicInbox::Over;
57 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
58 NumberValueRangeProcessor QueryParser Stem);
59 our $Xap; # 'Search::Xapian' or 'Xapian'
63 return 1 if defined $Xap;
64 for my $x (qw(Search::Xapian Xapian)) {
68 $x->import(qw(:standard));
70 $X{$_} = $Xap.'::'.$_ for (keys %X);
72 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
73 # so lets hope this part of the ABI is stable because it's
75 $ENQ_ASCENDING = $x eq 'Xapian' ?
76 1 : Search::Xapian::ENQ_ASCENDING();
79 *PublicInbox::Smsg::sortable_unserialise =
80 $Xap.'::sortable_unserialise';
81 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
82 # website as it could become a denial-of-service vector
83 # FLAG_PHRASE also seems to cause performance problems chert
84 # (and probably earlier Xapian DBs). glass seems fine...
85 # TODO: make this an option, maybe?
86 # or make indexlevel=medium as default
87 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
94 # This is English-only, everything else is non-standard and may be confused as
95 # a prefix common in patch emails
96 our $LANG = 'english';
98 # note: the non-X term prefix allocations are shared with
99 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
100 my %bool_pfx_external = (
101 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
102 lid => 'G', # newsGroup (or similar entity), just inside <>
105 dfblob => 'XDFPRE XDFPOST',
108 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
110 # for mairix compatibility
112 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
113 l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
120 b => $non_quoted_body . ' XQUOT',
121 bs => $non_quoted_body . ' XQUOT S',
125 nq => $non_quoted_body,
133 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
136 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
137 # not documenting lid: for now, either, it is probably redundant with l:,
138 # especially since we don't offer boolean searches for To/Cc/From
141 's:' => 'match within Subject e.g. s:"a quick brown fox"',
143 date range as YYYYMMDD e.g. d:19931002..20101002
144 Open-ended ranges such as d:19931002.. and d:..20101002
148 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
150 'b:' => 'match within message body, including text attachments',
151 'nq:' => 'match non-quoted text within message body',
152 'q:' => 'match quoted text within message body',
153 'n:' => 'match filename of attachment(s)',
154 't:' => 'match within the To header',
155 'c:' => 'match within the Cc header',
156 'f:' => 'match within the From header',
157 'a:' => 'match within the To, Cc, and From headers',
158 'tc:' => 'match within the To and Cc headers',
159 'l:' => 'match contents of the List-Id header',
160 'bs:' => 'match within the Subject and body',
161 'dfn:' => 'match filename from diff',
162 'dfa:' => 'match diff removed (-) lines',
163 'dfb:' => 'match diff added (+) lines',
164 'dfhh:' => 'match diff hunk header context (usually a function name)',
165 'dfctx:' => 'match diff context lines',
166 'dfpre:' => 'match pre-image git blob ID',
167 'dfpost:' => 'match post-image git blob ID',
168 'dfblob:' => 'match either pre or post-image git blob ID',
173 my ($self, $rdonly) = @_;
174 if ($rdonly || !defined($self->{shard})) {
177 "$self->{xpfx}/$self->{shard}";
183 my $dir = xdir($self, 1);
184 my ($xdb, $slow_phrase);
185 my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
186 if ($self->{ibx_ver} >= 2) {
188 opendir(my $dh, $dir) or return; # not initialized yet
190 # We need numeric sorting so shard[0] is first for reading
191 # Xapian metadata, if needed
192 for (sort { $a <=> $b } grep(/\A[0-9]+\z/, readdir($dh))) {
193 my $shard_dir = "$dir/$_";
194 if (-d $shard_dir && -r _) {
195 push @xdb, $X{Database}->new($shard_dir);
196 $slow_phrase ||= -f "$shard_dir/iamchert";
197 } else { # gaps from missing epochs throw off mdocid()
198 warn "E: $shard_dir missing or unreadable\n";
202 $self->{nshard} = scalar(@xdb);
204 $xdb->add_database($_) for @xdb;
206 $slow_phrase = -f "$dir/iamchert";
207 $xdb = $X{Database}->new($dir);
209 $$qpf |= FLAG_PHRASE() unless $slow_phrase;
213 # v2 Xapian docids don't conflict, so they're identical to
214 # NNTP article numbers and IMAP UIDs.
215 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
217 my ($nshard, $mitem) = @_;
218 my $docid = $mitem->get_docid;
219 int(($docid - 1) / $nshard) + 1;
224 $self->{xdb} ||= do {
232 if ($self->{ibx_ver} == 1) {
233 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
235 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
240 my ($class, $ibx) = @_;
241 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
243 xpfx => $ibx->{inboxdir}, # for xpfx_init
244 altid => $ibx->{altid},
245 ibx_ver => $ibx->version,
248 my $dir = xdir($self, 1);
249 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
255 if (my $xdb = $self->{xdb}) {
258 $self; # make chaining easier
263 my ($self, $query_string, $opts) = @_;
265 if ($query_string eq '' && !$opts->{mset}) {
266 $self->{over_ro}->recent($opts);
268 my $qp = $self->{qp} //= qparse_new($self);
269 my $qp_flags = $self->{qp_flags};
270 my $query = $qp->parse_query($query_string, $qp_flags);
271 $opts->{relevance} = 1 unless exists $opts->{relevance};
272 _do_enquire($self, $query, $opts);
277 my ($self, $cb, $arg) = @_;
281 eval { @ret = $cb->($arg) };
282 return @ret unless $@;
285 eval { $ret = $cb->($arg) };
286 return $ret unless $@;
288 # Exception: The revision being read has been discarded -
289 # you should call Xapian::Database::reopen()
290 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
291 warn "reopen try #$i on $@\n";
294 # let caller decide how to spew, because ExtMsg queries
295 # get wonky and trigger:
296 # "something terrible happened at .../Xapian/Enquire.pm"
300 die "Too many Xapian database modifications in progress\n";
304 my ($self, $query, $opts) = @_;
305 retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
308 sub _enquire_once { # retry_reopen callback
309 my ($self, $query, $opts) = @{$_[0]};
310 my $xdb = xdb($self);
311 my $enquire = $X{Enquire}->new($xdb);
312 $enquire->set_query($query);
314 my $desc = !$opts->{asc};
315 if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
316 $enquire->set_docid_order($ENQ_ASCENDING);
317 $enquire->set_weighting_scheme($X{BoolWeight}->new);
318 } elsif ($opts->{relevance}) {
319 $enquire->set_sort_by_relevance_then_value(TS, $desc);
321 $enquire->set_sort_by_value_then_relevance(TS, $desc);
323 my $offset = $opts->{offset} || 0;
324 my $limit = $opts->{limit} || 50;
325 my $mset = $enquire->get_mset($offset, $limit);
326 return $mset if $opts->{mset};
327 my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
328 return \@msgs unless wantarray;
330 ($mset->get_matches_estimated, \@msgs)
334 sub stemmer { $X{Stem}->new($LANG) }
340 my $xdb = xdb($self);
341 my $qp = $X{QueryParser}->new;
342 $qp->set_default_op(OP_AND());
343 $qp->set_database($xdb);
344 $qp->set_stemmer(stemmer($self));
345 $qp->set_stemming_strategy(STEM_SOME());
346 $qp->set_max_wildcard_expansion(100);
347 my $nvrp = $X{NumberValueRangeProcessor};
348 $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
349 $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
351 # for IMAP, undocumented for WWW and may be split off go away
352 $qp->add_valuerangeprocessor($nvrp->new(BYTES, 'bytes:'));
353 $qp->add_valuerangeprocessor($nvrp->new(TS, 'ts:'));
354 $qp->add_valuerangeprocessor($nvrp->new(UID, 'uid:'));
356 while (my ($name, $prefix) = each %bool_pfx_external) {
357 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
360 # we do not actually create AltId objects,
361 # just parse the spec to avoid the extra DB handles for now.
362 if (my $altid = $self->{altid}) {
363 my $user_pfx = $self->{-user_pfx} = [];
365 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
366 # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
367 # and '_' with prefixes matching \w+
368 /\Aserial:(\w+):/ or next;
370 push @$user_pfx, "$pfx:", <<EOF;
371 alternate serial number e.g. $pfx:12345 (boolean)
374 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
379 while (my ($name, $prefix) = each %prob_prefix) {
380 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
387 $self->{qp} //= qparse_new($self); # parse altids
389 if (my $user_pfx = $self->{-user_pfx}) {
390 push @ret, @$user_pfx;