]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
replace Xapian skeleton with SQLite overview DB
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2018 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <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;  # Received: header in Unix time
12 use constant YYYYMMDD => 1; # for searching in the WWW UI
13
14 use Search::Xapian qw/:standard/;
15 use PublicInbox::SearchMsg;
16 use PublicInbox::MIME;
17 use PublicInbox::MID qw/id_compress/;
18 use PublicInbox::Over;
19
20 # This is English-only, everything else is non-standard and may be confused as
21 # a prefix common in patch emails
22 our $REPLY_RE = qr/^re:\s+/i;
23 our $LANG = 'english';
24
25 use constant {
26         # SCHEMA_VERSION history
27         # 0 - initial
28         # 1 - subject_path is lower-cased
29         # 2 - subject_path is id_compress in the index, only
30         # 3 - message-ID is compressed if it includes '%' (hack!)
31         # 4 - change "Re: " normalization, avoid circular Reference ghosts
32         # 5 - subject_path drops trailing '.'
33         # 6 - preserve References: order in document data
34         # 7 - remove references and inreplyto terms
35         # 8 - remove redundant/unneeded document data
36         # 9 - disable Message-ID compression (SHA-1)
37         # 10 - optimize doc for NNTP overviews
38         # 11 - merge threads when vivifying ghosts
39         # 12 - change YYYYMMDD value column to numeric
40         # 13 - fix threading for empty References/In-Reply-To
41         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
42         # 14 - fix ghost root vivification
43         SCHEMA_VERSION => 15,
44
45         # n.b. FLAG_PURE_NOT is expensive not suitable for a public website
46         # as it could become a denial-of-service vector
47         QP_FLAGS => FLAG_PHRASE|FLAG_BOOLEAN|FLAG_LOVEHATE|FLAG_WILDCARD,
48 };
49
50 my %bool_pfx_external = (
51         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
52 );
53
54 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
55 my %prob_prefix = (
56         # for mairix compatibility
57         s => 'S',
58         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
59         f => 'A',
60         t => 'XTO',
61         tc => 'XTO XCC',
62         c => 'XCC',
63         tcf => 'XTO XCC A',
64         a => 'XTO XCC A',
65         b => $non_quoted_body . ' XQUOT',
66         bs => $non_quoted_body . ' XQUOT S',
67         n => 'XFN',
68
69         q => 'XQUOT',
70         nq => $non_quoted_body,
71         dfn => 'XDFN',
72         dfa => 'XDFA',
73         dfb => 'XDFB',
74         dfhh => 'XDFHH',
75         dfctx => 'XDFCTX',
76         dfpre => 'XDFPRE',
77         dfpost => 'XDFPOST',
78         dfblob => 'XDFPRE XDFPOST',
79
80         # default:
81         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
82 );
83
84 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
85 our @HELP = (
86         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
87         'd:' => <<EOF,
88 date range as YYYYMMDD  e.g. d:19931002..20101002
89 Open-ended ranges such as d:19931002.. and d:..20101002
90 are also supported
91 EOF
92         'b:' => 'match within message body, including text attachments',
93         'nq:' => 'match non-quoted text within message body',
94         'q:' => 'match quoted text within message body',
95         'n:' => 'match filename of attachment(s)',
96         't:' => 'match within the To header',
97         'c:' => 'match within the Cc header',
98         'f:' => 'match within the From header',
99         'a:' => 'match within the To, Cc, and From headers',
100         'tc:' => 'match within the To and Cc headers',
101         'bs:' => 'match within the Subject and body',
102         'dfn:' => 'match filename from diff',
103         'dfa:' => 'match diff removed (-) lines',
104         'dfb:' => 'match diff added (+) lines',
105         'dfhh:' => 'match diff hunk header context (usually a function name)',
106         'dfctx:' => 'match diff context lines',
107         'dfpre:' => 'match pre-image git blob ID',
108         'dfpost:' => 'match post-image git blob ID',
109         'dfblob:' => 'match either pre or post-image git blob ID',
110 );
111 chomp @HELP;
112
113 sub xdir {
114         my ($self) = @_;
115         if ($self->{version} == 1) {
116                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
117         } else {
118                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
119                 my $part = $self->{partition};
120                 defined $part or die "partition not given";
121                 $dir .= "/$part";
122         }
123 }
124
125 sub new {
126         my ($class, $mainrepo, $altid) = @_;
127         my $version = 1;
128         my $ibx = $mainrepo;
129         if (ref $ibx) {
130                 $version = $ibx->{version} || 1;
131                 $mainrepo = $ibx->{mainrepo};
132         }
133         my $self = bless {
134                 mainrepo => $mainrepo,
135                 altid => $altid,
136                 version => $version,
137         }, $class;
138         my $dir;
139         if ($version >= 2) {
140                 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
141                 my $xdb;
142                 my $parts = 0;
143                 foreach my $part (<$dir/*>) {
144                         -d $part && $part =~ m!/\d+\z! or next;
145                         $parts++;
146                         my $sub = Search::Xapian::Database->new($part);
147                         if ($xdb) {
148                                 $xdb->add_database($sub);
149                         } else {
150                                 $xdb = $sub;
151                         }
152                 }
153                 $self->{xdb} = $xdb;
154         } else {
155                 $dir = $self->xdir;
156                 $self->{xdb} = Search::Xapian::Database->new($dir);
157         }
158         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
159         $self;
160 }
161
162 sub reopen {
163         my ($self) = @_;
164         $self->{xdb}->reopen;
165         $self; # make chaining easier
166 }
167
168 # read-only
169 sub query {
170         my ($self, $query_string, $opts) = @_;
171         $opts ||= {};
172         if ($query_string eq '' && !$opts->{mset}) {
173                 $self->{over_ro}->recent($opts);
174         } else {
175                 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
176                 $opts->{relevance} = 1 unless exists $opts->{relevance};
177                 _do_enquire($self, $query, $opts);
178         }
179 }
180
181 sub get_thread {
182         my ($self, $mid, $opts) = @_;
183         $self->{over_ro}->get_thread($mid, $opts);
184 }
185
186 sub retry_reopen {
187         my ($self, $cb) = @_;
188         my $ret;
189         for my $i (1..10) {
190                 eval { $ret = $cb->() };
191                 return $ret unless $@;
192                 # Exception: The revision being read has been discarded -
193                 # you should call Xapian::Database::reopen()
194                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
195                         warn "reopen try #$i on $@\n";
196                         reopen($self);
197                 } else {
198                         warn "ref: ", ref($@), "\n";
199                         die;
200                 }
201         }
202         die "Too many Xapian database modifications in progress\n";
203 }
204
205 sub _do_enquire {
206         my ($self, $query, $opts) = @_;
207         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
208 }
209
210 sub _enquire_once {
211         my ($self, $query, $opts) = @_;
212         my $enquire = enquire($self);
213         $query = Search::Xapian::Query->new(OP_AND,$query);
214         $enquire->set_query($query);
215         $opts ||= {};
216         my $desc = !$opts->{asc};
217         if ($opts->{relevance}) {
218                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
219         } else {
220                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
221         }
222         my $offset = $opts->{offset} || 0;
223         my $limit = $opts->{limit} || 50;
224         my $mset = $enquire->get_mset($offset, $limit);
225         return $mset if $opts->{mset};
226         my @msgs = map {
227                 PublicInbox::SearchMsg->load_doc($_->get_document);
228         } $mset->items;
229
230         { total => $mset->get_matches_estimated, msgs => \@msgs }
231 }
232
233 # read-write
234 sub stemmer { Search::Xapian::Stem->new($LANG) }
235
236 # read-only
237 sub qp {
238         my ($self) = @_;
239
240         my $qp = $self->{query_parser};
241         return $qp if $qp;
242
243         # new parser
244         $qp = Search::Xapian::QueryParser->new;
245         $qp->set_default_op(OP_AND);
246         $qp->set_database($self->{xdb});
247         $qp->set_stemmer($self->stemmer);
248         $qp->set_stemming_strategy(STEM_SOME);
249         $qp->add_valuerangeprocessor(
250                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
251
252         while (my ($name, $prefix) = each %bool_pfx_external) {
253                 $qp->add_boolean_prefix($name, $prefix);
254         }
255
256         # we do not actually create AltId objects,
257         # just parse the spec to avoid the extra DB handles for now.
258         if (my $altid = $self->{altid}) {
259                 my $user_pfx = $self->{-user_pfx} ||= [];
260                 for (@$altid) {
261                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
262                         /\Aserial:(\w+):/ or next;
263                         my $pfx = $1;
264                         push @$user_pfx, "$pfx:", <<EOF;
265 alternate serial number  e.g. $pfx:12345 (boolean)
266 EOF
267                         # gmane => XGMANE
268                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
269                 }
270                 chomp @$user_pfx;
271         }
272
273         while (my ($name, $prefix) = each %prob_prefix) {
274                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
275         }
276
277         $self->{query_parser} = $qp;
278 }
279
280 # only used for NNTP server
281 sub query_xover {
282         my ($self, $beg, $end, $offset) = @_;
283         $self->{over_ro}->query_xover($beg, $end, $offset);
284 }
285
286 sub query_ts {
287         my ($self, $ts, $offset) = @_;
288         $self->{over_ro}->query_ts($ts, $offset);
289 }
290
291 sub first_smsg_by_mid {
292         my ($self, $mid) = @_;
293         my $smsg;
294         retry_reopen($self, sub {
295                 each_smsg_by_mid($self, $mid, sub { $smsg = $_[0]; undef });
296         });
297         $smsg;
298 }
299
300 sub lookup_article {
301         my ($self, $num) = @_;
302         my $term = 'XNUM'.$num;
303         my $db = $self->{xdb};
304         retry_reopen($self, sub {
305                 my $head = $db->postlist_begin($term);
306                 my $tail = $db->postlist_end($term);
307                 return if $head->equal($tail);
308                 my $doc_id = $head->get_docid;
309                 return unless defined $doc_id;
310                 $head->inc;
311                 if ($head->nequal($tail)) {
312                         warn "article #$num is not unique\n";
313                 }
314                 # raises on error:
315                 my $doc = $db->get_document($doc_id);
316                 my $smsg = PublicInbox::SearchMsg->wrap($doc);
317                 $smsg->{doc_id} = $doc_id;
318                 $smsg->load_expand;
319         });
320 }
321
322 sub each_smsg_by_mid {
323         my ($self, $mid, $cb) = @_;
324         # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
325         # interface will need it...
326         my $db = $self->{xdb};
327         my $term = 'Q' . $mid;
328         my $head = $db->postlist_begin($term);
329         my $tail = $db->postlist_end($term);
330         if ($head == $tail) {
331                 $db->reopen;
332                 $head = $db->postlist_begin($term);
333                 $tail = $db->postlist_end($term);
334         }
335         return ($head, $tail, $db) if wantarray;
336         for (; $head->nequal($tail); $head->inc) {
337                 my $doc_id = $head->get_docid;
338                 my $doc = $db->get_document($doc_id);
339                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
340                 $smsg->{doc_id} = $doc_id;
341                 $cb->($smsg) or return;
342         }
343 }
344
345 # normalize subjects so they are suitable as pathnames for URLs
346 # XXX: consider for removal
347 sub subject_path {
348         my $subj = pop;
349         $subj = subject_normalized($subj);
350         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
351         lc($subj);
352 }
353
354 sub subject_normalized {
355         my $subj = pop;
356         $subj =~ s/\A\s+//s; # no leading space
357         $subj =~ s/\s+\z//s; # no trailing space
358         $subj =~ s/\s+/ /gs; # no redundant spaces
359         $subj =~ s/\.+\z//; # no trailing '.'
360         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
361         $subj;
362 }
363
364 sub enquire {
365         my ($self) = @_;
366         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
367 }
368
369 sub help {
370         my ($self) = @_;
371         $self->qp; # parse altids
372         my @ret = @HELP;
373         if (my $user_pfx = $self->{-user_pfx}) {
374                 push @ret, @$user_pfx;
375         }
376         \@ret;
377 }
378
379 1;