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