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