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