]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
lei import: support adding keywords and labels on import
[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                         my $vals = xap_terms($pfx, $old);
439                         $doc->add_boolean_term($pfx.$_) for keys %$vals;
440                 }
441         }
442         $self->{xdb}->replace_document($smsg->{num}, $doc);
443 }
444
445 sub _msgmap_init ($) {
446         my ($self) = @_;
447         die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
448         $self->{mm} //= eval {
449                 require PublicInbox::Msgmap;
450                 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
451                 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
452         };
453 }
454
455 sub add_message {
456         # mime = PublicInbox::Eml or Email::MIME object
457         my ($self, $mime, $smsg, $sync) = @_;
458         begin_txn_lazy($self);
459         my $mids = mids_for_index($mime);
460         $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
461         $smsg->{mid} //= $mids->[0]; # v1 compatibility
462         $smsg->{num} //= do { # v1
463                 _msgmap_init($self);
464                 index_mm($self, $mime, $smsg->{blob}, $sync);
465         };
466
467         # v1 and tests only:
468         $smsg->populate($mime, $sync);
469         $smsg->{bytes} //= length($mime->as_string);
470
471         eval {
472                 # order matters, overview stores every possible piece of
473                 # data in doc_data (deflated).  Xapian only stores a subset
474                 # of the fields which exist in over.sqlite3.  We may stop
475                 # storing doc_data in Xapian sometime after we get multi-inbox
476                 # search working.
477                 if (my $oidx = $self->{oidx}) { # v1 only
478                         $oidx->add_overview($mime, $smsg);
479                 }
480                 if (need_xapian($self)) {
481                         add_xapian($self, $mime, $smsg, $mids);
482                 }
483         };
484
485         if ($@) {
486                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
487                 return undef;
488         }
489         $smsg->{num};
490 }
491
492 sub _get_doc ($$) {
493         my ($self, $docid) = @_;
494         my $doc = eval { $self->{xdb}->get_document($docid) };
495         $doc // do {
496                 warn "E: $@\n" if $@;
497                 warn "E: #$docid missing in Xapian\n";
498                 undef;
499         }
500 }
501
502 sub add_eidx_info {
503         my ($self, $docid, $eidx_key, $eml) = @_;
504         begin_txn_lazy($self);
505         my $doc = _get_doc($self, $docid) or return;
506         term_generator($self)->set_document($doc);
507
508         # '.' is special for lei_store
509         $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
510
511         index_list_id($self, $doc, $eml);
512         $self->{xdb}->replace_document($docid, $doc);
513 }
514
515 sub remove_eidx_info {
516         my ($self, $docid, $eidx_key, $eml) = @_;
517         begin_txn_lazy($self);
518         my $doc = _get_doc($self, $docid) or return;
519         eval { $doc->remove_term('O'.$eidx_key) };
520         warn "W: ->remove_term O$eidx_key: $@\n" if $@;
521         for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
522                 $l =~ /<([^>]+)>/ or next;
523                 my $lid = lc $1;
524                 eval { $doc->remove_term('G' . $lid) };
525                 warn "W: ->remove_term G$lid: $@\n" if $@;
526
527                 # nb: we don't remove the XL probabilistic terms
528                 # since terms may overlap if cross-posted.
529                 #
530                 # IOW, a message which has both <foo.example.com>
531                 # and <bar.example.com> would have overlapping
532                 # "XLexample" and "XLcom" as terms and which we
533                 # wouldn't know if they're safe to remove if we just
534                 # unindex <foo.example.com> while preserving
535                 # <bar.example.com>.
536                 #
537                 # In any case, this entire sub is will likely never
538                 # be needed and users using the "l:" prefix are probably
539                 # rarer.
540         }
541         $self->{xdb}->replace_document($docid, $doc);
542 }
543
544 sub set_vmd {
545         my ($self, $docid, $vmd) = @_;
546         begin_txn_lazy($self);
547         my $doc = _get_doc($self, $docid) or return;
548         my ($end, @rm, @add);
549         my @x = @VMD_MAP;
550         while (my ($field, $pfx) = splice(@x, 0, 2)) {
551                 my $set = $vmd->{$field} // next;
552                 my %keep = map { $_ => 1 } @$set;
553                 my %add = %keep;
554                 $end //= $doc->termlist_end;
555                 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
556                         $cur->skip_to($pfx);
557                         last if $cur == $end;
558                         my $v = $cur->get_termname;
559                         $v =~ s/\A$pfx//s or next;
560                         $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
561                 }
562                 push(@add, map { $pfx.$_ } keys %add);
563         }
564         return unless scalar(@rm) || scalar(@add);
565         $doc->remove_term($_) for @rm;
566         $doc->add_boolean_term($_) for @add;
567         $self->{xdb}->replace_document($docid, $doc);
568 }
569
570 sub apply_vmd_mod ($$) {
571         my ($doc, $vmd_mod) = @_;
572         my $updated = 0;
573         my @x = @VMD_MAP;
574         while (my ($field, $pfx) = splice(@x, 0, 2)) {
575                 # field: "label" or "kw"
576                 for my $val (@{$vmd_mod->{"-$field"} // []}) {
577                         eval {
578                                 $doc->remove_term($pfx . $val);
579                                 ++$updated;
580                         };
581                 }
582                 for my $val (@{$vmd_mod->{"+$field"} // []}) {
583                         $doc->add_boolean_term($pfx . $val);
584                         ++$updated;
585                 }
586         }
587         $updated;
588 }
589
590 sub add_vmd {
591         my ($self, $docid, $vmd) = @_;
592         begin_txn_lazy($self);
593         my $doc = _get_doc($self, $docid) or return;
594         my @x = @VMD_MAP;
595         my $updated = 0;
596         while (my ($field, $pfx) = splice(@x, 0, 2)) {
597                 my $add = $vmd->{$field} // next;
598                 $doc->add_boolean_term($pfx . $_) for @$add;
599                 $updated += scalar(@$add);
600         }
601         $updated += apply_vmd_mod($doc, $vmd);
602         $self->{xdb}->replace_document($docid, $doc) if $updated;
603 }
604
605 sub remove_vmd {
606         my ($self, $docid, $vmd) = @_;
607         begin_txn_lazy($self);
608         my $doc = _get_doc($self, $docid) or return;
609         my $replace;
610         my @x = @VMD_MAP;
611         while (my ($field, $pfx) = splice(@x, 0, 2)) {
612                 my $rm = $vmd->{$field} // next;
613                 for (@$rm) {
614                         eval {
615                                 $doc->remove_term($pfx . $_);
616                                 $replace = 1;
617                         };
618                 }
619         }
620         $self->{xdb}->replace_document($docid, $doc) if $replace;
621 }
622
623 sub update_vmd {
624         my ($self, $docid, $vmd_mod) = @_;
625         begin_txn_lazy($self);
626         my $doc = _get_doc($self, $docid) or return;
627         my $updated = apply_vmd_mod($doc, $vmd_mod);
628         $self->{xdb}->replace_document($docid, $doc) if $updated;
629         $updated;
630 }
631
632 sub xdb_remove {
633         my ($self, @docids) = @_;
634         $self->begin_txn_lazy;
635         my $xdb = $self->{xdb} or return;
636         for my $docid (@docids) {
637                 eval { $xdb->delete_document($docid) };
638                 warn "E: #$docid not in in Xapian? $@\n" if $@;
639         }
640 }
641
642 sub index_git_blob_id {
643         my ($doc, $pfx, $objid) = @_;
644
645         my $len = length($objid);
646         for (my $len = length($objid); $len >= 7; ) {
647                 $doc->add_term($pfx.$objid);
648                 $objid = substr($objid, 0, --$len);
649         }
650 }
651
652 # v1 only
653 sub unindex_eml {
654         my ($self, $oid, $eml) = @_;
655         my $mids = mids($eml);
656         my $nr = 0;
657         my %tmp;
658         for my $mid (@$mids) {
659                 my @removed = $self->{oidx}->remove_oid($oid, $mid);
660                 $nr += scalar @removed;
661                 $tmp{$_}++ for @removed;
662         }
663         if (!$nr) {
664                 my $m = join('> <', @$mids);
665                 warn "W: <$m> missing for removal from overview\n";
666         }
667         while (my ($num, $nr) = each %tmp) {
668                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
669         }
670         if ($nr) {
671                 $self->{mm}->num_delete($_) for (keys %tmp);
672         } else { # just in case msgmap and over.sqlite3 become desynched:
673                 $self->{mm}->mid_delete($mids->[0]);
674         }
675         xdb_remove($self, keys %tmp) if need_xapian($self);
676 }
677
678 sub index_mm {
679         my ($self, $mime, $oid, $sync) = @_;
680         my $mids = mids($mime);
681         my $mm = $self->{mm};
682         if ($sync->{reindex}) {
683                 my $oidx = $self->{oidx};
684                 for my $mid (@$mids) {
685                         my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
686                         return $num if defined $num;
687                 }
688                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
689         } else {
690                 # fallback to num_for since filters like RubyLang set the number
691                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
692         }
693 }
694
695 sub is_bad_blob ($$$$) {
696         my ($oid, $type, $size, $expect_oid) = @_;
697         if ($type ne 'blob') {
698                 carp "W: $expect_oid is not a blob (type=$type)";
699                 return 1;
700         }
701         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
702         $size == 0 ? 1 : 0; # size == 0 means purged
703 }
704
705 sub index_both { # git->cat_async callback
706         my ($bref, $oid, $type, $size, $sync) = @_;
707         return if is_bad_blob($oid, $type, $size, $sync->{oid});
708         my ($nr, $max) = @$sync{qw(nr max)};
709         ++$$nr;
710         $$max -= $size;
711         my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
712         $smsg->set_bytes($$bref, $size);
713         my $self = $sync->{sidx};
714         local $self->{current_info} = "$self->{current_info}: $oid";
715         my $eml = PublicInbox::Eml->new($bref);
716         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
717                 die "E: could not generate NNTP article number for $oid";
718         add_message($self, $eml, $smsg, $sync);
719         ++$self->{nidx};
720         my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
721         ${$sync->{latest_cmt}} = $cur_cmt;
722 }
723
724 sub unindex_both { # git->cat_async callback
725         my ($bref, $oid, $type, $size, $sync) = @_;
726         return if is_bad_blob($oid, $type, $size, $sync->{oid});
727         my $self = $sync->{sidx};
728         local $self->{current_info} = "$self->{current_info}: $oid";
729         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
730         # may be undef if leftover
731         if (defined(my $cur_cmt = $sync->{cur_cmt})) {
732                 ${$sync->{latest_cmt}} = $cur_cmt;
733         }
734         ++$self->{nidx};
735 }
736
737 sub with_umask {
738         my $self = shift;
739         ($self->{ibx} // $self->{eidx})->with_umask(@_);
740 }
741
742 # called by public-inbox-index
743 sub index_sync {
744         my ($self, $opt) = @_;
745         delete $self->{lock_path} if $opt->{-skip_lock};
746         $self->with_umask(\&_index_sync, $self, $opt);
747         if ($opt->{reindex} && !$opt->{quit}) {
748                 my %again = %$opt;
749                 delete @again{qw(rethread reindex)};
750                 index_sync($self, \%again);
751                 $opt->{quit} = $again{quit}; # propagate to caller
752         }
753 }
754
755 sub check_size { # check_async cb for -index --max-size=...
756         my ($oid, $type, $size, $arg, $git) = @_;
757         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
758         if ($size <= $arg->{max_size}) {
759                 $git->cat_async($oid, $arg->{index_oid}, $arg);
760         } else {
761                 warn "W: skipping $oid ($size > $arg->{max_size})\n";
762         }
763 }
764
765 sub v1_checkpoint ($$;$) {
766         my ($self, $sync, $stk) = @_;
767         $self->{ibx}->git->async_wait_all;
768
769         # $newest may be undef
770         my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
771         if (defined($newest)) {
772                 my $cur = $self->{mm}->last_commit || '';
773                 if (need_update($self, $cur, $newest)) {
774                         $self->{mm}->last_commit($newest);
775                 }
776         }
777         ${$sync->{max}} = $self->{batch_bytes};
778
779         $self->{mm}->{dbh}->commit;
780         my $xdb = need_xapian($self) ? $self->{xdb} : undef;
781         if ($newest && $xdb) {
782                 my $cur = $xdb->get_metadata('last_commit');
783                 if (need_update($self, $cur, $newest)) {
784                         $xdb->set_metadata('last_commit', $newest);
785                 }
786         }
787         if ($stk) { # all done if $stk is passed
788                 # let SearchView know a full --reindex was done so it can
789                 # generate ->has_threadid-dependent links
790                 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
791                         my $n = $xdb->get_metadata('has_threadid');
792                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
793                 }
794                 $self->{oidx}->rethread_done($sync->{-opt}); # all done
795         }
796         commit_txn_lazy($self);
797         $sync->{ibx}->git->cleanup;
798         my $nr = ${$sync->{nr}};
799         idx_release($self, $nr);
800         # let another process do some work...
801         if (my $pr = $sync->{-opt}->{-progress}) {
802                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
803         }
804         if (!$stk && !$sync->{quit}) { # more to come
805                 begin_txn_lazy($self);
806                 $self->{mm}->{dbh}->begin_work;
807         }
808 }
809
810 # only for v1
811 sub process_stack {
812         my ($self, $sync, $stk) = @_;
813         my $git = $sync->{ibx}->git;
814         my $max = $self->{batch_bytes};
815         my $nr = 0;
816         $sync->{nr} = \$nr;
817         $sync->{max} = \$max;
818         $sync->{sidx} = $self;
819         $sync->{latest_cmt} = \(my $latest_cmt);
820
821         $self->{mm}->{dbh}->begin_work;
822         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
823                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
824                 for my $oid (@leftovers) {
825                         last if $sync->{quit};
826                         $oid = unpack('H*', $oid);
827                         $git->cat_async($oid, \&unindex_both, $sync);
828                 }
829         }
830         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
831                 $sync->{index_oid} = \&index_both;
832         }
833         while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
834                 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
835                 last if $sync->{quit};
836                 if ($f eq 'm') {
837                         $arg->{autime} = $at;
838                         $arg->{cotime} = $ct;
839                         if ($sync->{max_size}) {
840                                 $git->check_async($oid, \&check_size, $arg);
841                         } else {
842                                 $git->cat_async($oid, \&index_both, $arg);
843                         }
844                         v1_checkpoint($self, $sync) if $max <= 0;
845                 } elsif ($f eq 'd') {
846                         $git->cat_async($oid, \&unindex_both, $arg);
847                 }
848         }
849         v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
850 }
851
852 sub log2stack ($$$) {
853         my ($sync, $git, $range) = @_;
854         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
855         my ($add, $del);
856         if ($sync->{ibx}->version == 1) {
857                 my $path = $hex.'{2}/'.$hex.'{38}';
858                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
859                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
860         } else {
861                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
862                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
863         }
864
865         # Count the new files so they can be added newest to oldest
866         # and still have numbers increasing from oldest to newest
867         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
868                                 --no-notes --no-color --no-renames --no-abbrev),
869                                 $range);
870         my ($at, $ct, $stk, $cmt);
871         while (<$fh>) {
872                 return if $sync->{quit};
873                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
874                         ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
875                         $stk //= PublicInbox::IdxStack->new($cmt);
876                 } elsif (/$del/) {
877                         my $oid = $1;
878                         if ($D) { # reindex case
879                                 $D->{pack('H*', $oid)}++;
880                         } else { # non-reindex case:
881                                 $stk->push_rec('d', $at, $ct, $oid, $cmt);
882                         }
883                 } elsif (/$add/) {
884                         my $oid = $1;
885                         if ($D) {
886                                 my $oid_bin = pack('H*', $oid);
887                                 my $nr = --$D->{$oid_bin};
888                                 delete($D->{$oid_bin}) if $nr <= 0;
889                                 # nr < 0 (-1) means it never existed
890                                 next if $nr >= 0;
891                         }
892                         $stk->push_rec('m', $at, $ct, $oid, $cmt);
893                 }
894         }
895         close $fh or die "git log failed: \$?=$?";
896         $stk //= PublicInbox::IdxStack->new;
897         $stk->read_prepare;
898 }
899
900 sub prepare_stack ($$) {
901         my ($sync, $range) = @_;
902         my $git = $sync->{ibx}->git;
903
904         if (index($range, '..') < 0) {
905                 # don't show annoying git errors to users who run -index
906                 # on empty inboxes
907                 $git->qx(qw(rev-parse -q --verify), "$range^0");
908                 return PublicInbox::IdxStack->new->read_prepare if $?;
909         }
910         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
911         log2stack($sync, $git, $range);
912 }
913
914 # --is-ancestor requires git 1.8.0+
915 sub is_ancestor ($$$) {
916         my ($git, $cur, $tip) = @_;
917         return 0 unless $git->check($cur);
918         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
919                 qw(merge-base --is-ancestor), $cur, $tip ];
920         my $pid = spawn($cmd);
921         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
922         $? == 0;
923 }
924
925 sub need_update ($$$) {
926         my ($self, $cur, $new) = @_;
927         my $git = $self->{ibx}->git;
928         return 1 if $cur && !is_ancestor($git, $cur, $new);
929         my $range = $cur eq '' ? $new : "$cur..$new";
930         chomp(my $n = $git->qx(qw(rev-list --count), $range));
931         ($n eq '' || $n > 0);
932 }
933
934 # The last git commit we indexed with Xapian or SQLite (msgmap)
935 # This needs to account for cases where Xapian or SQLite is
936 # out-of-date with respect to the other.
937 sub _last_x_commit {
938         my ($self, $mm) = @_;
939         my $lm = $mm->last_commit || '';
940         my $lx = '';
941         if (need_xapian($self)) {
942                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
943         } else {
944                 $lx = $lm;
945         }
946         # Use last_commit from msgmap if it is older or unset
947         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
948                 $lx = $lm;
949         }
950         $lx;
951 }
952
953 sub reindex_from ($$) {
954         my ($reindex, $last_commit) = @_;
955         return $last_commit unless $reindex;
956         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
957 }
958
959 sub quit_cb ($) {
960         my ($sync) = @_;
961         sub {
962                 # we set {-opt}->{quit} too, so ->index_sync callers
963                 # can abort multi-inbox loops this way
964                 $sync->{quit} = $sync->{-opt}->{quit} = 1;
965                 warn "gracefully quitting\n";
966         }
967 }
968
969 # indexes all unindexed messages (v1 only)
970 sub _index_sync {
971         my ($self, $opt) = @_;
972         my $tip = $opt->{ref} || 'HEAD';
973         my $ibx = $self->{ibx};
974         local $self->{current_info} = "$ibx->{inboxdir}";
975         $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
976         $ibx->git->batch_prepare;
977         my $pr = $opt->{-progress};
978         my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
979         my $quit = quit_cb($sync);
980         local $SIG{QUIT} = $quit;
981         local $SIG{INT} = $quit;
982         local $SIG{TERM} = $quit;
983         my $xdb = $self->begin_txn_lazy;
984         $self->{oidx}->rethread_prepare($opt);
985         my $mm = _msgmap_init($self);
986         if ($sync->{reindex}) {
987                 my $last = $mm->last_commit;
988                 if ($last) {
989                         $tip = $last;
990                 } else {
991                         # somebody just blindly added --reindex when indexing
992                         # for the first time, allow it:
993                         undef $sync->{reindex};
994                 }
995         }
996         my $last_commit = _last_x_commit($self, $mm);
997         my $lx = reindex_from($sync->{reindex}, $last_commit);
998         my $range = $lx eq '' ? $tip : "$lx..$tip";
999         $pr->("counting changes\n\t$range ... ") if $pr;
1000         my $stk = prepare_stack($sync, $range);
1001         $sync->{ntodo} = $stk ? $stk->num_records : 0;
1002         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
1003         process_stack($self, $sync, $stk) if !$sync->{quit};
1004 }
1005
1006 sub DESTROY {
1007         # order matters for unlocking
1008         $_[0]->{xdb} = undef;
1009         $_[0]->{lockfh} = undef;
1010 }
1011
1012 sub _begin_txn {
1013         my ($self) = @_;
1014         my $xdb = $self->{xdb} || idx_acquire($self);
1015         $self->{oidx}->begin_lazy if $self->{oidx};
1016         $xdb->begin_transaction if $xdb;
1017         $self->{txn} = 1;
1018         $xdb;
1019 }
1020
1021 sub begin_txn_lazy {
1022         my ($self) = @_;
1023         $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1024 }
1025
1026 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1027 # This metadata is read by Admin::detect_indexlevel:
1028 sub set_metadata_once {
1029         my ($self) = @_;
1030
1031         return if $self->{shard}; # only continue if undef or 0, not >0
1032         my $xdb = $self->{xdb};
1033
1034         if (delete($self->{-set_has_threadid_once})) {
1035                 $xdb->set_metadata('has_threadid', '1');
1036         }
1037         if (delete($self->{-set_indexlevel_once})) {
1038                 my $level = $xdb->get_metadata('indexlevel');
1039                 if (!$level || $level ne 'medium') {
1040                         $xdb->set_metadata('indexlevel', 'medium');
1041                 }
1042         }
1043         if (delete($self->{-set_skip_docdata_once})) {
1044                 $xdb->get_metadata('skip_docdata') or
1045                         $xdb->set_metadata('skip_docdata', '1');
1046         }
1047 }
1048
1049 sub _commit_txn {
1050         my ($self) = @_;
1051         if (my $eidx = $self->{eidx}) {
1052                 $eidx->git->async_wait_all;
1053                 $eidx->{transact_bytes} = 0;
1054         }
1055         if (my $xdb = $self->{xdb}) {
1056                 set_metadata_once($self);
1057                 $xdb->commit_transaction;
1058         }
1059         $self->{oidx}->commit_lazy if $self->{oidx};
1060 }
1061
1062 sub commit_txn_lazy {
1063         my ($self) = @_;
1064         delete($self->{txn}) and
1065                 $self->with_umask(\&_commit_txn, $self);
1066 }
1067
1068 sub eidx_shard_new {
1069         my ($class, $eidx, $shard) = @_;
1070         my $self = bless {
1071                 eidx => $eidx,
1072                 xpfx => $eidx->{xpfx},
1073                 indexlevel => $eidx->{indexlevel},
1074                 -skip_docdata => 1,
1075                 shard => $shard,
1076                 creat => 1,
1077         }, $class;
1078         $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1079         $self;
1080 }
1081
1082 # ensure there's no stale Xapian docs by treating $over as canonical
1083 sub over_check {
1084         my ($self, $over) = @_;
1085         begin_txn_lazy($self);
1086         my $sth = $over->dbh->prepare(<<'');
1087 SELECT COUNT(*) FROM over WHERE num = ?
1088
1089         my $xdb = $self->{xdb};
1090         my $cur = $xdb->postlist_begin('');
1091         my $end = $xdb->postlist_end('');
1092         my $xdir = $self->xdir;
1093         for (; $cur != $end; $cur++) {
1094                 my $docid = $cur->get_docid;
1095                 $sth->execute($docid);
1096                 my $x = $sth->fetchrow_array;
1097                 next if $x > 0;
1098                 warn "I: removing $xdir #$docid, not in `over'\n";
1099                 $xdb->delete_document($docid);
1100         }
1101 }
1102
1103 1;