]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
searchidx: remove smsg_from_doc
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015-2021 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files
4 #
5 # Indexes mail with Xapian and our (SQLite-based) ::Msgmap for use
6 # with the web and NNTP interfaces.  This index maintains thread
7 # relationships for use by PublicInbox::SearchThread.
8 # This writes to the search index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use v5.10.1;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
13 use PublicInbox::Eml;
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw(mids_for_index mids);
16 use PublicInbox::MsgIter;
17 use PublicInbox::IdxStack;
18 use Carp qw(croak carp);
19 use POSIX qw(strftime);
20 use Time::Local qw(timegm);
21 use PublicInbox::OverIdx;
22 use PublicInbox::Spawn qw(spawn nodatacow_dir);
23 use PublicInbox::Git qw(git_unquote);
24 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
25 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
26         index_text term_generator add_val is_bad_blob);
27 my $X = \%PublicInbox::Search::X;
28 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
29 our $DB_NO_SYNC = 0;
30 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
31 use constant DEBUG => !!$ENV{DEBUG};
32
33 my $xapianlevels = qr/\A(?:full|medium)\z/;
34 my $hex = '[a-f0-9]';
35 my $OID = $hex .'{40,}';
36 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
37
38 sub new {
39         my ($class, $ibx, $creat, $shard) = @_;
40         ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
41         my $inboxdir = $ibx->{inboxdir};
42         my $version = $ibx->version;
43         my $indexlevel = 'full';
44         my $altid = $ibx->{altid};
45         if ($altid) {
46                 require PublicInbox::AltId;
47                 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
48         }
49         if ($ibx->{indexlevel}) {
50                 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
51                         $indexlevel = $ibx->{indexlevel};
52                 } else {
53                         die("Invalid indexlevel $ibx->{indexlevel}\n");
54                 }
55         }
56         $ibx = PublicInbox::InboxWritable->new($ibx);
57         my $self = PublicInbox::Search->new($ibx);
58         bless $self, $class;
59         $self->{ibx} = $ibx;
60         $self->{-altid} = $altid;
61         $self->{indexlevel} = $indexlevel;
62         $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
63         if ($ibx->{-skip_docdata}) {
64                 $self->{-set_skip_docdata_once} = 1;
65                 $self->{-skip_docdata} = 1;
66         }
67         if ($version == 1) {
68                 $self->{lock_path} = "$inboxdir/ssoma.lock";
69                 my $dir = $self->xdir;
70                 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
71                 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
72         } elsif ($version == 2) {
73                 defined $shard or die "shard is required for v2\n";
74                 # shard is a number
75                 $self->{shard} = $shard;
76                 $self->{lock_path} = undef;
77         } else {
78                 die "unsupported inbox version=$version\n";
79         }
80         $self->{creat} = ($creat || 0) == 1;
81         $self;
82 }
83
84 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
85
86 sub idx_release {
87         my ($self, $wake) = @_;
88         if (need_xapian($self)) {
89                 my $xdb = delete $self->{xdb} or croak 'not acquired';
90                 $xdb->close;
91         }
92         $self->lock_release($wake) if $self->{creat};
93         undef;
94 }
95
96 sub load_xapian_writable () {
97         return 1 if $X->{WritableDatabase};
98         PublicInbox::Search::load_xapian() or return;
99         my $xap = $PublicInbox::Search::Xap;
100         for (qw(Document TermGenerator WritableDatabase)) {
101                 $X->{$_} = $xap.'::'.$_;
102         }
103         eval 'require '.$X->{WritableDatabase} or die;
104         *sortable_serialise = $xap.'::sortable_serialise';
105         $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
106         $DB_OPEN = eval($xap.'::DB_OPEN()');
107         my $ver = (eval($xap.'::major_version()') << 16) |
108                 (eval($xap.'::minor_version()') << 8) |
109                 eval($xap.'::revision()');
110         $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
111         # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
112         $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
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) if $eidx_key ne '.';
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                 $smsg->parse_references($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         begin_txn_lazy($self);
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}->version != 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         begin_txn_lazy($self);
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) if $eidx_key ne '.';
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 set_keywords {
505         my ($self, $docid, @kw) = @_;
506         begin_txn_lazy($self);
507         my $doc = _get_doc($self, $docid) or return;
508         my %keep = map { $_ => 1 } @kw;
509         my %add = %keep;
510         my @rm;
511         my $end = $doc->termlist_end;
512         for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
513                 $cur->skip_to('K');
514                 last if $cur == $end;
515                 my $kw = $cur->get_termname;
516                 $kw =~ s/\AK//s or next;
517                 $keep{$kw} ? delete($add{$kw}) : push(@rm, $kw);
518         }
519         return unless (scalar(@rm) + scalar(keys %add));
520         $doc->remove_term('K'.$_) for @rm;
521         $doc->add_boolean_term('K'.$_) for (keys %add);
522         $self->{xdb}->replace_document($docid, $doc);
523 }
524
525 sub add_keywords {
526         my ($self, $docid, @kw) = @_;
527         begin_txn_lazy($self);
528         my $doc = _get_doc($self, $docid) or return;
529         $doc->add_boolean_term('K'.$_) for @kw;
530         $self->{xdb}->replace_document($docid, $doc);
531 }
532
533 sub remove_keywords {
534         my ($self, $docid, @kw) = @_;
535         begin_txn_lazy($self);
536         my $doc = _get_doc($self, $docid) or return;
537         my $replace;
538         eval {
539                 $doc->remove_term('K'.$_);
540                 $replace = 1
541         } for @kw;
542         $self->{xdb}->replace_document($docid, $doc) if $replace;
543 }
544
545 sub xdb_remove {
546         my ($self, @docids) = @_;
547         $self->begin_txn_lazy;
548         my $xdb = $self->{xdb} or return;
549         for my $docid (@docids) {
550                 eval { $xdb->delete_document($docid) };
551                 warn "E: #$docid not in in Xapian? $@\n" if $@;
552         }
553 }
554
555 sub index_git_blob_id {
556         my ($doc, $pfx, $objid) = @_;
557
558         my $len = length($objid);
559         for (my $len = length($objid); $len >= 7; ) {
560                 $doc->add_term($pfx.$objid);
561                 $objid = substr($objid, 0, --$len);
562         }
563 }
564
565 # v1 only
566 sub unindex_eml {
567         my ($self, $oid, $eml) = @_;
568         my $mids = mids($eml);
569         my $nr = 0;
570         my %tmp;
571         for my $mid (@$mids) {
572                 my @removed = $self->{oidx}->remove_oid($oid, $mid);
573                 $nr += scalar @removed;
574                 $tmp{$_}++ for @removed;
575         }
576         if (!$nr) {
577                 my $m = join('> <', @$mids);
578                 warn "W: <$m> missing for removal from overview\n";
579         }
580         while (my ($num, $nr) = each %tmp) {
581                 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
582         }
583         if ($nr) {
584                 $self->{mm}->num_delete($_) for (keys %tmp);
585         } else { # just in case msgmap and over.sqlite3 become desynched:
586                 $self->{mm}->mid_delete($mids->[0]);
587         }
588         xdb_remove($self, keys %tmp) if need_xapian($self);
589 }
590
591 sub index_mm {
592         my ($self, $mime, $oid, $sync) = @_;
593         my $mids = mids($mime);
594         my $mm = $self->{mm};
595         if ($sync->{reindex}) {
596                 my $oidx = $self->{oidx};
597                 for my $mid (@$mids) {
598                         my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
599                         return $num if defined $num;
600                 }
601                 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
602         } else {
603                 # fallback to num_for since filters like RubyLang set the number
604                 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
605         }
606 }
607
608 sub is_bad_blob ($$$$) {
609         my ($oid, $type, $size, $expect_oid) = @_;
610         if ($type ne 'blob') {
611                 carp "W: $expect_oid is not a blob (type=$type)";
612                 return 1;
613         }
614         croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
615         $size == 0 ? 1 : 0; # size == 0 means purged
616 }
617
618 sub index_both { # git->cat_async callback
619         my ($bref, $oid, $type, $size, $sync) = @_;
620         return if is_bad_blob($oid, $type, $size, $sync->{oid});
621         my ($nr, $max) = @$sync{qw(nr max)};
622         ++$$nr;
623         $$max -= $size;
624         my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
625         $smsg->set_bytes($$bref, $size);
626         my $self = $sync->{sidx};
627         local $self->{current_info} = "$self->{current_info}: $oid";
628         my $eml = PublicInbox::Eml->new($bref);
629         $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
630                 die "E: could not generate NNTP article number for $oid";
631         add_message($self, $eml, $smsg, $sync);
632         ++$self->{nidx};
633         my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
634         ${$sync->{latest_cmt}} = $cur_cmt;
635 }
636
637 sub unindex_both { # git->cat_async callback
638         my ($bref, $oid, $type, $size, $sync) = @_;
639         return if is_bad_blob($oid, $type, $size, $sync->{oid});
640         my $self = $sync->{sidx};
641         local $self->{current_info} = "$self->{current_info}: $oid";
642         unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
643         # may be undef if leftover
644         if (defined(my $cur_cmt = $sync->{cur_cmt})) {
645                 ${$sync->{latest_cmt}} = $cur_cmt;
646         }
647         ++$self->{nidx};
648 }
649
650 sub with_umask {
651         my $self = shift;
652         ($self->{ibx} // $self->{eidx})->with_umask(@_);
653 }
654
655 # called by public-inbox-index
656 sub index_sync {
657         my ($self, $opt) = @_;
658         delete $self->{lock_path} if $opt->{-skip_lock};
659         $self->with_umask(\&_index_sync, $self, $opt);
660         if ($opt->{reindex} && !$opt->{quit}) {
661                 my %again = %$opt;
662                 delete @again{qw(rethread reindex)};
663                 index_sync($self, \%again);
664                 $opt->{quit} = $again{quit}; # propagate to caller
665         }
666 }
667
668 sub check_size { # check_async cb for -index --max-size=...
669         my ($oid, $type, $size, $arg, $git) = @_;
670         (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
671         if ($size <= $arg->{max_size}) {
672                 $git->cat_async($oid, $arg->{index_oid}, $arg);
673         } else {
674                 warn "W: skipping $oid ($size > $arg->{max_size})\n";
675         }
676 }
677
678 sub v1_checkpoint ($$;$) {
679         my ($self, $sync, $stk) = @_;
680         $self->{ibx}->git->async_wait_all;
681
682         # $newest may be undef
683         my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
684         if (defined($newest)) {
685                 my $cur = $self->{mm}->last_commit || '';
686                 if (need_update($self, $cur, $newest)) {
687                         $self->{mm}->last_commit($newest);
688                 }
689         }
690         ${$sync->{max}} = $self->{batch_bytes};
691
692         $self->{mm}->{dbh}->commit;
693         my $xdb = need_xapian($self) ? $self->{xdb} : undef;
694         if ($newest && $xdb) {
695                 my $cur = $xdb->get_metadata('last_commit');
696                 if (need_update($self, $cur, $newest)) {
697                         $xdb->set_metadata('last_commit', $newest);
698                 }
699         }
700         if ($stk) { # all done if $stk is passed
701                 # let SearchView know a full --reindex was done so it can
702                 # generate ->has_threadid-dependent links
703                 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
704                         my $n = $xdb->get_metadata('has_threadid');
705                         $xdb->set_metadata('has_threadid', '1') if $n ne '1';
706                 }
707                 $self->{oidx}->rethread_done($sync->{-opt}); # all done
708         }
709         commit_txn_lazy($self);
710         $sync->{ibx}->git->cleanup;
711         my $nr = ${$sync->{nr}};
712         idx_release($self, $nr);
713         # let another process do some work...
714         if (my $pr = $sync->{-opt}->{-progress}) {
715                 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
716         }
717         if (!$stk && !$sync->{quit}) { # more to come
718                 begin_txn_lazy($self);
719                 $self->{mm}->{dbh}->begin_work;
720         }
721 }
722
723 # only for v1
724 sub process_stack {
725         my ($self, $sync, $stk) = @_;
726         my $git = $sync->{ibx}->git;
727         my $max = $self->{batch_bytes};
728         my $nr = 0;
729         $sync->{nr} = \$nr;
730         $sync->{max} = \$max;
731         $sync->{sidx} = $self;
732         $sync->{latest_cmt} = \(my $latest_cmt);
733
734         $self->{mm}->{dbh}->begin_work;
735         if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
736                 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
737                 for my $oid (@leftovers) {
738                         last if $sync->{quit};
739                         $oid = unpack('H*', $oid);
740                         $git->cat_async($oid, \&unindex_both, $sync);
741                 }
742         }
743         if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
744                 $sync->{index_oid} = \&index_both;
745         }
746         while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
747                 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
748                 last if $sync->{quit};
749                 if ($f eq 'm') {
750                         $arg->{autime} = $at;
751                         $arg->{cotime} = $ct;
752                         if ($sync->{max_size}) {
753                                 $git->check_async($oid, \&check_size, $arg);
754                         } else {
755                                 $git->cat_async($oid, \&index_both, $arg);
756                         }
757                         v1_checkpoint($self, $sync) if $max <= 0;
758                 } elsif ($f eq 'd') {
759                         $git->cat_async($oid, \&unindex_both, $arg);
760                 }
761         }
762         v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
763 }
764
765 sub log2stack ($$$) {
766         my ($sync, $git, $range) = @_;
767         my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
768         my ($add, $del);
769         if ($sync->{ibx}->version == 1) {
770                 my $path = $hex.'{2}/'.$hex.'{38}';
771                 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
772                 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
773         } else {
774                 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
775                 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
776         }
777
778         # Count the new files so they can be added newest to oldest
779         # and still have numbers increasing from oldest to newest
780         my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
781                                 --no-notes --no-color --no-renames --no-abbrev),
782                                 $range);
783         my ($at, $ct, $stk, $cmt);
784         while (<$fh>) {
785                 return if $sync->{quit};
786                 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
787                         ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
788                         $stk //= PublicInbox::IdxStack->new($cmt);
789                 } elsif (/$del/) {
790                         my $oid = $1;
791                         if ($D) { # reindex case
792                                 $D->{pack('H*', $oid)}++;
793                         } else { # non-reindex case:
794                                 $stk->push_rec('d', $at, $ct, $oid, $cmt);
795                         }
796                 } elsif (/$add/) {
797                         my $oid = $1;
798                         if ($D) {
799                                 my $oid_bin = pack('H*', $oid);
800                                 my $nr = --$D->{$oid_bin};
801                                 delete($D->{$oid_bin}) if $nr <= 0;
802                                 # nr < 0 (-1) means it never existed
803                                 next if $nr >= 0;
804                         }
805                         $stk->push_rec('m', $at, $ct, $oid, $cmt);
806                 }
807         }
808         close $fh or die "git log failed: \$?=$?";
809         $stk //= PublicInbox::IdxStack->new;
810         $stk->read_prepare;
811 }
812
813 sub prepare_stack ($$) {
814         my ($sync, $range) = @_;
815         my $git = $sync->{ibx}->git;
816
817         if (index($range, '..') < 0) {
818                 # don't show annoying git errors to users who run -index
819                 # on empty inboxes
820                 $git->qx(qw(rev-parse -q --verify), "$range^0");
821                 return PublicInbox::IdxStack->new->read_prepare if $?;
822         }
823         $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
824         log2stack($sync, $git, $range);
825 }
826
827 # --is-ancestor requires git 1.8.0+
828 sub is_ancestor ($$$) {
829         my ($git, $cur, $tip) = @_;
830         return 0 unless $git->check($cur);
831         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
832                 qw(merge-base --is-ancestor), $cur, $tip ];
833         my $pid = spawn($cmd);
834         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
835         $? == 0;
836 }
837
838 sub need_update ($$$) {
839         my ($self, $cur, $new) = @_;
840         my $git = $self->{ibx}->git;
841         return 1 if $cur && !is_ancestor($git, $cur, $new);
842         my $range = $cur eq '' ? $new : "$cur..$new";
843         chomp(my $n = $git->qx(qw(rev-list --count), $range));
844         ($n eq '' || $n > 0);
845 }
846
847 # The last git commit we indexed with Xapian or SQLite (msgmap)
848 # This needs to account for cases where Xapian or SQLite is
849 # out-of-date with respect to the other.
850 sub _last_x_commit {
851         my ($self, $mm) = @_;
852         my $lm = $mm->last_commit || '';
853         my $lx = '';
854         if (need_xapian($self)) {
855                 $lx = $self->{xdb}->get_metadata('last_commit') || '';
856         } else {
857                 $lx = $lm;
858         }
859         # Use last_commit from msgmap if it is older or unset
860         if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
861                 $lx = $lm;
862         }
863         $lx;
864 }
865
866 sub reindex_from ($$) {
867         my ($reindex, $last_commit) = @_;
868         return $last_commit unless $reindex;
869         ref($reindex) eq 'HASH' ? $reindex->{from} : '';
870 }
871
872 sub quit_cb ($) {
873         my ($sync) = @_;
874         sub {
875                 # we set {-opt}->{quit} too, so ->index_sync callers
876                 # can abort multi-inbox loops this way
877                 $sync->{quit} = $sync->{-opt}->{quit} = 1;
878                 warn "gracefully quitting\n";
879         }
880 }
881
882 # indexes all unindexed messages (v1 only)
883 sub _index_sync {
884         my ($self, $opt) = @_;
885         my $tip = $opt->{ref} || 'HEAD';
886         my $ibx = $self->{ibx};
887         local $self->{current_info} = "$ibx->{inboxdir}";
888         $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
889         $ibx->git->batch_prepare;
890         my $pr = $opt->{-progress};
891         my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
892         my $quit = quit_cb($sync);
893         local $SIG{QUIT} = $quit;
894         local $SIG{INT} = $quit;
895         local $SIG{TERM} = $quit;
896         my $xdb = $self->begin_txn_lazy;
897         $self->{oidx}->rethread_prepare($opt);
898         my $mm = _msgmap_init($self);
899         if ($sync->{reindex}) {
900                 my $last = $mm->last_commit;
901                 if ($last) {
902                         $tip = $last;
903                 } else {
904                         # somebody just blindly added --reindex when indexing
905                         # for the first time, allow it:
906                         undef $sync->{reindex};
907                 }
908         }
909         my $last_commit = _last_x_commit($self, $mm);
910         my $lx = reindex_from($sync->{reindex}, $last_commit);
911         my $range = $lx eq '' ? $tip : "$lx..$tip";
912         $pr->("counting changes\n\t$range ... ") if $pr;
913         my $stk = prepare_stack($sync, $range);
914         $sync->{ntodo} = $stk ? $stk->num_records : 0;
915         $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
916         process_stack($self, $sync, $stk) if !$sync->{quit};
917 }
918
919 sub DESTROY {
920         # order matters for unlocking
921         $_[0]->{xdb} = undef;
922         $_[0]->{lockfh} = undef;
923 }
924
925 sub _begin_txn {
926         my ($self) = @_;
927         my $xdb = $self->{xdb} || idx_acquire($self);
928         $self->{oidx}->begin_lazy if $self->{oidx};
929         $xdb->begin_transaction if $xdb;
930         $self->{txn} = 1;
931         $xdb;
932 }
933
934 sub begin_txn_lazy {
935         my ($self) = @_;
936         $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
937 }
938
939 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
940 # This metadata is read by Admin::detect_indexlevel:
941 sub set_metadata_once {
942         my ($self) = @_;
943
944         return if $self->{shard}; # only continue if undef or 0, not >0
945         my $xdb = $self->{xdb};
946
947         if (delete($self->{-set_has_threadid_once})) {
948                 $xdb->set_metadata('has_threadid', '1');
949         }
950         if (delete($self->{-set_indexlevel_once})) {
951                 my $level = $xdb->get_metadata('indexlevel');
952                 if (!$level || $level ne 'medium') {
953                         $xdb->set_metadata('indexlevel', 'medium');
954                 }
955         }
956         if (delete($self->{-set_skip_docdata_once})) {
957                 $xdb->get_metadata('skip_docdata') or
958                         $xdb->set_metadata('skip_docdata', '1');
959         }
960 }
961
962 sub _commit_txn {
963         my ($self) = @_;
964         if (my $eidx = $self->{eidx}) {
965                 $eidx->git->async_wait_all;
966                 $eidx->{transact_bytes} = 0;
967         }
968         if (my $xdb = $self->{xdb}) {
969                 set_metadata_once($self);
970                 $xdb->commit_transaction;
971         }
972         $self->{oidx}->commit_lazy if $self->{oidx};
973 }
974
975 sub commit_txn_lazy {
976         my ($self) = @_;
977         delete($self->{txn}) and
978                 $self->with_umask(\&_commit_txn, $self);
979 }
980
981 sub eidx_shard_new {
982         my ($class, $eidx, $shard) = @_;
983         my $self = bless {
984                 eidx => $eidx,
985                 xpfx => $eidx->{xpfx},
986                 indexlevel => $eidx->{indexlevel},
987                 -skip_docdata => 1,
988                 shard => $shard,
989                 creat => 1,
990         }, $class;
991         $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
992         $self;
993 }
994
995 # ensure there's no stale Xapian docs by treating $over as canonical
996 sub over_check {
997         my ($self, $over) = @_;
998         begin_txn_lazy($self);
999         my $sth = $over->dbh->prepare(<<'');
1000 SELECT COUNT(*) FROM over WHERE num = ?
1001
1002         my $xdb = $self->{xdb};
1003         my $cur = $xdb->postlist_begin('');
1004         my $end = $xdb->postlist_end('');
1005         my $xdir = $self->xdir;
1006         for (; $cur != $end; $cur++) {
1007                 my $docid = $cur->get_docid;
1008                 $sth->execute($docid);
1009                 my $x = $sth->fetchrow_array;
1010                 next if $x > 0;
1011                 warn "I: removing $xdir #$docid, not in `over'\n";
1012                 $xdb->delete_document($docid);
1013         }
1014 }
1015
1016 1;