]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
search: make xap_terms easier-to-use and use it more
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015-2021 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
4 #
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces.  This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use v5.10.1;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
13 use PublicInbox::Eml;
14 use PublicInbox::Search qw(xap_terms);
15 use PublicInbox::InboxWritable;
16 use PublicInbox::MID qw(mids_for_index mids);
17 use PublicInbox::MsgIter;
18 use PublicInbox::IdxStack;
19 use Carp qw(croak carp);
20 use POSIX qw(strftime);
21 use Time::Local qw(timegm);
22 use PublicInbox::OverIdx;
23 use PublicInbox::Spawn qw(spawn nodatacow_dir);
24 use PublicInbox::Git qw(git_unquote);
25 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
26 use PublicInbox::Address;
27 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
28         index_text term_generator add_val is_bad_blob);
29 my $X = \%PublicInbox::Search::X;
30 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
31 our $DB_NO_SYNC = 0;
32 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
33 use constant DEBUG => !!$ENV{DEBUG};
34
35 my $xapianlevels = qr/\A(?:full|medium)\z/;
36 my $hex = '[a-f0-9]';
37 my $OID = $hex .'{40,}';
38 my @VMD_MAP = (kw => 'K', L => 'L');
39 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
40
41 sub new {
42         my ($class, $ibx, $creat, $shard) = @_;
43         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
44         my $inboxdir = $ibx->{inboxdir};
45         my $version = $ibx->version;
46         my $indexlevel = 'full';
47         my $altid = $ibx->{altid};
48         if ($altid) {
49                 require PublicInbox::AltId;
50                 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
51         }
52         if ($ibx->{indexlevel}) {
53                 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
54                         $indexlevel = $ibx->{indexlevel};
55                 } else {
56                         die("Invalid indexlevel $ibx->{indexlevel}\n");
57                 }
58         }
59         $ibx = PublicInbox::InboxWritable->new($ibx);
60         my $self = PublicInbox::Search->new($ibx);
61         bless $self, $class;
62         $self->{ibx} = $ibx;
63         $self->{-altid} = $altid;
64         $self->{indexlevel} = $indexlevel;
65         $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
66         if ($ibx->{-skip_docdata}) {
67                 $self->{-set_skip_docdata_once} = 1;
68                 $self->{-skip_docdata} = 1;
69         }
70         if ($version == 1) {
71                 $self->{lock_path} = "$inboxdir/ssoma.lock";
72                 my $dir = $self->xdir;
73                 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
74                 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
75         } elsif ($version == 2) {
76                 defined $shard or die "shard is required for v2\n";
77                 # shard is a number
78                 $self->{shard} = $shard;
79                 $self->{lock_path} = undef;
80         } else {
81                 die "unsupported inbox version=$version\n";
82         }
83         $self->{creat} = ($creat || 0) == 1;
84         $self;
85 }
86
87 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
88
89 sub idx_release {
90         my ($self, $wake) = @_;
91         if (need_xapian($self)) {
92                 my $xdb = delete $self->{xdb} or croak 'not acquired';
93                 $xdb->close;
94         }
95         $self->lock_release($wake) if $self->{creat};
96         undef;
97 }
98
99 sub load_xapian_writable () {
100         return 1 if $X->{WritableDatabase};
101         PublicInbox::Search::load_xapian() or return;
102         my $xap = $PublicInbox::Search::Xap;
103         for (qw(Document TermGenerator WritableDatabase)) {
104                 $X->{$_} = $xap.'::'.$_;
105         }
106         eval 'require '.$X->{WritableDatabase} or die;
107         *sortable_serialise = $xap.'::sortable_serialise';
108         $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
109         $DB_OPEN = eval($xap.'::DB_OPEN()');
110         my $ver = (eval($xap.'::major_version()') << 16) |
111                 (eval($xap.'::minor_version()') << 8) |
112                 eval($xap.'::revision()');
113         $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
114         # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
115         $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
116         1;
117 }
118
119 sub idx_acquire {
120         my ($self) = @_;
121         my $flag;
122         my $dir = $self->xdir;
123         if (need_xapian($self)) {
124                 croak 'already acquired' if $self->{xdb};
125                 load_xapian_writable();
126                 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
127         }
128         if ($self->{creat}) {
129                 require File::Path;
130                 $self->lock_acquire;
131
132                 # don't create empty Xapian directories if we don't need Xapian
133                 my $is_shard = defined($self->{shard});
134                 if (!-d $dir && (!$is_shard ||
135                                 ($is_shard && need_xapian($self)))) {
136                         File::Path::mkpath($dir);
137                         nodatacow_dir($dir);
138                         $self->{-set_has_threadid_once} = 1;
139                 }
140         }
141         return unless defined $flag;
142         $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
143         my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
144         croak "Failed opening $dir: $@" if $@;
145         $self->{xdb} = $xdb;
146 }
147
148 sub add_val ($$$) {
149         my ($doc, $col, $num) = @_;
150         $num = sortable_serialise($num);
151         $doc->add_value($col, $num);
152 }
153
154 sub term_generator ($) { # write-only
155         my ($self) = @_;
156
157         $self->{term_generator} //= do {
158                 my $tg = $X->{TermGenerator}->new;
159                 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
160                 $tg;
161         }
162 }
163
164 sub index_phrase ($$$$) {
165         my ($self, $text, $wdf_inc, $prefix) = @_;
166
167         my $tg = term_generator($self);
168         $tg->index_text($text, $wdf_inc, $prefix);
169         $tg->increase_termpos;
170 }
171
172 sub index_text ($$$$) {
173         my ($self, $text, $wdf_inc, $prefix) = @_;
174
175         if ($self->{indexlevel} eq 'full') {
176                 index_phrase($self, $text, $wdf_inc, $prefix);
177         } else {
178                 my $tg = term_generator($self);
179                 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
180         }
181 }
182
183 sub index_headers ($$) {
184         my ($self, $smsg) = @_;
185         my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
186         while (my ($field, $pfx) = splice(@x, 0, 2)) {
187                 my $val = $smsg->{$field};
188                 next if $val eq '';
189                 # include "(comments)" after the address, too, so not using
190                 # PublicInbox::Address::names or pairs
191                 index_text($self, $val, 1, $pfx);
192
193                 # we need positional info for email addresses since they
194                 # can be considered phrases
195                 if ($self->{indexlevel} eq 'medium') {
196                         for my $addr (PublicInbox::Address::emails($val)) {
197                                 index_phrase($self, $addr, 1, $pfx);
198                         }
199                 }
200         }
201         @x = (subject => 'S');
202         while (my ($field, $pfx) = splice(@x, 0, 2)) {
203                 my $val = $smsg->{$field};
204                 index_text($self, $val, 1, $pfx) if $val ne '';
205         }
206 }
207
208 sub index_diff_inc ($$$$) {
209         my ($self, $text, $pfx, $xnq) = @_;
210         if (@$xnq) {
211                 index_text($self, join("\n", @$xnq), 1, 'XNQ');
212                 @$xnq = ();
213         }
214         if ($pfx eq 'XDFN') {
215                 index_phrase($self, $text, 1, $pfx);
216         } else {
217                 index_text($self, $text, 1, $pfx);
218         }
219 }
220
221 sub index_old_diff_fn {
222         my ($self, $seen, $fa, $fb, $xnq) = @_;
223
224         # no renames or space support for traditional diffs,
225         # find the number of leading common paths to strip:
226         my @fa = split('/', $fa);
227         my @fb = split('/', $fb);
228         while (scalar(@fa) && scalar(@fb)) {
229                 $fa = join('/', @fa);
230                 $fb = join('/', @fb);
231                 if ($fa eq $fb) {
232                         unless ($seen->{$fa}++) {
233                                 index_diff_inc($self, $fa, 'XDFN', $xnq);
234                         }
235                         return 1;
236                 }
237                 shift @fa;
238                 shift @fb;
239         }
240         0;
241 }
242
243 sub index_diff ($$$) {
244         my ($self, $txt, $doc) = @_;
245         my %seen;
246         my $in_diff;
247         my @xnq;
248         my $xnq = \@xnq;
249         foreach (split(/\n/, $txt)) {
250                 if ($in_diff && s/^ //) { # diff context
251                         index_diff_inc($self, $_, 'XDFCTX', $xnq);
252                 } elsif (/^-- $/) { # email signature begins
253                         $in_diff = undef;
254                 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
255                         # wait until "---" and "+++" to capture filenames
256                         $in_diff = 1;
257                 # traditional diff:
258                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
259                         my ($opt, $fa, $fb) = ($1, $2, $3);
260                         push @xnq, $_;
261                         # only support unified:
262                         next unless $opt =~ /[uU]/;
263                         $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
264                                                         $xnq);
265                 } elsif (m!^--- ("?[^/]+/.+)!) {
266                         my $fn = $1;
267                         $fn = (split('/', git_unquote($fn), 2))[1];
268                         $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
269                         $in_diff = 1;
270                 } elsif (m!^\+\+\+ ("?[^/]+/.+)!)  {
271                         my $fn = $1;
272                         $fn = (split('/', git_unquote($fn), 2))[1];
273                         $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
274                         $in_diff = 1;
275                 } elsif (/^--- (\S+)/) {
276                         $in_diff = $1;
277                         push @xnq, $_;
278                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
279                         $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
280                                                         $1, $xnq);
281                 } elsif ($in_diff && s/^\+//) { # diff added
282                         index_diff_inc($self, $_, 'XDFB', $xnq);
283                 } elsif ($in_diff && s/^-//) { # diff removed
284                         index_diff_inc($self, $_, 'XDFA', $xnq);
285                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
286                         my ($ba, $bb) = ($1, $2);
287                         index_git_blob_id($doc, 'XDFPRE', $ba);
288                         index_git_blob_id($doc, 'XDFPOST', $bb);
289                         $in_diff = 1;
290                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
291                         # traditional diff w/o -p
292                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
293                         # hunk header context
294                         index_diff_inc($self, $1, 'XDFHH', $xnq);
295                 # ignore the following lines:
296                 } elsif (/^(?:dis)similarity index/ ||
297                                 /^(?:old|new) mode/ ||
298                                 /^(?:deleted|new) file mode/ ||
299                                 /^(?:copy|rename) (?:from|to) / ||
300                                 /^(?:dis)?similarity index / ||
301                                 /^\\ No newline at end of file/ ||
302                                 /^Binary files .* differ/) {
303                         push @xnq, $_;
304                 } elsif ($_ eq '') {
305                         # possible to be in diff context, some mail may be
306                         # stripped by MUA or even GNU diff(1).  "git apply"
307                         # treats a bare "\n" as diff context, too
308                 } else {
309                         push @xnq, $_;
310                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
311                         $in_diff = undef;
312                 }
313         }
314
315         index_text($self, join("\n", @xnq), 1, 'XNQ');
316 }
317
318 sub index_xapian { # msg_iter callback
319         my $part = $_[0]->[0]; # ignore $depth and $idx
320         my ($self, $doc) = @{$_[1]};
321         my $ct = $part->content_type || 'text/plain';
322         my $fn = $part->filename;
323         if (defined $fn && $fn ne '') {
324                 index_phrase($self, $fn, 1, 'XFN');
325         }
326         if ($part->{is_submsg}) {
327                 my $mids = mids_for_index($part);
328                 index_ids($self, $doc, $part, $mids);
329                 my $smsg = bless {}, 'PublicInbox::Smsg';
330                 $smsg->populate($part);
331                 index_headers($self, $smsg);
332         }
333
334         my ($s, undef) = msg_part_text($part, $ct);
335         defined $s or return;
336         $_[0]->[0] = $part = undef; # free memory
337
338         # split off quoted and unquoted blocks:
339         my @sections = PublicInbox::MsgIter::split_quotes($s);
340         undef $s; # free memory
341         for my $txt (@sections) {
342                 if ($txt =~ /\A>/) {
343                         index_text($self, $txt, 0, 'XQUOT');
344                 } else {
345                         # does it look like a diff?
346                         if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
347                                 index_diff($self, $txt, $doc);
348                         } else {
349                                 index_text($self, $txt, 1, 'XNQ');
350                         }
351                 }
352                 undef $txt; # free memory
353         }
354 }
355
356 sub index_list_id ($$$) {
357         my ($self, $doc, $hdr) = @_;
358         for my $l ($hdr->header_raw('List-Id')) {
359                 $l =~ /<([^>]+)>/ or next;
360                 my $lid = lc $1;
361                 $doc->add_boolean_term('G' . $lid);
362                 index_phrase($self, $lid, 1, 'XL'); # probabilistic
363         }
364 }
365
366 sub index_ids ($$$$) {
367         my ($self, $doc, $hdr, $mids) = @_;
368         for my $mid (@$mids) {
369                 index_phrase($self, $mid, 1, 'XM');
370
371                 # because too many Message-IDs are prefixed with
372                 # "Pine.LNX."...
373                 if ($mid =~ /\w{12,}/) {
374                         my @long = ($mid =~ /(\w{3,}+)/g);
375                         index_phrase($self, join(' ', @long), 1, 'XM');
376                 }
377         }
378         $doc->add_boolean_term('Q' . $_) for @$mids;
379         index_list_id($self, $doc, $hdr);
380 }
381
382 sub eml2doc ($$$;$) {
383         my ($self, $eml, $smsg, $mids) = @_;
384         $mids //= mids_for_index($eml);
385         my $doc = $X->{Document}->new;
386         add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
387         my @ds = gmtime($smsg->{ds});
388         my $yyyymmdd = strftime('%Y%m%d', @ds);
389         add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
390         my $dt = strftime('%Y%m%d%H%M%S', @ds);
391         add_val($doc, PublicInbox::Search::DT(), $dt);
392         add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
393         add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
394         add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
395
396         my $tg = term_generator($self);
397         $tg->set_document($doc);
398         index_headers($self, $smsg);
399
400         if (defined(my $eidx_key = $smsg->{eidx_key})) {
401                 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
402         }
403         msg_iter($eml, \&index_xapian, [ $self, $doc ]);
404         index_ids($self, $doc, $eml, $mids);
405
406         # by default, we maintain compatibility with v1.5.0 and earlier
407         # by writing to docdata.glass, users who never exect to downgrade can
408         # use --skip-docdata
409         if (!$self->{-skip_docdata}) {
410                 # WWW doesn't need {to} or {cc}, only NNTP
411                 $smsg->{to} = $smsg->{cc} = '';
412                 $smsg->parse_references($eml, $mids);
413                 my $data = $smsg->to_doc_data;
414                 $doc->set_data($data);
415         }
416
417         if (my $altid = $self->{-altid}) {
418                 foreach my $alt (@$altid) {
419                         my $pfx = $alt->{xprefix};
420                         foreach my $mid (@$mids) {
421                                 my $id = $alt->mid2alt($mid);
422                                 next unless defined $id;
423                                 $doc->add_boolean_term($pfx . $id);
424                         }
425                 }
426         }
427         $doc;
428 }
429
430 sub add_xapian ($$$$) {
431         my ($self, $eml, $smsg, $mids) = @_;
432         begin_txn_lazy($self);
433         my $merge_vmd = delete $smsg->{-merge_vmd};
434         my $doc = eml2doc($self, $eml, $smsg, $mids);
435         if (my $old = $merge_vmd ? _get_doc($self, $smsg->{num}) : undef) {
436                 my @x = @VMD_MAP;
437                 while (my ($field, $pfx) = splice(@x, 0, 2)) {
438                         for my $term (xap_terms($pfx, $old)) {
439                                 $doc->add_boolean_term($pfx.$term);
440                         }
441                 }
442         }
443         $self->{xdb}->replace_document($smsg->{num}, $doc);
444 }
445
446 sub _msgmap_init ($) {
447         my ($self) = @_;
448         die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
449         $self->{mm} //= eval {
450                 require PublicInbox::Msgmap;
451                 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
452                 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
453         };
454 }
455
456 sub add_message {
457         # mime = PublicInbox::Eml or Email::MIME object
458         my ($self, $mime, $smsg, $sync) = @_;
459         begin_txn_lazy($self);
460         my $mids = mids_for_index($mime);
461         $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
462         $smsg->{mid} //= $mids->[0]; # v1 compatibility
463         $smsg->{num} //= do { # v1
464                 _msgmap_init($self);
465                 index_mm($self, $mime, $smsg->{blob}, $sync);
466         };
467
468         # v1 and tests only:
469         $smsg->populate($mime, $sync);
470         $smsg->{bytes} //= length($mime->as_string);
471
472         eval {
473                 # order matters, overview stores every possible piece of
474                 # data in doc_data (deflated).  Xapian only stores a subset
475                 # of the fields which exist in over.sqlite3.  We may stop
476                 # storing doc_data in Xapian sometime after we get multi-inbox
477                 # search working.
478                 if (my $oidx = $self->{oidx}) { # v1 only
479                         $oidx->add_overview($mime, $smsg);
480                 }
481                 if (need_xapian($self)) {
482                         add_xapian($self, $mime, $smsg, $mids);
483                 }
484         };
485
486         if ($@) {
487                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
488                 return undef;
489         }
490         $smsg->{num};
491 }
492
493 sub _get_doc ($$) {
494         my ($self, $docid) = @_;
495         my $doc = eval { $self->{xdb}->get_document($docid) };
496         $doc // do {
497                 warn "E: $@\n" if $@;
498                 warn "E: #$docid missing in Xapian\n";
499                 undef;
500         }
501 }
502
503 sub add_eidx_info {
504         my ($self, $docid, $eidx_key, $eml) = @_;
505         begin_txn_lazy($self);
506         my $doc = _get_doc($self, $docid) or return;
507         term_generator($self)->set_document($doc);
508
509         # '.' is special for lei_store
510         $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
511
512         index_list_id($self, $doc, $eml);
513         $self->{xdb}->replace_document($docid, $doc);
514 }
515
516 sub remove_eidx_info {
517         my ($self, $docid, $eidx_key, $eml) = @_;
518         begin_txn_lazy($self);
519         my $doc = _get_doc($self, $docid) or return;
520         eval { $doc->remove_term('O'.$eidx_key) };
521         warn "W: ->remove_term O$eidx_key: $@\n" if $@;
522         for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
523                 $l =~ /<([^>]+)>/ or next;
524                 my $lid = lc $1;
525                 eval { $doc->remove_term('G' . $lid) };
526                 warn "W: ->remove_term G$lid: $@\n" if $@;
527
528                 # nb: we don't remove the XL probabilistic terms
529                 # since terms may overlap if cross-posted.
530                 #
531                 # IOW, a message which has both <foo.example.com>
532                 # and <bar.example.com> would have overlapping
533                 # "XLexample" and "XLcom" as terms and which we
534                 # wouldn't know if they're safe to remove if we just
535                 # unindex <foo.example.com> while preserving
536                 # <bar.example.com>.
537                 #
538                 # In any case, this entire sub is will likely never
539                 # be needed and users using the "l:" prefix are probably
540                 # rarer.
541         }
542         $self->{xdb}->replace_document($docid, $doc);
543 }
544
545 sub set_vmd {
546         my ($self, $docid, $vmd) = @_;
547         begin_txn_lazy($self);
548         my $doc = _get_doc($self, $docid) or return;
549         my ($end, @rm, @add);
550         my @x = @VMD_MAP;
551         while (my ($field, $pfx) = splice(@x, 0, 2)) {
552                 my $set = $vmd->{$field} // next;
553                 my %keep = map { $_ => 1 } @$set;
554                 my %add = %keep;
555                 $end //= $doc->termlist_end;
556                 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
557                         $cur->skip_to($pfx);
558                         last if $cur == $end;
559                         my $v = $cur->get_termname;
560                         $v =~ s/\A$pfx//s or next;
561                         $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
562                 }
563                 push(@add, map { $pfx.$_ } keys %add);
564         }
565         return unless scalar(@rm) || scalar(@add);
566         $doc->remove_term($_) for @rm;
567         $doc->add_boolean_term($_) for @add;
568         $self->{xdb}->replace_document($docid, $doc);
569 }
570
571 sub apply_vmd_mod ($$) {
572         my ($doc, $vmd_mod) = @_;
573         my $updated = 0;
574         my @x = @VMD_MAP;
575         while (my ($field, $pfx) = splice(@x, 0, 2)) {
576                 # field: "L" or "kw"
577                 for my $val (@{$vmd_mod->{"-$field"} // []}) {
578                         eval {
579                                 $doc->remove_term($pfx . $val);
580                                 ++$updated;
581                         };
582                 }
583                 for my $val (@{$vmd_mod->{"+$field"} // []}) {
584                         $doc->add_boolean_term($pfx . $val);
585                         ++$updated;
586                 }
587         }
588         $updated;
589 }
590
591 sub add_vmd {
592         my ($self, $docid, $vmd) = @_;
593         begin_txn_lazy($self);
594         my $doc = _get_doc($self, $docid) or return;
595         my @x = @VMD_MAP;
596         my $updated = 0;
597         while (my ($field, $pfx) = splice(@x, 0, 2)) {
598                 my $add = $vmd->{$field} // next;
599                 $doc->add_boolean_term($pfx . $_) for @$add;
600                 $updated += scalar(@$add);
601         }
602         $updated += apply_vmd_mod($doc, $vmd);
603         $self->{xdb}->replace_document($docid, $doc) if $updated;
604 }
605
606 sub remove_vmd {
607         my ($self, $docid, $vmd) = @_;
608         begin_txn_lazy($self);
609         my $doc = _get_doc($self, $docid) or return;
610         my $replace;
611         my @x = @VMD_MAP;
612         while (my ($field, $pfx) = splice(@x, 0, 2)) {
613                 my $rm = $vmd->{$field} // next;
614                 for (@$rm) {
615                         eval {
616                                 $doc->remove_term($pfx . $_);
617                                 $replace = 1;
618                         };
619                 }
620         }
621         $self->{xdb}->replace_document($docid, $doc) if $replace;
622 }
623
624 sub update_vmd {
625         my ($self, $docid, $vmd_mod) = @_;
626         begin_txn_lazy($self);
627         my $doc = _get_doc($self, $docid) or return;
628         my $updated = apply_vmd_mod($doc, $vmd_mod);
629         $self->{xdb}->replace_document($docid, $doc) if $updated;
630         $updated;
631 }
632
633 sub xdb_remove {
634         my ($self, @docids) = @_;
635         $self->begin_txn_lazy;
636         my $xdb = $self->{xdb} or return;
637         for my $docid (@docids) {
638                 eval { $xdb->delete_document($docid) };
639                 warn "E: #$docid not in in Xapian? $@\n" if $@;
640         }
641 }
642
643 sub index_git_blob_id {
644         my ($doc, $pfx, $objid) = @_;
645
646         my $len = length($objid);
647         for (my $len = length($objid); $len >= 7; ) {
648                 $doc->add_term($pfx.$objid);
649                 $objid = substr($objid, 0, --$len);
650         }
651 }
652
653 # v1 only
654 sub unindex_eml {
655         my ($self, $oid, $eml) = @_;
656         my $mids = mids($eml);
657         my $nr = 0;
658         my %tmp;
659         for my $mid (@$mids) {
660                 my @removed = $self->{oidx}->remove_oid($oid, $mid);
661                 $nr += scalar @removed;
662                 $tmp{$_}++ for @removed;
663         }
664         if (!$nr) {
665                 my $m = join('> <', @$mids);
666                 warn "W: <$m> missing for removal from overview\n";
667         }
668         while (my ($num, $nr) = each %tmp) {
669                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
670         }
671         if ($nr) {
672                 $self->{mm}->num_delete($_) for (keys %tmp);
673         } else { # just in case msgmap and over.sqlite3 become desynched:
674                 $self->{mm}->mid_delete($mids->[0]);
675         }
676         xdb_remove($self, keys %tmp) if need_xapian($self);
677 }
678
679 sub index_mm {
680         my ($self, $mime, $oid, $sync) = @_;
681         my $mids = mids($mime);
682         my $mm = $self->{mm};
683         if ($sync->{reindex}) {
684                 my $oidx = $self->{oidx};
685                 for my $mid (@$mids) {
686                         my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
687                         return $num if defined $num;
688                 }
689                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
690         } else {
691                 # fallback to num_for since filters like RubyLang set the number
692                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
693         }
694 }
695
696 sub is_bad_blob ($$$$) {
697         my ($oid, $type, $size, $expect_oid) = @_;
698         if ($type ne 'blob') {
699                 carp "W: $expect_oid is not a blob (type=$type)";
700                 return 1;
701         }
702         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
703         $size == 0 ? 1 : 0; # size == 0 means purged
704 }
705
706 sub index_both { # git->cat_async callback
707         my ($bref, $oid, $type, $size, $sync) = @_;
708         return if is_bad_blob($oid, $type, $size, $sync->{oid});
709         my ($nr, $max) = @$sync{qw(nr max)};
710         ++$$nr;
711         $$max -= $size;
712         my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
713         $smsg->set_bytes($$bref, $size);
714         my $self = $sync->{sidx};
715         local $self->{current_info} = "$self->{current_info}: $oid";
716         my $eml = PublicInbox::Eml->new($bref);
717         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
718                 die "E: could not generate NNTP article number for $oid";
719         add_message($self, $eml, $smsg, $sync);
720         ++$self->{nidx};
721         my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
722         ${$sync->{latest_cmt}} = $cur_cmt;
723 }
724
725 sub unindex_both { # git->cat_async callback
726         my ($bref, $oid, $type, $size, $sync) = @_;
727         return if is_bad_blob($oid, $type, $size, $sync->{oid});
728         my $self = $sync->{sidx};
729         local $self->{current_info} = "$self->{current_info}: $oid";
730         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
731         # may be undef if leftover
732         if (defined(my $cur_cmt = $sync->{cur_cmt})) {
733                 ${$sync->{latest_cmt}} = $cur_cmt;
734         }
735         ++$self->{nidx};
736 }
737
738 sub with_umask {
739         my $self = shift;
740         ($self->{ibx} // $self->{eidx})->with_umask(@_);
741 }
742
743 # called by public-inbox-index
744 sub index_sync {
745         my ($self, $opt) = @_;
746         delete $self->{lock_path} if $opt->{-skip_lock};
747         $self->with_umask(\&_index_sync, $self, $opt);
748         if ($opt->{reindex} && !$opt->{quit}) {
749                 my %again = %$opt;
750                 delete @again{qw(rethread reindex)};
751                 index_sync($self, \%again);
752                 $opt->{quit} = $again{quit}; # propagate to caller
753         }
754 }
755
756 sub check_size { # check_async cb for -index --max-size=...
757         my ($oid, $type, $size, $arg, $git) = @_;
758         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
759         if ($size <= $arg->{max_size}) {
760                 $git->cat_async($oid, $arg->{index_oid}, $arg);
761         } else {
762                 warn "W: skipping $oid ($size > $arg->{max_size})\n";
763         }
764 }
765
766 sub v1_checkpoint ($$;$) {
767         my ($self, $sync, $stk) = @_;
768         $self->{ibx}->git->async_wait_all;
769
770         # $newest may be undef
771         my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
772         if (defined($newest)) {
773                 my $cur = $self->{mm}->last_commit || '';
774                 if (need_update($self, $cur, $newest)) {
775                         $self->{mm}->last_commit($newest);
776                 }
777         }
778         ${$sync->{max}} = $self->{batch_bytes};
779
780         $self->{mm}->{dbh}->commit;
781         my $xdb = need_xapian($self) ? $self->{xdb} : undef;
782         if ($newest && $xdb) {
783                 my $cur = $xdb->get_metadata('last_commit');
784                 if (need_update($self, $cur, $newest)) {
785                         $xdb->set_metadata('last_commit', $newest);
786                 }
787         }
788         if ($stk) { # all done if $stk is passed
789                 # let SearchView know a full --reindex was done so it can
790                 # generate ->has_threadid-dependent links
791                 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
792                         my $n = $xdb->get_metadata('has_threadid');
793                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
794                 }
795                 $self->{oidx}->rethread_done($sync->{-opt}); # all done
796         }
797         commit_txn_lazy($self);
798         $sync->{ibx}->git->cleanup;
799         my $nr = ${$sync->{nr}};
800         idx_release($self, $nr);
801         # let another process do some work...
802         if (my $pr = $sync->{-opt}->{-progress}) {
803                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
804         }
805         if (!$stk && !$sync->{quit}) { # more to come
806                 begin_txn_lazy($self);
807                 $self->{mm}->{dbh}->begin_work;
808         }
809 }
810
811 # only for v1
812 sub process_stack {
813         my ($self, $sync, $stk) = @_;
814         my $git = $sync->{ibx}->git;
815         my $max = $self->{batch_bytes};
816         my $nr = 0;
817         $sync->{nr} = \$nr;
818         $sync->{max} = \$max;
819         $sync->{sidx} = $self;
820         $sync->{latest_cmt} = \(my $latest_cmt);
821
822         $self->{mm}->{dbh}->begin_work;
823         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
824                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
825                 for my $oid (@leftovers) {
826                         last if $sync->{quit};
827                         $oid = unpack('H*', $oid);
828                         $git->cat_async($oid, \&unindex_both, $sync);
829                 }
830         }
831         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
832                 $sync->{index_oid} = \&index_both;
833         }
834         while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
835                 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
836                 last if $sync->{quit};
837                 if ($f eq 'm') {
838                         $arg->{autime} = $at;
839                         $arg->{cotime} = $ct;
840                         if ($sync->{max_size}) {
841                                 $git->check_async($oid, \&check_size, $arg);
842                         } else {
843                                 $git->cat_async($oid, \&index_both, $arg);
844                         }
845                         v1_checkpoint($self, $sync) if $max <= 0;
846                 } elsif ($f eq 'd') {
847                         $git->cat_async($oid, \&unindex_both, $arg);
848                 }
849         }
850         v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
851 }
852
853 sub log2stack ($$$) {
854         my ($sync, $git, $range) = @_;
855         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
856         my ($add, $del);
857         if ($sync->{ibx}->version == 1) {
858                 my $path = $hex.'{2}/'.$hex.'{38}';
859                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
860                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
861         } else {
862                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
863                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
864         }
865
866         # Count the new files so they can be added newest to oldest
867         # and still have numbers increasing from oldest to newest
868         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
869                                 --no-notes --no-color --no-renames --no-abbrev),
870                                 $range);
871         my ($at, $ct, $stk, $cmt);
872         while (<$fh>) {
873                 return if $sync->{quit};
874                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
875                         ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
876                         $stk //= PublicInbox::IdxStack->new($cmt);
877                 } elsif (/$del/) {
878                         my $oid = $1;
879                         if ($D) { # reindex case
880                                 $D->{pack('H*', $oid)}++;
881                         } else { # non-reindex case:
882                                 $stk->push_rec('d', $at, $ct, $oid, $cmt);
883                         }
884                 } elsif (/$add/) {
885                         my $oid = $1;
886                         if ($D) {
887                                 my $oid_bin = pack('H*', $oid);
888                                 my $nr = --$D->{$oid_bin};
889                                 delete($D->{$oid_bin}) if $nr <= 0;
890                                 # nr < 0 (-1) means it never existed
891                                 next if $nr >= 0;
892                         }
893                         $stk->push_rec('m', $at, $ct, $oid, $cmt);
894                 }
895         }
896         close $fh or die "git log failed: \$?=$?";
897         $stk //= PublicInbox::IdxStack->new;
898         $stk->read_prepare;
899 }
900
901 sub prepare_stack ($$) {
902         my ($sync, $range) = @_;
903         my $git = $sync->{ibx}->git;
904
905         if (index($range, '..') < 0) {
906                 # don't show annoying git errors to users who run -index
907                 # on empty inboxes
908                 $git->qx(qw(rev-parse -q --verify), "$range^0");
909                 return PublicInbox::IdxStack->new->read_prepare if $?;
910         }
911         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
912         log2stack($sync, $git, $range);
913 }
914
915 # --is-ancestor requires git 1.8.0+
916 sub is_ancestor ($$$) {
917         my ($git, $cur, $tip) = @_;
918         return 0 unless $git->check($cur);
919         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
920                 qw(merge-base --is-ancestor), $cur, $tip ];
921         my $pid = spawn($cmd);
922         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
923         $? == 0;
924 }
925
926 sub need_update ($$$) {
927         my ($self, $cur, $new) = @_;
928         my $git = $self->{ibx}->git;
929         return 1 if $cur && !is_ancestor($git, $cur, $new);
930         my $range = $cur eq '' ? $new : "$cur..$new";
931         chomp(my $n = $git->qx(qw(rev-list --count), $range));
932         ($n eq '' || $n > 0);
933 }
934
935 # The last git commit we indexed with Xapian or SQLite (msgmap)
936 # This needs to account for cases where Xapian or SQLite is
937 # out-of-date with respect to the other.
938 sub _last_x_commit {
939         my ($self, $mm) = @_;
940         my $lm = $mm->last_commit || '';
941         my $lx = '';
942         if (need_xapian($self)) {
943                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
944         } else {
945                 $lx = $lm;
946         }
947         # Use last_commit from msgmap if it is older or unset
948         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
949                 $lx = $lm;
950         }
951         $lx;
952 }
953
954 sub reindex_from ($$) {
955         my ($reindex, $last_commit) = @_;
956         return $last_commit unless $reindex;
957         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
958 }
959
960 sub quit_cb ($) {
961         my ($sync) = @_;
962         sub {
963                 # we set {-opt}->{quit} too, so ->index_sync callers
964                 # can abort multi-inbox loops this way
965                 $sync->{quit} = $sync->{-opt}->{quit} = 1;
966                 warn "gracefully quitting\n";
967         }
968 }
969
970 # indexes all unindexed messages (v1 only)
971 sub _index_sync {
972         my ($self, $opt) = @_;
973         my $tip = $opt->{ref} || 'HEAD';
974         my $ibx = $self->{ibx};
975         local $self->{current_info} = "$ibx->{inboxdir}";
976         $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
977         $ibx->git->batch_prepare;
978         my $pr = $opt->{-progress};
979         my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
980         my $quit = quit_cb($sync);
981         local $SIG{QUIT} = $quit;
982         local $SIG{INT} = $quit;
983         local $SIG{TERM} = $quit;
984         my $xdb = $self->begin_txn_lazy;
985         $self->{oidx}->rethread_prepare($opt);
986         my $mm = _msgmap_init($self);
987         if ($sync->{reindex}) {
988                 my $last = $mm->last_commit;
989                 if ($last) {
990                         $tip = $last;
991                 } else {
992                         # somebody just blindly added --reindex when indexing
993                         # for the first time, allow it:
994                         undef $sync->{reindex};
995                 }
996         }
997         my $last_commit = _last_x_commit($self, $mm);
998         my $lx = reindex_from($sync->{reindex}, $last_commit);
999         my $range = $lx eq '' ? $tip : "$lx..$tip";
1000         $pr->("counting changes\n\t$range ... ") if $pr;
1001         my $stk = prepare_stack($sync, $range);
1002         $sync->{ntodo} = $stk ? $stk->num_records : 0;
1003         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
1004         process_stack($self, $sync, $stk) if !$sync->{quit};
1005 }
1006
1007 sub DESTROY {
1008         # order matters for unlocking
1009         $_[0]->{xdb} = undef;
1010         $_[0]->{lockfh} = undef;
1011 }
1012
1013 sub _begin_txn {
1014         my ($self) = @_;
1015         my $xdb = $self->{xdb} || idx_acquire($self);
1016         $self->{oidx}->begin_lazy if $self->{oidx};
1017         $xdb->begin_transaction if $xdb;
1018         $self->{txn} = 1;
1019         $xdb;
1020 }
1021
1022 sub begin_txn_lazy {
1023         my ($self) = @_;
1024         $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1025 }
1026
1027 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1028 # This metadata is read by Admin::detect_indexlevel:
1029 sub set_metadata_once {
1030         my ($self) = @_;
1031
1032         return if $self->{shard}; # only continue if undef or 0, not >0
1033         my $xdb = $self->{xdb};
1034
1035         if (delete($self->{-set_has_threadid_once})) {
1036                 $xdb->set_metadata('has_threadid', '1');
1037         }
1038         if (delete($self->{-set_indexlevel_once})) {
1039                 my $level = $xdb->get_metadata('indexlevel');
1040                 if (!$level || $level ne 'medium') {
1041                         $xdb->set_metadata('indexlevel', 'medium');
1042                 }
1043         }
1044         if (delete($self->{-set_skip_docdata_once})) {
1045                 $xdb->get_metadata('skip_docdata') or
1046                         $xdb->set_metadata('skip_docdata', '1');
1047         }
1048 }
1049
1050 sub _commit_txn {
1051         my ($self) = @_;
1052         if (my $eidx = $self->{eidx}) {
1053                 $eidx->git->async_wait_all;
1054                 $eidx->{transact_bytes} = 0;
1055         }
1056         if (my $xdb = $self->{xdb}) {
1057                 set_metadata_once($self);
1058                 $xdb->commit_transaction;
1059         }
1060         $self->{oidx}->commit_lazy if $self->{oidx};
1061 }
1062
1063 sub commit_txn_lazy {
1064         my ($self) = @_;
1065         delete($self->{txn}) and
1066                 $self->with_umask(\&_commit_txn, $self);
1067 }
1068
1069 sub eidx_shard_new {
1070         my ($class, $eidx, $shard) = @_;
1071         my $self = bless {
1072                 eidx => $eidx,
1073                 xpfx => $eidx->{xpfx},
1074                 indexlevel => $eidx->{indexlevel},
1075                 -skip_docdata => 1,
1076                 shard => $shard,
1077                 creat => 1,
1078         }, $class;
1079         $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1080         $self;
1081 }
1082
1083 # ensure there's no stale Xapian docs by treating $over as canonical
1084 sub over_check {
1085         my ($self, $over) = @_;
1086         begin_txn_lazy($self);
1087         my $sth = $over->dbh->prepare(<<'');
1088 SELECT COUNT(*) FROM over WHERE num = ?
1089
1090         my $xdb = $self->{xdb};
1091         my $cur = $xdb->postlist_begin('');
1092         my $end = $xdb->postlist_end('');
1093         my $xdir = $self->xdir;
1094         for (; $cur != $end; $cur++) {
1095                 my $docid = $cur->get_docid;
1096                 $sth->execute($docid);
1097                 my $x = $sth->fetchrow_array;
1098                 next if $x > 0;
1099                 warn "I: removing $xdir #$docid, not in `over'\n";
1100                 $xdb->delete_document($docid);
1101         }
1102 }
1103
1104 1;