]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
bca2036cae6778d4bc76ba18a8019603e830a689
[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);
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 our $ENQ_ASCENDING;
62
63 sub load_xapian () {
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') {
69                 eval "require $x";
70                 next if $@;
71
72                 $x->import(qw(:standard));
73                 $Xap = $x;
74
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()'));
78
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);
86
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
89                 # just an integer:
90                 $ENQ_ASCENDING = $x eq 'Xapian' ?
91                                 1 : Search::Xapian::ENQ_ASCENDING();
92
93                 *sortable_serialise = $x.'::sortable_serialise';
94                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
95                 # website as it could become a denial-of-service vector
96                 # FLAG_PHRASE also seems to cause performance problems chert
97                 # (and probably earlier Xapian DBs).  glass seems fine...
98                 # TODO: make this an option, maybe?
99                 # or make indexlevel=medium as default
100                 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
101                                 FLAG_WILDCARD();
102                 return 1;
103         }
104         undef;
105 }
106
107 # This is English-only, everything else is non-standard and may be confused as
108 # a prefix common in patch emails
109 our $LANG = 'english';
110
111 # note: the non-X term prefix allocations are shared with
112 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
113 my %bool_pfx_external = (
114         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
115         lid => 'G', # newsGroup (or similar entity), just inside <>
116         dfpre => 'XDFPRE',
117         dfpost => 'XDFPOST',
118         dfblob => 'XDFPRE XDFPOST',
119 );
120
121 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
122 my %prob_prefix = (
123         # for mairix compatibility
124         s => 'S',
125         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
126         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
127         f => 'A',
128         t => 'XTO',
129         tc => 'XTO XCC',
130         c => 'XCC',
131         tcf => 'XTO XCC A',
132         a => 'XTO XCC A',
133         b => $non_quoted_body . ' XQUOT',
134         bs => $non_quoted_body . ' XQUOT S',
135         n => 'XFN',
136
137         q => 'XQUOT',
138         nq => $non_quoted_body,
139         dfn => 'XDFN',
140         dfa => 'XDFA',
141         dfb => 'XDFB',
142         dfhh => 'XDFHH',
143         dfctx => 'XDFCTX',
144
145         # default:
146         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
147 );
148
149 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
150 # not documenting lid: for now, either, it is probably redundant with l:,
151 # especially since we don't offer boolean searches for To/Cc/From
152 # headers, either
153 our @HELP = (
154         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
155         'd:' => <<EOF,
156 date range as YYYYMMDD  e.g. d:19931002..20101002
157 Open-ended ranges such as d:19931002.. and d:..20101002
158 are also supported
159 EOF
160         'dt:' => <<EOF,
161 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
162 EOF
163         'b:' => 'match within message body, including text attachments',
164         'nq:' => 'match non-quoted text within message body',
165         'q:' => 'match quoted text within message body',
166         'n:' => 'match filename of attachment(s)',
167         't:' => 'match within the To header',
168         'c:' => 'match within the Cc header',
169         'f:' => 'match within the From header',
170         'a:' => 'match within the To, Cc, and From headers',
171         'tc:' => 'match within the To and Cc headers',
172         'l:' => 'match contents of the List-Id header',
173         'bs:' => 'match within the Subject and body',
174         'dfn:' => 'match filename from diff',
175         'dfa:' => 'match diff removed (-) lines',
176         'dfb:' => 'match diff added (+) lines',
177         'dfhh:' => 'match diff hunk header context (usually a function name)',
178         'dfctx:' => 'match diff context lines',
179         'dfpre:' => 'match pre-image git blob ID',
180         'dfpost:' => 'match post-image git blob ID',
181         'dfblob:' => 'match either pre or post-image git blob ID',
182 );
183 chomp @HELP;
184
185 sub xdir ($;$) {
186         my ($self, $rdonly) = @_;
187         if ($rdonly || !defined($self->{shard})) {
188                 $self->{xpfx};
189         } else { # v2 only:
190                 "$self->{xpfx}/$self->{shard}";
191         }
192 }
193
194 # returns all shards as separate Xapian::Database objects w/o combining
195 sub xdb_shards_flat ($) {
196         my ($self) = @_;
197         my $xpfx = $self->{xpfx};
198         my (@xdb, $slow_phrase);
199         load_xapian();
200         if ($xpfx =~ m/xapian${\SCHEMA_VERSION}\z/) {
201                 @xdb = ($X{Database}->new($xpfx));
202                 $self->{qp_flags} |= FLAG_PHRASE() if !-f "$xpfx/iamchert";
203         } else {
204                 opendir(my $dh, $xpfx) or return (); # not initialized yet
205                 # We need numeric sorting so shard[0] is first for reading
206                 # Xapian metadata, if needed
207                 my $last = max(grep(/\A[0-9]+\z/, readdir($dh))) // return ();
208                 for (0..$last) {
209                         my $shard_dir = "$self->{xpfx}/$_";
210                         push @xdb, $X{Database}->new($shard_dir);
211                         $slow_phrase ||= -f "$shard_dir/iamchert";
212                 }
213                 $self->{qp_flags} |= FLAG_PHRASE() if !$slow_phrase;
214         }
215         @xdb;
216 }
217
218 # v2 Xapian docids don't conflict, so they're identical to
219 # NNTP article numbers and IMAP UIDs.
220 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
221 sub mdocid {
222         my ($nshard, $mitem) = @_;
223         my $docid = $mitem->get_docid;
224         int(($docid - 1) / $nshard) + 1;
225 }
226
227 sub mset_to_artnums {
228         my ($self, $mset) = @_;
229         my $nshard = $self->{nshard};
230         [ map { mdocid($nshard, $_) } $mset->items ];
231 }
232
233 sub xdb ($) {
234         my ($self) = @_;
235         $self->{xdb} //= do {
236                 $self->{qp_flags} //= $QP_FLAGS;
237                 my @xdb = $self->xdb_shards_flat or return;
238                 $self->{nshard} = scalar(@xdb);
239                 my $xdb = shift @xdb;
240                 $xdb->add_database($_) for @xdb;
241                 $xdb;
242         };
243 }
244
245 sub new {
246         my ($class, $ibx) = @_;
247         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
248         my $xap = $ibx->version > 1 ? 'xap' : 'public-inbox/xapian';
249         bless {
250                 xpfx => "$ibx->{inboxdir}/$xap" . SCHEMA_VERSION,
251                 altid => $ibx->{altid},
252         }, $class;
253 }
254
255 sub reopen {
256         my ($self) = @_;
257         if (my $xdb = $self->{xdb}) {
258                 $xdb->reopen;
259         }
260         $self; # make chaining easier
261 }
262
263 # read-only
264 sub mset {
265         my ($self, $query_string, $opts) = @_;
266         $opts ||= {};
267         my $qp = $self->{qp} //= qparse_new($self);
268         my $query = $qp->parse_query($query_string, $self->{qp_flags});
269         $opts->{relevance} = 1 unless exists $opts->{relevance};
270         _do_enquire($self, $query, $opts);
271 }
272
273 sub retry_reopen {
274         my ($self, $cb, @arg) = @_;
275         for my $i (1..10) {
276                 if (wantarray) {
277                         my @ret;
278                         eval { @ret = $cb->($self, @arg) };
279                         return @ret unless $@;
280                 } else {
281                         my $ret;
282                         eval { $ret = $cb->($self, @arg) };
283                         return $ret unless $@;
284                 }
285                 # Exception: The revision being read has been discarded -
286                 # you should call Xapian::Database::reopen()
287                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
288                         warn "reopen try #$i on $@\n";
289                         reopen($self);
290                 } else {
291                         # let caller decide how to spew, because ExtMsg queries
292                         # get wonky and trigger:
293                         # "something terrible happened at .../Xapian/Enquire.pm"
294                         die;
295                 }
296         }
297         die "Too many Xapian database modifications in progress\n";
298 }
299
300 sub _do_enquire {
301         my ($self, $query, $opts) = @_;
302         retry_reopen($self, \&_enquire_once, $query, $opts);
303 }
304
305 # returns true if all docs have the THREADID value
306 sub has_threadid ($) {
307         my ($self) = @_;
308         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
309 }
310
311 sub _enquire_once { # retry_reopen callback
312         my ($self, $query, $opts) = @_;
313         my $xdb = xdb($self);
314         if (defined(my $eidx_key = $opts->{eidx_key})) {
315                 $query = $X{Query}->new(OP_FILTER(), $query, 'O'.$eidx_key);
316         }
317         if (defined(my $uid_range = $opts->{uid_range})) {
318                 my $range = $X{Query}->new(OP_VALUE_RANGE(), UID,
319                                         sortable_serialise($uid_range->[0]),
320                                         sortable_serialise($uid_range->[1]));
321                 $query = $X{Query}->new(OP_FILTER(), $query, $range);
322         }
323         my $enquire = $X{Enquire}->new($xdb);
324         $enquire->set_query($query);
325         $opts ||= {};
326         my $desc = !$opts->{asc};
327         if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
328                 $enquire->set_docid_order($ENQ_ASCENDING);
329                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
330         } elsif ($opts->{relevance}) {
331                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
332         } else {
333                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
334         }
335
336         # `mairix -t / --threads' or JMAP collapseThreads
337         if ($opts->{thread} && has_threadid($self)) {
338                 $enquire->set_collapse_key(THREADID);
339         }
340         $enquire->get_mset($opts->{offset} || 0, $opts->{limit} || 50);
341 }
342
343 sub mset_to_smsg {
344         my ($self, $ibx, $mset) = @_;
345         my $nshard = $self->{nshard};
346         my $i = 0;
347         my %order = map { mdocid($nshard, $_) => ++$i } $mset->items;
348         my @msgs = sort {
349                 $order{$a->{num}} <=> $order{$b->{num}}
350         } @{$ibx->over->get_all(keys %order)};
351         wantarray ? ($mset->get_matches_estimated, \@msgs) : \@msgs;
352 }
353
354 # read-write
355 sub stemmer { $X{Stem}->new($LANG) }
356
357 # read-only
358 sub qparse_new ($) {
359         my ($self) = @_;
360
361         my $xdb = xdb($self);
362         my $qp = $X{QueryParser}->new;
363         $qp->set_default_op(OP_AND());
364         $qp->set_database($xdb);
365         $qp->set_stemmer(stemmer($self));
366         $qp->set_stemming_strategy(STEM_SOME());
367         my $cb = $qp->can('set_max_wildcard_expansion') //
368                 $qp->can('set_max_expansion'); # Xapian 1.5.0+
369         $cb->($qp, 100);
370         $cb = $qp->can('add_valuerangeprocessor') //
371                 $qp->can('add_rangeprocessor'); # Xapian 1.5.0+
372         $cb->($qp, $NVRP->new(YYYYMMDD, 'd:'));
373         $cb->($qp, $NVRP->new(DT, 'dt:'));
374
375         # for IMAP, undocumented for WWW and may be split off go away
376         $cb->($qp, $NVRP->new(BYTES, 'bytes:'));
377         $cb->($qp, $NVRP->new(TS, 'ts:'));
378         $cb->($qp, $NVRP->new(UID, 'uid:'));
379
380         while (my ($name, $prefix) = each %bool_pfx_external) {
381                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
382         }
383
384         # we do not actually create AltId objects,
385         # just parse the spec to avoid the extra DB handles for now.
386         if (my $altid = $self->{altid}) {
387                 my $user_pfx = $self->{-user_pfx} = [];
388                 for (@$altid) {
389                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
390                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
391                         # and '_' with prefixes matching \w+
392                         /\Aserial:(\w+):/ or next;
393                         my $pfx = $1;
394                         push @$user_pfx, "$pfx:", <<EOF;
395 alternate serial number  e.g. $pfx:12345 (boolean)
396 EOF
397                         # gmane => XGMANE
398                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
399                 }
400                 chomp @$user_pfx;
401         }
402
403         while (my ($name, $prefix) = each %prob_prefix) {
404                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
405         }
406         $qp;
407 }
408
409 sub help {
410         my ($self) = @_;
411         $self->{qp} //= qparse_new($self); # parse altids
412         my @ret = @HELP;
413         if (my $user_pfx = $self->{-user_pfx}) {
414                 push @ret, @$user_pfx;
415         }
416         \@ret;
417 }
418
419 1;