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