]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
ds: flatten + reuse @events, epoll_wait style fixes
[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         ++$self->{nidx};
619         my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
620         ${$sync->{latest_cmt}} = $cur_cmt;
621 }
622
623 sub unindex_both { # git->cat_async callback
624         my ($bref, $oid, $type, $size, $sync) = @_;
625         return if is_bad_blob($oid, $type, $size, $sync->{oid});
626         my $self = $sync->{sidx};
627         local $self->{current_info} = "$self->{current_info}: $oid";
628         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
629         # may be undef if leftover
630         if (defined(my $cur_cmt = $sync->{cur_cmt})) {
631                 ${$sync->{latest_cmt}} = $cur_cmt;
632         }
633         ++$self->{nidx};
634 }
635
636 sub with_umask {
637         my $self = shift;
638         ($self->{ibx} // $self->{eidx})->with_umask(@_);
639 }
640
641 # called by public-inbox-index
642 sub index_sync {
643         my ($self, $opt) = @_;
644         delete $self->{lock_path} if $opt->{-skip_lock};
645         $self->with_umask(\&_index_sync, $self, $opt);
646         if ($opt->{reindex} && !$opt->{quit}) {
647                 my %again = %$opt;
648                 delete @again{qw(rethread reindex)};
649                 index_sync($self, \%again);
650                 $opt->{quit} = $again{quit}; # propagate to caller
651         }
652 }
653
654 sub check_size { # check_async cb for -index --max-size=...
655         my ($oid, $type, $size, $arg, $git) = @_;
656         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
657         if ($size <= $arg->{max_size}) {
658                 $git->cat_async($oid, $arg->{index_oid}, $arg);
659         } else {
660                 warn "W: skipping $oid ($size > $arg->{max_size})\n";
661         }
662 }
663
664 sub v1_checkpoint ($$;$) {
665         my ($self, $sync, $stk) = @_;
666         $self->{ibx}->git->async_wait_all;
667
668         # $newest may be undef
669         my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
670         if (defined($newest)) {
671                 my $cur = $self->{mm}->last_commit || '';
672                 if (need_update($self, $cur, $newest)) {
673                         $self->{mm}->last_commit($newest);
674                 }
675         }
676         ${$sync->{max}} = $self->{batch_bytes};
677
678         $self->{mm}->{dbh}->commit;
679         my $xdb = need_xapian($self) ? $self->{xdb} : undef;
680         if ($newest && $xdb) {
681                 my $cur = $xdb->get_metadata('last_commit');
682                 if (need_update($self, $cur, $newest)) {
683                         $xdb->set_metadata('last_commit', $newest);
684                 }
685         }
686         if ($stk) { # all done if $stk is passed
687                 # let SearchView know a full --reindex was done so it can
688                 # generate ->has_threadid-dependent links
689                 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
690                         my $n = $xdb->get_metadata('has_threadid');
691                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
692                 }
693                 $self->{oidx}->rethread_done($sync->{-opt}); # all done
694         }
695         commit_txn_lazy($self);
696         $sync->{ibx}->git->cleanup;
697         my $nr = ${$sync->{nr}};
698         idx_release($self, $nr);
699         # let another process do some work...
700         if (my $pr = $sync->{-opt}->{-progress}) {
701                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
702         }
703         if (!$stk && !$sync->{quit}) { # more to come
704                 begin_txn_lazy($self);
705                 $self->{mm}->{dbh}->begin_work;
706         }
707 }
708
709 # only for v1
710 sub process_stack {
711         my ($self, $sync, $stk) = @_;
712         my $git = $sync->{ibx}->git;
713         my $max = $self->{batch_bytes};
714         my $nr = 0;
715         $sync->{nr} = \$nr;
716         $sync->{max} = \$max;
717         $sync->{sidx} = $self;
718         $sync->{latest_cmt} = \(my $latest_cmt);
719
720         $self->{mm}->{dbh}->begin_work;
721         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
722                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
723                 for my $oid (@leftovers) {
724                         last if $sync->{quit};
725                         $oid = unpack('H*', $oid);
726                         $git->cat_async($oid, \&unindex_both, $sync);
727                 }
728         }
729         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
730                 $sync->{index_oid} = \&index_both;
731         }
732         while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
733                 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
734                 last if $sync->{quit};
735                 if ($f eq 'm') {
736                         $arg->{autime} = $at;
737                         $arg->{cotime} = $ct;
738                         if ($sync->{max_size}) {
739                                 $git->check_async($oid, \&check_size, $arg);
740                         } else {
741                                 $git->cat_async($oid, \&index_both, $arg);
742                         }
743                         v1_checkpoint($self, $sync) if $max <= 0;
744                 } elsif ($f eq 'd') {
745                         $git->cat_async($oid, \&unindex_both, $arg);
746                 }
747         }
748         v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
749 }
750
751 sub log2stack ($$$) {
752         my ($sync, $git, $range) = @_;
753         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
754         my ($add, $del);
755         if ($sync->{ibx}->version == 1) {
756                 my $path = $hex.'{2}/'.$hex.'{38}';
757                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
758                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
759         } else {
760                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
761                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
762         }
763
764         # Count the new files so they can be added newest to oldest
765         # and still have numbers increasing from oldest to newest
766         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
767                                 --no-notes --no-color --no-renames --no-abbrev),
768                                 $range);
769         my ($at, $ct, $stk, $cmt);
770         while (<$fh>) {
771                 return if $sync->{quit};
772                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
773                         ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
774                         $stk //= PublicInbox::IdxStack->new($cmt);
775                 } elsif (/$del/) {
776                         my $oid = $1;
777                         if ($D) { # reindex case
778                                 $D->{pack('H*', $oid)}++;
779                         } else { # non-reindex case:
780                                 $stk->push_rec('d', $at, $ct, $oid, $cmt);
781                         }
782                 } elsif (/$add/) {
783                         my $oid = $1;
784                         if ($D) {
785                                 my $oid_bin = pack('H*', $oid);
786                                 my $nr = --$D->{$oid_bin};
787                                 delete($D->{$oid_bin}) if $nr <= 0;
788                                 # nr < 0 (-1) means it never existed
789                                 next if $nr >= 0;
790                         }
791                         $stk->push_rec('m', $at, $ct, $oid, $cmt);
792                 }
793         }
794         close $fh or die "git log failed: \$?=$?";
795         $stk //= PublicInbox::IdxStack->new;
796         $stk->read_prepare;
797 }
798
799 sub prepare_stack ($$) {
800         my ($sync, $range) = @_;
801         my $git = $sync->{ibx}->git;
802
803         if (index($range, '..') < 0) {
804                 # don't show annoying git errors to users who run -index
805                 # on empty inboxes
806                 $git->qx(qw(rev-parse -q --verify), "$range^0");
807                 return PublicInbox::IdxStack->new->read_prepare if $?;
808         }
809         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
810         log2stack($sync, $git, $range);
811 }
812
813 # --is-ancestor requires git 1.8.0+
814 sub is_ancestor ($$$) {
815         my ($git, $cur, $tip) = @_;
816         return 0 unless $git->check($cur);
817         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
818                 qw(merge-base --is-ancestor), $cur, $tip ];
819         my $pid = spawn($cmd);
820         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
821         $? == 0;
822 }
823
824 sub need_update ($$$) {
825         my ($self, $cur, $new) = @_;
826         my $git = $self->{ibx}->git;
827         return 1 if $cur && !is_ancestor($git, $cur, $new);
828         my $range = $cur eq '' ? $new : "$cur..$new";
829         chomp(my $n = $git->qx(qw(rev-list --count), $range));
830         ($n eq '' || $n > 0);
831 }
832
833 # The last git commit we indexed with Xapian or SQLite (msgmap)
834 # This needs to account for cases where Xapian or SQLite is
835 # out-of-date with respect to the other.
836 sub _last_x_commit {
837         my ($self, $mm) = @_;
838         my $lm = $mm->last_commit || '';
839         my $lx = '';
840         if (need_xapian($self)) {
841                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
842         } else {
843                 $lx = $lm;
844         }
845         # Use last_commit from msgmap if it is older or unset
846         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
847                 $lx = $lm;
848         }
849         $lx;
850 }
851
852 sub reindex_from ($$) {
853         my ($reindex, $last_commit) = @_;
854         return $last_commit unless $reindex;
855         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
856 }
857
858 sub quit_cb ($) {
859         my ($sync) = @_;
860         sub {
861                 # we set {-opt}->{quit} too, so ->index_sync callers
862                 # can abort multi-inbox loops this way
863                 $sync->{quit} = $sync->{-opt}->{quit} = 1;
864                 warn "gracefully quitting\n";
865         }
866 }
867
868 # indexes all unindexed messages (v1 only)
869 sub _index_sync {
870         my ($self, $opt) = @_;
871         my $tip = $opt->{ref} || 'HEAD';
872         my $ibx = $self->{ibx};
873         local $self->{current_info} = "$ibx->{inboxdir}";
874         $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
875         $ibx->git->batch_prepare;
876         my $pr = $opt->{-progress};
877         my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
878         my $quit = quit_cb($sync);
879         local $SIG{QUIT} = $quit;
880         local $SIG{INT} = $quit;
881         local $SIG{TERM} = $quit;
882         my $xdb = $self->begin_txn_lazy;
883         $self->{oidx}->rethread_prepare($opt);
884         my $mm = _msgmap_init($self);
885         if ($sync->{reindex}) {
886                 my $last = $mm->last_commit;
887                 if ($last) {
888                         $tip = $last;
889                 } else {
890                         # somebody just blindly added --reindex when indexing
891                         # for the first time, allow it:
892                         undef $sync->{reindex};
893                 }
894         }
895         my $last_commit = _last_x_commit($self, $mm);
896         my $lx = reindex_from($sync->{reindex}, $last_commit);
897         my $range = $lx eq '' ? $tip : "$lx..$tip";
898         $pr->("counting changes\n\t$range ... ") if $pr;
899         my $stk = prepare_stack($sync, $range);
900         $sync->{ntodo} = $stk ? $stk->num_records : 0;
901         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
902         process_stack($self, $sync, $stk) if !$sync->{quit};
903 }
904
905 sub DESTROY {
906         # order matters for unlocking
907         $_[0]->{xdb} = undef;
908         $_[0]->{lockfh} = undef;
909 }
910
911 sub _begin_txn {
912         my ($self) = @_;
913         my $xdb = $self->{xdb} || idx_acquire($self);
914         $self->{oidx}->begin_lazy if $self->{oidx};
915         $xdb->begin_transaction if $xdb;
916         $self->{txn} = 1;
917         $xdb;
918 }
919
920 sub begin_txn_lazy {
921         my ($self) = @_;
922         $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
923 }
924
925 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
926 # This metadata is read by Admin::detect_indexlevel:
927 sub set_metadata_once {
928         my ($self) = @_;
929
930         return if $self->{shard}; # only continue if undef or 0, not >0
931         my $xdb = $self->{xdb};
932
933         if (delete($self->{-set_has_threadid_once})) {
934                 $xdb->set_metadata('has_threadid', '1');
935         }
936         if (delete($self->{-set_indexlevel_once})) {
937                 my $level = $xdb->get_metadata('indexlevel');
938                 if (!$level || $level ne 'medium') {
939                         $xdb->set_metadata('indexlevel', 'medium');
940                 }
941         }
942         if (delete($self->{-set_skip_docdata_once})) {
943                 $xdb->get_metadata('skip_docdata') or
944                         $xdb->set_metadata('skip_docdata', '1');
945         }
946 }
947
948 sub _commit_txn {
949         my ($self) = @_;
950         if (my $eidx = $self->{eidx}) {
951                 $eidx->git->async_wait_all;
952                 $eidx->{transact_bytes} = 0;
953         }
954         if (my $xdb = $self->{xdb}) {
955                 set_metadata_once($self);
956                 $xdb->commit_transaction;
957         }
958         $self->{oidx}->commit_lazy if $self->{oidx};
959 }
960
961 sub commit_txn_lazy {
962         my ($self) = @_;
963         delete($self->{txn}) and
964                 $self->with_umask(\&_commit_txn, $self);
965 }
966
967 sub worker_done {
968         my ($self) = @_;
969         if (need_xapian($self)) {
970                 die "$$ $0 xdb not released\n" if $self->{xdb};
971         }
972         die "$$ $0 still in transaction\n" if $self->{txn};
973 }
974
975 sub eidx_shard_new {
976         my ($class, $eidx, $shard) = @_;
977         my $self = bless {
978                 eidx => $eidx,
979                 xpfx => $eidx->{xpfx},
980                 indexlevel => $eidx->{indexlevel},
981                 -skip_docdata => 1,
982                 shard => $shard,
983                 creat => 1,
984         }, $class;
985         $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
986         $self;
987 }
988
989 # ensure there's no stale Xapian docs by treating $over as canonical
990 sub over_check {
991         my ($self, $over) = @_;
992         begin_txn_lazy($self);
993         my $sth = $over->dbh->prepare(<<'');
994 SELECT COUNT(*) FROM over WHERE num = ?
995
996         my $xdb = $self->{xdb};
997         my $cur = $xdb->postlist_begin('');
998         my $end = $xdb->postlist_end('');
999         my $xdir = $self->xdir;
1000         for (; $cur != $end; $cur++) {
1001                 my $docid = $cur->get_docid;
1002                 $sth->execute($docid);
1003                 my $x = $sth->fetchrow_array;
1004                 next if $x > 0;
1005                 warn "I: removing $xdir #$docid, not in `over'\n";
1006                 $xdb->delete_document($docid);
1007         }
1008 }
1009
1010 1;