]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
imap: wire up Xapian, MSN SEARCH and multi sequence-sets
[public-inbox.git] / lib / PublicInbox / Search.pm
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
4 #
5 # Read-only search interface for use by the web and NNTP interfaces
6 package PublicInbox::Search;
7 use strict;
8
9 # values for searching
10 use constant {
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
16         # TODO
17         # REPLYCNT => 4, # IMAP ANSWERED
18 };
19
20 use PublicInbox::Smsg;
21 use PublicInbox::Over;
22 my $QP_FLAGS;
23 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
24                         NumberValueRangeProcessor QueryParser Stem);
25 our $Xap; # 'Search::Xapian' or 'Xapian'
26 my $ENQ_ASCENDING;
27
28 sub load_xapian () {
29         return 1 if defined $Xap;
30         for my $x (qw(Search::Xapian Xapian)) {
31                 eval "require $x";
32                 next if $@;
33
34                 $x->import(qw(:standard));
35                 $Xap = $x;
36                 $X{$_} = $Xap.'::'.$_ for (keys %X);
37
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
40                 # just an integer:
41                 $ENQ_ASCENDING = $x eq 'Xapian' ?
42                                 1 : Search::Xapian::ENQ_ASCENDING();
43
44                 # for Smsg:
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() |
54                                 FLAG_WILDCARD();
55                 return 1;
56         }
57         undef;
58 }
59
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';
63
64 use constant {
65         # SCHEMA_VERSION history
66         # 0 - initial
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
85         #
86         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
87         #      * "lid:" and "l:" for List-Id searches
88         SCHEMA_VERSION => 15,
89 };
90
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 <>
96         dfpre => 'XDFPRE',
97         dfpost => 'XDFPOST',
98         dfblob => 'XDFPRE XDFPOST',
99 );
100
101 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
102 my %prob_prefix = (
103         # for mairix compatibility
104         s => 'S',
105         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
106         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
107         f => 'A',
108         t => 'XTO',
109         tc => 'XTO XCC',
110         c => 'XCC',
111         tcf => 'XTO XCC A',
112         a => 'XTO XCC A',
113         b => $non_quoted_body . ' XQUOT',
114         bs => $non_quoted_body . ' XQUOT S',
115         n => 'XFN',
116
117         q => 'XQUOT',
118         nq => $non_quoted_body,
119         dfn => 'XDFN',
120         dfa => 'XDFA',
121         dfb => 'XDFB',
122         dfhh => 'XDFHH',
123         dfctx => 'XDFCTX',
124
125         # default:
126         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
127 );
128
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
132 # headers, either
133 our @HELP = (
134         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
135         'd:' => <<EOF,
136 date range as YYYYMMDD  e.g. d:19931002..20101002
137 Open-ended ranges such as d:19931002.. and d:..20101002
138 are also supported
139 EOF
140         'dt:' => <<EOF,
141 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
142 EOF
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',
162 );
163 chomp @HELP;
164
165 sub xdir ($;$) {
166         my ($self, $rdonly) = @_;
167         if ($self->{ibx_ver} == 1) {
168                 "$self->{inboxdir}/public-inbox/xapian" . SCHEMA_VERSION;
169         } else {
170                 my $dir = "$self->{inboxdir}/xap" . SCHEMA_VERSION;
171                 return $dir if $rdonly;
172
173                 my $shard = $self->{shard};
174                 defined $shard or die "shard not given";
175                 $dir .= "/$shard";
176         }
177 }
178
179 sub _xdb ($) {
180         my ($self) = @_;
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) {
185                 my $n = 0;
186                 foreach my $shard (<$dir/*>) {
187                         -d $shard && $shard =~ m!/[0-9]+\z! or next;
188                         my $sub = $X{Database}->new($shard);
189                         if ($xdb) {
190                                 $xdb->add_database($sub);
191                         } else {
192                                 $xdb = $sub;
193                         }
194                         $slow_phrase ||= -f "$shard/iamchert";
195                         ++$n;
196                 }
197                 $self->{nshard} = $n;
198         } else {
199                 $slow_phrase = -f "$dir/iamchert";
200                 $xdb = $X{Database}->new($dir);
201         }
202         $$qpf |= FLAG_PHRASE() unless $slow_phrase;
203         $xdb;
204 }
205
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
209 sub mdocid {
210         my ($nshard, $mitem) = @_;
211         my $docid = $mitem->get_docid;
212         int(($docid - 1) / $nshard) + 1;
213 }
214
215 sub xdb ($) {
216         my ($self) = @_;
217         $self->{xdb} ||= do {
218                 load_xapian();
219                 _xdb($self);
220         };
221 }
222
223 sub new {
224         my ($class, $ibx) = @_;
225         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
226         my $self = bless {
227                 inboxdir => $ibx->{inboxdir},
228                 altid => $ibx->{altid},
229                 ibx_ver => $ibx->version,
230         }, $class;
231         my $dir = xdir($self, 1);
232         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
233         $self;
234 }
235
236 sub reopen {
237         my ($self) = @_;
238         if (my $xdb = $self->{xdb}) {
239                 $xdb->reopen;
240         }
241         $self; # make chaining easier
242 }
243
244 # read-only
245 sub query {
246         my ($self, $query_string, $opts) = @_;
247         $opts ||= {};
248         if ($query_string eq '' && !$opts->{mset}) {
249                 $self->{over_ro}->recent($opts);
250         } else {
251                 my $qp = qp($self);
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);
256         }
257 }
258
259 sub retry_reopen {
260         my ($self, $cb, $arg) = @_;
261         for my $i (1..10) {
262                 if (wantarray) {
263                         my @ret;
264                         eval { @ret = $cb->($arg) };
265                         return @ret unless $@;
266                 } else {
267                         my $ret;
268                         eval { $ret = $cb->($arg) };
269                         return $ret unless $@;
270                 }
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";
275                         reopen($self);
276                 } else {
277                         # let caller decide how to spew, because ExtMsg queries
278                         # get wonky and trigger:
279                         # "something terrible happened at .../Xapian/Enquire.pm"
280                         die;
281                 }
282         }
283         die "Too many Xapian database modifications in progress\n";
284 }
285
286 sub _do_enquire {
287         my ($self, $query, $opts) = @_;
288         retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
289 }
290
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);
296         $opts ||= {};
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);
303         } else {
304                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
305         }
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;
312
313         ($mset->get_matches_estimated, \@msgs)
314 }
315
316 # read-write
317 sub stemmer { $X{Stem}->new($LANG) }
318
319 # read-only
320 sub qp {
321         my ($self) = @_;
322
323         my $qp = $self->{query_parser};
324         return $qp if $qp;
325         my $xdb = xdb($self);
326         # new parser
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:'));
336
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:'));
341
342         while (my ($name, $prefix) = each %bool_pfx_external) {
343                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
344         }
345
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} = [];
350                 for (@$altid) {
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;
355                         my $pfx = $1;
356                         push @$user_pfx, "$pfx:", <<EOF;
357 alternate serial number  e.g. $pfx:12345 (boolean)
358 EOF
359                         # gmane => XGMANE
360                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
361                 }
362                 chomp @$user_pfx;
363         }
364
365         while (my ($name, $prefix) = each %prob_prefix) {
366                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
367         }
368
369         $self->{query_parser} = $qp;
370 }
371
372 sub help {
373         my ($self) = @_;
374         $self->qp; # parse altids
375         my @ret = @HELP;
376         if (my $user_pfx = $self->{-user_pfx}) {
377                 push @ret, @$user_pfx;
378         }
379         \@ret;
380 }
381
382 1;