]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: drop pointless range processors for Unix timestamp
[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, $altid) = @_;
83         my $dir = $class->xdir($git_dir);
84         my $db = Search::Xapian::Database->new($dir);
85         bless { xdb => $db, git_dir => $git_dir, altid => $altid }, $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 = $smsg->path;
111         if (defined $path && $path ne '') {
112                 my $path = id_compress($smsg->path);
113                 my $qsub = Search::Xapian::Query->new(xpfx('path').$path);
114                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
115         }
116         $opts ||= {};
117         $opts->{limit} ||= 1000;
118         _do_enquire($self, $qtid, $opts);
119 }
120
121 sub _do_enquire {
122         my ($self, $query, $opts) = @_;
123         my $ret;
124         for (1..10) {
125                 eval { $ret = _enquire_once($self, $query, $opts) };
126                 return $ret unless $@;
127                 # Exception: The revision being read has been discarded -
128                 # you should call Xapian::Database::reopen()
129                 if (index($@, 'Xapian::Database::reopen') >= 0) {
130                         reopen($self);
131                 } else {
132                         die $@;
133                 }
134         }
135 }
136
137 sub _enquire_once {
138         my ($self, $query, $opts) = @_;
139         my $enquire = $self->enquire;
140         if (defined $query) {
141                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
142         } else {
143                 $query = $mail_query;
144         }
145         $enquire->set_query($query);
146         $opts ||= {};
147         my $desc = !$opts->{asc};
148         if ($opts->{relevance}) {
149                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
150         } elsif ($opts->{num}) {
151                 $enquire->set_sort_by_value(NUM, 0);
152         } else {
153                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
154         }
155         my $offset = $opts->{offset} || 0;
156         my $limit = $opts->{limit} || 50;
157         my $mset = $enquire->get_mset($offset, $limit);
158         return $mset if $opts->{mset};
159         my @msgs = map {
160                 PublicInbox::SearchMsg->load_doc($_->get_document);
161         } $mset->items;
162
163         { total => $mset->get_matches_estimated, msgs => \@msgs }
164 }
165
166 # read-write
167 sub stemmer { Search::Xapian::Stem->new($LANG) }
168
169 # read-only
170 sub qp {
171         my ($self) = @_;
172
173         my $qp = $self->{query_parser};
174         return $qp if $qp;
175
176         # new parser
177         $qp = Search::Xapian::QueryParser->new;
178         $qp->set_default_op(OP_AND);
179         $qp->set_database($self->{xdb});
180         $qp->set_stemmer($self->stemmer);
181         $qp->set_stemming_strategy(STEM_SOME);
182
183         while (my ($name, $prefix) = each %bool_pfx_external) {
184                 $qp->add_boolean_prefix($name, $prefix);
185         }
186
187         # we do not actually create AltId objects,
188         # just parse the spec to avoid the extra DB handles for now.
189         if (my $altid = $self->{altid}) {
190                 for (@$altid) {
191                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
192                         /\Aserial:(\w+):/ or next;
193                         my $pfx = $1;
194                         # gmane => XGMANE
195                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
196                 }
197         }
198
199         while (my ($name, $prefix) = each %prob_prefix) {
200                 $qp->add_prefix($name, $prefix);
201         }
202
203         $self->{query_parser} = $qp;
204 }
205
206 sub num_range_processor {
207         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
208 }
209
210 # only used for NNTP server
211 sub query_xover {
212         my ($self, $beg, $end, $offset) = @_;
213         my $qp = Search::Xapian::QueryParser->new;
214         $qp->set_database($self->{xdb});
215         $qp->add_valuerangeprocessor($self->num_range_processor);
216         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
217
218         _do_enquire($self, $query, {num => 1, limit => 200, offset => $offset});
219 }
220
221 sub lookup_message {
222         my ($self, $mid) = @_;
223         $mid = mid_clean($mid);
224
225         my $doc_id = $self->find_unique_doc_id('mid', $mid);
226         my $smsg;
227         if (defined $doc_id) {
228                 # raises on error:
229                 my $doc = $self->{xdb}->get_document($doc_id);
230                 $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
231                 $smsg->doc_id($doc_id);
232         }
233         $smsg;
234 }
235
236 sub lookup_mail { # no ghosts!
237         my ($self, $mid) = @_;
238         my $smsg = lookup_message($self, $mid) or return;
239         PublicInbox::SearchMsg->load_doc($smsg->{doc});
240 }
241
242 sub find_unique_doc_id {
243         my ($self, $term, $value) = @_;
244
245         my ($begin, $end) = $self->find_doc_ids($term, $value);
246
247         return undef if $begin->equal($end); # not found
248
249         my $rv = $begin->get_docid;
250
251         # sanity check
252         $begin->inc;
253         $begin->equal($end) or die "Term '$term:$value' is not unique\n";
254         $rv;
255 }
256
257 # returns begin and end PostingIterator
258 sub find_doc_ids {
259         my ($self, $term, $value) = @_;
260
261         $self->find_doc_ids_for_term(xpfx($term) . $value);
262 }
263
264 # returns begin and end PostingIterator
265 sub find_doc_ids_for_term {
266         my ($self, $term) = @_;
267         my $db = $self->{xdb};
268
269         ($db->postlist_begin($term), $db->postlist_end($term));
270 }
271
272 # normalize subjects so they are suitable as pathnames for URLs
273 sub subject_path {
274         my $subj = pop;
275         $subj = subject_normalized($subj);
276         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
277         lc($subj);
278 }
279
280 sub subject_normalized {
281         my $subj = pop;
282         $subj =~ s/\A\s+//s; # no leading space
283         $subj =~ s/\s+\z//s; # no trailing space
284         $subj =~ s/\s+/ /gs; # no redundant spaces
285         $subj =~ s/\.+\z//; # no trailing '.'
286         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
287         $subj;
288 }
289
290 # for doc data
291 sub subject_summary {
292         my $subj = pop;
293         my $max = 68;
294         if (length($subj) > $max) {
295                 my @subj = split(/\s+/, $subj);
296                 $subj = '';
297                 my $l;
298
299                 while ($l = shift @subj) {
300                         my $new = $subj . $l . ' ';
301                         last if length($new) >= $max;
302                         $subj = $new;
303                 }
304                 if ($subj ne '') {
305                         my $r = scalar @subj ? ' ...' : '';
306                         $subj =~ s/ \z/$r/s;
307                 } else {
308                         # subject has one REALLY long word, and NOT spam? wtf
309                         @subj = ($l =~ /\A(.{1,72})/);
310                         $subj = $subj[0] . ' ...';
311                 }
312         }
313         $subj;
314 }
315
316 sub enquire {
317         my ($self) = @_;
318         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
319 }
320
321 1;