]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: remove {mset} option for ->mset method
[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 use parent qw(Exporter);
9 our @EXPORT_OK = qw(retry_reopen int_val);
10 use List::Util qw(max);
11
12 # values for searching, changing the numeric value breaks
13 # compatibility with old indices (so don't change them it)
14 use constant {
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
18
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
23
24         # TODO
25         # REPLYCNT => ?, # IMAP ANSWERED
26
27         # SCHEMA_VERSION history
28         # 0 - initial
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:
47         #
48         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
49         #      * "lid:" and "l:" for List-Id searches
50         #
51         #      v1.6.0 adds BYTES, UID and THREADID values
52         SCHEMA_VERSION => 15,
53 };
54
55 use PublicInbox::Smsg;
56 use PublicInbox::Over;
57 our $QP_FLAGS;
58 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire QueryParser Stem Query);
59 our $Xap; # 'Search::Xapian' or 'Xapian'
60 our $NVRP; # '$Xap::'.('NumberValueRangeProcessor' or 'NumberRangeProcessor')
61
62 # ENQ_DESCENDING and ENQ_ASCENDING weren't in SWIG Xapian.pm prior to 1.4.16,
63 # let's hope the ABI is stable
64 our $ENQ_DESCENDING = 0;
65 our $ENQ_ASCENDING = 1;
66
67 sub load_xapian () {
68         return 1 if defined $Xap;
69         # n.b. PI_XAPIAN is intended for development use only.  We still
70         # favor Search::Xapian since that's what's available in current
71         # Debian stable (10.x) and derived distros.
72         for my $x (($ENV{PI_XAPIAN} // 'Search::Xapian'), 'Xapian') {
73                 eval "require $x";
74                 next if $@;
75
76                 $x->import(qw(:standard));
77                 $Xap = $x;
78
79                 # `version_string' was added in Xapian 1.1
80                 my $xver = eval('v'.eval($x.'::version_string()')) //
81                                 eval('v'.eval($x.'::xapian_version_string()'));
82
83                 # NumberRangeProcessor was added in Xapian 1.3.6,
84                 # NumberValueRangeProcessor was removed for 1.5.0+,
85                 # favor the older /Value/ variant since that's what our
86                 # (currently) preferred Search::Xapian supports
87                 $NVRP = $x.'::'.($x eq 'Xapian' && $xver ge v1.5 ?
88                         'NumberRangeProcessor' : 'NumberValueRangeProcessor');
89                 $X{$_} = $Xap.'::'.$_ for (keys %X);
90
91                 *sortable_serialise = $x.'::sortable_serialise';
92                 *sortable_unserialise = $x.'::sortable_unserialise';
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() |
100                                 FLAG_WILDCARD();
101                 return 1;
102         }
103         undef;
104 }
105
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';
109
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 <>
115         dfpre => 'XDFPRE',
116         dfpost => 'XDFPOST',
117         dfblob => 'XDFPRE XDFPOST',
118 );
119
120 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
121 my %prob_prefix = (
122         # for mairix compatibility
123         s => 'S',
124         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
125         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
126         f => 'A',
127         t => 'XTO',
128         tc => 'XTO XCC',
129         c => 'XCC',
130         tcf => 'XTO XCC A',
131         a => 'XTO XCC A',
132         b => $non_quoted_body . ' XQUOT',
133         bs => $non_quoted_body . ' XQUOT S',
134         n => 'XFN',
135
136         q => 'XQUOT',
137         nq => $non_quoted_body,
138         dfn => 'XDFN',
139         dfa => 'XDFA',
140         dfb => 'XDFB',
141         dfhh => 'XDFHH',
142         dfctx => 'XDFCTX',
143
144         # default:
145         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
146 );
147
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
151 # headers, either
152 our @HELP = (
153         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
154         'd:' => <<EOF,
155 date range as YYYYMMDD  e.g. d:19931002..20101002
156 Open-ended ranges such as d:19931002.. and d:..20101002
157 are also supported
158 EOF
159         'dt:' => <<EOF,
160 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
161 EOF
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',
181 );
182 chomp @HELP;
183
184 sub xdir ($;$) {
185         my ($self, $rdonly) = @_;
186         if ($rdonly || !defined($self->{shard})) {
187                 $self->{xpfx};
188         } else { # v2 only:
189                 "$self->{xpfx}/$self->{shard}";
190         }
191 }
192
193 sub xdb_sharded {
194         my ($self) = @_;
195         opendir(my $dh, $self->{xpfx}) or return; # not initialized yet
196
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))) // return;
200         my (@xdb, $slow_phrase);
201         for (0..$last) {
202                 my $shard_dir = "$self->{xpfx}/$_";
203                 if (-d $shard_dir && -r _) {
204                         push @xdb, $X{Database}->new($shard_dir);
205                         $slow_phrase ||= -f "$shard_dir/iamchert";
206                 } else { # gaps from missing epochs throw off mdocid()
207                         warn "E: $shard_dir missing or unreadable\n";
208                         return;
209                 }
210         }
211         $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
212         $self->{nshard} = scalar(@xdb);
213         my $xdb = shift @xdb;
214         $xdb->add_database($_) for @xdb;
215         $xdb;
216 }
217
218 sub _xdb {
219         my ($self) = @_;
220         my $dir = xdir($self, 1);
221         $self->{qp_flags} //= $QP_FLAGS;
222         if ($self->{ibx_ver} >= 2) {
223                 xdb_sharded($self);
224         } else {
225                 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$dir/iamchert";
226                 $X{Database}->new($dir);
227         }
228 }
229
230 # v2 Xapian docids don't conflict, so they're identical to
231 # NNTP article numbers and IMAP UIDs.
232 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
233 sub mdocid {
234         my ($nshard, $mitem) = @_;
235         my $docid = $mitem->get_docid;
236         int(($docid - 1) / $nshard) + 1;
237 }
238
239 sub mset_to_artnums {
240         my ($self, $mset) = @_;
241         my $nshard = $self->{nshard} // 1;
242         [ map { mdocid($nshard, $_) } $mset->items ];
243 }
244
245 sub xdb ($) {
246         my ($self) = @_;
247         $self->{xdb} //= do {
248                 load_xapian();
249                 $self->_xdb;
250         };
251 }
252
253 sub xpfx_init ($) {
254         my ($self) = @_;
255         if ($self->{ibx_ver} == 1) {
256                 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
257         } else {
258                 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
259         }
260 }
261
262 sub new {
263         my ($class, $ibx) = @_;
264         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
265         my $self = bless {
266                 xpfx => $ibx->{inboxdir}, # for xpfx_init
267                 altid => $ibx->{altid},
268                 ibx_ver => $ibx->version,
269         }, $class;
270         xpfx_init($self);
271         $self;
272 }
273
274 sub reopen {
275         my ($self) = @_;
276         if (my $xdb = $self->{xdb}) {
277                 $xdb->reopen;
278         }
279         $self; # make chaining easier
280 }
281
282 # read-only
283 sub mset {
284         my ($self, $query_string, $opts) = @_;
285         $opts ||= {};
286         my $qp = $self->{qp} //= qparse_new($self);
287         my $query = $qp->parse_query($query_string, $self->{qp_flags});
288         _do_enquire($self, $query, $opts);
289 }
290
291 sub retry_reopen {
292         my ($self, $cb, @arg) = @_;
293         for my $i (1..10) {
294                 if (wantarray) {
295                         my @ret;
296                         eval { @ret = $cb->($self, @arg) };
297                         return @ret unless $@;
298                 } else {
299                         my $ret;
300                         eval { $ret = $cb->($self, @arg) };
301                         return $ret unless $@;
302                 }
303                 # Exception: The revision being read has been discarded -
304                 # you should call Xapian::Database::reopen()
305                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
306                         warn "reopen try #$i on $@\n";
307                         reopen($self);
308                 } else {
309                         # let caller decide how to spew, because ExtMsg queries
310                         # get wonky and trigger:
311                         # "something terrible happened at .../Xapian/Enquire.pm"
312                         die;
313                 }
314         }
315         die "Too many Xapian database modifications in progress\n";
316 }
317
318 sub _do_enquire {
319         my ($self, $query, $opts) = @_;
320         retry_reopen($self, \&_enquire_once, $query, $opts);
321 }
322
323 # returns true if all docs have the THREADID value
324 sub has_threadid ($) {
325         my ($self) = @_;
326         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
327 }
328
329 sub _enquire_once { # retry_reopen callback
330         my ($self, $query, $opts) = @_;
331         my $xdb = xdb($self);
332         if (defined(my $eidx_key = $opts->{eidx_key})) {
333                 $query = $X{Query}->new(OP_FILTER(), $query, 'O'.$eidx_key);
334         }
335         if (defined(my $uid_range = $opts->{uid_range})) {
336                 my $range = $X{Query}->new(OP_VALUE_RANGE(), UID,
337                                         sortable_serialise($uid_range->[0]),
338                                         sortable_serialise($uid_range->[1]));
339                 $query = $X{Query}->new(OP_FILTER(), $query, $range);
340         }
341         my $enquire = $X{Enquire}->new($xdb);
342         $enquire->set_query($query);
343         $opts ||= {};
344         my $desc = !$opts->{asc};
345         my $rel = $opts->{relevance} // 0;
346         if ($rel == -1) { # ORDER BY docid/UID
347                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
348                 $enquire->set_docid_order($ENQ_ASCENDING);
349         } elsif ($rel == 0) {
350                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
351         } elsif ($rel == -2) {
352                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
353                 $enquire->set_docid_order($ENQ_DESCENDING);
354         } else { # rel > 0
355                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
356         }
357
358         # `mairix -t / --threads' or JMAP collapseThreads
359         if ($opts->{thread} && has_threadid($self)) {
360                 $enquire->set_collapse_key(THREADID);
361         }
362         $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
363 }
364
365 sub mset_to_smsg {
366         my ($self, $ibx, $mset) = @_;
367         my $nshard = $self->{nshard} // 1;
368         my $i = 0;
369         my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
370         my @msgs = sort {
371                 $order{$a->{num}} <=> $order{$b->{num}}
372         } @{$ibx->over->get_all(keys %order)};
373         wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
374 }
375
376 # read-write
377 sub stemmer { $X{Stem}->new($LANG) }
378
379 # read-only
380 sub qparse_new ($) {
381         my ($self) = @_;
382
383         my $xdb = xdb($self);
384         my $qp = $X{QueryParser}->new;
385         $qp->set_default_op(OP_AND());
386         $qp->set_database($xdb);
387         $qp->set_stemmer(stemmer($self));
388         $qp->set_stemming_strategy(STEM_SOME());
389         my $cb = $qp->can('set_max_wildcard_expansion') //
390                 $qp->can('set_max_expansion'); # Xapian 1.5.0+
391         $cb->($qp, 100);
392         $cb = $qp->can('add_valuerangeprocessor') //
393                 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
394         $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
395         $cb->($qp, $NVRP->new(DT, 'dt:'));
396
397         # for IMAP, undocumented for WWW and may be split off go away
398         $cb->($qp, $NVRP->new(BYTES, 'bytes:'));
399         $cb->($qp, $NVRP->new(TS, 'ts:'));
400         $cb->($qp, $NVRP->new(UID, 'uid:'));
401
402         while (my ($name, $prefix) = each %bool_pfx_external) {
403                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
404         }
405
406         # we do not actually create AltId objects,
407         # just parse the spec to avoid the extra DB handles for now.
408         if (my $altid = $self->{altid}) {
409                 my $user_pfx = $self->{-user_pfx} = [];
410                 for (@$altid) {
411                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
412                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
413                         # and '_' with prefixes matching \w+
414                         /\Aserial:(\w+):/ or next;
415                         my $pfx = $1;
416                         push @$user_pfx, "$pfx:", <<EOF;
417 alternate serial number  e.g. $pfx:12345 (boolean)
418 EOF
419                         # gmane => XGMANE
420                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
421                 }
422                 chomp @$user_pfx;
423         }
424
425         while (my ($name, $prefix) = each %prob_prefix) {
426                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
427         }
428         $qp;
429 }
430
431 sub help {
432         my ($self) = @_;
433         $self->{qp} //= qparse_new($self); # parse altids
434         my @ret = @HELP;
435         if (my $user_pfx = $self->{-user_pfx}) {
436                 push @ret, @$user_pfx;
437         }
438         \@ret;
439 }
440
441 sub int_val ($$) {
442         my ($doc, $col) = @_;
443         my $val = $doc->get_value($col) or return; # undefined is '' in Xapian
444         sortable_unserialise($val) + 0; # PV => IV conversion
445 }
446
447 1;