]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
e79ec0f80a0ead18b122108220bd6b1b80c13757
[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; # Date: header for searching in the WWW UI
13 use constant DT => 2; # Date: YYYYMMDDHHMMSS
14
15 use Search::Xapian qw/:standard/;
16 use PublicInbox::SearchMsg;
17 use PublicInbox::MIME;
18 use PublicInbox::MID qw/id_compress/;
19 use PublicInbox::Over;
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 $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         dfpre => 'XDFPRE',
53         dfpost => 'XDFPOST',
54         dfblob => 'XDFPRE XDFPOST',
55 );
56
57 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
58 my %prob_prefix = (
59         # for mairix compatibility
60         s => 'S',
61         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
62         f => 'A',
63         t => 'XTO',
64         tc => 'XTO XCC',
65         c => 'XCC',
66         tcf => 'XTO XCC A',
67         a => 'XTO XCC A',
68         b => $non_quoted_body . ' XQUOT',
69         bs => $non_quoted_body . ' XQUOT S',
70         n => 'XFN',
71
72         q => 'XQUOT',
73         nq => $non_quoted_body,
74         dfn => 'XDFN',
75         dfa => 'XDFA',
76         dfb => 'XDFB',
77         dfhh => 'XDFHH',
78         dfctx => 'XDFCTX',
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         'dt:' => <<EOF,
93 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
94 EOF
95         'b:' => 'match within message body, including text attachments',
96         'nq:' => 'match non-quoted text within message body',
97         'q:' => 'match quoted text within message body',
98         'n:' => 'match filename of attachment(s)',
99         't:' => 'match within the To header',
100         'c:' => 'match within the Cc header',
101         'f:' => 'match within the From header',
102         'a:' => 'match within the To, Cc, and From headers',
103         'tc:' => 'match within the To and Cc headers',
104         'bs:' => 'match within the Subject and body',
105         'dfn:' => 'match filename from diff',
106         'dfa:' => 'match diff removed (-) lines',
107         'dfb:' => 'match diff added (+) lines',
108         'dfhh:' => 'match diff hunk header context (usually a function name)',
109         'dfctx:' => 'match diff context lines',
110         'dfpre:' => 'match pre-image git blob ID',
111         'dfpost:' => 'match post-image git blob ID',
112         'dfblob:' => 'match either pre or post-image git blob ID',
113 );
114 chomp @HELP;
115
116 sub xdir {
117         my ($self) = @_;
118         if ($self->{version} == 1) {
119                 "$self->{mainrepo}/public-inbox/xapian" . SCHEMA_VERSION;
120         } else {
121                 my $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
122                 my $part = $self->{partition};
123                 defined $part or die "partition not given";
124                 $dir .= "/$part";
125         }
126 }
127
128 sub new {
129         my ($class, $mainrepo, $altid) = @_;
130         my $version = 1;
131         my $ibx = $mainrepo;
132         if (ref $ibx) {
133                 $version = $ibx->{version} || 1;
134                 $mainrepo = $ibx->{mainrepo};
135         }
136         my $self = bless {
137                 mainrepo => $mainrepo,
138                 altid => $altid,
139                 version => $version,
140         }, $class;
141         my $dir;
142         if ($version >= 2) {
143                 $dir = "$self->{mainrepo}/xap" . SCHEMA_VERSION;
144                 my $xdb;
145                 my $parts = 0;
146                 foreach my $part (<$dir/*>) {
147                         -d $part && $part =~ m!/\d+\z! or next;
148                         $parts++;
149                         my $sub = Search::Xapian::Database->new($part);
150                         if ($xdb) {
151                                 $xdb->add_database($sub);
152                         } else {
153                                 $xdb = $sub;
154                         }
155                 }
156                 $self->{xdb} = $xdb;
157         } else {
158                 $dir = $self->xdir;
159                 $self->{xdb} = Search::Xapian::Database->new($dir);
160         }
161         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
162         $self;
163 }
164
165 sub reopen {
166         my ($self) = @_;
167         $self->{xdb}->reopen;
168         $self; # make chaining easier
169 }
170
171 # read-only
172 sub query {
173         my ($self, $query_string, $opts) = @_;
174         $opts ||= {};
175         if ($query_string eq '' && !$opts->{mset}) {
176                 $self->{over_ro}->recent($opts);
177         } else {
178                 my $query = $self->qp->parse_query($query_string, QP_FLAGS);
179                 $opts->{relevance} = 1 unless exists $opts->{relevance};
180                 _do_enquire($self, $query, $opts);
181         }
182 }
183
184 sub retry_reopen {
185         my ($self, $cb) = @_;
186         for my $i (1..10) {
187                 if (wantarray) {
188                         my @ret;
189                         eval { @ret = $cb->() };
190                         return @ret unless $@;
191                 } else {
192                         my $ret;
193                         eval { $ret = $cb->() };
194                         return $ret unless $@;
195                 }
196                 # Exception: The revision being read has been discarded -
197                 # you should call Xapian::Database::reopen()
198                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
199                         warn "reopen try #$i on $@\n";
200                         reopen($self);
201                 } else {
202                         warn "ref: ", ref($@), "\n";
203                         die;
204                 }
205         }
206         die "Too many Xapian database modifications in progress\n";
207 }
208
209 sub _do_enquire {
210         my ($self, $query, $opts) = @_;
211         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
212 }
213
214 sub _enquire_once {
215         my ($self, $query, $opts) = @_;
216         my $enquire = Search::Xapian::Enquire->new($self->{xdb});
217         $enquire->set_query($query);
218         $opts ||= {};
219         my $desc = !$opts->{asc};
220         if (($opts->{mset} || 0) == 2) {
221                 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
222                 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
223         } elsif ($opts->{relevance}) {
224                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
225         } else {
226                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
227         }
228         my $offset = $opts->{offset} || 0;
229         my $limit = $opts->{limit} || 50;
230         my $mset = $enquire->get_mset($offset, $limit);
231         return $mset if $opts->{mset};
232         my @msgs = map {
233                 PublicInbox::SearchMsg->load_doc($_->get_document);
234         } $mset->items;
235         return \@msgs unless wantarray;
236
237         ($mset->get_matches_estimated, \@msgs)
238 }
239
240 # read-write
241 sub stemmer { Search::Xapian::Stem->new($LANG) }
242
243 # read-only
244 sub qp {
245         my ($self) = @_;
246
247         my $qp = $self->{query_parser};
248         return $qp if $qp;
249
250         # new parser
251         $qp = Search::Xapian::QueryParser->new;
252         $qp->set_default_op(OP_AND);
253         $qp->set_database($self->{xdb});
254         $qp->set_stemmer($self->stemmer);
255         $qp->set_stemming_strategy(STEM_SOME);
256         $qp->set_max_wildcard_expansion(100);
257         $qp->add_valuerangeprocessor(
258                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
259         $qp->add_valuerangeprocessor(
260                 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
261
262         while (my ($name, $prefix) = each %bool_pfx_external) {
263                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
264         }
265
266         # we do not actually create AltId objects,
267         # just parse the spec to avoid the extra DB handles for now.
268         if (my $altid = $self->{altid}) {
269                 my $user_pfx = $self->{-user_pfx} ||= [];
270                 for (@$altid) {
271                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
272                         /\Aserial:(\w+):/ or next;
273                         my $pfx = $1;
274                         push @$user_pfx, "$pfx:", <<EOF;
275 alternate serial number  e.g. $pfx:12345 (boolean)
276 EOF
277                         # gmane => XGMANE
278                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
279                 }
280                 chomp @$user_pfx;
281         }
282
283         while (my ($name, $prefix) = each %prob_prefix) {
284                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
285         }
286
287         $self->{query_parser} = $qp;
288 }
289
290 sub lookup_article {
291         my ($self, $num) = @_;
292         $self->{over_ro}->get_art($num);
293 }
294
295 sub help {
296         my ($self) = @_;
297         $self->qp; # parse altids
298         my @ret = @HELP;
299         if (my $user_pfx = $self->{-user_pfx}) {
300                 push @ret, @$user_pfx;
301         }
302         \@ret;
303 }
304
305 1;