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