]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
4d02a7c169c202ebd150ccd1e0158ab21939c56a
[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 ($rdonly || !defined($self->{shard})) {
168                 $self->{xpfx};
169         } else { # v2 only:
170                 "$self->{xpfx}/$self->{shard}";
171         }
172 }
173
174 sub _xdb ($) {
175         my ($self) = @_;
176         my $dir = xdir($self, 1);
177         my ($xdb, $slow_phrase);
178         my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
179         if ($self->{ibx_ver} >= 2) {
180                 my @xdb;
181                 opendir(my $dh, $dir) or return; # not initialized yet
182
183                 # We need numeric sorting so shard[0] is first for reading
184                 # Xapian metadata, if needed
185                 for (sort { $a <=> $b } grep(/\A[0-9]+\z/, readdir($dh))) {
186                         my $shard_dir = "$dir/$_";
187                         if (-d $shard_dir && -r _) {
188                                 push @xdb, $X{Database}->new($shard_dir);
189                                 $slow_phrase ||= -f "$shard_dir/iamchert";
190                         } else { # gaps from missing epochs throw off mdocid()
191                                 warn "E: $shard_dir missing or unreadable\n";
192                                 return;
193                         }
194                 }
195                 $self->{nshard} = scalar(@xdb);
196                 $xdb = shift @xdb;
197                 $xdb->add_database($_) for @xdb;
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 xpfx_init ($) {
224         my ($self) = @_;
225         if ($self->{ibx_ver} == 1) {
226                 $self->{xpfx} .= '/public-inbox/xapian' . SCHEMA_VERSION;
227         } else {
228                 $self->{xpfx} .= '/xap'.SCHEMA_VERSION;
229         }
230 }
231
232 sub new {
233         my ($class, $ibx) = @_;
234         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
235         my $self = bless {
236                 xpfx => $ibx->{inboxdir}, # for xpfx_init
237                 altid => $ibx->{altid},
238                 ibx_ver => $ibx->version,
239         }, $class;
240         xpfx_init($self);
241         my $dir = xdir($self, 1);
242         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
243         $self;
244 }
245
246 sub reopen {
247         my ($self) = @_;
248         if (my $xdb = $self->{xdb}) {
249                 $xdb->reopen;
250         }
251         $self; # make chaining easier
252 }
253
254 # read-only
255 sub query {
256         my ($self, $query_string, $opts) = @_;
257         $opts ||= {};
258         if ($query_string eq '' && !$opts->{mset}) {
259                 $self->{over_ro}->recent($opts);
260         } else {
261                 my $qp = qp($self);
262                 my $qp_flags = $self->{qp_flags};
263                 my $query = $qp->parse_query($query_string, $qp_flags);
264                 $opts->{relevance} = 1 unless exists $opts->{relevance};
265                 _do_enquire($self, $query, $opts);
266         }
267 }
268
269 sub retry_reopen {
270         my ($self, $cb, $arg) = @_;
271         for my $i (1..10) {
272                 if (wantarray) {
273                         my @ret;
274                         eval { @ret = $cb->($arg) };
275                         return @ret unless $@;
276                 } else {
277                         my $ret;
278                         eval { $ret = $cb->($arg) };
279                         return $ret unless $@;
280                 }
281                 # Exception: The revision being read has been discarded -
282                 # you should call Xapian::Database::reopen()
283                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
284                         warn "reopen try #$i on $@\n";
285                         reopen($self);
286                 } else {
287                         # let caller decide how to spew, because ExtMsg queries
288                         # get wonky and trigger:
289                         # "something terrible happened at .../Xapian/Enquire.pm"
290                         die;
291                 }
292         }
293         die "Too many Xapian database modifications in progress\n";
294 }
295
296 sub _do_enquire {
297         my ($self, $query, $opts) = @_;
298         retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
299 }
300
301 sub _enquire_once { # retry_reopen callback
302         my ($self, $query, $opts) = @{$_[0]};
303         my $xdb = xdb($self);
304         my $enquire = $X{Enquire}->new($xdb);
305         $enquire->set_query($query);
306         $opts ||= {};
307         my $desc = !$opts->{asc};
308         if (($opts->{mset} || 0) == 2) { # mset == 2: ORDER BY docid/UID
309                 $enquire->set_docid_order($ENQ_ASCENDING);
310                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
311         } elsif ($opts->{relevance}) {
312                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
313         } else {
314                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
315         }
316         my $offset = $opts->{offset} || 0;
317         my $limit = $opts->{limit} || 50;
318         my $mset = $enquire->get_mset($offset, $limit);
319         return $mset if $opts->{mset};
320         my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
321         return \@msgs unless wantarray;
322
323         ($mset->get_matches_estimated, \@msgs)
324 }
325
326 # read-write
327 sub stemmer { $X{Stem}->new($LANG) }
328
329 # read-only
330 sub qp {
331         my ($self) = @_;
332
333         my $qp = $self->{query_parser};
334         return $qp if $qp;
335         my $xdb = xdb($self);
336         # new parser
337         $qp = $X{QueryParser}->new;
338         $qp->set_default_op(OP_AND());
339         $qp->set_database($xdb);
340         $qp->set_stemmer($self->stemmer);
341         $qp->set_stemming_strategy(STEM_SOME());
342         $qp->set_max_wildcard_expansion(100);
343         my $nvrp = $X{NumberValueRangeProcessor};
344         $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
345         $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
346
347         # for IMAP, undocumented for WWW and may be split off go away
348         $qp->add_valuerangeprocessor($nvrp->new(BYTES, 'bytes:'));
349         $qp->add_valuerangeprocessor($nvrp->new(TS, 'ts:'));
350         $qp->add_valuerangeprocessor($nvrp->new(UID, 'uid:'));
351
352         while (my ($name, $prefix) = each %bool_pfx_external) {
353                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
354         }
355
356         # we do not actually create AltId objects,
357         # just parse the spec to avoid the extra DB handles for now.
358         if (my $altid = $self->{altid}) {
359                 my $user_pfx = $self->{-user_pfx} = [];
360                 for (@$altid) {
361                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
362                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
363                         # and '_' with prefixes matching \w+
364                         /\Aserial:(\w+):/ or next;
365                         my $pfx = $1;
366                         push @$user_pfx, "$pfx:", <<EOF;
367 alternate serial number  e.g. $pfx:12345 (boolean)
368 EOF
369                         # gmane => XGMANE
370                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
371                 }
372                 chomp @$user_pfx;
373         }
374
375         while (my ($name, $prefix) = each %prob_prefix) {
376                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
377         }
378
379         $self->{query_parser} = $qp;
380 }
381
382 sub help {
383         my ($self) = @_;
384         $self->qp; # parse altids
385         my @ret = @HELP;
386         if (my $user_pfx = $self->{-user_pfx}) {
387                 push @ret, @$user_pfx;
388         }
389         \@ret;
390 }
391
392 1;