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