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