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