]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: use different Enquire object for skeleton queries
[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                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
128                 my $part = $self->{partition};
129                 defined $part or die "partition not given";
130                 $dir .= "/$part";
131         }
132 }
133
134 sub new {
135         my ($class, $mainrepo, $altid) = @_;
136         my $version = 1;
137         my $ibx = $mainrepo;
138         if (ref $ibx) {
139                 $version = $ibx->{version} || 1;
140                 $mainrepo = $ibx->{mainrepo};
141         }
142         my $self = bless {
143                 mainrepo => $mainrepo,
144                 altid => $altid,
145                 version => $version,
146         }, $class;
147         if ($version >= 2) {
148                 my $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                 warn "v2 repo with $parts found in $dir\n";
162                 $self->{xdb} = $xdb;
163                 $self->{skel} = Search::Xapian::Database->new("$dir/all");
164         } else {
165                 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
166         }
167         $self;
168 }
169
170 sub reopen {
171         my ($self) = @_;
172         $self->{xdb}->reopen;
173         if (my $skel = $self->{skel}) {
174                 $skel->reopen;
175         }
176 }
177
178 # read-only
179 sub query {
180         my ($self, $query_string, $opts) = @_;
181         my $query;
182
183         $opts ||= {};
184         unless ($query_string eq '') {
185                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
186                 $opts->{relevance} = 1 unless exists $opts->{relevance};
187         }
188
189         _do_enquire($self, $query, $opts);
190 }
191
192 sub get_thread {
193         my ($self, $mid, $opts) = @_;
194         my $smsg = retry_reopen($self, sub { lookup_skeleton($self, $mid) });
195
196         return { total => 0, msgs => [] } unless $smsg;
197         my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
198         my $path = $smsg->path;
199         if (defined $path && $path ne '') {
200                 my $path = id_compress($smsg->path);
201                 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
202                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
203         }
204         $opts ||= {};
205         $opts->{limit} ||= 1000;
206
207         # always sort threads by timestamp, this makes life easier
208         # for the threading algorithm (in SearchThread.pm)
209         $opts->{asc} = 1;
210         $opts->{enquire} = enquire_skel($self);
211         _do_enquire($self, $qtid, $opts);
212 }
213
214 sub retry_reopen {
215         my ($self, $cb) = @_;
216         my $ret;
217         for (1..10) {
218                 eval { $ret = $cb->() };
219                 return $ret unless $@;
220                 # Exception: The revision being read has been discarded -
221                 # you should call Xapian::Database::reopen()
222                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
223                         reopen($self);
224                 } else {
225                         warn "ref: ", ref($@), "\n";
226                         die;
227                 }
228         }
229 }
230
231 sub _do_enquire {
232         my ($self, $query, $opts) = @_;
233         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
234 }
235
236 sub _enquire_once {
237         my ($self, $query, $opts) = @_;
238         my $enquire = $opts->{enquire} || enquire($self);
239         if (defined $query) {
240                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
241         } else {
242                 $query = $mail_query;
243         }
244         $enquire->set_query($query);
245         $opts ||= {};
246         my $desc = !$opts->{asc};
247         if ($opts->{relevance}) {
248                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
249         } elsif ($opts->{num}) {
250                 $enquire->set_sort_by_value(NUM, 0);
251         } else {
252                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
253         }
254         my $offset = $opts->{offset} || 0;
255         my $limit = $opts->{limit} || 50;
256         my $mset = $enquire->get_mset($offset, $limit);
257         return $mset if $opts->{mset};
258         my @msgs = map {
259                 PublicInbox::SearchMsg->load_doc($_->get_document);
260         } $mset->items;
261
262         { total => $mset->get_matches_estimated, msgs => \@msgs }
263 }
264
265 # read-write
266 sub stemmer { Search::Xapian::Stem->new($LANG) }
267
268 # read-only
269 sub qp {
270         my ($self) = @_;
271
272         my $qp = $self->{query_parser};
273         return $qp if $qp;
274
275         # new parser
276         $qp = Search::Xapian::QueryParser->new;
277         $qp->set_default_op(OP_AND);
278         $qp->set_database($self->{xdb});
279         $qp->set_stemmer($self->stemmer);
280         $qp->set_stemming_strategy(STEM_SOME);
281         $qp->add_valuerangeprocessor(
282                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
283
284         while (my ($name, $prefix) = each %bool_pfx_external) {
285                 $qp->add_boolean_prefix($name, $prefix);
286         }
287
288         # we do not actually create AltId objects,
289         # just parse the spec to avoid the extra DB handles for now.
290         if (my $altid = $self->{altid}) {
291                 my $user_pfx = $self->{-user_pfx} ||= [];
292                 for (@$altid) {
293                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
294                         /\Aserial:(\w+):/ or next;
295                         my $pfx = $1;
296                         push @$user_pfx, "$pfx:", <<EOF;
297 alternate serial number  e.g. $pfx:12345 (boolean)
298 EOF
299                         # gmane => XGMANE
300                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
301                 }
302                 chomp @$user_pfx;
303         }
304
305         while (my ($name, $prefix) = each %prob_prefix) {
306                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
307         }
308
309         $self->{query_parser} = $qp;
310 }
311
312 sub num_range_processor {
313         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
314 }
315
316 # only used for NNTP server
317 sub query_xover {
318         my ($self, $beg, $end, $offset) = @_;
319         my $qp = Search::Xapian::QueryParser->new;
320         $qp->set_database($self->{xdb});
321         $qp->add_valuerangeprocessor($self->num_range_processor);
322         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
323
324         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
325 }
326
327 sub lookup_skeleton {
328         my ($self, $mid) = @_;
329         my $skel = $self->{skel} or return lookup_message($self, $mid);
330         $mid = mid_clean($mid);
331         my $term = 'XMID' . $mid;
332         my $smsg;
333         my $beg = $skel->postlist_begin($term);
334         if ($beg != $skel->postlist_end($term)) {
335                 my $doc_id = $beg->get_docid;
336                 if (defined $doc_id) {
337                         # raises on error:
338                         my $doc = $skel->get_document($doc_id);
339                         $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
340                         $smsg->{doc_id} = $doc_id;
341                 }
342         }
343         $smsg;
344 }
345
346 sub lookup_message {
347         my ($self, $mid) = @_;
348         $mid = mid_clean($mid);
349
350         my $doc_id = $self->find_first_doc_id('XMID' . $mid);
351         my $smsg;
352         if (defined $doc_id) {
353                 # raises on error:
354                 my $doc = $self->{xdb}->get_document($doc_id);
355                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
356                 $smsg->{doc_id} = $doc_id;
357         }
358         $smsg;
359 }
360
361 sub lookup_mail { # no ghosts!
362         my ($self, $mid) = @_;
363         retry_reopen($self, sub {
364                 my $smsg = lookup_message($self, $mid) or return;
365                 $smsg->load_expand;
366         });
367 }
368
369 sub find_unique_doc_id {
370         my ($self, $termval) = @_;
371
372         my ($begin, $end) = $self->find_doc_ids($termval);
373
374         return undef if $begin->equal($end); # not found
375
376         my $rv = $begin->get_docid;
377
378         # sanity check
379         $begin->inc;
380         $begin->equal($end) or die "Term '$termval' is not unique\n";
381         $rv;
382 }
383
384 # returns begin and end PostingIterator
385 sub find_doc_ids {
386         my ($self, $termval) = @_;
387         my $db = $self->{xdb};
388
389         ($db->postlist_begin($termval), $db->postlist_end($termval));
390 }
391
392 sub find_first_doc_id {
393         my ($self, $termval) = @_;
394
395         my ($begin, $end) = $self->find_doc_ids($termval);
396
397         return undef if $begin->equal($end); # not found
398
399         $begin->get_docid;
400 }
401
402 # normalize subjects so they are suitable as pathnames for URLs
403 # XXX: consider for removal
404 sub subject_path {
405         my $subj = pop;
406         $subj = subject_normalized($subj);
407         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
408         lc($subj);
409 }
410
411 sub subject_normalized {
412         my $subj = pop;
413         $subj =~ s/\A\s+//s; # no leading space
414         $subj =~ s/\s+\z//s; # no trailing space
415         $subj =~ s/\s+/ /gs; # no redundant spaces
416         $subj =~ s/\.+\z//; # no trailing '.'
417         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
418         $subj;
419 }
420
421 sub enquire {
422         my ($self) = @_;
423         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
424 }
425
426 sub enquire_skel {
427         my ($self) = @_;
428         if (my $skel = $self->{skel}) {
429                 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
430         } else {
431                 enquire($self);
432         }
433 }
434
435 sub help {
436         my ($self) = @_;
437         $self->qp; # parse altids
438         my @ret = @HELP;
439         if (my $user_pfx = $self->{-user_pfx}) {
440                 push @ret, @$user_pfx;
441         }
442         \@ret;
443 }
444
445 1;