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