]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
01bbe73de2090b4bdbd539abb109edc33bb5fece
[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
11 # values for searching, changing the numeric value breaks
12 # compatibility with old indices (so don't change them it)
13 use constant {
14         TS => 0, # Received: header in Unix time (IMAP INTERNALDATE)
15         YYYYMMDD => 1, # Date: header for searching in the WWW UI
16         DT => 2, # Date: YYYYMMDDHHMMSS
17
18         # added for public-inbox 1.6.0+
19         BYTES => 3, # IMAP RFC822.SIZE
20         UID => 4, # IMAP UID == NNTP article number == Xapian docid
21         THREADID => 5, # RFC 8474, RFC 8621
22
23         # TODO
24         # REPLYCNT => ?, # IMAP ANSWERED
25
26         # SCHEMA_VERSION history
27         # 0 - initial
28         # 1 - subject_path is lower-cased
29         # 2 - subject_path is id_compress in the index, only
30         # 3 - message-ID is compressed if it includes '%' (hack!)
31         # 4 - change "Re: " normalization, avoid circular Reference ghosts
32         # 5 - subject_path drops trailing '.'
33         # 6 - preserve References: order in document data
34         # 7 - remove references and inreplyto terms
35         # 8 - remove redundant/unneeded document data
36         # 9 - disable Message-ID compression (SHA-1)
37         # 10 - optimize doc for NNTP overviews
38         # 11 - merge threads when vivifying ghosts
39         # 12 - change YYYYMMDD value column to numeric
40         # 13 - fix threading for empty References/In-Reply-To
41         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
42         # 14 - fix ghost root vivification
43         # 15 - see public-inbox-v2-format(5)
44         #      further bumps likely unnecessary, we'll suggest in-place
45         #      "--reindex" use for further fixes and tweaks:
46         #
47         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
48         #      * "lid:" and "l:" for List-Id searches
49         #
50         #      v1.6.0 adds BYTES, UID and THREADID values
51         SCHEMA_VERSION => 15,
52 };
53
54 use PublicInbox::Smsg;
55 use PublicInbox::Over;
56 my $QP_FLAGS;
57 our %X = map { $_ => 0 } qw(BoolWeight Database Enquire
58                         NumberValueRangeProcessor QueryParser Stem);
59 our $Xap; # 'Search::Xapian' or 'Xapian'
60 my $ENQ_ASCENDING;
61
62 sub load_xapian () {
63         return 1 if defined $Xap;
64         for my $x (qw(Search::Xapian Xapian)) {
65                 eval "require $x";
66                 next if $@;
67
68                 $x->import(qw(:standard));
69                 $Xap = $x;
70                 $X{$_} = $Xap.'::'.$_ for (keys %X);
71
72                 # ENQ_ASCENDING doesn't seem exported by SWIG Xapian.pm,
73                 # so lets hope this part of the ABI is stable because it's
74                 # just an integer:
75                 $ENQ_ASCENDING = $x eq 'Xapian' ?
76                                 1 : Search::Xapian::ENQ_ASCENDING();
77
78                 # for Smsg:
79                 *PublicInbox::Smsg::sortable_unserialise =
80                                                 $Xap.'::sortable_unserialise';
81                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
82                 # website as it could become a denial-of-service vector
83                 # FLAG_PHRASE also seems to cause performance problems chert
84                 # (and probably earlier Xapian DBs).  glass seems fine...
85                 # TODO: make this an option, maybe?
86                 # or make indexlevel=medium as default
87                 $QP_FLAGS = FLAG_PHRASE() | FLAG_BOOLEAN() | FLAG_LOVEHATE() |
88                                 FLAG_WILDCARD();
89                 return 1;
90         }
91         undef;
92 }
93
94 # This is English-only, everything else is non-standard and may be confused as
95 # a prefix common in patch emails
96 our $LANG = 'english';
97
98 # note: the non-X term prefix allocations are shared with
99 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
100 my %bool_pfx_external = (
101         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
102         lid => 'G', # newsGroup (or similar entity), just inside <>
103         dfpre => 'XDFPRE',
104         dfpost => 'XDFPOST',
105         dfblob => 'XDFPRE XDFPOST',
106 );
107
108 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
109 my %prob_prefix = (
110         # for mairix compatibility
111         s => 'S',
112         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
113         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
114         f => 'A',
115         t => 'XTO',
116         tc => 'XTO XCC',
117         c => 'XCC',
118         tcf => 'XTO XCC A',
119         a => 'XTO XCC A',
120         b => $non_quoted_body . ' XQUOT',
121         bs => $non_quoted_body . ' XQUOT S',
122         n => 'XFN',
123
124         q => 'XQUOT',
125         nq => $non_quoted_body,
126         dfn => 'XDFN',
127         dfa => 'XDFA',
128         dfb => 'XDFB',
129         dfhh => 'XDFHH',
130         dfctx => 'XDFCTX',
131
132         # default:
133         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
134 );
135
136 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
137 # not documenting lid: for now, either, it is probably redundant with l:,
138 # especially since we don't offer boolean searches for To/Cc/From
139 # headers, either
140 our @HELP = (
141         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
142         'd:' => <<EOF,
143 date range as YYYYMMDD  e.g. d:19931002..20101002
144 Open-ended ranges such as d:19931002.. and d:..20101002
145 are also supported
146 EOF
147         'dt:' => <<EOF,
148 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
149 EOF
150         'b:' => 'match within message body, including text attachments',
151         'nq:' => 'match non-quoted text within message body',
152         'q:' => 'match quoted text within message body',
153         'n:' => 'match filename of attachment(s)',
154         't:' => 'match within the To header',
155         'c:' => 'match within the Cc header',
156         'f:' => 'match within the From header',
157         'a:' => 'match within the To, Cc, and From headers',
158         'tc:' => 'match within the To and Cc headers',
159         'l:' => 'match contents of the List-Id header',
160         'bs:' => 'match within the Subject and body',
161         'dfn:' => 'match filename from diff',
162         'dfa:' => 'match diff removed (-) lines',
163         'dfb:' => 'match diff added (+) lines',
164         'dfhh:' => 'match diff hunk header context (usually a function name)',
165         'dfctx:' => 'match diff context lines',
166         'dfpre:' => 'match pre-image git blob ID',
167         'dfpost:' => 'match post-image git blob ID',
168         'dfblob:' => 'match either pre or post-image git blob ID',
169 );
170 chomp @HELP;
171
172 sub xdir ($;$) {
173         my ($self, $rdonly) = @_;
174         if ($rdonly || !defined($self->{shard})) {
175                 $self->{xpfx};
176         } else { # v2 only:
177                 "$self->{xpfx}/$self->{shard}";
178         }
179 }
180
181 sub _xdb ($) {
182         my ($self) = @_;
183         my $dir = xdir($self, 1);
184         my ($xdb, $slow_phrase);
185         my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
186         if ($self->{ibx_ver} >= 2) {
187                 my @xdb;
188                 opendir(my $dh, $dir) or return; # not initialized yet
189
190                 # We need numeric sorting so shard[0] is first for reading
191                 # Xapian metadata, if needed
192                 for (sort { $a <=> $b } grep(/\A[0-9]+\z/, readdir($dh))) {
193                         my $shard_dir = "$dir/$_";
194                         if (-d $shard_dir && -r _) {
195                                 push @xdb, $X{Database}->new($shard_dir);
196                                 $slow_phrase ||= -f "$shard_dir/iamchert";
197                         } else { # gaps from missing epochs throw off mdocid()
198                                 warn "E: $shard_dir missing or unreadable\n";
199                                 return;
200                         }
201                 }
202                 $self->{nshard} = scalar(@xdb);
203                 $xdb = shift @xdb;
204                 $xdb->add_database($_) for @xdb;
205         } else {
206                 $slow_phrase = -f "$dir/iamchert";
207                 $xdb = $X{Database}->new($dir);
208         }
209         $$qpf |= FLAG_PHRASE() unless $slow_phrase;
210         $xdb;
211 }
212
213 # v2 Xapian docids don't conflict, so they're identical to
214 # NNTP article numbers and IMAP UIDs.
215 # https://trac.xapian.org/wiki/FAQ/MultiDatabaseDocumentID
216 sub mdocid {
217         my ($nshard, $mitem) = @_;
218         my $docid = $mitem->get_docid;
219         int(($docid - 1) / $nshard) + 1;
220 }
221
222 sub mset_to_artnums {
223         my ($self, $mset) = @_;
224         my $nshard = $self->{nshard} // 1;
225         [ map { mdocid($nshard, $_) } $mset->items ];
226 }
227
228 sub xdb ($) {
229         my ($self) = @_;
230         $self->{xdb} ||= do {
231                 load_xapian();
232                 _xdb($self);
233         };
234 }
235
236 sub xpfx_init ($) {
237         my ($self) = @_;
238         if ($self->{ibx_ver} == 1) {
239                 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
240         } else {
241                 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
242         }
243 }
244
245 sub new {
246         my ($class, $ibx) = @_;
247         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
248         my $self = bless {
249                 xpfx => $ibx->{inboxdir}, # for xpfx_init
250                 altid => $ibx->{altid},
251                 ibx_ver => $ibx->version,
252         }, $class;
253         xpfx_init($self);
254         my $dir = xdir($self, 1);
255         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
256         $self;
257 }
258
259 sub reopen {
260         my ($self) = @_;
261         if (my $xdb = $self->{xdb}) {
262                 $xdb->reopen;
263         }
264         $self; # make chaining easier
265 }
266
267 # read-only
268 sub query {
269         my ($self, $query_string, $opts) = @_;
270         $opts ||= {};
271         if ($query_string eq '' && !$opts->{mset}) {
272                 $self->{over_ro}->recent($opts);
273         } else {
274                 my $qp = $self->{qp} //= qparse_new($self);
275                 my $qp_flags = $self->{qp_flags};
276                 my $query = $qp->parse_query($query_string, $qp_flags);
277                 $opts->{relevance} = 1 unless exists $opts->{relevance};
278                 _do_enquire($self, $query, $opts);
279         }
280 }
281
282 sub retry_reopen {
283         my ($self, $cb, $arg) = @_;
284         for my $i (1..10) {
285                 if (wantarray) {
286                         my @ret;
287                         eval { @ret = $cb->($arg) };
288                         return @ret unless $@;
289                 } else {
290                         my $ret;
291                         eval { $ret = $cb->($arg) };
292                         return $ret unless $@;
293                 }
294                 # Exception: The revision being read has been discarded -
295                 # you should call Xapian::Database::reopen()
296                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
297                         warn "reopen try #$i on $@\n";
298                         reopen($self);
299                 } else {
300                         # let caller decide how to spew, because ExtMsg queries
301                         # get wonky and trigger:
302                         # "something terrible happened at .../Xapian/Enquire.pm"
303                         die;
304                 }
305         }
306         die "Too many Xapian database modifications in progress\n";
307 }
308
309 sub _do_enquire {
310         my ($self, $query, $opts) = @_;
311         retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
312 }
313
314 # returns true if all docs have the THREADID value
315 sub has_threadid ($) {
316         my ($self) = @_;
317         (xdb($self)->get_metadata('has_threadid') // '') eq '1';
318 }
319
320 sub _enquire_once { # retry_reopen callback
321         my ($self, $query, $opts) = @{$_[0]};
322         my $xdb = xdb($self);
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
341         my $offset = $opts->{offset} || 0;
342         my $limit = $opts->{limit} || 50;
343         my $mset = $enquire->get_mset($offset, $limit);
344         return $mset if $opts->{mset};
345         my $nshard = $self->{nshard} // 1;
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         } @{$self->{over_ro}->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         $qp->set_max_wildcard_expansion(100);
368         my $nvrp = $X{NumberValueRangeProcessor};
369         $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
370         $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
371
372         # for IMAP, undocumented for WWW and may be split off go away
373         $qp->add_valuerangeprocessor($nvrp->new(BYTES, 'bytes:'));
374         $qp->add_valuerangeprocessor($nvrp->new(TS, 'ts:'));
375         $qp->add_valuerangeprocessor($nvrp->new(UID, 'uid:'));
376
377         while (my ($name, $prefix) = each %bool_pfx_external) {
378                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
379         }
380
381         # we do not actually create AltId objects,
382         # just parse the spec to avoid the extra DB handles for now.
383         if (my $altid = $self->{altid}) {
384                 my $user_pfx = $self->{-user_pfx} = [];
385                 for (@$altid) {
386                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
387                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
388                         # and '_' with prefixes matching \w+
389                         /\Aserial:(\w+):/ or next;
390                         my $pfx = $1;
391                         push @$user_pfx, "$pfx:", <<EOF;
392 alternate serial number  e.g. $pfx:12345 (boolean)
393 EOF
394                         # gmane => XGMANE
395                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
396                 }
397                 chomp @$user_pfx;
398         }
399
400         while (my ($name, $prefix) = each %prob_prefix) {
401                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
402         }
403         $qp;
404 }
405
406 sub help {
407         my ($self) = @_;
408         $self->{qp} //= qparse_new($self); # parse altids
409         my @ret = @HELP;
410         if (my $user_pfx = $self->{-user_pfx}) {
411                 push @ret, @$user_pfx;
412         }
413         \@ret;
414 }
415
416 1;