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