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