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