]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/Search.pm
search: remove documentation for "lid:"
[public-inbox.git] / lib / PublicInbox / Search.pm
1 # Copyright (C) 2015-2020 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::Smsg;
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 Smsg:
40                 *PublicInbox::Smsg::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         #
81         #      public-inbox v1.5.0 adds (still SCHEMA_VERSION=15):
82         #      * "lid:" and "l:" for List-Id searches
83         SCHEMA_VERSION => 15,
84 };
85
86 # note: the non-X term prefix allocations are shared with
87 # Xapian omega, see xapian-applications/omega/docs/termprefixes.rst
88 my %bool_pfx_external = (
89         mid => 'Q', # Message-ID (full/exact), this is mostly uniQue
90         lid => 'G', # newsGroup (or similar entity), just inside <>
91         dfpre => 'XDFPRE',
92         dfpost => 'XDFPOST',
93         dfblob => 'XDFPRE XDFPOST',
94 );
95
96 my $non_quoted_body = 'XNQ XDFN XDFA XDFB XDFHH XDFCTX XDFPRE XDFPOST';
97 my %prob_prefix = (
98         # for mairix compatibility
99         s => 'S',
100         m => 'XM', # 'mid:' (bool) is exact, 'm:' (prob) can do partial
101         l => 'XL', # 'lid:' (bool) is exact, 'l:' (prob) can do partial
102         f => 'A',
103         t => 'XTO',
104         tc => 'XTO XCC',
105         c => 'XCC',
106         tcf => 'XTO XCC A',
107         a => 'XTO XCC A',
108         b => $non_quoted_body . ' XQUOT',
109         bs => $non_quoted_body . ' XQUOT S',
110         n => 'XFN',
111
112         q => 'XQUOT',
113         nq => $non_quoted_body,
114         dfn => 'XDFN',
115         dfa => 'XDFA',
116         dfb => 'XDFB',
117         dfhh => 'XDFHH',
118         dfctx => 'XDFCTX',
119
120         # default:
121         '' => 'XM S A XQUOT XFN ' . $non_quoted_body,
122 );
123
124 # not documenting m: and mid: for now, the using the URLs works w/o Xapian
125 # not documenting lid: for now, either, it is probably redundant with l:,
126 # especially since we don't offer boolean searches for To/Cc/From
127 # headers, either
128 our @HELP = (
129         's:' => 'match within Subject  e.g. s:"a quick brown fox"',
130         'd:' => <<EOF,
131 date range as YYYYMMDD  e.g. d:19931002..20101002
132 Open-ended ranges such as d:19931002.. and d:..20101002
133 are also supported
134 EOF
135         'dt:' => <<EOF,
136 date-time range as YYYYMMDDhhmmss (e.g. dt:19931002011000..19931002011200)
137 EOF
138         'b:' => 'match within message body, including text attachments',
139         'nq:' => 'match non-quoted text within message body',
140         'q:' => 'match quoted text within message body',
141         'n:' => 'match filename of attachment(s)',
142         't:' => 'match within the To header',
143         'c:' => 'match within the Cc header',
144         'f:' => 'match within the From header',
145         'a:' => 'match within the To, Cc, and From headers',
146         'tc:' => 'match within the To and Cc headers',
147         'l:' => 'match contents of the List-Id header',
148         'bs:' => 'match within the Subject and body',
149         'dfn:' => 'match filename from diff',
150         'dfa:' => 'match diff removed (-) lines',
151         'dfb:' => 'match diff added (+) lines',
152         'dfhh:' => 'match diff hunk header context (usually a function name)',
153         'dfctx:' => 'match diff context lines',
154         'dfpre:' => 'match pre-image git blob ID',
155         'dfpost:' => 'match post-image git blob ID',
156         'dfblob:' => 'match either pre or post-image git blob ID',
157 );
158 chomp @HELP;
159
160 sub xdir ($;$) {
161         my ($self, $rdonly) = @_;
162         if ($self->{ibx_ver} == 1) {
163                 "$self->{inboxdir}/public-inbox/xapian" . SCHEMA_VERSION;
164         } else {
165                 my $dir = "$self->{inboxdir}/xap" . SCHEMA_VERSION;
166                 return $dir if $rdonly;
167
168                 my $shard = $self->{shard};
169                 defined $shard or die "shard not given";
170                 $dir .= "/$shard";
171         }
172 }
173
174 sub _xdb ($) {
175         my ($self) = @_;
176         my $dir = xdir($self, 1);
177         my ($xdb, $slow_phrase);
178         my $qpf = \($self->{qp_flags} ||= $QP_FLAGS);
179         if ($self->{ibx_ver} >= 2) {
180                 foreach my $shard (<$dir/*>) {
181                         -d $shard && $shard =~ m!/[0-9]+\z! or next;
182                         my $sub = $X{Database}->new($shard);
183                         if ($xdb) {
184                                 $xdb->add_database($sub);
185                         } else {
186                                 $xdb = $sub;
187                         }
188                         $slow_phrase ||= -f "$shard/iamchert";
189                 }
190         } else {
191                 $slow_phrase = -f "$dir/iamchert";
192                 $xdb = $X{Database}->new($dir);
193         }
194         $$qpf |= FLAG_PHRASE() unless $slow_phrase;
195         $xdb;
196 }
197
198 sub xdb ($) {
199         my ($self) = @_;
200         $self->{xdb} ||= do {
201                 load_xapian();
202                 _xdb($self);
203         };
204 }
205
206 sub new {
207         my ($class, $ibx) = @_;
208         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
209         my $self = bless {
210                 inboxdir => $ibx->{inboxdir},
211                 altid => $ibx->{altid},
212                 ibx_ver => $ibx->version,
213         }, $class;
214         my $dir = xdir($self, 1);
215         $self->{over_ro} = PublicInbox::Over->new("$dir/over.sqlite3");
216         $self;
217 }
218
219 sub reopen {
220         my ($self) = @_;
221         if (my $xdb = $self->{xdb}) {
222                 $xdb->reopen;
223         }
224         $self; # make chaining easier
225 }
226
227 # read-only
228 sub query {
229         my ($self, $query_string, $opts) = @_;
230         $opts ||= {};
231         if ($query_string eq '' && !$opts->{mset}) {
232                 $self->{over_ro}->recent($opts);
233         } else {
234                 my $qp = qp($self);
235                 my $qp_flags = $self->{qp_flags};
236                 my $query = $qp->parse_query($query_string, $qp_flags);
237                 $opts->{relevance} = 1 unless exists $opts->{relevance};
238                 _do_enquire($self, $query, $opts);
239         }
240 }
241
242 sub retry_reopen {
243         my ($self, $cb, $arg) = @_;
244         for my $i (1..10) {
245                 if (wantarray) {
246                         my @ret;
247                         eval { @ret = $cb->($arg) };
248                         return @ret unless $@;
249                 } else {
250                         my $ret;
251                         eval { $ret = $cb->($arg) };
252                         return $ret unless $@;
253                 }
254                 # Exception: The revision being read has been discarded -
255                 # you should call Xapian::Database::reopen()
256                 if (ref($@) =~ /\bDatabaseModifiedError\b/) {
257                         warn "reopen try #$i on $@\n";
258                         reopen($self);
259                 } else {
260                         # let caller decide how to spew, because ExtMsg queries
261                         # get wonky and trigger:
262                         # "something terrible happened at .../Xapian/Enquire.pm"
263                         die;
264                 }
265         }
266         die "Too many Xapian database modifications in progress\n";
267 }
268
269 sub _do_enquire {
270         my ($self, $query, $opts) = @_;
271         retry_reopen($self, \&_enquire_once, [ $self, $query, $opts ]);
272 }
273
274 sub _enquire_once { # retry_reopen callback
275         my ($self, $query, $opts) = @{$_[0]};
276         my $xdb = xdb($self);
277         my $enquire = $X{Enquire}->new($xdb);
278         $enquire->set_query($query);
279         $opts ||= {};
280         my $desc = !$opts->{asc};
281         if (($opts->{mset} || 0) == 2) {
282                 $enquire->set_docid_order($ENQ_ASCENDING);
283                 $enquire->set_weighting_scheme($X{BoolWeight}->new);
284         } elsif ($opts->{relevance}) {
285                 $enquire->set_sort_by_relevance_then_value(TS, $desc);
286         } else {
287                 $enquire->set_sort_by_value_then_relevance(TS, $desc);
288         }
289         my $offset = $opts->{offset} || 0;
290         my $limit = $opts->{limit} || 50;
291         my $mset = $enquire->get_mset($offset, $limit);
292         return $mset if $opts->{mset};
293         my @msgs = map { PublicInbox::Smsg::from_mitem($_) } $mset->items;
294         return \@msgs unless wantarray;
295
296         ($mset->get_matches_estimated, \@msgs)
297 }
298
299 # read-write
300 sub stemmer { $X{Stem}->new($LANG) }
301
302 # read-only
303 sub qp {
304         my ($self) = @_;
305
306         my $qp = $self->{query_parser};
307         return $qp if $qp;
308         my $xdb = xdb($self);
309         # new parser
310         $qp = $X{QueryParser}->new;
311         $qp->set_default_op(OP_AND());
312         $qp->set_database($xdb);
313         $qp->set_stemmer($self->stemmer);
314         $qp->set_stemming_strategy(STEM_SOME());
315         $qp->set_max_wildcard_expansion(100);
316         my $nvrp = $X{NumberValueRangeProcessor};
317         $qp->add_valuerangeprocessor($nvrp->new(YYYYMMDD, 'd:'));
318         $qp->add_valuerangeprocessor($nvrp->new(DT, 'dt:'));
319
320         while (my ($name, $prefix) = each %bool_pfx_external) {
321                 $qp->add_boolean_prefix($name, $_) foreach split(/ /, $prefix);
322         }
323
324         # we do not actually create AltId objects,
325         # just parse the spec to avoid the extra DB handles for now.
326         if (my $altid = $self->{altid}) {
327                 my $user_pfx = $self->{-user_pfx} = [];
328                 for (@$altid) {
329                         # $_ = 'serial:gmane:/path/to/gmane.msgmap.sqlite3'
330                         # note: Xapian supports multibyte UTF-8, /^[0-9]+$/,
331                         # and '_' with prefixes matching \w+
332                         /\Aserial:(\w+):/ or next;
333                         my $pfx = $1;
334                         push @$user_pfx, "$pfx:", <<EOF;
335 alternate serial number  e.g. $pfx:12345 (boolean)
336 EOF
337                         # gmane => XGMANE
338                         $qp->add_boolean_prefix($pfx, 'X'.uc($pfx));
339                 }
340                 chomp @$user_pfx;
341         }
342
343         while (my ($name, $prefix) = each %prob_prefix) {
344                 $qp->add_prefix($name, $_) foreach split(/ /, $prefix);
345         }
346
347         $self->{query_parser} = $qp;
348 }
349
350 sub help {
351         my ($self) = @_;
352         $self->qp; # parse altids
353         my @ret = @HELP;
354         if (my $user_pfx = $self->{-user_pfx}) {
355                 push @ret, @$user_pfx;
356         }
357         \@ret;
358 }
359
360 1;