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 retry_reopen);
10 use List::Util qw(max);
12 # values for searching, changing the numeric value breaks
13 # compatibility with old indices (so don't change them it)
15 TS => 0, # Received: header in Unix time (IMAP INTERNALDATE)
16 YYYYMMDD => 1, # Date: header for searching in the WWW UI
17 DT => 2, # Date: YYYYMMDDHHMMSS
19 # added for public-inbox 1.6.0+
20 BYTES => 3, # IMAP RFC822.SIZE
21 UID => 4, # IMAP UID == NNTP article number == Xapian docid
22 THREADID => 5, # RFC 8474, RFC 8621
25 # REPLYCNT => ?, # IMAP ANSWERED
27 # SCHEMA_VERSION history
29 # 1 - subject_path is lower-cased
30 # 2 - subject_path is id_compress in the index, only
31 # 3 - message-ID is compressed if it includes '%' (hack!)
32 # 4 - change "Re: " normalization, avoid circular Reference ghosts
33 # 5 - subject_path drops trailing '.'
34 # 6 - preserve References: order in document data
35 # 7 - remove references and inreplyto terms
36 # 8 - remove redundant/unneeded document data
37 # 9 - disable Message-ID compression (SHA-1)
38 # 10 - optimize doc for NNTP overviews
39 # 11 - merge threads when vivifying ghosts
40 # 12 - change YYYYMMDD value column to numeric
41 # 13 - fix threading for empty References/In-Reply-To
42 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
43 # 14 - fix ghost root vivification
44 # 15 - see public-inbox-v2-format(5)
45 # further bumps likely unnecessary, we'll suggest in-place
46 # "--reindex" use for further fixes and tweaks:
48 # public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
49 # * "lid:" and "l:" for List-Id searches
51 # v1.6.0 adds BYTES, UID and THREADID values
55 use PublicInbox::Smsg;
56 use PublicInbox::Over;
58 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire QueryParser Stem);
59 our $Xap; # 'Search::Xapian' or 'Xapian'
60 our $NVRP; # '$Xap::'.('NumberValueRangeProcessor' or 'NumberRangeProcessor')
64 return 1 if defined $Xap;
65 # n.b. PI_XAPIAN is intended for development use only. We still
66 # favor Search::Xapian since that's what's available in current
67 # Debian stable (10.x) and derived distros.
68 for my $x (($ENV{PI_XAPIAN} // 'Search::Xapian'), 'Xapian') {
72 $x->import(qw(:standard));
75 # `version_string' was added in Xapian 1.1
76 my $xver = eval('v'.eval($x.'::version_string()')) //
77 eval('v'.eval($x.'::xapian_version_string()'));
79 # NumberRangeProcessor was added in Xapian 1.3.6,
80 # NumberValueRangeProcessor was removed for 1.5.0+,
81 # favor the older /Value/ variant since that's what our
82 # (currently) preferred Search::Xapian supports
83 $NVRP = $x.'::'.($x eq 'Xapian' && $xver ge v1.5 ?
84 'NumberRangeProcessor' : 'NumberValueRangeProcessor');
85 $X{$_} = $Xap.'::'.$_ for (keys %X);
87 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
88 # so lets hope this part of the ABI is stable because it's
90 $ENQ_ASCENDING = $x eq 'Xapian' ?
91 1 : Search::Xapian::ENQ_ASCENDING();
93 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
94 # website as it could become a denial-of-service vector
95 # FLAG_PHRASE also seems to cause performance problems chert
96 # (and probably earlier Xapian DBs). glass seems fine...
97 # TODO: make this an option, maybe?
98 # or make indexlevel=medium as default
99 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
106 # This is English-only, everything else is non-standard and may be confused as
107 # a prefix common in patch emails
108 our $LANG = 'english';
110 # note: the non-X term prefix allocations are shared with
111 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
112 my %bool_pfx_external = (
113 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
114 lid => 'G', # newsGroup (or similar entity), just inside <>
117 dfblob => 'XDFPRE XDFPOST',
120 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
122 # for mairix compatibility
124 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
125 l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
132 b => $non_quoted_body . ' XQUOT',
133 bs => $non_quoted_body . ' XQUOT S',
137 nq => $non_quoted_body,
145 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
148 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
149 # not documenting lid: for now, either, it is probably redundant with l:,
150 # especially since we don't offer boolean searches for To/Cc/From
153 's:' => 'match within Subject e.g. s:"a quick brown fox"',
155 date range as YYYYMMDD e.g. d:19931002..20101002
156 Open-ended ranges such as d:19931002.. and d:..20101002
160 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
162 'b:' => 'match within message body, including text attachments',
163 'nq:' => 'match non-quoted text within message body',
164 'q:' => 'match quoted text within message body',
165 'n:' => 'match filename of attachment(s)',
166 't:' => 'match within the To header',
167 'c:' => 'match within the Cc header',
168 'f:' => 'match within the From header',
169 'a:' => 'match within the To, Cc, and From headers',
170 'tc:' => 'match within the To and Cc headers',
171 'l:' => 'match contents of the List-Id header',
172 'bs:' => 'match within the Subject and body',
173 'dfn:' => 'match filename from diff',
174 'dfa:' => 'match diff removed (-) lines',
175 'dfb:' => 'match diff added (+) lines',
176 'dfhh:' => 'match diff hunk header context (usually a function name)',
177 'dfctx:' => 'match diff context lines',
178 'dfpre:' => 'match pre-image git blob ID',
179 'dfpost:' => 'match post-image git blob ID',
180 'dfblob:' => 'match either pre or post-image git blob ID',
185 my ($self, $rdonly) = @_;
186 if ($rdonly || !defined($self->{shard})) {
189 "$self->{xpfx}/$self->{shard}";
195 opendir(my $dh, $self->{xpfx}) or return; # not initialized yet
197 # We need numeric sorting so shard[0] is first for reading
198 # Xapian metadata, if needed
199 my $last = max(grep(/\A[0-9]+\z/, readdir($dh)));
200 return if !defined($last);
201 my (@xdb, $slow_phrase);
203 my $shard_dir = "$self->{xpfx}/$_";
204 if (-d $shard_dir && -r _) {
205 push @xdb, $X{Database}->new($shard_dir);
206 $slow_phrase ||= -f "$shard_dir/iamchert";
207 } else { # gaps from missing epochs throw off mdocid()
208 warn "E: $shard_dir missing or unreadable\n";
212 $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
213 $self->{nshard} = scalar(@xdb);
214 my $xdb = shift @xdb;
215 $xdb->add_database($_) for @xdb;
221 my $dir = xdir($self, 1);
222 $self->{qp_flags} //= $QP_FLAGS;
223 if ($self->{ibx_ver} >= 2) {
226 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$dir/iamchert";
227 $X{Database}->new($dir);
231 # v2 Xapian docids don't conflict, so they're identical to
232 # NNTP article numbers and IMAP UIDs.
233 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
235 my ($nshard, $mitem) = @_;
236 my $docid = $mitem->get_docid;
237 int(($docid - 1) / $nshard) + 1;
240 sub mset_to_artnums {
241 my ($self, $mset) = @_;
242 my $nshard = $self->{nshard} // 1;
243 [ map { mdocid($nshard, $_) } $mset->items ];
248 $self->{xdb} //= do {
256 if ($self->{ibx_ver} == 1) {
257 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
259 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
264 my ($class, $ibx) = @_;
265 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
267 xpfx => $ibx->{inboxdir}, # for xpfx_init
268 altid => $ibx->{altid},
269 ibx_ver => $ibx->version,
277 if (my $xdb = $self->{xdb}) {
280 $self; # make chaining easier
285 my ($self, $query_string, $opts) = @_;
287 my $qp = $self->{qp} //= qparse_new($self);
288 my $query = $qp->parse_query($query_string, $self->{qp_flags});
289 $opts->{relevance} = 1 unless exists $opts->{relevance};
290 _do_enquire($self, $query, $opts);
294 my ($self, $cb, @arg) = @_;
298 eval { @ret = $cb->($self, @arg) };
299 return @ret unless $@;
302 eval { $ret = $cb->($self, @arg) };
303 return $ret unless $@;
305 # Exception: The revision being read has been discarded -
306 # you should call Xapian::Database::reopen()
307 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
308 warn "reopen try #$i on $@\n";
311 # let caller decide how to spew, because ExtMsg queries
312 # get wonky and trigger:
313 # "something terrible happened at .../Xapian/Enquire.pm"
317 die "Too many Xapian database modifications in progress\n";
321 my ($self, $query, $opts) = @_;
322 retry_reopen($self, \&_enquire_once, $query, $opts);
325 # returns true if all docs have the THREADID value
326 sub has_threadid ($) {
328 (xdb($self)->get_metadata('has_threadid') // '') eq '1';
331 sub _enquire_once { # retry_reopen callback
332 my ($self, $query, $opts) = @_;
333 my $xdb = xdb($self);
334 my $enquire = $X{Enquire}->new($xdb);
335 $enquire->set_query($query);
337 my $desc = !$opts->{asc};
338 if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
339 $enquire->set_docid_order($ENQ_ASCENDING);
340 $enquire->set_weighting_scheme($X{BoolWeight}->new);
341 } elsif ($opts->{relevance}) {
342 $enquire->set_sort_by_relevance_then_value(TS, $desc);
344 $enquire->set_sort_by_value_then_relevance(TS, $desc);
347 # `mairix -t / --threads' or JMAP collapseThreads
348 if ($opts->{thread} && has_threadid($self)) {
349 $enquire->set_collapse_key(THREADID);
351 $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
355 my ($self, $ibx, $mset) = @_;
356 my $nshard = $self->{nshard} // 1;
358 my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
360 $order{$a->{num}} <=> $order{$b->{num}}
361 } @{$ibx->over->get_all(keys %order)};
362 wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
366 sub stemmer { $X{Stem}->new($LANG) }
372 my $xdb = xdb($self);
373 my $qp = $X{QueryParser}->new;
374 $qp->set_default_op(OP_AND());
375 $qp->set_database($xdb);
376 $qp->set_stemmer(stemmer($self));
377 $qp->set_stemming_strategy(STEM_SOME());
378 my $cb = $qp->can('set_max_wildcard_expansion') //
379 $qp->can('set_max_expansion'); # Xapian 1.5.0+
381 $cb = $qp->can('add_valuerangeprocessor') //
382 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
383 $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
384 $cb->($qp, $NVRP->new(DT, 'dt:'));
386 # for IMAP, undocumented for WWW and may be split off go away
387 $cb->($qp, $NVRP->new(BYTES, 'bytes:'));
388 $cb->($qp, $NVRP->new(TS, 'ts:'));
389 $cb->($qp, $NVRP->new(UID, 'uid:'));
391 while (my ($name, $prefix) = each %bool_pfx_external) {
392 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
395 # we do not actually create AltId objects,
396 # just parse the spec to avoid the extra DB handles for now.
397 if (my $altid = $self->{altid}) {
398 my $user_pfx = $self->{-user_pfx} = [];
400 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
401 # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
402 # and '_' with prefixes matching \w+
403 /\Aserial:(\w+):/ or next;
405 push @$user_pfx, "$pfx:", <<EOF;
406 alternate serial number e.g. $pfx:12345 (boolean)
409 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
414 while (my ($name, $prefix) = each %prob_prefix) {
415 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
422 $self->{qp} //= qparse_new($self); # parse altids
424 if (my $user_pfx = $self->{-user_pfx}) {
425 push @ret, @$user_pfx;