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