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;
9 # values for searching, changing the numeric value breaks
10 # compatibility with old indices (so don't change them it)
12 TS => 0, # Received: header in Unix time (IMAP INTERNALDATE)
13 YYYYMMDD => 1, # Date: header for searching in the WWW UI
14 DT => 2, # Date: YYYYMMDDHHMMSS
16 # added for public-inbox 1.6.0+
17 BYTES => 3, # IMAP RFC822.SIZE
18 UID => 4, # IMAP UID == NNTP article number == Xapian docid
22 # REPLYCNT => ?, # IMAP ANSWERED
24 # SCHEMA_VERSION history
26 # 1 - subject_path is lower-cased
27 # 2 - subject_path is id_compress in the index, only
28 # 3 - message-ID is compressed if it includes '%' (hack!)
29 # 4 - change "Re: " normalization, avoid circular Reference ghosts
30 # 5 - subject_path drops trailing '.'
31 # 6 - preserve References: order in document data
32 # 7 - remove references and inreplyto terms
33 # 8 - remove redundant/unneeded document data
34 # 9 - disable Message-ID compression (SHA-1)
35 # 10 - optimize doc for NNTP overviews
36 # 11 - merge threads when vivifying ghosts
37 # 12 - change YYYYMMDD value column to numeric
38 # 13 - fix threading for empty References/In-Reply-To
39 # (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
40 # 14 - fix ghost root vivification
41 # 15 - see public-inbox-v2-format(5)
42 # further bumps likely unnecessary, we'll suggest in-place
43 # "--reindex" use for further fixes and tweaks:
45 # public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
46 # * "lid:" and "l:" for List-Id searches
48 # v1.6.0 adds BYTES and UID values
52 use PublicInbox::Smsg;
53 use PublicInbox::Over;
55 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
56 NumberValueRangeProcessor QueryParser Stem);
57 our $Xap; # 'Search::Xapian' or 'Xapian'
61 return 1 if defined $Xap;
62 for my $x (qw(Search::Xapian Xapian)) {
66 $x->import(qw(:standard));
68 $X{$_} = $Xap.'::'.$_ for (keys %X);
70 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
71 # so lets hope this part of the ABI is stable because it's
73 $ENQ_ASCENDING = $x eq 'Xapian' ?
74 1 : Search::Xapian::ENQ_ASCENDING();
77 *PublicInbox::Smsg::sortable_unserialise =
78 $Xap.'::sortable_unserialise';
79 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
80 # website as it could become a denial-of-service vector
81 # FLAG_PHRASE also seems to cause performance problems chert
82 # (and probably earlier Xapian DBs). glass seems fine...
83 # TODO: make this an option, maybe?
84 # or make indexlevel=medium as default
85 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
92 # This is English-only, everything else is non-standard and may be confused as
93 # a prefix common in patch emails
94 our $LANG = 'english';
96 # note: the non-X term prefix allocations are shared with
97 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
98 my %bool_pfx_external = (
99 mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
100 lid => 'G', # newsGroup (or similar entity), just inside <>
103 dfblob => 'XDFPRE XDFPOST',
106 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
108 # for mairix compatibility
110 m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
111 l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
118 b => $non_quoted_body . ' XQUOT',
119 bs => $non_quoted_body . ' XQUOT S',
123 nq => $non_quoted_body,
131 '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
134 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
135 # not documenting lid: for now, either, it is probably redundant with l:,
136 # especially since we don't offer boolean searches for To/Cc/From
139 's:' => 'match within Subject e.g. s:"a quick brown fox"',
141 date range as YYYYMMDD e.g. d:19931002..20101002
142 Open-ended ranges such as d:19931002.. and d:..20101002
146 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
148 'b:' => 'match within message body, including text attachments',
149 'nq:' => 'match non-quoted text within message body',
150 'q:' => 'match quoted text within message body',
151 'n:' => 'match filename of attachment(s)',
152 't:' => 'match within the To header',
153 'c:' => 'match within the Cc header',
154 'f:' => 'match within the From header',
155 'a:' => 'match within the To, Cc, and From headers',
156 'tc:' => 'match within the To and Cc headers',
157 'l:' => 'match contents of the List-Id header',
158 'bs:' => 'match within the Subject and body',
159 'dfn:' => 'match filename from diff',
160 'dfa:' => 'match diff removed (-) lines',
161 'dfb:' => 'match diff added (+) lines',
162 'dfhh:' => 'match diff hunk header context (usually a function name)',
163 'dfctx:' => 'match diff context lines',
164 'dfpre:' => 'match pre-image git blob ID',
165 'dfpost:' => 'match post-image git blob ID',
166 'dfblob:' => 'match either pre or post-image git blob ID',
171 my ($self, $rdonly) = @_;
172 if ($rdonly || !defined($self->{shard})) {
175 "$self->{xpfx}/$self->{shard}";
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 opendir(my $dh, $dir) or return; # not initialized yet
188 # We need numeric sorting so shard[0] is first for reading
189 # Xapian metadata, if needed
190 for (sort { $a <=> $b } grep(/\A[0-9]+\z/, readdir($dh))) {
191 my $shard_dir = "$dir/$_";
192 if (-d $shard_dir && -r _) {
193 push @xdb, $X{Database}->new($shard_dir);
194 $slow_phrase ||= -f "$shard_dir/iamchert";
195 } else { # gaps from missing epochs throw off mdocid()
196 warn "E: $shard_dir missing or unreadable\n";
200 $self->{nshard} = scalar(@xdb);
202 $xdb->add_database($_) for @xdb;
204 $slow_phrase = -f "$dir/iamchert";
205 $xdb = $X{Database}->new($dir);
207 $$qpf |= FLAG_PHRASE() unless $slow_phrase;
211 # v2 Xapian docids don't conflict, so they're identical to
212 # NNTP article numbers and IMAP UIDs.
213 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
215 my ($nshard, $mitem) = @_;
216 my $docid = $mitem->get_docid;
217 int(($docid - 1) / $nshard) + 1;
222 $self->{xdb} ||= do {
230 if ($self->{ibx_ver} == 1) {
231 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
233 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
238 my ($class, $ibx) = @_;
239 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
241 xpfx => $ibx->{inboxdir}, # for xpfx_init
242 altid => $ibx->{altid},
243 ibx_ver => $ibx->version,
246 my $dir = xdir($self, 1);
247 $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
253 if (my $xdb = $self->{xdb}) {
256 $self; # make chaining easier
261 my ($self, $query_string, $opts) = @_;
263 if ($query_string eq '' && !$opts->{mset}) {
264 $self->{over_ro}->recent($opts);
267 my $qp_flags = $self->{qp_flags};
268 my $query = $qp->parse_query($query_string, $qp_flags);
269 $opts->{relevance} = 1 unless exists $opts->{relevance};
270 _do_enquire($self, $query, $opts);
275 my ($self, $cb, $arg) = @_;
279 eval { @ret = $cb->($arg) };
280 return @ret unless $@;
283 eval { $ret = $cb->($arg) };
284 return $ret unless $@;
286 # Exception: The revision being read has been discarded -
287 # you should call Xapian::Database::reopen()
288 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
289 warn "reopen try #$i on $@\n";
292 # let caller decide how to spew, because ExtMsg queries
293 # get wonky and trigger:
294 # "something terrible happened at .../Xapian/Enquire.pm"
298 die "Too many Xapian database modifications in progress\n";
302 my ($self, $query, $opts) = @_;
303 retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
306 sub _enquire_once { # retry_reopen callback
307 my ($self, $query, $opts) = @{$_[0]};
308 my $xdb = xdb($self);
309 my $enquire = $X{Enquire}->new($xdb);
310 $enquire->set_query($query);
312 my $desc = !$opts->{asc};
313 if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
314 $enquire->set_docid_order($ENQ_ASCENDING);
315 $enquire->set_weighting_scheme($X{BoolWeight}->new);
316 } elsif ($opts->{relevance}) {
317 $enquire->set_sort_by_relevance_then_value(TS, $desc);
319 $enquire->set_sort_by_value_then_relevance(TS, $desc);
321 my $offset = $opts->{offset} || 0;
322 my $limit = $opts->{limit} || 50;
323 my $mset = $enquire->get_mset($offset, $limit);
324 return $mset if $opts->{mset};
325 my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
326 return \@msgs unless wantarray;
328 ($mset->get_matches_estimated, \@msgs)
332 sub stemmer { $X{Stem}->new($LANG) }
338 my $qp = $self->{query_parser};
340 my $xdb = xdb($self);
342 $qp = $X{QueryParser}->new;
343 $qp->set_default_op(OP_AND());
344 $qp->set_database($xdb);
345 $qp->set_stemmer($self->stemmer);
346 $qp->set_stemming_strategy(STEM_SOME());
347 $qp->set_max_wildcard_expansion(100);
348 my $nvrp = $X{NumberValueRangeProcessor};
349 $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
350 $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
352 # for IMAP, undocumented for WWW and may be split off go away
353 $qp->add_valuerangeprocessor($nvrp->new(BYTES, 'bytes:'));
354 $qp->add_valuerangeprocessor($nvrp->new(TS, 'ts:'));
355 $qp->add_valuerangeprocessor($nvrp->new(UID, 'uid:'));
357 while (my ($name, $prefix) = each %bool_pfx_external) {
358 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
361 # we do not actually create AltId objects,
362 # just parse the spec to avoid the extra DB handles for now.
363 if (my $altid = $self->{altid}) {
364 my $user_pfx = $self->{-user_pfx} = [];
366 # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
367 # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
368 # and '_' with prefixes matching \w+
369 /\Aserial:(\w+):/ or next;
371 push @$user_pfx, "$pfx:", <<EOF;
372 alternate serial number e.g. $pfx:12345 (boolean)
375 $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
380 while (my ($name, $prefix) = each %prob_prefix) {
381 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
384 $self->{query_parser} = $qp;
389 $self->qp; # parse altids
391 if (my $user_pfx = $self->{-user_pfx}) {
392 push @ret, @$user_pfx;