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