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
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;
12 use parent qw(PublicInbox::Search PublicInbox::Lock Exporter);
14 use PublicInbox::Search qw(xap_terms);
15 use PublicInbox::InboxWritable;
16 use PublicInbox::MID qw(mids_for_index mids);
17 use PublicInbox::MsgIter;
18 use PublicInbox::IdxStack;
19 use Carp qw(croak carp);
20 use POSIX qw(strftime);
21 use Time::Local qw(timegm);
22 use PublicInbox::OverIdx;
23 use PublicInbox::Spawn qw(spawn nodatacow_dir);
24 use PublicInbox::Git qw(git_unquote);
25 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
26 use PublicInbox::Address;
27 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
28 index_text term_generator add_val is_bad_blob);
29 my $X = \%PublicInbox::Search::X;
30 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
32 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff : 1_000_000;
33 use constant DEBUG => !!$ENV{DEBUG};
35 my $xapianlevels = qr/\A(?:full|medium)\z/;
37 my $OID = $hex .'{40,}';
38 my @VMD_MAP = (kw => 'K', L => 'L');
39 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
42 my ($class, $ibx, $creat, $shard) = @_;
43 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
44 my $inboxdir = $ibx->{inboxdir};
45 my $version = $ibx->version;
46 my $indexlevel = 'full';
47 my $altid = $ibx->{altid};
49 require PublicInbox::AltId;
50 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
52 if ($ibx->{indexlevel}) {
53 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
54 $indexlevel = $ibx->{indexlevel};
56 die("Invalid indexlevel $ibx->{indexlevel}\n");
59 $ibx = PublicInbox::InboxWritable->new($ibx);
60 my $self = PublicInbox::Search->new($ibx);
63 $self->{-altid} = $altid;
64 $self->{indexlevel} = $indexlevel;
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;
71 $self->{lock_path} = "$inboxdir/ssoma.lock";
72 my $dir = $self->xdir;
73 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
74 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
75 } elsif ($version == 2) {
76 defined $shard or die "shard is required for v2\n";
78 $self->{shard} = $shard;
79 $self->{lock_path} = undef;
81 die "unsupported inbox version=$version\n";
83 $self->{creat} = ($creat || 0) == 1;
87 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
90 my ($self, $wake) = @_;
91 if (need_xapian($self)) {
92 my $xdb = delete $self->{xdb} or croak 'not acquired';
95 $self->lock_release($wake) if $self->{creat};
99 sub load_xapian_writable () {
100 return 1 if $X->{WritableDatabase};
101 PublicInbox::Search::load_xapian() or return;
102 my $xap = $PublicInbox::Search::Xap;
103 for (qw(Document TermGenerator WritableDatabase)) {
104 $X->{$_} = $xap.'::'.$_;
106 eval 'require '.$X->{WritableDatabase} or die;
107 *sortable_serialise = $xap.'::sortable_serialise';
108 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
109 $DB_OPEN = eval($xap.'::DB_OPEN()');
110 my $ver = (eval($xap.'::major_version()') << 16) |
111 (eval($xap.'::minor_version()') << 8) |
112 eval($xap.'::revision()');
113 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
114 # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
115 $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
122 my $dir = $self->xdir;
123 if (need_xapian($self)) {
124 croak 'already acquired' if $self->{xdb};
125 load_xapian_writable();
126 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
128 if ($self->{creat}) {
132 # don't create empty Xapian directories if we don't need Xapian
133 my $is_shard = defined($self->{shard});
134 if (!-d $dir && (!$is_shard ||
135 ($is_shard && need_xapian($self)))) {
136 File::Path::mkpath($dir);
138 $self->{-set_has_threadid_once} = 1;
141 return unless defined $flag;
142 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
143 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
144 croak "Failed opening $dir: $@" if $@;
149 my ($doc, $col, $num) = @_;
150 $num = sortable_serialise($num);
151 $doc->add_value($col, $num);
154 sub term_generator ($) { # write-only
157 $self->{term_generator} //= do {
158 my $tg = $X->{TermGenerator}->new;
159 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
164 sub index_phrase ($$$$) {
165 my ($self, $text, $wdf_inc, $prefix) = @_;
167 my $tg = term_generator($self);
168 $tg->index_text($text, $wdf_inc, $prefix);
169 $tg->increase_termpos;
172 sub index_text ($$$$) {
173 my ($self, $text, $wdf_inc, $prefix) = @_;
175 if ($self->{indexlevel} eq 'full') {
176 index_phrase($self, $text, $wdf_inc, $prefix);
178 my $tg = term_generator($self);
179 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
183 sub index_headers ($$) {
184 my ($self, $smsg) = @_;
185 my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
186 while (my ($field, $pfx) = splice(@x, 0, 2)) {
187 my $val = $smsg->{$field};
189 # include "(comments)" after the address, too, so not using
190 # PublicInbox::Address::names or pairs
191 index_text($self, $val, 1, $pfx);
193 # we need positional info for email addresses since they
194 # can be considered phrases
195 if ($self->{indexlevel} eq 'medium') {
196 for my $addr (PublicInbox::Address::emails($val)) {
197 index_phrase($self, $addr, 1, $pfx);
201 @x = (subject => 'S');
202 while (my ($field, $pfx) = splice(@x, 0, 2)) {
203 my $val = $smsg->{$field};
204 index_text($self, $val, 1, $pfx) if $val ne '';
208 sub index_diff_inc ($$$$) {
209 my ($self, $text, $pfx, $xnq) = @_;
211 index_text($self, join("\n", @$xnq), 1, 'XNQ');
214 if ($pfx eq 'XDFN') {
215 index_phrase($self, $text, 1, $pfx);
217 index_text($self, $text, 1, $pfx);
221 sub index_old_diff_fn {
222 my ($self, $seen, $fa, $fb, $xnq) = @_;
224 # no renames or space support for traditional diffs,
225 # find the number of leading common paths to strip:
226 my @fa = split('/', $fa);
227 my @fb = split('/', $fb);
228 while (scalar(@fa) && scalar(@fb)) {
229 $fa = join('/', @fa);
230 $fb = join('/', @fb);
232 unless ($seen->{$fa}++) {
233 index_diff_inc($self, $fa, 'XDFN', $xnq);
243 sub index_diff ($$$) {
244 my ($self, $txt, $doc) = @_;
249 foreach (split(/\n/, $txt)) {
250 if ($in_diff && s/^ //) { # diff context
251 index_diff_inc($self, $_, 'XDFCTX', $xnq);
252 } elsif (/^-- $/) { # email signature begins
254 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
255 # wait until "---" and "+++" to capture filenames
258 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
259 my ($opt, $fa, $fb) = ($1, $2, $3);
261 # only support unified:
262 next unless $opt =~ /[uU]/;
263 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
265 } elsif (m!^--- ("?[^/]+/.+)!) {
267 $fn = (split('/', git_unquote($fn), 2))[1];
268 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
270 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
272 $fn = (split('/', git_unquote($fn), 2))[1];
273 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
275 } elsif (/^--- (\S+)/) {
278 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
279 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
281 } elsif ($in_diff && s/^\+//) { # diff added
282 index_diff_inc($self, $_, 'XDFB', $xnq);
283 } elsif ($in_diff && s/^-//) { # diff removed
284 index_diff_inc($self, $_, 'XDFA', $xnq);
285 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
286 my ($ba, $bb) = ($1, $2);
287 index_git_blob_id($doc, 'XDFPRE', $ba);
288 index_git_blob_id($doc, 'XDFPOST', $bb);
290 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
291 # traditional diff w/o -p
292 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
293 # hunk header context
294 index_diff_inc($self, $1, 'XDFHH', $xnq);
295 # ignore the following lines:
296 } elsif (/^(?:dis)similarity index/ ||
297 /^(?:old|new) mode/ ||
298 /^(?:deleted|new) file mode/ ||
299 /^(?:copy|rename) (?:from|to) / ||
300 /^(?:dis)?similarity index / ||
301 /^\\ No newline at end of file/ ||
302 /^Binary files .* differ/) {
305 # possible to be in diff context, some mail may be
306 # stripped by MUA or even GNU diff(1). "git apply"
307 # treats a bare "\n" as diff context, too
310 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
315 index_text($self, join("\n", @xnq), 1, 'XNQ');
318 sub index_xapian { # msg_iter callback
319 my $part = $_[0]->[0]; # ignore $depth and $idx
320 my ($self, $doc) = @{$_[1]};
321 my $ct = $part->content_type || 'text/plain';
322 my $fn = $part->filename;
323 if (defined $fn && $fn ne '') {
324 index_phrase($self, $fn, 1, 'XFN');
326 if ($part->{is_submsg}) {
327 my $mids = mids_for_index($part);
328 index_ids($self, $doc, $part, $mids);
329 my $smsg = bless {}, 'PublicInbox::Smsg';
330 $smsg->populate($part);
331 index_headers($self, $smsg);
334 my ($s, undef) = msg_part_text($part, $ct);
335 defined $s or return;
336 $_[0]->[0] = $part = undef; # free memory
338 # split off quoted and unquoted blocks:
339 my @sections = PublicInbox::MsgIter::split_quotes($s);
340 undef $s; # free memory
341 for my $txt (@sections) {
343 index_text($self, $txt, 0, 'XQUOT');
345 # does it look like a diff?
346 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
347 index_diff($self, $txt, $doc);
349 index_text($self, $txt, 1, 'XNQ');
352 undef $txt; # free memory
356 sub index_list_id ($$$) {
357 my ($self, $doc, $hdr) = @_;
358 for my $l ($hdr->header_raw('List-Id')) {
359 $l =~ /<([^>]+)>/ or next;
361 $doc->add_boolean_term('G' . $lid);
362 index_phrase($self, $lid, 1, 'XL'); # probabilistic
366 sub index_ids ($$$$) {
367 my ($self, $doc, $hdr, $mids) = @_;
368 for my $mid (@$mids) {
369 index_phrase($self, $mid, 1, 'XM');
371 # because too many Message-IDs are prefixed with
373 if ($mid =~ /\w{12,}/) {
374 my @long = ($mid =~ /(\w{3,}+)/g);
375 index_phrase($self, join(' ', @long), 1, 'XM');
378 $doc->add_boolean_term('Q' . $_) for @$mids;
379 index_list_id($self, $doc, $hdr);
382 sub eml2doc ($$$;$) {
383 my ($self, $eml, $smsg, $mids) = @_;
384 $mids //= mids_for_index($eml);
385 my $doc = $X->{Document}->new;
386 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
387 my @ds = gmtime($smsg->{ds});
388 my $yyyymmdd = strftime('%Y%m%d', @ds);
389 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
390 my $dt = strftime('%Y%m%d%H%M%S', @ds);
391 add_val($doc, PublicInbox::Search::DT(), $dt);
392 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
393 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
394 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
396 my $tg = term_generator($self);
397 $tg->set_document($doc);
398 index_headers($self, $smsg);
400 if (defined(my $eidx_key = $smsg->{eidx_key})) {
401 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
403 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
404 index_ids($self, $doc, $eml, $mids);
406 # by default, we maintain compatibility with v1.5.0 and earlier
407 # by writing to docdata.glass, users who never exect to downgrade can
409 if (!$self->{-skip_docdata}) {
410 # WWW doesn't need {to} or {cc}, only NNTP
411 $smsg->{to} = $smsg->{cc} = '';
412 $smsg->parse_references($eml, $mids);
413 my $data = $smsg->to_doc_data;
414 $doc->set_data($data);
417 if (my $altid = $self->{-altid}) {
418 foreach my $alt (@$altid) {
419 my $pfx = $alt->{xprefix};
420 foreach my $mid (@$mids) {
421 my $id = $alt->mid2alt($mid);
422 next unless defined $id;
423 $doc->add_boolean_term($pfx . $id);
430 sub add_xapian ($$$$) {
431 my ($self, $eml, $smsg, $mids) = @_;
432 begin_txn_lazy($self);
433 my $merge_vmd = delete $smsg->{-merge_vmd};
434 my $doc = eml2doc($self, $eml, $smsg, $mids);
435 if (my $old = $merge_vmd ? _get_doc($self, $smsg->{num}) : undef) {
437 while (my ($field, $pfx) = splice(@x, 0, 2)) {
438 my $vals = xap_terms($pfx, $old);
439 $doc->add_boolean_term($pfx.$_) for keys %$vals;
442 $self->{xdb}->replace_document($smsg->{num}, $doc);
445 sub _msgmap_init ($) {
447 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
448 $self->{mm} //= eval {
449 require PublicInbox::Msgmap;
450 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
451 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
456 # mime = PublicInbox::Eml or Email::MIME object
457 my ($self, $mime, $smsg, $sync) = @_;
458 begin_txn_lazy($self);
459 my $mids = mids_for_index($mime);
460 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
461 $smsg->{mid} //= $mids->[0]; # v1 compatibility
462 $smsg->{num} //= do { # v1
464 index_mm($self, $mime, $smsg->{blob}, $sync);
468 $smsg->populate($mime, $sync);
469 $smsg->{bytes} //= length($mime->as_string);
472 # order matters, overview stores every possible piece of
473 # data in doc_data (deflated). Xapian only stores a subset
474 # of the fields which exist in over.sqlite3. We may stop
475 # storing doc_data in Xapian sometime after we get multi-inbox
477 if (my $oidx = $self->{oidx}) { # v1 only
478 $oidx->add_overview($mime, $smsg);
480 if (need_xapian($self)) {
481 add_xapian($self, $mime, $smsg, $mids);
486 warn "failed to index message <".join('> <',@$mids).">: $@\n";
493 my ($self, $docid) = @_;
494 my $doc = eval { $self->{xdb}->get_document($docid) };
496 warn "E: $@\n" if $@;
497 warn "E: #$docid missing in Xapian\n";
503 my ($self, $docid, $eidx_key, $eml) = @_;
504 begin_txn_lazy($self);
505 my $doc = _get_doc($self, $docid) or return;
506 term_generator($self)->set_document($doc);
508 # '.' is special for lei_store
509 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
511 index_list_id($self, $doc, $eml);
512 $self->{xdb}->replace_document($docid, $doc);
515 sub remove_eidx_info {
516 my ($self, $docid, $eidx_key, $eml) = @_;
517 begin_txn_lazy($self);
518 my $doc = _get_doc($self, $docid) or return;
519 eval { $doc->remove_term('O'.$eidx_key) };
520 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
521 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
522 $l =~ /<([^>]+)>/ or next;
524 eval { $doc->remove_term('G' . $lid) };
525 warn "W: ->remove_term G$lid: $@\n" if $@;
527 # nb: we don't remove the XL probabilistic terms
528 # since terms may overlap if cross-posted.
530 # IOW, a message which has both <foo.example.com>
531 # and <bar.example.com> would have overlapping
532 # "XLexample" and "XLcom" as terms and which we
533 # wouldn't know if they're safe to remove if we just
534 # unindex <foo.example.com> while preserving
537 # In any case, this entire sub is will likely never
538 # be needed and users using the "l:" prefix are probably
541 $self->{xdb}->replace_document($docid, $doc);
545 my ($self, $docid, $vmd) = @_;
546 begin_txn_lazy($self);
547 my $doc = _get_doc($self, $docid) or return;
548 my ($end, @rm, @add);
550 while (my ($field, $pfx) = splice(@x, 0, 2)) {
551 my $set = $vmd->{$field} // next;
552 my %keep = map { $_ => 1 } @$set;
554 $end //= $doc->termlist_end;
555 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
557 last if $cur == $end;
558 my $v = $cur->get_termname;
559 $v =~ s/\A$pfx//s or next;
560 $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
562 push(@add, map { $pfx.$_ } keys %add);
564 return unless scalar(@rm) || scalar(@add);
565 $doc->remove_term($_) for @rm;
566 $doc->add_boolean_term($_) for @add;
567 $self->{xdb}->replace_document($docid, $doc);
571 my ($self, $docid, $vmd) = @_;
572 begin_txn_lazy($self);
573 my $doc = _get_doc($self, $docid) or return;
575 while (my ($field, $pfx) = splice(@x, 0, 2)) {
576 my $add = $vmd->{$field} // next;
577 $doc->add_boolean_term($pfx . $_) for @$add;
579 $self->{xdb}->replace_document($docid, $doc);
583 my ($self, $docid, $vmd) = @_;
584 begin_txn_lazy($self);
585 my $doc = _get_doc($self, $docid) or return;
588 while (my ($field, $pfx) = splice(@x, 0, 2)) {
589 my $rm = $vmd->{$field} // next;
592 $doc->remove_term($pfx . $_);
597 $self->{xdb}->replace_document($docid, $doc) if $replace;
601 my ($self, $docid, $vmd_mod) = @_;
602 begin_txn_lazy($self);
603 my $doc = _get_doc($self, $docid) or return;
606 while (my ($field, $pfx) = splice(@x, 0, 2)) {
607 # field: "label" or "kw"
608 for my $val (@{$vmd_mod->{"-$field"} // []}) {
610 $doc->remove_term($pfx . $val);
614 for my $val (@{$vmd_mod->{"+$field"} // []}) {
615 $doc->add_boolean_term($pfx . $val);
619 $self->{xdb}->replace_document($docid, $doc) if $updated;
624 my ($self, @docids) = @_;
625 $self->begin_txn_lazy;
626 my $xdb = $self->{xdb} or return;
627 for my $docid (@docids) {
628 eval { $xdb->delete_document($docid) };
629 warn "E: #$docid not in in Xapian? $@\n" if $@;
633 sub index_git_blob_id {
634 my ($doc, $pfx, $objid) = @_;
636 my $len = length($objid);
637 for (my $len = length($objid); $len >= 7; ) {
638 $doc->add_term($pfx.$objid);
639 $objid = substr($objid, 0, --$len);
645 my ($self, $oid, $eml) = @_;
646 my $mids = mids($eml);
649 for my $mid (@$mids) {
650 my @removed = $self->{oidx}->remove_oid($oid, $mid);
651 $nr += scalar @removed;
652 $tmp{$_}++ for @removed;
655 my $m = join('> <', @$mids);
656 warn "W: <$m> missing for removal from overview\n";
658 while (my ($num, $nr) = each %tmp) {
659 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
662 $self->{mm}->num_delete($_) for (keys %tmp);
663 } else { # just in case msgmap and over.sqlite3 become desynched:
664 $self->{mm}->mid_delete($mids->[0]);
666 xdb_remove($self, keys %tmp) if need_xapian($self);
670 my ($self, $mime, $oid, $sync) = @_;
671 my $mids = mids($mime);
672 my $mm = $self->{mm};
673 if ($sync->{reindex}) {
674 my $oidx = $self->{oidx};
675 for my $mid (@$mids) {
676 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
677 return $num if defined $num;
679 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
681 # fallback to num_for since filters like RubyLang set the number
682 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
686 sub is_bad_blob ($$$$) {
687 my ($oid, $type, $size, $expect_oid) = @_;
688 if ($type ne 'blob') {
689 carp "W: $expect_oid is not a blob (type=$type)";
692 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
693 $size == 0 ? 1 : 0; # size == 0 means purged
696 sub index_both { # git->cat_async callback
697 my ($bref, $oid, $type, $size, $sync) = @_;
698 return if is_bad_blob($oid, $type, $size, $sync->{oid});
699 my ($nr, $max) = @$sync{qw(nr max)};
702 my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
703 $smsg->set_bytes($$bref, $size);
704 my $self = $sync->{sidx};
705 local $self->{current_info} = "$self->{current_info}: $oid";
706 my $eml = PublicInbox::Eml->new($bref);
707 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
708 die "E: could not generate NNTP article number for $oid";
709 add_message($self, $eml, $smsg, $sync);
711 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
712 ${$sync->{latest_cmt}} = $cur_cmt;
715 sub unindex_both { # git->cat_async callback
716 my ($bref, $oid, $type, $size, $sync) = @_;
717 return if is_bad_blob($oid, $type, $size, $sync->{oid});
718 my $self = $sync->{sidx};
719 local $self->{current_info} = "$self->{current_info}: $oid";
720 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
721 # may be undef if leftover
722 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
723 ${$sync->{latest_cmt}} = $cur_cmt;
730 ($self->{ibx} // $self->{eidx})->with_umask(@_);
733 # called by public-inbox-index
735 my ($self, $opt) = @_;
736 delete $self->{lock_path} if $opt->{-skip_lock};
737 $self->with_umask(\&_index_sync, $self, $opt);
738 if ($opt->{reindex} && !$opt->{quit}) {
740 delete @again{qw(rethread reindex)};
741 index_sync($self, \%again);
742 $opt->{quit} = $again{quit}; # propagate to caller
746 sub check_size { # check_async cb for -index --max-size=...
747 my ($oid, $type, $size, $arg, $git) = @_;
748 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
749 if ($size <= $arg->{max_size}) {
750 $git->cat_async($oid, $arg->{index_oid}, $arg);
752 warn "W: skipping $oid ($size > $arg->{max_size})\n";
756 sub v1_checkpoint ($$;$) {
757 my ($self, $sync, $stk) = @_;
758 $self->{ibx}->git->async_wait_all;
760 # $newest may be undef
761 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
762 if (defined($newest)) {
763 my $cur = $self->{mm}->last_commit || '';
764 if (need_update($self, $cur, $newest)) {
765 $self->{mm}->last_commit($newest);
768 ${$sync->{max}} = $self->{batch_bytes};
770 $self->{mm}->{dbh}->commit;
771 my $xdb = need_xapian($self) ? $self->{xdb} : undef;
772 if ($newest && $xdb) {
773 my $cur = $xdb->get_metadata('last_commit');
774 if (need_update($self, $cur, $newest)) {
775 $xdb->set_metadata('last_commit', $newest);
778 if ($stk) { # all done if $stk is passed
779 # let SearchView know a full --reindex was done so it can
780 # generate ->has_threadid-dependent links
781 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
782 my $n = $xdb->get_metadata('has_threadid');
783 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
785 $self->{oidx}->rethread_done($sync->{-opt}); # all done
787 commit_txn_lazy($self);
788 $sync->{ibx}->git->cleanup;
789 my $nr = ${$sync->{nr}};
790 idx_release($self, $nr);
791 # let another process do some work...
792 if (my $pr = $sync->{-opt}->{-progress}) {
793 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
795 if (!$stk && !$sync->{quit}) { # more to come
796 begin_txn_lazy($self);
797 $self->{mm}->{dbh}->begin_work;
803 my ($self, $sync, $stk) = @_;
804 my $git = $sync->{ibx}->git;
805 my $max = $self->{batch_bytes};
808 $sync->{max} = \$max;
809 $sync->{sidx} = $self;
810 $sync->{latest_cmt} = \(my $latest_cmt);
812 $self->{mm}->{dbh}->begin_work;
813 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
814 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
815 for my $oid (@leftovers) {
816 last if $sync->{quit};
817 $oid = unpack('H*', $oid);
818 $git->cat_async($oid, \&unindex_both, $sync);
821 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
822 $sync->{index_oid} = \&index_both;
824 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
825 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
826 last if $sync->{quit};
828 $arg->{autime} = $at;
829 $arg->{cotime} = $ct;
830 if ($sync->{max_size}) {
831 $git->check_async($oid, \&check_size, $arg);
833 $git->cat_async($oid, \&index_both, $arg);
835 v1_checkpoint($self, $sync) if $max <= 0;
836 } elsif ($f eq 'd') {
837 $git->cat_async($oid, \&unindex_both, $arg);
840 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
843 sub log2stack ($$$) {
844 my ($sync, $git, $range) = @_;
845 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
847 if ($sync->{ibx}->version == 1) {
848 my $path = $hex.'{2}/'.$hex.'{38}';
849 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
850 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
852 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
853 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
856 # Count the new files so they can be added newest to oldest
857 # and still have numbers increasing from oldest to newest
858 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
859 --no-notes --no-color --no-renames --no-abbrev),
861 my ($at, $ct, $stk, $cmt);
863 return if $sync->{quit};
864 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
865 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
866 $stk //= PublicInbox::IdxStack->new($cmt);
869 if ($D) { # reindex case
870 $D->{pack('H*', $oid)}++;
871 } else { # non-reindex case:
872 $stk->push_rec('d', $at, $ct, $oid, $cmt);
877 my $oid_bin = pack('H*', $oid);
878 my $nr = --$D->{$oid_bin};
879 delete($D->{$oid_bin}) if $nr <= 0;
880 # nr < 0 (-1) means it never existed
883 $stk->push_rec('m', $at, $ct, $oid, $cmt);
886 close $fh or die "git log failed: \$?=$?";
887 $stk //= PublicInbox::IdxStack->new;
891 sub prepare_stack ($$) {
892 my ($sync, $range) = @_;
893 my $git = $sync->{ibx}->git;
895 if (index($range, '..') < 0) {
896 # don't show annoying git errors to users who run -index
898 $git->qx(qw(rev-parse -q --verify), "$range^0");
899 return PublicInbox::IdxStack->new->read_prepare if $?;
901 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
902 log2stack($sync, $git, $range);
905 # --is-ancestor requires git 1.8.0+
906 sub is_ancestor ($$$) {
907 my ($git, $cur, $tip) = @_;
908 return 0 unless $git->check($cur);
909 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
910 qw(merge-base --is-ancestor), $cur, $tip ];
911 my $pid = spawn($cmd);
912 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
916 sub need_update ($$$) {
917 my ($self, $cur, $new) = @_;
918 my $git = $self->{ibx}->git;
919 return 1 if $cur && !is_ancestor($git, $cur, $new);
920 my $range = $cur eq '' ? $new : "$cur..$new";
921 chomp(my $n = $git->qx(qw(rev-list --count), $range));
922 ($n eq '' || $n > 0);
925 # The last git commit we indexed with Xapian or SQLite (msgmap)
926 # This needs to account for cases where Xapian or SQLite is
927 # out-of-date with respect to the other.
929 my ($self, $mm) = @_;
930 my $lm = $mm->last_commit || '';
932 if (need_xapian($self)) {
933 $lx = $self->{xdb}->get_metadata('last_commit') || '';
937 # Use last_commit from msgmap if it is older or unset
938 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
944 sub reindex_from ($$) {
945 my ($reindex, $last_commit) = @_;
946 return $last_commit unless $reindex;
947 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
953 # we set {-opt}->{quit} too, so ->index_sync callers
954 # can abort multi-inbox loops this way
955 $sync->{quit} = $sync->{-opt}->{quit} = 1;
956 warn "gracefully quitting\n";
960 # indexes all unindexed messages (v1 only)
962 my ($self, $opt) = @_;
963 my $tip = $opt->{ref} || 'HEAD';
964 my $ibx = $self->{ibx};
965 local $self->{current_info} = "$ibx->{inboxdir}";
966 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
967 $ibx->git->batch_prepare;
968 my $pr = $opt->{-progress};
969 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
970 my $quit = quit_cb($sync);
971 local $SIG{QUIT} = $quit;
972 local $SIG{INT} = $quit;
973 local $SIG{TERM} = $quit;
974 my $xdb = $self->begin_txn_lazy;
975 $self->{oidx}->rethread_prepare($opt);
976 my $mm = _msgmap_init($self);
977 if ($sync->{reindex}) {
978 my $last = $mm->last_commit;
982 # somebody just blindly added --reindex when indexing
983 # for the first time, allow it:
984 undef $sync->{reindex};
987 my $last_commit = _last_x_commit($self, $mm);
988 my $lx = reindex_from($sync->{reindex}, $last_commit);
989 my $range = $lx eq '' ? $tip : "$lx..$tip";
990 $pr->("counting changes\n\t$range ... ") if $pr;
991 my $stk = prepare_stack($sync, $range);
992 $sync->{ntodo} = $stk ? $stk->num_records : 0;
993 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
994 process_stack($self, $sync, $stk) if !$sync->{quit};
998 # order matters for unlocking
999 $_[0]->{xdb} = undef;
1000 $_[0]->{lockfh} = undef;
1005 my $xdb = $self->{xdb} || idx_acquire($self);
1006 $self->{oidx}->begin_lazy if $self->{oidx};
1007 $xdb->begin_transaction if $xdb;
1012 sub begin_txn_lazy {
1014 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1017 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1018 # This metadata is read by Admin::detect_indexlevel:
1019 sub set_metadata_once {
1022 return if $self->{shard}; # only continue if undef or 0, not >0
1023 my $xdb = $self->{xdb};
1025 if (delete($self->{-set_has_threadid_once})) {
1026 $xdb->set_metadata('has_threadid', '1');
1028 if (delete($self->{-set_indexlevel_once})) {
1029 my $level = $xdb->get_metadata('indexlevel');
1030 if (!$level || $level ne 'medium') {
1031 $xdb->set_metadata('indexlevel', 'medium');
1034 if (delete($self->{-set_skip_docdata_once})) {
1035 $xdb->get_metadata('skip_docdata') or
1036 $xdb->set_metadata('skip_docdata', '1');
1042 if (my $eidx = $self->{eidx}) {
1043 $eidx->git->async_wait_all;
1044 $eidx->{transact_bytes} = 0;
1046 if (my $xdb = $self->{xdb}) {
1047 set_metadata_once($self);
1048 $xdb->commit_transaction;
1050 $self->{oidx}->commit_lazy if $self->{oidx};
1053 sub commit_txn_lazy {
1055 delete($self->{txn}) and
1056 $self->with_umask(\&_commit_txn, $self);
1059 sub eidx_shard_new {
1060 my ($class, $eidx, $shard) = @_;
1063 xpfx => $eidx->{xpfx},
1064 indexlevel => $eidx->{indexlevel},
1069 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1073 # ensure there's no stale Xapian docs by treating $over as canonical
1075 my ($self, $over) = @_;
1076 begin_txn_lazy($self);
1077 my $sth = $over->dbh->prepare(<<'');
1078 SELECT COUNT(*) FROM over WHERE num = ?
1080 my $xdb = $self->{xdb};
1081 my $cur = $xdb->postlist_begin('');
1082 my $end = $xdb->postlist_end('');
1083 my $xdir = $self->xdir;
1084 for (; $cur != $end; $cur++) {
1085 my $docid = $cur->get_docid;
1086 $sth->execute($docid);
1087 my $x = $sth->fetchrow_array;
1089 warn "I: removing $xdir #$docid, not in `over'\n";
1090 $xdb->delete_document($docid);