]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
7561ef447ec8b6f07add73152e086495075bbcbc
[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         SCHEMA_VERSION => 11,
42
43         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
44         # as it could become a denial-of-service vector
45         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
46 };
47
48 # setup prefixes
49 my %bool_pfx_internal = (
50         type => 'T', # "mail" or "ghost"
51         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
52 );
53
54 my %bool_pfx_external = (
55         path => 'XPATH',
56         mid => 'Q', # uniQue id (Message-ID)
57 );
58
59 my %prob_prefix = (
60         subject => 'S',
61         s => 'S', # for mairix compatibility
62         m => 'Q', # 'mid' is exact, 'm' can do partial
63 );
64
65 my %all_pfx = (%bool_pfx_internal, %bool_pfx_external, %prob_prefix);
66
67 sub xpfx { $all_pfx{$_[0]} }
68
69 our %PFX2TERM_RMAP;
70 my %meta_pfx = (mid => 1, thread => 1, path => 1);
71 while (my ($k, $v) = each %all_pfx) {
72         $PFX2TERM_RMAP{$v} = $k if $meta_pfx{$k};
73 }
74
75 my $mail_query = Search::Xapian::Query->new(xpfx('type') . 'mail');
76
77 sub xdir {
78         my (undef, $git_dir) = @_;
79         "$git_dir/public-inbox/xapian" . SCHEMA_VERSION;
80 }
81
82 sub new {
83         my ($class, $git_dir, $altid) = @_;
84         my $dir = $class->xdir($git_dir);
85         my $db = Search::Xapian::Database->new($dir);
86         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $class;
87 }
88
89 sub reopen { $_[0]->{xdb}->reopen }
90
91 # read-only
92 sub query {
93         my ($self, $query_string, $opts) = @_;
94         my $query;
95
96         $opts ||= {};
97         unless ($query_string eq '') {
98                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
99                 $opts->{relevance} = 1 unless exists $opts->{relevance};
100         }
101
102         _do_enquire($self, $query, $opts);
103 }
104
105 sub get_thread {
106         my ($self, $mid, $opts) = @_;
107         my $smsg = eval { $self->lookup_message($mid) };
108
109         return { total => 0, msgs => [] } unless $smsg;
110         my $qtid = Search::Xapian::Query->new(xpfx('thread').$smsg->thread_id);
111         my $path = $smsg->path;
112         if (defined $path && $path ne '') {
113                 my $path = id_compress($smsg->path);
114                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
115                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
116         }
117         $opts ||= {};
118         $opts->{limit} ||= 1000;
119         _do_enquire($self, $qtid, $opts);
120 }
121
122 sub _do_enquire {
123         my ($self, $query, $opts) = @_;
124         my $ret;
125         for (1..10) {
126                 eval { $ret = _enquire_once($self, $query, $opts) };
127                 return $ret unless $@;
128                 # Exception: The revision being read has been discarded -
129                 # you should call Xapian::Database::reopen()
130                 if (index($@, 'Xapian::Database::reopen') >= 0) {
131                         reopen($self);
132                 } else {
133                         die $@;
134                 }
135         }
136 }
137
138 sub _enquire_once {
139         my ($self, $query, $opts) = @_;
140         my $enquire = $self->enquire;
141         if (defined $query) {
142                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
143         } else {
144                 $query = $mail_query;
145         }
146         $enquire->set_query($query);
147         $opts ||= {};
148         my $desc = !$opts->{asc};
149         if ($opts->{relevance}) {
150                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
151         } elsif ($opts->{num}) {
152                 $enquire->set_sort_by_value(NUM, 0);
153         } else {
154                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
155         }
156         my $offset = $opts->{offset} || 0;
157         my $limit = $opts->{limit} || 50;
158         my $mset = $enquire->get_mset($offset, $limit);
159         return $mset if $opts->{mset};
160         my @msgs = map {
161                 PublicInbox::SearchMsg->load_doc($_->get_document);
162         } $mset->items;
163
164         { total => $mset->get_matches_estimated, msgs => \@msgs }
165 }
166
167 # read-write
168 sub stemmer { Search::Xapian::Stem->new($LANG) }
169
170 # read-only
171 sub qp {
172         my ($self) = @_;
173
174         my $qp = $self->{query_parser};
175         return $qp if $qp;
176
177         # new parser
178         $qp = Search::Xapian::QueryParser->new;
179         $qp->set_default_op(OP_AND);
180         $qp->set_database($self->{xdb});
181         $qp->set_stemmer($self->stemmer);
182         $qp->set_stemming_strategy(STEM_SOME);
183         $qp->add_valuerangeprocessor(
184                 Search::Xapian::StringValueRangeProcessor->new(YYYYMMDD, 'd:'));
185
186         while (my ($name, $prefix) = each %bool_pfx_external) {
187                 $qp->add_boolean_prefix($name, $prefix);
188         }
189
190         # we do not actually create AltId objects,
191         # just parse the spec to avoid the extra DB handles for now.
192         if (my $altid = $self->{altid}) {
193                 for (@$altid) {
194                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
195                         /\Aserial:(\w+):/ or next;
196                         my $pfx = $1;
197                         # gmane => XGMANE
198                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
199                 }
200         }
201
202         while (my ($name, $prefix) = each %prob_prefix) {
203                 $qp->add_prefix($name, $prefix);
204         }
205
206         $self->{query_parser} = $qp;
207 }
208
209 sub num_range_processor {
210         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
211 }
212
213 # only used for NNTP server
214 sub query_xover {
215         my ($self, $beg, $end, $offset) = @_;
216         my $qp = Search::Xapian::QueryParser->new;
217         $qp->set_database($self->{xdb});
218         $qp->add_valuerangeprocessor($self->num_range_processor);
219         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
220
221         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
222 }
223
224 sub lookup_message {
225         my ($self, $mid) = @_;
226         $mid = mid_clean($mid);
227
228         my $doc_id = $self->find_unique_doc_id('mid', $mid);
229         my $smsg;
230         if (defined $doc_id) {
231                 # raises on error:
232                 my $doc = $self->{xdb}->get_document($doc_id);
233                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
234                 $smsg->doc_id($doc_id);
235         }
236         $smsg;
237 }
238
239 sub lookup_mail { # no ghosts!
240         my ($self, $mid) = @_;
241         my $smsg = lookup_message($self, $mid) or return;
242         PublicInbox::SearchMsg->load_doc($smsg->{doc});
243 }
244
245 sub find_unique_doc_id {
246         my ($self, $term, $value) = @_;
247
248         my ($begin, $end) = $self->find_doc_ids($term, $value);
249
250         return undef if $begin->equal($end); # not found
251
252         my $rv = $begin->get_docid;
253
254         # sanity check
255         $begin->inc;
256         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
257         $rv;
258 }
259
260 # returns begin and end PostingIterator
261 sub find_doc_ids {
262         my ($self, $term, $value) = @_;
263
264         $self->find_doc_ids_for_term(xpfx($term) . $value);
265 }
266
267 # returns begin and end PostingIterator
268 sub find_doc_ids_for_term {
269         my ($self, $term) = @_;
270         my $db = $self->{xdb};
271
272         ($db->postlist_begin($term), $db->postlist_end($term));
273 }
274
275 # normalize subjects so they are suitable as pathnames for URLs
276 sub subject_path {
277         my $subj = pop;
278         $subj = subject_normalized($subj);
279         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
280         lc($subj);
281 }
282
283 sub subject_normalized {
284         my $subj = pop;
285         $subj =~ s/\A\s+//s; # no leading space
286         $subj =~ s/\s+\z//s; # no trailing space
287         $subj =~ s/\s+/ /gs; # no redundant spaces
288         $subj =~ s/\.+\z//; # no trailing '.'
289         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
290         $subj;
291 }
292
293 # for doc data
294 sub subject_summary {
295         my $subj = pop;
296         my $max = 68;
297         if (length($subj) > $max) {
298                 my @subj = split(/\s+/, $subj);
299                 $subj = '';
300                 my $l;
301
302                 while ($l = shift @subj) {
303                         my $new = $subj . $l . ' ';
304                         last if length($new) >= $max;
305                         $subj = $new;
306                 }
307                 if ($subj ne '') {
308                         my $r = scalar @subj ? ' ...' : '';
309                         $subj =~ s/ \z/$r/s;
310                 } else {
311                         # subject has one REALLY long word, and NOT spam? wtf
312                         @subj = ($l =~ /\A(.{1,72})/);
313                         $subj = $subj[0] . ' ...';
314                 }
315         }
316         $subj;
317 }
318
319 sub enquire {
320         my ($self) = @_;
321         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
322 }
323
324 1;