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