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