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