]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
82a6e5416240e19876203fc61fcd5b25d289d420
[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         # do we still need these? probably not..
60         path => 'XPATH',
61         mid => 'Q', # uniQue id (Message-ID)
62 );
63
64 my %prob_prefix = (
65         # for mairix compatibility
66         s => 'S',
67         m => 'XMID', # '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 => 'XNQ XQUOT',
75         bs => 'XNQ XQUOT S',
76         n => 'XFN',
77
78         q => 'XQUOT',
79         nq => 'XNQ',
80
81         # default:
82         '' => 'XMID S A XNQ XQUOT XFN',
83 );
84
85 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
86 our @HELP = (
87         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
88         'd:' => <<EOF,
89 date range as YYYYMMDD  e.g. d:19931002..20101002
90 Open-ended ranges such as d:19931002.. and d:..20101002
91 are also supported
92 EOF
93         'b:' => 'match within message body, including text attachments',
94         'nq:' => 'match non-quoted text within message body',
95         'q:' => 'match quoted text within message body',
96         'n:' => 'match filename of attachment(s)',
97         't:' => 'match within the To header',
98         'c:' => 'match within the Cc header',
99         'f:' => 'match within the From header',
100         'a:' => 'match within the To, Cc, and From headers',
101         'tc:' => 'match within the To and Cc headers',
102         'bs:' => 'match within the Subject and body',
103 );
104 chomp @HELP;
105 # TODO:
106 # df (filenames from diff)
107 # da (diff a/ removed lines)
108 # db (diff b/ added lines)
109
110 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
111
112 sub xpfx { $all_pfx{$_[0]} }
113
114 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
115
116 sub xdir {
117         my (undef, $git_dir) = @_;
118         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
119 }
120
121 sub new {
122         my ($class, $git_dir, $altid) = @_;
123         my $dir = $class->xdir($git_dir);
124         my $db = Search::Xapian::Database->new($dir);
125         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
126 }
127
128 sub reopen { $_[0]->{xdb}->reopen }
129
130 # read-only
131 sub query {
132         my ($self, $query_string, $opts) = @_;
133         my $query;
134
135         $opts ||= {};
136         unless ($query_string eq '') {
137                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
138                 $opts->{relevance} = 1 unless exists $opts->{relevance};
139         }
140
141         _do_enquire($self, $query, $opts);
142 }
143
144 sub get_thread {
145         my ($self, $mid, $opts) = @_;
146         my $smsg = eval { $self->lookup_message($mid) };
147
148         return { total => 0, msgs => [] } unless $smsg;
149         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
150         my $path = $smsg->path;
151         if (defined $path && $path ne '') {
152                 my $path = id_compress($smsg->path);
153                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
154                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
155         }
156         $opts ||= {};
157         $opts->{limit} ||= 1000;
158
159         # always sort threads by timestamp, this makes life easier
160         # for the threading algorithm (in SearchThread.pm)
161         $opts->{asc} = 1;
162
163         _do_enquire($self, $qtid, $opts);
164 }
165
166 sub retry_reopen {
167         my ($self, $cb) = @_;
168         my $ret;
169         for (1..10) {
170                 eval { $ret = $cb->() };
171                 return $ret unless $@;
172                 # Exception: The revision being read has been discarded -
173                 # you should call Xapian::Database::reopen()
174                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
175                         reopen($self);
176                 } else {
177                         die;
178                 }
179         }
180 }
181
182 sub _do_enquire {
183         my ($self, $query, $opts) = @_;
184         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
185 }
186
187 sub _enquire_once {
188         my ($self, $query, $opts) = @_;
189         my $enquire = $self->enquire;
190         if (defined $query) {
191                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
192         } else {
193                 $query = $mail_query;
194         }
195         $enquire->set_query($query);
196         $opts ||= {};
197         my $desc = !$opts->{asc};
198         if ($opts->{relevance}) {
199                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
200         } elsif ($opts->{num}) {
201                 $enquire->set_sort_by_value(NUM, 0);
202         } else {
203                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
204         }
205         my $offset = $opts->{offset} || 0;
206         my $limit = $opts->{limit} || 50;
207         my $mset = $enquire->get_mset($offset, $limit);
208         return $mset if $opts->{mset};
209         my @msgs = map {
210                 PublicInbox::SearchMsg->load_doc($_->get_document);
211         } $mset->items;
212
213         { total => $mset->get_matches_estimated, msgs => \@msgs }
214 }
215
216 # read-write
217 sub stemmer { Search::Xapian::Stem->new($LANG) }
218
219 # read-only
220 sub qp {
221         my ($self) = @_;
222
223         my $qp = $self->{query_parser};
224         return $qp if $qp;
225
226         # new parser
227         $qp = Search::Xapian::QueryParser->new;
228         $qp->set_default_op(OP_AND);
229         $qp->set_database($self->{xdb});
230         $qp->set_stemmer($self->stemmer);
231         $qp->set_stemming_strategy(STEM_SOME);
232         $qp->add_valuerangeprocessor(
233                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
234
235         while (my ($name, $prefix) = each %bool_pfx_external) {
236                 $qp->add_boolean_prefix($name, $prefix);
237         }
238
239         # we do not actually create AltId objects,
240         # just parse the spec to avoid the extra DB handles for now.
241         if (my $altid = $self->{altid}) {
242                 my $user_pfx = $self->{-user_pfx} ||= [];
243                 for (@$altid) {
244                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
245                         /\Aserial:(\w+):/ or next;
246                         my $pfx = $1;
247                         push @$user_pfx, "$pfx:", <<EOF;
248 alternate serial number  e.g. $pfx:12345 (boolean)
249 EOF
250                         # gmane => XGMANE
251                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
252                 }
253                 chomp @$user_pfx;
254         }
255
256         while (my ($name, $prefix) = each %prob_prefix) {
257                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
258         }
259
260         $self->{query_parser} = $qp;
261 }
262
263 sub num_range_processor {
264         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
265 }
266
267 # only used for NNTP server
268 sub query_xover {
269         my ($self, $beg, $end, $offset) = @_;
270         my $qp = Search::Xapian::QueryParser->new;
271         $qp->set_database($self->{xdb});
272         $qp->add_valuerangeprocessor($self->num_range_processor);
273         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
274
275         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
276 }
277
278 sub lookup_message {
279         my ($self, $mid) = @_;
280         $mid = mid_clean($mid);
281
282         my $doc_id = $self->find_unique_doc_id('mid', $mid);
283         my $smsg;
284         if (defined $doc_id) {
285                 # raises on error:
286                 my $doc = $self->{xdb}->get_document($doc_id);
287                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
288                 $smsg->{doc_id} = $doc_id;
289         }
290         $smsg;
291 }
292
293 sub lookup_mail { # no ghosts!
294         my ($self, $mid) = @_;
295         retry_reopen($self, sub {
296                 my $smsg = lookup_message($self, $mid) or return;
297                 PublicInbox::SearchMsg->load_doc($smsg->{doc});
298         });
299 }
300
301 sub find_unique_doc_id {
302         my ($self, $term, $value) = @_;
303
304         my ($begin, $end) = $self->find_doc_ids($term, $value);
305
306         return undef if $begin->equal($end); # not found
307
308         my $rv = $begin->get_docid;
309
310         # sanity check
311         $begin->inc;
312         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
313         $rv;
314 }
315
316 # returns begin and end PostingIterator
317 sub find_doc_ids {
318         my ($self, $term, $value) = @_;
319
320         $self->find_doc_ids_for_term(xpfx($term) . $value);
321 }
322
323 # returns begin and end PostingIterator
324 sub find_doc_ids_for_term {
325         my ($self, $term) = @_;
326         my $db = $self->{xdb};
327
328         ($db->postlist_begin($term), $db->postlist_end($term));
329 }
330
331 # normalize subjects so they are suitable as pathnames for URLs
332 # XXX: consider for removal
333 sub subject_path {
334         my $subj = pop;
335         $subj = subject_normalized($subj);
336         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
337         lc($subj);
338 }
339
340 sub subject_normalized {
341         my $subj = pop;
342         $subj =~ s/\A\s+//s; # no leading space
343         $subj =~ s/\s+\z//s; # no trailing space
344         $subj =~ s/\s+/ /gs; # no redundant spaces
345         $subj =~ s/\.+\z//; # no trailing '.'
346         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
347         $subj;
348 }
349
350 sub enquire {
351         my ($self) = @_;
352         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
353 }
354
355 sub help {
356         my ($self) = @_;
357         $self->qp; # parse altids
358         my @ret = @HELP;
359         if (my $user_pfx = $self->{-user_pfx}) {
360                 push @ret, @$user_pfx;
361         }
362         \@ret;
363 }
364
365 1;