]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
ca389e320b2706edacbbd578b33dacc65812dece
[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 use constant NUM => 2; # NNTP article number
14
15 use Search::Xapian qw/:standard/;
16 use PublicInbox::SearchMsg;
17 use PublicInbox::MIME;
18 use PublicInbox::MID qw/id_compress/;
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 => 14,
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 # setup prefixes
51 my %bool_pfx_internal = (
52         type => 'T', # "mail" or "ghost"
53         thread => 'G', # newsGroup (or similar entity - e.g. a web forum name)
54 );
55
56 my %bool_pfx_external = (
57         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
58 );
59
60 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
61 my %prob_prefix = (
62         # for mairix compatibility
63         s => 'S',
64         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
65         f => 'A',
66         t => 'XTO',
67         tc => 'XTO XCC',
68         c => 'XCC',
69         tcf => 'XTO XCC A',
70         a => 'XTO XCC A',
71         b => $non_quoted_body . ' XQUOT',
72         bs => $non_quoted_body . ' XQUOT S',
73         n => 'XFN',
74
75         q => 'XQUOT',
76         nq => $non_quoted_body,
77         dfn => 'XDFN',
78         dfa => 'XDFA',
79         dfb => 'XDFB',
80         dfhh => 'XDFHH',
81         dfctx => 'XDFCTX',
82         dfpre => 'XDFPRE',
83         dfpost => 'XDFPOST',
84         dfblob => 'XDFPRE XDFPOST',
85
86         # default:
87         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
88 );
89
90 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
91 our @HELP = (
92         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
93         'd:' => <<EOF,
94 date range as YYYYMMDD  e.g. d:19931002..20101002
95 Open-ended ranges such as d:19931002.. and d:..20101002
96 are also supported
97 EOF
98         'b:' => 'match within message body, including text attachments',
99         'nq:' => 'match non-quoted text within message body',
100         'q:' => 'match quoted text within message body',
101         'n:' => 'match filename of attachment(s)',
102         't:' => 'match within the To header',
103         'c:' => 'match within the Cc header',
104         'f:' => 'match within the From header',
105         'a:' => 'match within the To, Cc, and From headers',
106         'tc:' => 'match within the To and Cc headers',
107         'bs:' => 'match within the Subject and body',
108         'dfn:' => 'match filename from diff',
109         'dfa:' => 'match diff removed (-) lines',
110         'dfb:' => 'match diff added (+) lines',
111         'dfhh:' => 'match diff hunk header context (usually a function name)',
112         'dfctx:' => 'match diff context lines',
113         'dfpre:' => 'match pre-image git blob ID',
114         'dfpost:' => 'match post-image git blob ID',
115         'dfblob:' => 'match either pre or post-image git blob ID',
116 );
117 chomp @HELP;
118
119 my $mail_query = Search::Xapian::Query->new('T' . 'mail');
120
121 sub xdir {
122         my ($self) = @_;
123         if ($self->{version} == 1) {
124                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
125         } else {
126                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
127                 my $part = $self->{partition};
128                 defined $part or die "partition not given";
129                 $dir .= "/$part";
130         }
131 }
132
133 sub new {
134         my ($class, $mainrepo, $altid) = @_;
135         my $version = 1;
136         my $ibx = $mainrepo;
137         if (ref $ibx) {
138                 $version = $ibx->{version} || 1;
139                 $mainrepo = $ibx->{mainrepo};
140         }
141         my $self = bless {
142                 mainrepo => $mainrepo,
143                 altid => $altid,
144                 version => $version,
145         }, $class;
146         if ($version >= 2) {
147                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
148                 my $xdb;
149                 my $parts = 0;
150                 foreach my $part (<$dir/*>) {
151                         -d $part && $part =~ m!/\d+\z! or next;
152                         $parts++;
153                         my $sub = Search::Xapian::Database->new($part);
154                         if ($xdb) {
155                                 $xdb->add_database($sub);
156                         } else {
157                                 $xdb = $sub;
158                         }
159                 }
160                 $self->{xdb} = $xdb;
161                 $self->{skel} = Search::Xapian::Database->new("$dir/skel");
162         } else {
163                 $self->{xdb} = Search::Xapian::Database->new($self->xdir);
164         }
165         $self;
166 }
167
168 sub reopen {
169         my ($self) = @_;
170         $self->{xdb}->reopen;
171         if (my $skel = $self->{skel}) {
172                 $skel->reopen;
173         }
174         $self; # make chaining easier
175 }
176
177 # read-only
178 sub query {
179         my ($self, $query_string, $opts) = @_;
180         my $query;
181
182         $opts ||= {};
183         unless ($query_string eq '') {
184                 $query = $self->qp->parse_query($query_string, QP_FLAGS);
185                 $opts->{relevance} = 1 unless exists $opts->{relevance};
186         }
187
188         _do_enquire($self, $query, $opts);
189 }
190
191 sub get_thread {
192         my ($self, $mid, $opts) = @_;
193         my $smsg = first_smsg_by_mid($self, $mid) or
194                         return { total => 0, msgs => [] };
195         my $qtid = Search::Xapian::Query->new('G' . $smsg->thread_id);
196         my $path = $smsg->path;
197         if (defined $path && $path ne '') {
198                 my $path = id_compress($smsg->path);
199                 my $qsub = Search::Xapian::Query->new('XPATH' . $path);
200                 $qtid = Search::Xapian::Query->new(OP_OR, $qtid, $qsub);
201         }
202         $opts ||= {};
203         $opts->{limit} ||= 1000;
204
205         # always sort threads by timestamp, this makes life easier
206         # for the threading algorithm (in SearchThread.pm)
207         $opts->{asc} = 1;
208         $opts->{enquire} = enquire_skel($self);
209         _do_enquire($self, $qtid, $opts);
210 }
211
212 sub retry_reopen {
213         my ($self, $cb) = @_;
214         my $ret;
215         for my $i (1..10) {
216                 eval { $ret = $cb->() };
217                 return $ret unless $@;
218                 # Exception: The revision being read has been discarded -
219                 # you should call Xapian::Database::reopen()
220                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
221                         warn "reopen try #$i on $@\n";
222                         reopen($self);
223                 } else {
224                         warn "ref: ", ref($@), "\n";
225                         die;
226                 }
227         }
228         die "Too many Xapian database modifications in progress\n";
229 }
230
231 sub _do_enquire {
232         my ($self, $query, $opts) = @_;
233         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
234 }
235
236 sub _enquire_once {
237         my ($self, $query, $opts) = @_;
238         my $enquire = $opts->{enquire} || enquire($self);
239         if (defined $query) {
240                 $query = Search::Xapian::Query->new(OP_AND,$query,$mail_query);
241         } else {
242                 $query = $mail_query;
243         }
244         $enquire->set_query($query);
245         $opts ||= {};
246         my $desc = !$opts->{asc};
247         if ($opts->{relevance}) {
248                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
249         } elsif ($opts->{num}) {
250                 $enquire->set_sort_by_value(NUM, 0);
251         } else {
252                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
253         }
254         my $offset = $opts->{offset} || 0;
255         my $limit = $opts->{limit} || 50;
256         my $mset = $enquire->get_mset($offset, $limit);
257         return $mset if $opts->{mset};
258         my @msgs = map {
259                 PublicInbox::SearchMsg->load_doc($_->get_document);
260         } $mset->items;
261
262         { total => $mset->get_matches_estimated, msgs => \@msgs }
263 }
264
265 # read-write
266 sub stemmer { Search::Xapian::Stem->new($LANG) }
267
268 # read-only
269 sub qp {
270         my ($self) = @_;
271
272         my $qp = $self->{query_parser};
273         return $qp if $qp;
274
275         # new parser
276         $qp = Search::Xapian::QueryParser->new;
277         $qp->set_default_op(OP_AND);
278         $qp->set_database($self->{xdb});
279         $qp->set_stemmer($self->stemmer);
280         $qp->set_stemming_strategy(STEM_SOME);
281         $qp->add_valuerangeprocessor(
282                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
283
284         while (my ($name, $prefix) = each %bool_pfx_external) {
285                 $qp->add_boolean_prefix($name, $prefix);
286         }
287
288         # we do not actually create AltId objects,
289         # just parse the spec to avoid the extra DB handles for now.
290         if (my $altid = $self->{altid}) {
291                 my $user_pfx = $self->{-user_pfx} ||= [];
292                 for (@$altid) {
293                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
294                         /\Aserial:(\w+):/ or next;
295                         my $pfx = $1;
296                         push @$user_pfx, "$pfx:", <<EOF;
297 alternate serial number  e.g. $pfx:12345 (boolean)
298 EOF
299                         # gmane => XGMANE
300                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
301                 }
302                 chomp @$user_pfx;
303         }
304
305         while (my ($name, $prefix) = each %prob_prefix) {
306                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
307         }
308
309         $self->{query_parser} = $qp;
310 }
311
312 sub num_range_processor {
313         $_[0]->{nrp} ||= Search::Xapian::NumberValueRangeProcessor->new(NUM);
314 }
315
316 # only used for NNTP server
317 sub query_xover {
318         my ($self, $beg, $end, $offset) = @_;
319         my $qp = Search::Xapian::QueryParser->new;
320         $qp->set_database($self->{skel} || $self->{xdb});
321         $qp->add_valuerangeprocessor($self->num_range_processor);
322         my $query = $qp->parse_query("$beg..$end", QP_FLAGS);
323
324         my $opts = {
325                 enquire => enquire_skel($self),
326                 num => 1,
327                 limit => 200,
328                 offset => $offset,
329         };
330         _do_enquire($self, $query, $opts);
331 }
332
333 sub query_ts {
334         my ($self, $ts, $opts) = @_;
335         my $qp = $self->{qp_ts} ||= eval {
336                 my $q = Search::Xapian::QueryParser->new;
337                 $q->set_database($self->{skel} || $self->{xdb});
338                 $q->add_valuerangeprocessor(
339                         Search::Xapian::NumberValueRangeProcessor->new(TS));
340                 $q
341         };
342         my $query = $qp->parse_query($ts, QP_FLAGS);
343         $opts->{enquire} = enquire_skel($self);
344         _do_enquire($self, $query, $opts);
345 }
346
347 sub first_smsg_by_mid {
348         my ($self, $mid) = @_;
349         my $smsg;
350         retry_reopen($self, sub {
351                 each_smsg_by_mid($self, $mid, sub { $smsg = $_[0]; undef });
352         });
353         $smsg;
354 }
355
356 sub lookup_article {
357         my ($self, $num) = @_;
358         my $term = 'XNUM'.$num;
359         my $db = $self->{skel} || $self->{xdb};
360         retry_reopen($self, sub {
361                 my $head = $db->postlist_begin($term);
362                 my $tail = $db->postlist_end($term);
363                 return if $head->equal($tail);
364                 my $doc_id = $head->get_docid;
365                 return unless defined $doc_id;
366                 $head->inc;
367                 if ($head->nequal($tail)) {
368                         my $loc= $self->{mainrepo} .
369                                 ($self->{skel} ? 'skel' : 'xdb');
370                         warn "article #$num is not unique in $loc\n";
371                 }
372                 # raises on error:
373                 my $doc = $db->get_document($doc_id);
374                 my $smsg = PublicInbox::SearchMsg->wrap($doc);
375                 $smsg->{doc_id} = $doc_id;
376                 $smsg->load_expand;
377         });
378 }
379
380 sub each_smsg_by_mid {
381         my ($self, $mid, $cb) = @_;
382         # XXX retry_reopen isn't necessary for V2Writable, but the PSGI
383         # interface will need it...
384         my $db = $self->{skel} || $self->{xdb};
385         my $term = 'Q' . $mid;
386         my $head = $db->postlist_begin($term);
387         my $tail = $db->postlist_end($term);
388         if ($head == $tail) {
389                 $db->reopen;
390                 $head = $db->postlist_begin($term);
391                 $tail = $db->postlist_end($term);
392         }
393         return ($head, $tail, $db) if wantarray;
394         for (; $head->nequal($tail); $head->inc) {
395                 my $doc_id = $head->get_docid;
396                 my $doc = $db->get_document($doc_id);
397                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
398                 $smsg->{doc_id} = $doc_id;
399                 $cb->($smsg) or return;
400         }
401 }
402
403 # normalize subjects so they are suitable as pathnames for URLs
404 # XXX: consider for removal
405 sub subject_path {
406         my $subj = pop;
407         $subj = subject_normalized($subj);
408         $subj =~ s![^a-zA-Z0-9_\.~/\-]+!_!g;
409         lc($subj);
410 }
411
412 sub subject_normalized {
413         my $subj = pop;
414         $subj =~ s/\A\s+//s; # no leading space
415         $subj =~ s/\s+\z//s; # no trailing space
416         $subj =~ s/\s+/ /gs; # no redundant spaces
417         $subj =~ s/\.+\z//; # no trailing '.'
418         $subj =~ s/$REPLY_RE//igo; # remove reply prefix
419         $subj;
420 }
421
422 sub enquire {
423         my ($self) = @_;
424         $self->{enquire} ||= Search::Xapian::Enquire->new($self->{xdb});
425 }
426
427 sub enquire_skel {
428         my ($self) = @_;
429         if (my $skel = $self->{skel}) {
430                 $self->{enquire_skel} ||= Search::Xapian::Enquire->new($skel);
431         } else {
432                 enquire($self);
433         }
434 }
435
436 sub help {
437         my ($self) = @_;
438         $self->qp; # parse altids
439         my @ret = @HELP;
440         if (my $user_pfx = $self->{-user_pfx}) {
441                 push @ret, @$user_pfx;
442         }
443         \@ret;
444 }
445
446 1;