]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: allow ->reopen to be chainable
[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 => 'Q', # Message-ID (full/exact), this is mostly uniQue
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         dfpre => 'XDFPRE',
85         dfpost => 'XDFPOST',
86         dfblob => 'XDFPRE XDFPOST',
87
88         # default:
89         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
90 );
91
92 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
93 our @HELP = (
94         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
95         'd:' => <<EOF,
96 date range as YYYYMMDD  e.g. d:19931002..20101002
97 Open-ended ranges such as d:19931002.. and d:..20101002
98 are also supported
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 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
122
123 sub xdir {
124         my ($self) = @_;
125         if ($self->{version} == 1) {
126                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
127         } else {
128                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
129                 my $part = $self->{partition};
130                 defined $part or die "partition not given";
131                 $dir .= "/$part";
132         }
133 }
134
135 sub new {
136         my ($class, $mainrepo, $altid) = @_;
137         my $version = 1;
138         my $ibx = $mainrepo;
139         if (ref $ibx) {
140                 $version = $ibx->{version} || 1;
141                 $mainrepo = $ibx->{mainrepo};
142         }
143         my $self = bless {
144                 mainrepo => $mainrepo,
145                 altid => $altid,
146                 version => $version,
147         }, $class;
148         if ($version >= 2) {
149                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
150                 my $xdb;
151                 my $parts = 0;
152                 foreach my $part (<$dir/*>) {
153                         -d $part && $part =~ m!/\d+\z! or next;
154                         $parts++;
155                         my $sub = Search::Xapian::Database->new($part);
156                         if ($xdb) {
157                                 $xdb->add_database($sub);
158                         } else {
159                                 $xdb = $sub;
160                         }
161                 }
162                 $self->{xdb} = $xdb;
163                 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
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         $self; # make chaining easier
177 }
178
179 # read-only
180 sub query {
181         my ($self, $query_string, $opts) = @_;
182         my $query;
183
184         $opts ||= {};
185         unless ($query_string eq '') {
186                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
187                 $opts->{relevance} = 1 unless exists $opts->{relevance};
188         }
189
190         _do_enquire($self, $query, $opts);
191 }
192
193 sub get_thread {
194         my ($self, $mid, $opts) = @_;
195         my $smsg = retry_reopen($self, sub { lookup_skeleton($self, $mid) });
196
197         return { total => 0, msgs => [] } unless $smsg;
198         my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
199         my $path = $smsg->path;
200         if (defined $path && $path ne '') {
201                 my $path = id_compress($smsg->path);
202                 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
203                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
204         }
205         $opts ||= {};
206         $opts->{limit} ||= 1000;
207
208         # always sort threads by timestamp, this makes life easier
209         # for the threading algorithm (in SearchThread.pm)
210         $opts->{asc} = 1;
211         $opts->{enquire} = enquire_skel($self);
212         _do_enquire($self, $qtid, $opts);
213 }
214
215 sub retry_reopen {
216         my ($self, $cb) = @_;
217         my $ret;
218         for (1..10) {
219                 eval { $ret = $cb->() };
220                 return $ret unless $@;
221                 # Exception: The revision being read has been discarded -
222                 # you should call Xapian::Database::reopen()
223                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
224                         reopen($self);
225                 } else {
226                         warn "ref: ", ref($@), "\n";
227                         die;
228                 }
229         }
230 }
231
232 sub _do_enquire {
233         my ($self, $query, $opts) = @_;
234         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
235 }
236
237 sub _enquire_once {
238         my ($self, $query, $opts) = @_;
239         my $enquire = $opts->{enquire} || enquire($self);
240         if (defined $query) {
241                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
242         } else {
243                 $query = $mail_query;
244         }
245         $enquire->set_query($query);
246         $opts ||= {};
247         my $desc = !$opts->{asc};
248         if ($opts->{relevance}) {
249                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
250         } elsif ($opts->{num}) {
251                 $enquire->set_sort_by_value(NUM, 0);
252         } else {
253                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
254         }
255         my $offset = $opts->{offset} || 0;
256         my $limit = $opts->{limit} || 50;
257         my $mset = $enquire->get_mset($offset, $limit);
258         return $mset if $opts->{mset};
259         my @msgs = map {
260                 PublicInbox::SearchMsg->load_doc($_->get_document);
261         } $mset->items;
262
263         { total => $mset->get_matches_estimated, msgs => \@msgs }
264 }
265
266 # read-write
267 sub stemmer { Search::Xapian::Stem->new($LANG) }
268
269 # read-only
270 sub qp {
271         my ($self) = @_;
272
273         my $qp = $self->{query_parser};
274         return $qp if $qp;
275
276         # new parser
277         $qp = Search::Xapian::QueryParser->new;
278         $qp->set_default_op(OP_AND);
279         $qp->set_database($self->{xdb});
280         $qp->set_stemmer($self->stemmer);
281         $qp->set_stemming_strategy(STEM_SOME);
282         $qp->add_valuerangeprocessor(
283                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
284
285         while (my ($name, $prefix) = each %bool_pfx_external) {
286                 $qp->add_boolean_prefix($name, $prefix);
287         }
288
289         # we do not actually create AltId objects,
290         # just parse the spec to avoid the extra DB handles for now.
291         if (my $altid = $self->{altid}) {
292                 my $user_pfx = $self->{-user_pfx} ||= [];
293                 for (@$altid) {
294                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
295                         /\Aserial:(\w+):/ or next;
296                         my $pfx = $1;
297                         push @$user_pfx, "$pfx:", <<EOF;
298 alternate serial number  e.g. $pfx:12345 (boolean)
299 EOF
300                         # gmane => XGMANE
301                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
302                 }
303                 chomp @$user_pfx;
304         }
305
306         while (my ($name, $prefix) = each %prob_prefix) {
307                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
308         }
309
310         $self->{query_parser} = $qp;
311 }
312
313 sub num_range_processor {
314         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
315 }
316
317 # only used for NNTP server
318 sub query_xover {
319         my ($self, $beg, $end, $offset) = @_;
320         my $qp = Search::Xapian::QueryParser->new;
321         $qp->set_database($self->{skel} || $self->{xdb});
322         $qp->add_valuerangeprocessor($self->num_range_processor);
323         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
324
325         my $opts = {
326                 enquire => enquire_skel($self),
327                 num => 1,
328                 limit => 200,
329                 offset => $offset,
330         };
331         _do_enquire($self, $query, $opts);
332 }
333
334 sub query_ts {
335         my ($self, $ts, $opts) = @_;
336         my $qp = $self->{qp_ts} ||= eval {
337                 my $q = Search::Xapian::QueryParser->new;
338                 $q->set_database($self->{skel} || $self->{xdb});
339                 $q->add_valuerangeprocessor(
340                         Search::Xapian::NumberValueRangeProcessor->new(TS));
341                 $q
342         };
343         my $query = $qp->parse_query($ts, QP_FLAGS);
344         $opts->{enquire} = enquire_skel($self);
345         _do_enquire($self, $query, $opts);
346 }
347
348 sub lookup_skeleton {
349         my ($self, $mid) = @_;
350         my $skel = $self->{skel} or return lookup_message($self, $mid);
351         $mid = mid_clean($mid);
352         my $term = 'Q' . $mid;
353         my $smsg;
354         my $beg = $skel->postlist_begin($term);
355         if ($beg != $skel->postlist_end($term)) {
356                 my $doc_id = $beg->get_docid;
357                 if (defined $doc_id) {
358                         # raises on error:
359                         my $doc = $skel->get_document($doc_id);
360                         $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
361                         $smsg->{doc_id} = $doc_id;
362                 }
363         }
364         $smsg;
365 }
366
367 sub lookup_message {
368         my ($self, $mid) = @_;
369         $mid = mid_clean($mid);
370
371         my $doc_id = $self->find_first_doc_id('Q' . $mid);
372         my $smsg;
373         if (defined $doc_id) {
374                 # raises on error:
375                 my $doc = $self->{xdb}->get_document($doc_id);
376                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
377                 $smsg->{doc_id} = $doc_id;
378         }
379         $smsg;
380 }
381
382 sub lookup_mail { # no ghosts!
383         my ($self, $mid) = @_;
384         retry_reopen($self, sub {
385                 my $smsg = lookup_skeleton($self, $mid) or return;
386                 $smsg->load_expand;
387         });
388 }
389
390 sub lookup_article {
391         my ($self, $num) = @_;
392         my $term = 'XNUM'.$num;
393         my $smsg;
394         eval {
395                 retry_reopen($self, sub {
396                         my $db = $self->{skel} || $self->{xdb};
397                         my $head = $db->postlist_begin($term);
398                         return if $head == $db->postlist_end($term);
399                         my $doc_id = $head->get_docid;
400                         return unless defined $doc_id;
401                         # raises on error:
402                         my $doc = $db->get_document($doc_id);
403                         $smsg = PublicInbox::SearchMsg->wrap($doc);
404                         $smsg->load_expand;
405                         $smsg->{doc_id} = $doc_id;
406                 });
407         };
408         $smsg;
409 }
410
411 sub each_smsg_by_mid {
412         my ($self, $mid, $cb) = @_;
413         # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
414         # interface will need it...
415         my $db = $self->{skel} || $self->{xdb};
416         my $term = 'Q' . $mid;
417         my $head = $db->postlist_begin($term);
418         my $tail = $db->postlist_end($term);
419         for (; $head->nequal($tail); $head->inc) {
420                 my $doc_id = $head->get_docid;
421                 my $doc = $db->get_document($doc_id);
422                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
423                 $smsg->{doc_id} = $doc_id;
424                 $cb->($smsg) or return;
425         }
426 }
427
428 sub find_unique_doc_id {
429         my ($self, $termval) = @_;
430
431         my ($begin, $end) = $self->find_doc_ids($termval);
432
433         return undef if $begin->equal($end); # not found
434
435         my $rv = $begin->get_docid;
436
437         # sanity check
438         $begin->inc;
439         $begin->equal($end) or die "Term '$termval' is not unique\n";
440         $rv;
441 }
442
443 # returns begin and end PostingIterator
444 sub find_doc_ids {
445         my ($self, $termval) = @_;
446         my $db = $self->{xdb};
447
448         ($db->postlist_begin($termval), $db->postlist_end($termval));
449 }
450
451 sub find_first_doc_id {
452         my ($self, $termval) = @_;
453
454         my ($begin, $end) = $self->find_doc_ids($termval);
455
456         return undef if $begin->equal($end); # not found
457
458         $begin->get_docid;
459 }
460
461 # normalize subjects so they are suitable as pathnames for URLs
462 # XXX: consider for removal
463 sub subject_path {
464         my $subj = pop;
465         $subj = subject_normalized($subj);
466         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
467         lc($subj);
468 }
469
470 sub subject_normalized {
471         my $subj = pop;
472         $subj =~ s/\A\s+//s; # no leading space
473         $subj =~ s/\s+\z//s; # no trailing space
474         $subj =~ s/\s+/ /gs; # no redundant spaces
475         $subj =~ s/\.+\z//; # no trailing '.'
476         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
477         $subj;
478 }
479
480 sub enquire {
481         my ($self) = @_;
482         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
483 }
484
485 sub enquire_skel {
486         my ($self) = @_;
487         if (my $skel = $self->{skel}) {
488                 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
489         } else {
490                 enquire($self);
491         }
492 }
493
494 sub help {
495         my ($self) = @_;
496         $self->qp; # parse altids
497         my @ret = @HELP;
498         if (my $user_pfx = $self->{-user_pfx}) {
499                 push @ret, @$user_pfx;
500         }
501         \@ret;
502 }
503
504 1;