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