]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
v2: support Xapian + SQLite indexing
[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; # timestamp
12 use constant NUM => 1; # NNTP article number
13 use constant BYTES => 2; # :bytes as defined in RFC 3977
14 use constant LINES => 3; # :lines as defined in RFC 3977
15 use constant YYYYMMDD => 4; # for searching in the WWW UI
16
17 use Search::Xapian qw/:standard/;
18 use PublicInbox::SearchMsg;
19 use PublicInbox::MIME;
20 use PublicInbox::MID qw/mid_clean id_compress/;
21
22 # This is English-only, everything else is non-standard and may be confused as
23 # a prefix common in patch emails
24 our $REPLY_RE = qr/^re:\s+/i;
25 our $LANG = 'english';
26
27 use constant {
28         # SCHEMA_VERSION history
29         # 0 - initial
30         # 1 - subject_path is lower-cased
31         # 2 - subject_path is id_compress in the index, only
32         # 3 - message-ID is compressed if it includes '%' (hack!)
33         # 4 - change "Re: " normalization, avoid circular Reference ghosts
34         # 5 - subject_path drops trailing '.'
35         # 6 - preserve References: order in document data
36         # 7 - remove references and inreplyto terms
37         # 8 - remove redundant/unneeded document data
38         # 9 - disable Message-ID compression (SHA-1)
39         # 10 - optimize doc for NNTP overviews
40         # 11 - merge threads when vivifying ghosts
41         # 12 - change YYYYMMDD value column to numeric
42         # 13 - fix threading for empty References/In-Reply-To
43         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
44         # 14 - fix ghost root vivification
45         SCHEMA_VERSION => 14,
46
47         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
48         # as it could become a denial-of-service vector
49         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
50 };
51
52 # setup prefixes
53 my %bool_pfx_internal = (
54         type => 'T', # "mail" or "ghost"
55         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
56 );
57
58 my %bool_pfx_external = (
59         mid => 'XMID', # Message-ID (full/exact)
60 );
61
62 my %prob_prefix = (
63         # for mairix compatibility
64         s => 'S',
65         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
66         f => 'A',
67         t => 'XTO',
68         tc => 'XTO XCC',
69         c => 'XCC',
70         tcf => 'XTO XCC A',
71         a => 'XTO XCC A',
72         b => 'XNQ XQUOT',
73         bs => 'XNQ XQUOT S',
74         n => 'XFN',
75
76         q => 'XQUOT',
77         nq => 'XNQ',
78         dfn => 'XDFN',
79         dfa => 'XDFA',
80         dfb => 'XDFB',
81         dfhh => 'XDFHH',
82         dfctx => 'XDFCTX',
83         dfpre => 'XDFPRE',
84         dfpost => 'XDFPOST',
85         dfblob => 'XDFPRE XDFPOST',
86
87         # default:
88         '' => 'XM S A XNQ XQUOT XFN',
89 );
90
91 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
92 our @HELP = (
93         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
94         'd:' => <<EOF,
95 date range as YYYYMMDD  e.g. d:19931002..20101002
96 Open-ended ranges such as d:19931002.. and d:..20101002
97 are also supported
98 EOF
99         'b:' => 'match within message body, including text attachments',
100         'nq:' => 'match non-quoted text within message body',
101         'q:' => 'match quoted text within message body',
102         'n:' => 'match filename of attachment(s)',
103         't:' => 'match within the To header',
104         'c:' => 'match within the Cc header',
105         'f:' => 'match within the From header',
106         'a:' => 'match within the To, Cc, and From headers',
107         'tc:' => 'match within the To and Cc headers',
108         'bs:' => 'match within the Subject and body',
109         'dfn:' => 'match filename from diff',
110         'dfa:' => 'match diff removed (-) lines',
111         'dfb:' => 'match diff added (+) lines',
112         'dfhh:' => 'match diff hunk header context (usually a function name)',
113         'dfctx:' => 'match diff context lines',
114         'dfpre:' => 'match pre-image git blob ID',
115         'dfpost:' => 'match post-image git blob ID',
116         'dfblob:' => 'match either pre or post-image git blob ID',
117 );
118 chomp @HELP;
119
120 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
121
122 sub xdir {
123         my ($self) = @_;
124         if ($self->{version} == 1) {
125                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
126         } else {
127                 "$self->{mainrepo}/xap" . SCHEMA_VERSION;
128         }
129 }
130
131 sub new {
132         my ($class, $mainrepo, $altid) = @_;
133         my $version = 1;
134         my $ibx = $mainrepo;
135         if (ref $ibx) {
136                 $version = $ibx->{version} || 1;
137                 $mainrepo = $ibx->{mainrepo};
138         }
139         my $self = bless {
140                 mainrepo => $mainrepo,
141                 altid => $altid,
142                 version => $version,
143         }, $class;
144         $self->{xdb} = Search::Xapian::Database->new($self->xdir);
145         $self;
146 }
147
148 sub reopen { $_[0]->{xdb}->reopen }
149
150 # read-only
151 sub query {
152         my ($self, $query_string, $opts) = @_;
153         my $query;
154
155         $opts ||= {};
156         unless ($query_string eq '') {
157                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
158                 $opts->{relevance} = 1 unless exists $opts->{relevance};
159         }
160
161         _do_enquire($self, $query, $opts);
162 }
163
164 sub get_thread {
165         my ($self, $mid, $opts) = @_;
166         my $smsg = eval { $self->lookup_message($mid) };
167
168         return { total => 0, msgs => [] } unless $smsg;
169         my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
170         my $path = $smsg->path;
171         if (defined $path && $path ne '') {
172                 my $path = id_compress($smsg->path);
173                 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
174                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
175         }
176         $opts ||= {};
177         $opts->{limit} ||= 1000;
178
179         # always sort threads by timestamp, this makes life easier
180         # for the threading algorithm (in SearchThread.pm)
181         $opts->{asc} = 1;
182
183         _do_enquire($self, $qtid, $opts);
184 }
185
186 sub retry_reopen {
187         my ($self, $cb) = @_;
188         my $ret;
189         for (1..10) {
190                 eval { $ret = $cb->() };
191                 return $ret unless $@;
192                 # Exception: The revision being read has been discarded -
193                 # you should call Xapian::Database::reopen()
194                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
195                         reopen($self);
196                 } else {
197                         die;
198                 }
199         }
200 }
201
202 sub _do_enquire {
203         my ($self, $query, $opts) = @_;
204         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
205 }
206
207 sub _enquire_once {
208         my ($self, $query, $opts) = @_;
209         my $enquire = $self->enquire;
210         if (defined $query) {
211                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
212         } else {
213                 $query = $mail_query;
214         }
215         $enquire->set_query($query);
216         $opts ||= {};
217         my $desc = !$opts->{asc};
218         if ($opts->{relevance}) {
219                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
220         } elsif ($opts->{num}) {
221                 $enquire->set_sort_by_value(NUM, 0);
222         } else {
223                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
224         }
225         my $offset = $opts->{offset} || 0;
226         my $limit = $opts->{limit} || 50;
227         my $mset = $enquire->get_mset($offset, $limit);
228         return $mset if $opts->{mset};
229         my @msgs = map {
230                 PublicInbox::SearchMsg->load_doc($_->get_document);
231         } $mset->items;
232
233         { total => $mset->get_matches_estimated, msgs => \@msgs }
234 }
235
236 # read-write
237 sub stemmer { Search::Xapian::Stem->new($LANG) }
238
239 # read-only
240 sub qp {
241         my ($self) = @_;
242
243         my $qp = $self->{query_parser};
244         return $qp if $qp;
245
246         # new parser
247         $qp = Search::Xapian::QueryParser->new;
248         $qp->set_default_op(OP_AND);
249         $qp->set_database($self->{xdb});
250         $qp->set_stemmer($self->stemmer);
251         $qp->set_stemming_strategy(STEM_SOME);
252         $qp->add_valuerangeprocessor(
253                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
254
255         while (my ($name, $prefix) = each %bool_pfx_external) {
256                 $qp->add_boolean_prefix($name, $prefix);
257         }
258
259         # we do not actually create AltId objects,
260         # just parse the spec to avoid the extra DB handles for now.
261         if (my $altid = $self->{altid}) {
262                 my $user_pfx = $self->{-user_pfx} ||= [];
263                 for (@$altid) {
264                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
265                         /\Aserial:(\w+):/ or next;
266                         my $pfx = $1;
267                         push @$user_pfx, "$pfx:", <<EOF;
268 alternate serial number  e.g. $pfx:12345 (boolean)
269 EOF
270                         # gmane => XGMANE
271                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
272                 }
273                 chomp @$user_pfx;
274         }
275
276         while (my ($name, $prefix) = each %prob_prefix) {
277                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
278         }
279
280         $self->{query_parser} = $qp;
281 }
282
283 sub num_range_processor {
284         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
285 }
286
287 # only used for NNTP server
288 sub query_xover {
289         my ($self, $beg, $end, $offset) = @_;
290         my $qp = Search::Xapian::QueryParser->new;
291         $qp->set_database($self->{xdb});
292         $qp->add_valuerangeprocessor($self->num_range_processor);
293         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
294
295         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
296 }
297
298 sub lookup_message {
299         my ($self, $mid) = @_;
300         $mid = mid_clean($mid);
301
302         my $doc_id = $self->find_first_doc_id('XMID' . $mid);
303         my $smsg;
304         if (defined $doc_id) {
305                 # raises on error:
306                 my $doc = $self->{xdb}->get_document($doc_id);
307                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
308                 $smsg->{doc_id} = $doc_id;
309         }
310         $smsg;
311 }
312
313 sub lookup_mail { # no ghosts!
314         my ($self, $mid) = @_;
315         retry_reopen($self, sub {
316                 my $smsg = lookup_message($self, $mid) or return;
317                 $smsg->load_expand;
318         });
319 }
320
321 sub find_unique_doc_id {
322         my ($self, $termval) = @_;
323
324         my ($begin, $end) = $self->find_doc_ids($termval);
325
326         return undef if $begin->equal($end); # not found
327
328         my $rv = $begin->get_docid;
329
330         # sanity check
331         $begin->inc;
332         $begin->equal($end) or die "Term '$termval' is not unique\n";
333         $rv;
334 }
335
336 # returns begin and end PostingIterator
337 sub find_doc_ids {
338         my ($self, $termval) = @_;
339         my $db = $self->{xdb};
340
341         ($db->postlist_begin($termval), $db->postlist_end($termval));
342 }
343
344 sub find_first_doc_id {
345         my ($self, $termval) = @_;
346
347         my ($begin, $end) = $self->find_doc_ids($termval);
348
349         return undef if $begin->equal($end); # not found
350
351         $begin->get_docid;
352 }
353
354 # normalize subjects so they are suitable as pathnames for URLs
355 # XXX: consider for removal
356 sub subject_path {
357         my $subj = pop;
358         $subj = subject_normalized($subj);
359         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
360         lc($subj);
361 }
362
363 sub subject_normalized {
364         my $subj = pop;
365         $subj =~ s/\A\s+//s; # no leading space
366         $subj =~ s/\s+\z//s; # no trailing space
367         $subj =~ s/\s+/ /gs; # no redundant spaces
368         $subj =~ s/\.+\z//; # no trailing '.'
369         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
370         $subj;
371 }
372
373 sub enquire {
374         my ($self) = @_;
375         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
376 }
377
378 sub help {
379         my ($self) = @_;
380         $self->qp; # parse altids
381         my @ret = @HELP;
382         if (my $user_pfx = $self->{-user_pfx}) {
383                 push @ret, @$user_pfx;
384         }
385         \@ret;
386 }
387
388 1;