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