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