]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
c7c5455d744d6fab782572c9f0af2848b55f5769
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (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', # uniQue id (Message-ID)
60 );
61
62 my %prob_prefix = (
63         # for mairix compatibility
64         s => 'S',
65         m => 'XMID', # '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         '' => 'XMID 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 (undef, $git_dir) = @_;
124         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
125 }
126
127 sub new {
128         my ($class, $git_dir, $altid) = @_;
129         my $dir = $class->xdir($git_dir);
130         my $db = Search::Xapian::Database->new($dir);
131         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
132 }
133
134 sub reopen { $_[0]->{xdb}->reopen }
135
136 # read-only
137 sub query {
138         my ($self, $query_string, $opts) = @_;
139         my $query;
140
141         $opts ||= {};
142         unless ($query_string eq '') {
143                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
144                 $opts->{relevance} = 1 unless exists $opts->{relevance};
145         }
146
147         _do_enquire($self, $query, $opts);
148 }
149
150 sub get_thread {
151         my ($self, $mid, $opts) = @_;
152         my $smsg = eval { $self->lookup_message($mid) };
153
154         return { total => 0, msgs => [] } unless $smsg;
155         my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
156         my $path = $smsg->path;
157         if (defined $path && $path ne '') {
158                 my $path = id_compress($smsg->path);
159                 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
160                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
161         }
162         $opts ||= {};
163         $opts->{limit} ||= 1000;
164
165         # always sort threads by timestamp, this makes life easier
166         # for the threading algorithm (in SearchThread.pm)
167         $opts->{asc} = 1;
168
169         _do_enquire($self, $qtid, $opts);
170 }
171
172 sub retry_reopen {
173         my ($self, $cb) = @_;
174         my $ret;
175         for (1..10) {
176                 eval { $ret = $cb->() };
177                 return $ret unless $@;
178                 # Exception: The revision being read has been discarded -
179                 # you should call Xapian::Database::reopen()
180                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
181                         reopen($self);
182                 } else {
183                         die;
184                 }
185         }
186 }
187
188 sub _do_enquire {
189         my ($self, $query, $opts) = @_;
190         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
191 }
192
193 sub _enquire_once {
194         my ($self, $query, $opts) = @_;
195         my $enquire = $self->enquire;
196         if (defined $query) {
197                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
198         } else {
199                 $query = $mail_query;
200         }
201         $enquire->set_query($query);
202         $opts ||= {};
203         my $desc = !$opts->{asc};
204         if ($opts->{relevance}) {
205                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
206         } elsif ($opts->{num}) {
207                 $enquire->set_sort_by_value(NUM, 0);
208         } else {
209                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
210         }
211         my $offset = $opts->{offset} || 0;
212         my $limit = $opts->{limit} || 50;
213         my $mset = $enquire->get_mset($offset, $limit);
214         return $mset if $opts->{mset};
215         my @msgs = map {
216                 PublicInbox::SearchMsg->load_doc($_->get_document);
217         } $mset->items;
218
219         { total => $mset->get_matches_estimated, msgs => \@msgs }
220 }
221
222 # read-write
223 sub stemmer { Search::Xapian::Stem->new($LANG) }
224
225 # read-only
226 sub qp {
227         my ($self) = @_;
228
229         my $qp = $self->{query_parser};
230         return $qp if $qp;
231
232         # new parser
233         $qp = Search::Xapian::QueryParser->new;
234         $qp->set_default_op(OP_AND);
235         $qp->set_database($self->{xdb});
236         $qp->set_stemmer($self->stemmer);
237         $qp->set_stemming_strategy(STEM_SOME);
238         $qp->add_valuerangeprocessor(
239                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
240
241         while (my ($name, $prefix) = each %bool_pfx_external) {
242                 $qp->add_boolean_prefix($name, $prefix);
243         }
244
245         # we do not actually create AltId objects,
246         # just parse the spec to avoid the extra DB handles for now.
247         if (my $altid = $self->{altid}) {
248                 my $user_pfx = $self->{-user_pfx} ||= [];
249                 for (@$altid) {
250                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
251                         /\Aserial:(\w+):/ or next;
252                         my $pfx = $1;
253                         push @$user_pfx, "$pfx:", <<EOF;
254 alternate serial number  e.g. $pfx:12345 (boolean)
255 EOF
256                         # gmane => XGMANE
257                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
258                 }
259                 chomp @$user_pfx;
260         }
261
262         while (my ($name, $prefix) = each %prob_prefix) {
263                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
264         }
265
266         $self->{query_parser} = $qp;
267 }
268
269 sub num_range_processor {
270         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
271 }
272
273 # only used for NNTP server
274 sub query_xover {
275         my ($self, $beg, $end, $offset) = @_;
276         my $qp = Search::Xapian::QueryParser->new;
277         $qp->set_database($self->{xdb});
278         $qp->add_valuerangeprocessor($self->num_range_processor);
279         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
280
281         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
282 }
283
284 sub lookup_message {
285         my ($self, $mid) = @_;
286         $mid = mid_clean($mid);
287
288         my $doc_id = $self->find_unique_doc_id('Q' . $mid);
289         my $smsg;
290         if (defined $doc_id) {
291                 # raises on error:
292                 my $doc = $self->{xdb}->get_document($doc_id);
293                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
294                 $smsg->{doc_id} = $doc_id;
295         }
296         $smsg;
297 }
298
299 sub lookup_mail { # no ghosts!
300         my ($self, $mid) = @_;
301         retry_reopen($self, sub {
302                 my $smsg = lookup_message($self, $mid) or return;
303                 PublicInbox::SearchMsg->load_doc($smsg->{doc});
304         });
305 }
306
307 sub find_unique_doc_id {
308         my ($self, $termval) = @_;
309
310         my ($begin, $end) = $self->find_doc_ids($termval);
311
312         return undef if $begin->equal($end); # not found
313
314         my $rv = $begin->get_docid;
315
316         # sanity check
317         $begin->inc;
318         $begin->equal($end) or die "Term '$termval' is not unique\n";
319         $rv;
320 }
321
322 # returns begin and end PostingIterator
323 sub find_doc_ids {
324         my ($self, $termval) = @_;
325         my $db = $self->{xdb};
326
327         ($db->postlist_begin($termval), $db->postlist_end($termval));
328 }
329
330 # normalize subjects so they are suitable as pathnames for URLs
331 # XXX: consider for removal
332 sub subject_path {
333         my $subj = pop;
334         $subj = subject_normalized($subj);
335         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
336         lc($subj);
337 }
338
339 sub subject_normalized {
340         my $subj = pop;
341         $subj =~ s/\A\s+//s; # no leading space
342         $subj =~ s/\s+\z//s; # no trailing space
343         $subj =~ s/\s+/ /gs; # no redundant spaces
344         $subj =~ s/\.+\z//; # no trailing '.'
345         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
346         $subj;
347 }
348
349 sub enquire {
350         my ($self) = @_;
351         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
352 }
353
354 sub help {
355         my ($self) = @_;
356         $self->qp; # parse altids
357         my @ret = @HELP;
358         if (my $user_pfx = $self->{-user_pfx}) {
359                 push @ret, @$user_pfx;
360         }
361         \@ret;
362 }
363
364 1;