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