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