]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
www: favor reading more from SQLite, and less from Xapian
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2018 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 warnings;
9
10 # values for searching
11 use constant TS => 0;  # Received: header in Unix time
12 use constant YYYYMMDD => 1; # Date: header for searching in the WWW UI
13 use constant DT => 2; # Date: YYYYMMDDHHMMSS
14
15 use Search::Xapian qw/:standard/;
16 use PublicInbox::SearchMsg;
17 use PublicInbox::MIME;
18 use PublicInbox::MID qw/id_compress/;
19 use PublicInbox::Over;
20
21 # This is English-only, everything else is non-standard and may be confused as
22 # a prefix common in patch emails
23 our $REPLY_RE = qr/^re:\s+/i;
24 our $LANG = 'english';
25
26 use constant {
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         SCHEMA_VERSION => 15,
45
46         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
47         # as it could become a denial-of-service vector
48         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
49 };
50
51 my %bool_pfx_external = (
52         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
53 );
54
55 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
56 my %prob_prefix = (
57         # for mairix compatibility
58         s => 'S',
59         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
60         f => 'A',
61         t => 'XTO',
62         tc => 'XTO XCC',
63         c => 'XCC',
64         tcf => 'XTO XCC A',
65         a => 'XTO XCC A',
66         b => $non_quoted_body . ' XQUOT',
67         bs => $non_quoted_body . ' XQUOT S',
68         n => 'XFN',
69
70         q => 'XQUOT',
71         nq => $non_quoted_body,
72         dfn => 'XDFN',
73         dfa => 'XDFA',
74         dfb => 'XDFB',
75         dfhh => 'XDFHH',
76         dfctx => 'XDFCTX',
77         dfpre => 'XDFPRE',
78         dfpost => 'XDFPOST',
79         dfblob => 'XDFPRE XDFPOST',
80
81         # default:
82         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
83 );
84
85 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
86 our @HELP = (
87         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
88         'd:' => <<EOF,
89 date range as YYYYMMDD  e.g. d:19931002..20101002
90 Open-ended ranges such as d:19931002.. and d:..20101002
91 are also supported
92 EOF
93         'dt:' => <<EOF,
94 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
95 EOF
96         'b:' => 'match within message body, including text attachments',
97         'nq:' => 'match non-quoted text within message body',
98         'q:' => 'match quoted text within message body',
99         'n:' => 'match filename of attachment(s)',
100         't:' => 'match within the To header',
101         'c:' => 'match within the Cc header',
102         'f:' => 'match within the From header',
103         'a:' => 'match within the To, Cc, and From headers',
104         'tc:' => 'match within the To and Cc headers',
105         'bs:' => 'match within the Subject and body',
106         'dfn:' => 'match filename from diff',
107         'dfa:' => 'match diff removed (-) lines',
108         'dfb:' => 'match diff added (+) lines',
109         'dfhh:' => 'match diff hunk header context (usually a function name)',
110         'dfctx:' => 'match diff context lines',
111         'dfpre:' => 'match pre-image git blob ID',
112         'dfpost:' => 'match post-image git blob ID',
113         'dfblob:' => 'match either pre or post-image git blob ID',
114 );
115 chomp @HELP;
116
117 sub xdir {
118         my ($self) = @_;
119         if ($self->{version} == 1) {
120                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
121         } else {
122                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
123                 my $part = $self->{partition};
124                 defined $part or die "partition not given";
125                 $dir .= "/$part";
126         }
127 }
128
129 sub new {
130         my ($class, $mainrepo, $altid) = @_;
131         my $version = 1;
132         my $ibx = $mainrepo;
133         if (ref $ibx) {
134                 $version = $ibx->{version} || 1;
135                 $mainrepo = $ibx->{mainrepo};
136         }
137         my $self = bless {
138                 mainrepo => $mainrepo,
139                 altid => $altid,
140                 version => $version,
141         }, $class;
142         my $dir;
143         if ($version >= 2) {
144                 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
145                 my $xdb;
146                 my $parts = 0;
147                 foreach my $part (<$dir/*>) {
148                         -d $part && $part =~ m!/\d+\z! or next;
149                         $parts++;
150                         my $sub = Search::Xapian::Database->new($part);
151                         if ($xdb) {
152                                 $xdb->add_database($sub);
153                         } else {
154                                 $xdb = $sub;
155                         }
156                 }
157                 $self->{xdb} = $xdb;
158         } else {
159                 $dir = $self->xdir;
160                 $self->{xdb} = Search::Xapian::Database->new($dir);
161         }
162         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
163         $self;
164 }
165
166 sub reopen {
167         my ($self) = @_;
168         $self->{xdb}->reopen;
169         $self; # make chaining easier
170 }
171
172 # read-only
173 sub query {
174         my ($self, $query_string, $opts) = @_;
175         $opts ||= {};
176         if ($query_string eq '' && !$opts->{mset}) {
177                 $self->{over_ro}->recent($opts);
178         } else {
179                 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
180                 $opts->{relevance} = 1 unless exists $opts->{relevance};
181                 _do_enquire($self, $query, $opts);
182         }
183 }
184
185 sub get_thread {
186         my ($self, $mid, $prev) = @_;
187         $self->{over_ro}->get_thread($mid, $prev);
188 }
189
190 sub retry_reopen {
191         my ($self, $cb) = @_;
192         for my $i (1..10) {
193                 if (wantarray) {
194                         my @ret;
195                         eval { @ret = $cb->() };
196                         return @ret unless $@;
197                 } else {
198                         my $ret;
199                         eval { $ret = $cb->() };
200                         return $ret unless $@;
201                 }
202                 # Exception: The revision being read has been discarded -
203                 # you should call Xapian::Database::reopen()
204                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
205                         warn "reopen try #$i on $@\n";
206                         reopen($self);
207                 } else {
208                         warn "ref: ", ref($@), "\n";
209                         die;
210                 }
211         }
212         die "Too many Xapian database modifications in progress\n";
213 }
214
215 sub _do_enquire {
216         my ($self, $query, $opts) = @_;
217         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
218 }
219
220 sub _enquire_once {
221         my ($self, $query, $opts) = @_;
222         my $enquire = enquire($self);
223         $enquire->set_query($query);
224         $opts ||= {};
225         my $desc = !$opts->{asc};
226         if (($opts->{mset} || 0) == 2) {
227                 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
228                 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
229                 delete $self->{enquire};
230         } elsif ($opts->{relevance}) {
231                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
232         } else {
233                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
234         }
235         my $offset = $opts->{offset} || 0;
236         my $limit = $opts->{limit} || 50;
237         my $mset = $enquire->get_mset($offset, $limit);
238         return $mset if $opts->{mset};
239         my @msgs = map {
240                 PublicInbox::SearchMsg->load_doc($_->get_document);
241         } $mset->items;
242         return \@msgs unless wantarray;
243
244         ($mset->get_matches_estimated, \@msgs)
245 }
246
247 # read-write
248 sub stemmer { Search::Xapian::Stem->new($LANG) }
249
250 # read-only
251 sub qp {
252         my ($self) = @_;
253
254         my $qp = $self->{query_parser};
255         return $qp if $qp;
256
257         # new parser
258         $qp = Search::Xapian::QueryParser->new;
259         $qp->set_default_op(OP_AND);
260         $qp->set_database($self->{xdb});
261         $qp->set_stemmer($self->stemmer);
262         $qp->set_stemming_strategy(STEM_SOME);
263         $qp->add_valuerangeprocessor(
264                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
265         $qp->add_valuerangeprocessor(
266                 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
267
268         while (my ($name, $prefix) = each %bool_pfx_external) {
269                 $qp->add_boolean_prefix($name, $prefix);
270         }
271
272         # we do not actually create AltId objects,
273         # just parse the spec to avoid the extra DB handles for now.
274         if (my $altid = $self->{altid}) {
275                 my $user_pfx = $self->{-user_pfx} ||= [];
276                 for (@$altid) {
277                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
278                         /\Aserial:(\w+):/ or next;
279                         my $pfx = $1;
280                         push @$user_pfx, "$pfx:", <<EOF;
281 alternate serial number  e.g. $pfx:12345 (boolean)
282 EOF
283                         # gmane => XGMANE
284                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
285                 }
286                 chomp @$user_pfx;
287         }
288
289         while (my ($name, $prefix) = each %prob_prefix) {
290                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
291         }
292
293         $self->{query_parser} = $qp;
294 }
295
296 # only used for NNTP server
297 sub query_xover {
298         my ($self, $beg, $end, $offset) = @_;
299         $self->{over_ro}->query_xover($beg, $end, $offset);
300 }
301
302 sub query_ts {
303         my ($self, $ts, $prev) = @_;
304         $self->{over_ro}->query_ts($ts, $prev);
305 }
306
307 sub lookup_article {
308         my ($self, $num) = @_;
309         $self->{over_ro}->get_art($num);
310 }
311
312 sub next_by_mid {
313         my ($self, $mid, $id, $prev) = @_;
314         $self->{over_ro}->next_by_mid($mid, $id, $prev);
315 }
316
317 # normalize subjects so they are suitable as pathnames for URLs
318 # XXX: consider for removal
319 sub subject_path {
320         my $subj = pop;
321         $subj = subject_normalized($subj);
322         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
323         lc($subj);
324 }
325
326 sub subject_normalized {
327         my $subj = pop;
328         $subj =~ s/\A\s+//s; # no leading space
329         $subj =~ s/\s+\z//s; # no trailing space
330         $subj =~ s/\s+/ /gs; # no redundant spaces
331         $subj =~ s/\.+\z//; # no trailing '.'
332         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
333         $subj;
334 }
335
336 sub enquire {
337         my ($self) = @_;
338         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
339 }
340
341 sub help {
342         my ($self) = @_;
343         $self->qp; # parse altids
344         my @ret = @HELP;
345         if (my $user_pfx = $self->{-user_pfx}) {
346                 push @ret, @$user_pfx;
347         }
348         \@ret;
349 }
350
351 1;