]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: add note about SCHEMA_VERSION 15
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2019 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 PublicInbox::SearchMsg;
16 use PublicInbox::MIME;
17 use PublicInbox::MID qw/id_compress/;
18 use PublicInbox::Over;
19 my $QP_FLAGS;
20 sub load_xapian () {
21         $QP_FLAGS ||= eval {
22                 require Search::Xapian;
23                 Search::Xapian->import(qw(:standard));
24
25                 # n.b. FLAG_PURE_NOT is expensive not suitable for a public
26                 # website as it could become a denial-of-service vector
27                 # FLAG_PHRASE also seems to cause performance problems chert
28                 # (and probably earlier Xapian DBs).  glass seems fine...
29                 # TODO: make this an option, maybe?
30                 # or make indexlevel=medium as default
31                 FLAG_PHRASE()|FLAG_BOOLEAN()|FLAG_LOVEHATE()|FLAG_WILDCARD();
32         };
33 };
34
35 # This is English-only, everything else is non-standard and may be confused as
36 # a prefix common in patch emails
37 our $LANG = 'english';
38
39 use constant {
40         # SCHEMA_VERSION history
41         # 0 - initial
42         # 1 - subject_path is lower-cased
43         # 2 - subject_path is id_compress in the index, only
44         # 3 - message-ID is compressed if it includes '%' (hack!)
45         # 4 - change "Re: " normalization, avoid circular Reference ghosts
46         # 5 - subject_path drops trailing '.'
47         # 6 - preserve References: order in document data
48         # 7 - remove references and inreplyto terms
49         # 8 - remove redundant/unneeded document data
50         # 9 - disable Message-ID compression (SHA-1)
51         # 10 - optimize doc for NNTP overviews
52         # 11 - merge threads when vivifying ghosts
53         # 12 - change YYYYMMDD value column to numeric
54         # 13 - fix threading for empty References/In-Reply-To
55         #      (commit 83425ef12e4b65cdcecd11ddcb38175d4a91d5a0)
56         # 14 - fix ghost root vivification
57         # 15 - see public-inbox-v2-format(5)
58         #      further bumps likely unnecessary, we'll suggest in-place
59         #      "--reindex" use for further fixes and tweaks
60         SCHEMA_VERSION => 15,
61 };
62
63 my %bool_pfx_external = (
64         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
65         dfpre => 'XDFPRE',
66         dfpost => 'XDFPOST',
67         dfblob => 'XDFPRE XDFPOST',
68 );
69
70 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
71 my %prob_prefix = (
72         # for mairix compatibility
73         s => 'S',
74         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
75         f => 'A',
76         t => 'XTO',
77         tc => 'XTO XCC',
78         c => 'XCC',
79         tcf => 'XTO XCC A',
80         a => 'XTO XCC A',
81         b => $non_quoted_body . ' XQUOT',
82         bs => $non_quoted_body . ' XQUOT S',
83         n => 'XFN',
84
85         q => 'XQUOT',
86         nq => $non_quoted_body,
87         dfn => 'XDFN',
88         dfa => 'XDFA',
89         dfb => 'XDFB',
90         dfhh => 'XDFHH',
91         dfctx => 'XDFCTX',
92
93         # default:
94         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
95 );
96
97 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
98 our @HELP = (
99         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
100         'd:' => <<EOF,
101 date range as YYYYMMDD  e.g. d:19931002..20101002
102 Open-ended ranges such as d:19931002.. and d:..20101002
103 are also supported
104 EOF
105         'dt:' => <<EOF,
106 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
107 EOF
108         'b:' => 'match within message body, including text attachments',
109         'nq:' => 'match non-quoted text within message body',
110         'q:' => 'match quoted text within message body',
111         'n:' => 'match filename of attachment(s)',
112         't:' => 'match within the To header',
113         'c:' => 'match within the Cc header',
114         'f:' => 'match within the From header',
115         'a:' => 'match within the To, Cc, and From headers',
116         'tc:' => 'match within the To and Cc headers',
117         'bs:' => 'match within the Subject and body',
118         'dfn:' => 'match filename from diff',
119         'dfa:' => 'match diff removed (-) lines',
120         'dfb:' => 'match diff added (+) lines',
121         'dfhh:' => 'match diff hunk header context (usually a function name)',
122         'dfctx:' => 'match diff context lines',
123         'dfpre:' => 'match pre-image git blob ID',
124         'dfpost:' => 'match post-image git blob ID',
125         'dfblob:' => 'match either pre or post-image git blob ID',
126 );
127 chomp @HELP;
128
129 sub xdir ($;$) {
130         my ($self, $rdonly) = @_;
131         if ($self->{version} == 1) {
132                 "$self->{inboxdir}/public-inbox/xapian" . SCHEMA_VERSION;
133         } else {
134                 my $dir = "$self->{inboxdir}/xap" . SCHEMA_VERSION;
135                 return $dir if $rdonly;
136
137                 my $shard = $self->{shard};
138                 defined $shard or die "shard not given";
139                 $dir .= "/$shard";
140         }
141 }
142
143 sub _xdb ($) {
144         my ($self) = @_;
145         my $dir = xdir($self, 1);
146         my ($xdb, $slow_phrase);
147         my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
148         if ($self->{version} >= 2) {
149                 foreach my $shard (<$dir/*>) {
150                         -d $shard && $shard =~ m!/[0-9]+\z! or next;
151                         my $sub = Search::Xapian::Database->new($shard);
152                         if ($xdb) {
153                                 $xdb->add_database($sub);
154                         } else {
155                                 $xdb = $sub;
156                         }
157                         $slow_phrase ||= -f "$shard/iamchert";
158                 }
159         } else {
160                 $slow_phrase = -f "$dir/iamchert";
161                 $xdb = Search::Xapian::Database->new($dir);
162         }
163         $$qpf |= FLAG_PHRASE() unless $slow_phrase;
164         $xdb;
165 }
166
167 sub xdb ($) {
168         my ($self) = @_;
169         $self->{xdb} ||= do {
170                 load_xapian();
171                 _xdb($self);
172         };
173 }
174
175 sub new {
176         my ($class, $ibx) = @_;
177         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
178         my $self = bless {
179                 inboxdir => $ibx->{inboxdir},
180                 altid => $ibx->{altid},
181                 version => $ibx->{version} // 1,
182         }, $class;
183         my $dir = xdir($self, 1);
184         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
185         $self;
186 }
187
188 sub reopen {
189         my ($self) = @_;
190         if (my $xdb = $self->{xdb}) {
191                 $xdb->reopen;
192         }
193         $self; # make chaining easier
194 }
195
196 # read-only
197 sub query {
198         my ($self, $query_string, $opts) = @_;
199         $opts ||= {};
200         if ($query_string eq '' && !$opts->{mset}) {
201                 $self->{over_ro}->recent($opts);
202         } else {
203                 my $qp = qp($self);
204                 my $qp_flags = $self->{qp_flags};
205                 my $query = $qp->parse_query($query_string, $qp_flags);
206                 $opts->{relevance} = 1 unless exists $opts->{relevance};
207                 _do_enquire($self, $query, $opts);
208         }
209 }
210
211 sub retry_reopen {
212         my ($self, $cb) = @_;
213         for my $i (1..10) {
214                 if (wantarray) {
215                         my @ret;
216                         eval { @ret = $cb->() };
217                         return @ret unless $@;
218                 } else {
219                         my $ret;
220                         eval { $ret = $cb->() };
221                         return $ret unless $@;
222                 }
223                 # Exception: The revision being read has been discarded -
224                 # you should call Xapian::Database::reopen()
225                 if (ref($@) eq 'Search::Xapian::DatabaseModifiedError') {
226                         warn "reopen try #$i on $@\n";
227                         reopen($self);
228                 } else {
229                         # let caller decide how to spew, because ExtMsg queries
230                         # get wonky and trigger:
231                         # "something terrible happened at .../Xapian/Enquire.pm"
232                         die;
233                 }
234         }
235         die "Too many Xapian database modifications in progress\n";
236 }
237
238 sub _do_enquire {
239         my ($self, $query, $opts) = @_;
240         retry_reopen($self, sub { _enquire_once($self, $query, $opts) });
241 }
242
243 sub _enquire_once {
244         my ($self, $query, $opts) = @_;
245         my $xdb = xdb($self);
246         my $enquire = Search::Xapian::Enquire->new($xdb);
247         $enquire->set_query($query);
248         $opts ||= {};
249         my $desc = !$opts->{asc};
250         if (($opts->{mset} || 0) == 2) {
251                 $enquire->set_docid_order(Search::Xapian::ENQ_ASCENDING());
252                 $enquire->set_weighting_scheme(Search::Xapian::BoolWeight->new);
253         } elsif ($opts->{relevance}) {
254                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
255         } else {
256                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
257         }
258         my $offset = $opts->{offset} || 0;
259         my $limit = $opts->{limit} || 50;
260         my $mset = $enquire->get_mset($offset, $limit);
261         return $mset if $opts->{mset};
262         my @msgs = map {
263                 PublicInbox::SearchMsg->load_doc($_->get_document);
264         } $mset->items;
265         return \@msgs unless wantarray;
266
267         ($mset->get_matches_estimated, \@msgs)
268 }
269
270 # read-write
271 sub stemmer { Search::Xapian::Stem->new($LANG) }
272
273 # read-only
274 sub qp {
275         my ($self) = @_;
276
277         my $qp = $self->{query_parser};
278         return $qp if $qp;
279         my $xdb = xdb($self);
280         # new parser
281         $qp = Search::Xapian::QueryParser->new;
282         $qp->set_default_op(OP_AND());
283         $qp->set_database($xdb);
284         $qp->set_stemmer($self->stemmer);
285         $qp->set_stemming_strategy(STEM_SOME());
286         $qp->set_max_wildcard_expansion(100);
287         $qp->add_valuerangeprocessor(
288                 Search::Xapian::NumberValueRangeProcessor->new(YYYYMMDD, 'd:'));
289         $qp->add_valuerangeprocessor(
290                 Search::Xapian::NumberValueRangeProcessor->new(DT, 'dt:'));
291
292         while (my ($name, $prefix) = each %bool_pfx_external) {
293                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
294         }
295
296         # we do not actually create AltId objects,
297         # just parse the spec to avoid the extra DB handles for now.
298         if (my $altid = $self->{altid}) {
299                 my $user_pfx = $self->{-user_pfx} ||= [];
300                 for (@$altid) {
301                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
302                         /\Aserial:(\w+):/ or next;
303                         my $pfx = $1;
304                         push @$user_pfx, "$pfx:", <<EOF;
305 alternate serial number  e.g. $pfx:12345 (boolean)
306 EOF
307                         # gmane => XGMANE
308                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
309                 }
310                 chomp @$user_pfx;
311         }
312
313         while (my ($name, $prefix) = each %prob_prefix) {
314                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
315         }
316
317         $self->{query_parser} = $qp;
318 }
319
320 sub lookup_article {
321         my ($self, $num) = @_;
322         $self->{over_ro}->get_art($num);
323 }
324
325 sub help {
326         my ($self) = @_;
327         $self->qp; # parse altids
328         my @ret = @HELP;
329         if (my $user_pfx = $self->{-user_pfx}) {
330                 push @ret, @$user_pfx;
331         }
332         \@ret;
333 }
334
335 1;