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