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