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;
28 our @EXPORT_OK = qw(log2stack is_ancestor check_size prepare_stack
29 index_text term_generator add_val is_bad_blob);
30 my $X = \%PublicInbox::Search::X;
31 our ($DB_CREATE_OR_OPEN, $DB_OPEN);
33 our $BATCH_BYTES = $ENV{XAPIAN_FLUSH_THRESHOLD} ? 0x7fffffff :
34 # assume a typical 64-bit system has 8x more RAM than a
35 # typical 32-bit system:
36 (($Config{ptrsize} >= 8 ? 8192 : 1024) * 1024);
38 use constant DEBUG => !!$ENV{DEBUG};
40 my $xapianlevels = qr/\A(?:full|medium)\z/;
42 my $OID = $hex .'{40,}';
43 my @VMD_MAP = (kw => 'K', L => 'L');
44 our $INDEXLEVELS = qr/\A(?:full|medium|basic)\z/;
47 my ($class, $ibx, $creat, $shard) = @_;
48 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
49 my $inboxdir = $ibx->{inboxdir};
50 my $version = $ibx->version;
51 my $indexlevel = 'full';
52 my $altid = $ibx->{altid};
54 require PublicInbox::AltId;
55 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
57 if ($ibx->{indexlevel}) {
58 if ($ibx->{indexlevel} =~ $INDEXLEVELS) {
59 $indexlevel = $ibx->{indexlevel};
61 die("Invalid indexlevel $ibx->{indexlevel}\n");
64 $ibx = PublicInbox::InboxWritable->new($ibx);
65 my $self = PublicInbox::Search->new($ibx);
68 $self->{-altid} = $altid;
69 $self->{indexlevel} = $indexlevel;
70 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
71 if ($ibx->{-skip_docdata}) {
72 $self->{-set_skip_docdata_once} = 1;
73 $self->{-skip_docdata} = 1;
76 $self->{lock_path} = "$inboxdir/ssoma.lock";
77 my $dir = $self->xdir;
78 $self->{oidx} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
79 $self->{oidx}->{-no_fsync} = 1 if $ibx->{-no_fsync};
80 } elsif ($version == 2) {
81 defined $shard or die "shard is required for v2\n";
83 $self->{shard} = $shard;
84 $self->{lock_path} = undef;
86 die "unsupported inbox version=$version\n";
88 $self->{creat} = ($creat || 0) == 1;
92 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
95 my ($self, $wake) = @_;
96 if (need_xapian($self)) {
97 my $xdb = delete $self->{xdb} or croak '{xdb} not acquired';
100 $self->lock_release($wake) if $self->{creat};
104 sub load_xapian_writable () {
105 return 1 if $X->{WritableDatabase};
106 PublicInbox::Search::load_xapian() or die "failed to load Xapian: $@\n";
107 my $xap = $PublicInbox::Search::Xap;
108 for (qw(Document TermGenerator WritableDatabase)) {
109 $X->{$_} = $xap.'::'.$_;
111 eval 'require '.$X->{WritableDatabase} or die;
112 *sortable_serialise = $xap.'::sortable_serialise';
113 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
114 $DB_OPEN = eval($xap.'::DB_OPEN()');
115 my $ver = (eval($xap.'::major_version()') << 16) |
116 (eval($xap.'::minor_version()') << 8) |
117 eval($xap.'::revision()');
118 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
119 # Xapian v1.2.21..v1.2.24 were missing close-on-exec on OFD locks
120 $X->{CLOEXEC_UNSET} = 1 if $ver >= 0x010215 && $ver <= 0x010218;
127 my $dir = $self->xdir;
128 if (need_xapian($self)) {
129 croak 'already acquired' if $self->{xdb};
130 load_xapian_writable();
131 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
133 if ($self->{creat}) {
137 # don't create empty Xapian directories if we don't need Xapian
138 my $is_shard = defined($self->{shard});
139 if (!-d $dir && (!$is_shard ||
140 ($is_shard && need_xapian($self)))) {
141 File::Path::mkpath($dir);
143 $self->{-set_has_threadid_once} = 1;
146 return unless defined $flag;
147 $flag |= $DB_NO_SYNC if ($self->{ibx} // $self->{eidx})->{-no_fsync};
148 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
149 croak "Failed opening $dir: $@" if $@;
154 my ($doc, $col, $num) = @_;
155 $num = sortable_serialise($num);
156 $doc->add_value($col, $num);
159 sub term_generator ($) { # write-only
162 $self->{term_generator} //= do {
163 my $tg = $X->{TermGenerator}->new;
164 $tg->set_stemmer(PublicInbox::Search::stemmer($self));
169 sub index_phrase ($$$$) {
170 my ($self, $text, $wdf_inc, $prefix) = @_;
172 my $tg = term_generator($self);
173 $tg->index_text($text, $wdf_inc, $prefix);
174 $tg->increase_termpos;
177 sub index_text ($$$$) {
178 my ($self, $text, $wdf_inc, $prefix) = @_;
180 if ($self->{indexlevel} eq 'full') {
181 index_phrase($self, $text, $wdf_inc, $prefix);
183 my $tg = term_generator($self);
184 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
188 sub index_headers ($$) {
189 my ($self, $smsg) = @_;
190 my @x = (from => 'A', to => 'XTO', cc => 'XCC'); # A: Author
191 while (my ($field, $pfx) = splice(@x, 0, 2)) {
192 my $val = $smsg->{$field};
194 # include "(comments)" after the address, too, so not using
195 # PublicInbox::Address::names or pairs
196 index_text($self, $val, 1, $pfx);
198 # we need positional info for email addresses since they
199 # can be considered phrases
200 if ($self->{indexlevel} eq 'medium') {
201 for my $addr (PublicInbox::Address::emails($val)) {
202 index_phrase($self, $addr, 1, $pfx);
206 @x = (subject => 'S');
207 while (my ($field, $pfx) = splice(@x, 0, 2)) {
208 my $val = $smsg->{$field};
209 index_text($self, $val, 1, $pfx) if $val ne '';
213 sub index_diff_inc ($$$$) {
214 my ($self, $text, $pfx, $xnq) = @_;
216 index_text($self, join("\n", @$xnq), 1, 'XNQ');
219 if ($pfx eq 'XDFN') {
220 index_phrase($self, $text, 1, $pfx);
222 index_text($self, $text, 1, $pfx);
226 sub index_old_diff_fn {
227 my ($self, $seen, $fa, $fb, $xnq) = @_;
229 # no renames or space support for traditional diffs,
230 # find the number of leading common paths to strip:
231 my @fa = split('/', $fa);
232 my @fb = split('/', $fb);
233 while (scalar(@fa) && scalar(@fb)) {
234 $fa = join('/', @fa);
235 $fb = join('/', @fb);
237 unless ($seen->{$fa}++) {
238 index_diff_inc($self, $fa, 'XDFN', $xnq);
248 sub index_diff ($$$) {
249 my ($self, $txt, $doc) = @_;
254 foreach (split(/\n/, $txt)) {
255 if ($in_diff && s/^ //) { # diff context
256 index_diff_inc($self, $_, 'XDFCTX', $xnq);
257 } elsif (/^-- $/) { # email signature begins
259 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
260 # wait until "---" and "+++" to capture filenames
263 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
264 my ($opt, $fa, $fb) = ($1, $2, $3);
266 # only support unified:
267 next unless $opt =~ /[uU]/;
268 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
270 } elsif (m!^--- ("?[^/]+/.+)!) {
272 $fn = (split('/', git_unquote($fn), 2))[1];
273 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
275 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
277 $fn = (split('/', git_unquote($fn), 2))[1];
278 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
280 } elsif (/^--- (\S+)/) {
283 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
284 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
286 } elsif ($in_diff && s/^\+//) { # diff added
287 index_diff_inc($self, $_, 'XDFB', $xnq);
288 } elsif ($in_diff && s/^-//) { # diff removed
289 index_diff_inc($self, $_, 'XDFA', $xnq);
290 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
291 my ($ba, $bb) = ($1, $2);
292 index_git_blob_id($doc, 'XDFPRE', $ba);
293 index_git_blob_id($doc, 'XDFPOST', $bb);
295 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
296 # traditional diff w/o -p
297 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
298 # hunk header context
299 index_diff_inc($self, $1, 'XDFHH', $xnq);
300 # ignore the following lines:
301 } elsif (/^(?:dis)similarity index/ ||
302 /^(?:old|new) mode/ ||
303 /^(?:deleted|new) file mode/ ||
304 /^(?:copy|rename) (?:from|to) / ||
305 /^(?:dis)?similarity index / ||
306 /^\\ No newline at end of file/ ||
307 /^Binary files .* differ/) {
310 # possible to be in diff context, some mail may be
311 # stripped by MUA or even GNU diff(1). "git apply"
312 # treats a bare "\n" as diff context, too
315 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
320 index_text($self, join("\n", @xnq), 1, 'XNQ');
323 sub index_xapian { # msg_iter callback
324 my $part = $_[0]->[0]; # ignore $depth and $idx
325 my ($self, $doc) = @{$_[1]};
326 my $ct = $part->content_type || 'text/plain';
327 my $fn = $part->filename;
328 if (defined $fn && $fn ne '') {
329 index_phrase($self, $fn, 1, 'XFN');
331 if ($part->{is_submsg}) {
332 my $mids = mids_for_index($part);
333 index_ids($self, $doc, $part, $mids);
334 my $smsg = bless {}, 'PublicInbox::Smsg';
335 $smsg->populate($part);
336 index_headers($self, $smsg);
339 my ($s, undef) = msg_part_text($part, $ct);
340 defined $s or return;
341 $_[0]->[0] = $part = undef; # free memory
343 # split off quoted and unquoted blocks:
344 my @sections = PublicInbox::MsgIter::split_quotes($s);
345 undef $s; # free memory
346 for my $txt (@sections) {
348 index_text($self, $txt, 0, 'XQUOT');
350 # does it look like a diff?
351 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
352 index_diff($self, $txt, $doc);
354 index_text($self, $txt, 1, 'XNQ');
357 undef $txt; # free memory
361 sub index_list_id ($$$) {
362 my ($self, $doc, $hdr) = @_;
363 for my $l ($hdr->header_raw('List-Id')) {
364 $l =~ /<([^>]+)>/ or next;
366 $doc->add_boolean_term('G' . $lid);
367 index_phrase($self, $lid, 1, 'XL'); # probabilistic
371 sub index_ids ($$$$) {
372 my ($self, $doc, $hdr, $mids) = @_;
373 for my $mid (@$mids) {
374 index_phrase($self, $mid, 1, 'XM');
376 # because too many Message-IDs are prefixed with
378 if ($mid =~ /\w{12,}/) {
379 my @long = ($mid =~ /(\w{3,}+)/g);
380 index_phrase($self, join(' ', @long), 1, 'XM');
383 $doc->add_boolean_term('Q' . $_) for @$mids;
384 index_list_id($self, $doc, $hdr);
387 sub eml2doc ($$$;$) {
388 my ($self, $eml, $smsg, $mids) = @_;
389 $mids //= mids_for_index($eml);
390 my $doc = $X->{Document}->new;
391 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
392 my @ds = gmtime($smsg->{ds});
393 my $yyyymmdd = strftime('%Y%m%d', @ds);
394 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
395 my $dt = strftime('%Y%m%d%H%M%S', @ds);
396 add_val($doc, PublicInbox::Search::DT(), $dt);
397 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
398 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
399 add_val($doc, PublicInbox::Search::THREADID, $smsg->{tid});
401 my $tg = term_generator($self);
402 $tg->set_document($doc);
403 index_headers($self, $smsg);
405 if (defined(my $eidx_key = $smsg->{eidx_key})) {
406 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
408 msg_iter($eml, \&index_xapian, [ $self, $doc ]);
409 index_ids($self, $doc, $eml, $mids);
411 # by default, we maintain compatibility with v1.5.0 and earlier
412 # by writing to docdata.glass, users who never exect to downgrade can
414 if (!$self->{-skip_docdata}) {
415 # WWW doesn't need {to} or {cc}, only NNTP
416 $smsg->{to} = $smsg->{cc} = '';
417 $smsg->parse_references($eml, $mids);
418 my $data = $smsg->to_doc_data;
419 $doc->set_data($data);
422 if (my $altid = $self->{-altid}) {
423 foreach my $alt (@$altid) {
424 my $pfx = $alt->{xprefix};
425 foreach my $mid (@$mids) {
426 my $id = $alt->mid2alt($mid);
427 next unless defined $id;
428 $doc->add_boolean_term($pfx . $id);
435 sub add_xapian ($$$$) {
436 my ($self, $eml, $smsg, $mids) = @_;
437 begin_txn_lazy($self);
438 my $merge_vmd = delete $smsg->{-merge_vmd};
439 my $doc = eml2doc($self, $eml, $smsg, $mids);
440 if (my $old = $merge_vmd ? _get_doc($self, $smsg->{num}) : undef) {
442 while (my ($field, $pfx) = splice(@x, 0, 2)) {
443 for my $term (xap_terms($pfx, $old)) {
444 $doc->add_boolean_term($pfx.$term);
448 $self->{xdb}->replace_document($smsg->{num}, $doc);
451 sub _msgmap_init ($) {
453 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx}->version != 1;
454 $self->{mm} //= eval {
455 require PublicInbox::Msgmap;
456 my $rw = $self->{ibx}->{-no_fsync} ? 2 : 1;
457 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
462 # mime = PublicInbox::Eml or Email::MIME object
463 my ($self, $mime, $smsg, $sync) = @_;
464 begin_txn_lazy($self);
465 my $mids = mids_for_index($mime);
466 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
467 $smsg->{mid} //= $mids->[0]; # v1 compatibility
468 $smsg->{num} //= do { # v1
470 index_mm($self, $mime, $smsg->{blob}, $sync);
474 $smsg->populate($mime, $sync);
475 $smsg->{bytes} //= length($mime->as_string);
478 # order matters, overview stores every possible piece of
479 # data in doc_data (deflated). Xapian only stores a subset
480 # of the fields which exist in over.sqlite3. We may stop
481 # storing doc_data in Xapian sometime after we get multi-inbox
483 if (my $oidx = $self->{oidx}) { # v1 only
484 $oidx->add_overview($mime, $smsg);
486 if (need_xapian($self)) {
487 add_xapian($self, $mime, $smsg, $mids);
492 warn "failed to index message <".join('> <',@$mids).">: $@\n";
499 my ($self, $docid) = @_;
500 my $doc = eval { $self->{xdb}->get_document($docid) };
502 warn "E: $@\n" if $@;
503 warn "E: #$docid missing in Xapian\n";
509 my ($self, $docid, $eidx_key, $eml) = @_;
510 begin_txn_lazy($self);
511 my $doc = _get_doc($self, $docid) or return;
512 term_generator($self)->set_document($doc);
514 # '.' is special for lei_store
515 $doc->add_boolean_term('O'.$eidx_key) if $eidx_key ne '.';
517 index_list_id($self, $doc, $eml);
518 $self->{xdb}->replace_document($docid, $doc);
521 sub remove_eidx_info {
522 my ($self, $docid, $eidx_key, $eml) = @_;
523 begin_txn_lazy($self);
524 my $doc = _get_doc($self, $docid) or return;
525 eval { $doc->remove_term('O'.$eidx_key) };
526 warn "W: ->remove_term O$eidx_key: $@\n" if $@;
527 for my $l ($eml ? $eml->header_raw('List-Id') : ()) {
528 $l =~ /<([^>]+)>/ or next;
530 eval { $doc->remove_term('G' . $lid) };
531 warn "W: ->remove_term G$lid: $@\n" if $@;
533 # nb: we don't remove the XL probabilistic terms
534 # since terms may overlap if cross-posted.
536 # IOW, a message which has both <foo.example.com>
537 # and <bar.example.com> would have overlapping
538 # "XLexample" and "XLcom" as terms and which we
539 # wouldn't know if they're safe to remove if we just
540 # unindex <foo.example.com> while preserving
543 # In any case, this entire sub is will likely never
544 # be needed and users using the "l:" prefix are probably
547 $self->{xdb}->replace_document($docid, $doc);
551 my ($self, $docid, $vmd) = @_;
552 begin_txn_lazy($self);
553 my $doc = _get_doc($self, $docid) or return;
554 my ($end, @rm, @add);
556 while (my ($field, $pfx) = splice(@x, 0, 2)) {
557 my $set = $vmd->{$field} // next;
558 my %keep = map { $_ => 1 } @$set;
560 $end //= $doc->termlist_end;
561 for (my $cur = $doc->termlist_begin; $cur != $end; $cur++) {
563 last if $cur == $end;
564 my $v = $cur->get_termname;
565 $v =~ s/\A$pfx//s or next;
566 $keep{$v} ? delete($add{$v}) : push(@rm, $pfx.$v);
568 push(@add, map { $pfx.$_ } keys %add);
570 return unless scalar(@rm) || scalar(@add);
571 $doc->remove_term($_) for @rm;
572 $doc->add_boolean_term($_) for @add;
573 $self->{xdb}->replace_document($docid, $doc);
576 sub apply_vmd_mod ($$) {
577 my ($doc, $vmd_mod) = @_;
580 while (my ($field, $pfx) = splice(@x, 0, 2)) {
582 for my $val (@{$vmd_mod->{"-$field"} // []}) {
584 $doc->remove_term($pfx . $val);
588 for my $val (@{$vmd_mod->{"+$field"} // []}) {
589 $doc->add_boolean_term($pfx . $val);
597 my ($self, $docid, $vmd) = @_;
598 begin_txn_lazy($self);
599 my $doc = _get_doc($self, $docid) or return;
602 while (my ($field, $pfx) = splice(@x, 0, 2)) {
603 my $add = $vmd->{$field} // next;
604 $doc->add_boolean_term($pfx . $_) for @$add;
605 $updated += scalar(@$add);
607 $updated += apply_vmd_mod($doc, $vmd);
608 $self->{xdb}->replace_document($docid, $doc) if $updated;
612 my ($self, $docid, $vmd) = @_;
613 begin_txn_lazy($self);
614 my $doc = _get_doc($self, $docid) or return;
617 while (my ($field, $pfx) = splice(@x, 0, 2)) {
618 my $rm = $vmd->{$field} // next;
621 $doc->remove_term($pfx . $_);
626 $self->{xdb}->replace_document($docid, $doc) if $replace;
630 my ($self, $docid, $vmd_mod) = @_;
631 begin_txn_lazy($self);
632 my $doc = _get_doc($self, $docid) or return;
633 my $updated = apply_vmd_mod($doc, $vmd_mod);
634 $self->{xdb}->replace_document($docid, $doc) if $updated;
639 my ($self, @docids) = @_;
640 $self->begin_txn_lazy;
641 my $xdb = $self->{xdb} or return;
642 for my $docid (@docids) {
643 eval { $xdb->delete_document($docid) };
644 warn "E: #$docid not in in Xapian? $@\n" if $@;
648 sub index_git_blob_id {
649 my ($doc, $pfx, $objid) = @_;
651 my $len = length($objid);
652 for (my $len = length($objid); $len >= 7; ) {
653 $doc->add_term($pfx.$objid);
654 $objid = substr($objid, 0, --$len);
660 my ($self, $oid, $eml) = @_;
661 my $mids = mids($eml);
664 for my $mid (@$mids) {
665 my @removed = $self->{oidx}->remove_oid($oid, $mid);
666 $nr += scalar @removed;
667 $tmp{$_}++ for @removed;
670 my $m = join('> <', @$mids);
671 warn "W: <$m> missing for removal from overview\n";
673 while (my ($num, $nr) = each %tmp) {
674 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
677 $self->{mm}->num_delete($_) for (keys %tmp);
678 } else { # just in case msgmap and over.sqlite3 become desynched:
679 $self->{mm}->mid_delete($mids->[0]);
681 xdb_remove($self, keys %tmp) if need_xapian($self);
685 my ($self, $mime, $oid, $sync) = @_;
686 my $mids = mids($mime);
687 my $mm = $self->{mm};
688 if ($sync->{reindex}) {
689 my $oidx = $self->{oidx};
690 for my $mid (@$mids) {
691 my ($num, undef) = $oidx->num_mid0_for_oid($oid, $mid);
692 return $num if defined $num;
694 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
696 # fallback to num_for since filters like RubyLang set the number
697 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
701 sub is_bad_blob ($$$$) {
702 my ($oid, $type, $size, $expect_oid) = @_;
703 if ($type ne 'blob') {
704 carp "W: $expect_oid is not a blob (type=$type)";
707 croak "BUG: $oid != $expect_oid" if $oid ne $expect_oid;
708 $size == 0 ? 1 : 0; # size == 0 means purged
711 sub index_both { # git->cat_async callback
712 my ($bref, $oid, $type, $size, $sync) = @_;
713 return if is_bad_blob($oid, $type, $size, $sync->{oid});
714 my ($nr, $max) = @$sync{qw(nr max)};
717 my $smsg = bless { blob => $oid }, 'PublicInbox::Smsg';
718 $smsg->set_bytes($$bref, $size);
719 my $self = $sync->{sidx};
720 local $self->{current_info} = "$self->{current_info}: $oid";
721 my $eml = PublicInbox::Eml->new($bref);
722 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
723 die "E: could not generate NNTP article number for $oid";
724 add_message($self, $eml, $smsg, $sync);
726 my $cur_cmt = $sync->{cur_cmt} // die 'BUG: {cur_cmt} missing';
727 ${$sync->{latest_cmt}} = $cur_cmt;
730 sub unindex_both { # git->cat_async callback
731 my ($bref, $oid, $type, $size, $sync) = @_;
732 return if is_bad_blob($oid, $type, $size, $sync->{oid});
733 my $self = $sync->{sidx};
734 local $self->{current_info} = "$self->{current_info}: $oid";
735 unindex_eml($self, $oid, PublicInbox::Eml->new($bref));
736 # may be undef if leftover
737 if (defined(my $cur_cmt = $sync->{cur_cmt})) {
738 ${$sync->{latest_cmt}} = $cur_cmt;
745 ($self->{ibx} // $self->{eidx})->with_umask(@_);
748 # called by public-inbox-index
750 my ($self, $opt) = @_;
751 delete $self->{lock_path} if $opt->{-skip_lock};
752 $self->with_umask(\&_index_sync, $self, $opt);
753 if ($opt->{reindex} && !$opt->{quit}) {
755 delete @again{qw(rethread reindex)};
756 index_sync($self, \%again);
757 $opt->{quit} = $again{quit}; # propagate to caller
761 sub check_size { # check_async cb for -index --max-size=...
762 my ($oid, $type, $size, $arg, $git) = @_;
763 (($type // '') eq 'blob') or die "E: bad $oid in $git->{git_dir}";
764 if ($size <= $arg->{max_size}) {
765 $git->cat_async($oid, $arg->{index_oid}, $arg);
767 warn "W: skipping $oid ($size > $arg->{max_size})\n";
771 sub v1_checkpoint ($$;$) {
772 my ($self, $sync, $stk) = @_;
773 $self->{ibx}->git->async_wait_all;
775 # $newest may be undef
776 my $newest = $stk ? $stk->{latest_cmt} : ${$sync->{latest_cmt}};
777 if (defined($newest)) {
778 my $cur = $self->{mm}->last_commit || '';
779 if (need_update($self, $cur, $newest)) {
780 $self->{mm}->last_commit($newest);
783 ${$sync->{max}} = $self->{batch_bytes};
785 $self->{mm}->{dbh}->commit;
786 my $xdb = $self->{xdb};
787 if ($newest && $xdb) {
788 my $cur = $xdb->get_metadata('last_commit');
789 if (need_update($self, $cur, $newest)) {
790 $xdb->set_metadata('last_commit', $newest);
793 if ($stk) { # all done if $stk is passed
794 # let SearchView know a full --reindex was done so it can
795 # generate ->has_threadid-dependent links
796 if ($xdb && $sync->{reindex} && !ref($sync->{reindex})) {
797 my $n = $xdb->get_metadata('has_threadid');
798 $xdb->set_metadata('has_threadid', '1') if $n ne '1';
800 $self->{oidx}->rethread_done($sync->{-opt}); # all done
802 commit_txn_lazy($self);
803 $sync->{ibx}->git->cleanup;
804 my $nr = ${$sync->{nr}};
805 idx_release($self, $nr);
806 # let another process do some work...
807 if (my $pr = $sync->{-opt}->{-progress}) {
808 $pr->("indexed $nr/$sync->{ntodo}\n") if $nr;
810 if (!$stk && !$sync->{quit}) { # more to come
811 begin_txn_lazy($self);
812 $self->{mm}->{dbh}->begin_work;
818 my ($self, $sync, $stk) = @_;
819 my $git = $sync->{ibx}->git;
820 my $max = $self->{batch_bytes};
823 $sync->{max} = \$max;
824 $sync->{sidx} = $self;
825 $sync->{latest_cmt} = \(my $latest_cmt);
827 $self->{mm}->{dbh}->begin_work;
828 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
829 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
830 for my $oid (@leftovers) {
831 last if $sync->{quit};
832 $oid = unpack('H*', $oid);
833 $git->cat_async($oid, \&unindex_both, $sync);
836 if ($sync->{max_size} = $sync->{-opt}->{max_size}) {
837 $sync->{index_oid} = \&index_both;
839 while (my ($f, $at, $ct, $oid, $cur_cmt) = $stk->pop_rec) {
840 my $arg = { %$sync, cur_cmt => $cur_cmt, oid => $oid };
841 last if $sync->{quit};
843 $arg->{autime} = $at;
844 $arg->{cotime} = $ct;
845 if ($sync->{max_size}) {
846 $git->check_async($oid, \&check_size, $arg);
848 $git->cat_async($oid, \&index_both, $arg);
850 v1_checkpoint($self, $sync) if $max <= 0;
851 } elsif ($f eq 'd') {
852 $git->cat_async($oid, \&unindex_both, $arg);
855 v1_checkpoint($self, $sync, $sync->{quit} ? undef : $stk);
858 sub log2stack ($$$) {
859 my ($sync, $git, $range) = @_;
860 my $D = $sync->{D}; # OID_BIN => NR (if reindexing, undef otherwise)
862 if ($sync->{ibx}->version == 1) {
863 my $path = $hex.'{2}/'.$hex.'{38}';
864 $add = qr!\A:000000 100644 \S+ ($OID) A\t$path$!;
865 $del = qr!\A:100644 000000 ($OID) \S+ D\t$path$!;
867 $del = qr!\A:\d{6} 100644 $OID ($OID) [AM]\td$!;
868 $add = qr!\A:\d{6} 100644 $OID ($OID) [AM]\tm$!;
871 # Count the new files so they can be added newest to oldest
872 # and still have numbers increasing from oldest to newest
873 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
874 --no-notes --no-color --no-renames --no-abbrev),
876 my ($at, $ct, $stk, $cmt);
878 return if $sync->{quit};
879 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
880 ($at, $ct, $cmt) = ($1 + 0, $2 + 0, $3);
881 $stk //= PublicInbox::IdxStack->new($cmt);
884 if ($D) { # reindex case
885 $D->{pack('H*', $oid)}++;
886 } else { # non-reindex case:
887 $stk->push_rec('d', $at, $ct, $oid, $cmt);
892 my $oid_bin = pack('H*', $oid);
893 my $nr = --$D->{$oid_bin};
894 delete($D->{$oid_bin}) if $nr <= 0;
895 # nr < 0 (-1) means it never existed
898 $stk->push_rec('m', $at, $ct, $oid, $cmt);
901 close $fh or die "git log failed: \$?=$?";
902 $stk //= PublicInbox::IdxStack->new;
906 sub prepare_stack ($$) {
907 my ($sync, $range) = @_;
908 my $git = $sync->{ibx}->git;
910 if (index($range, '..') < 0) {
911 # don't show annoying git errors to users who run -index
913 $git->qx(qw(rev-parse -q --verify), "$range^0");
914 return PublicInbox::IdxStack->new->read_prepare if $?;
916 $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
917 log2stack($sync, $git, $range);
920 # --is-ancestor requires git 1.8.0+
921 sub is_ancestor ($$$) {
922 my ($git, $cur, $tip) = @_;
923 return 0 unless $git->check($cur);
924 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
925 qw(merge-base --is-ancestor), $cur, $tip ];
926 my $pid = spawn($cmd);
927 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
931 sub need_update ($$$) {
932 my ($self, $cur, $new) = @_;
933 my $git = $self->{ibx}->git;
934 return 1 if $cur && !is_ancestor($git, $cur, $new);
935 my $range = $cur eq '' ? $new : "$cur..$new";
936 chomp(my $n = $git->qx(qw(rev-list --count), $range));
937 ($n eq '' || $n > 0);
940 # The last git commit we indexed with Xapian or SQLite (msgmap)
941 # This needs to account for cases where Xapian or SQLite is
942 # out-of-date with respect to the other.
944 my ($self, $mm) = @_;
945 my $lm = $mm->last_commit || '';
947 if (need_xapian($self)) {
948 $lx = $self->{xdb}->get_metadata('last_commit') || '';
952 # Use last_commit from msgmap if it is older or unset
953 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
959 sub reindex_from ($$) {
960 my ($reindex, $last_commit) = @_;
961 return $last_commit unless $reindex;
962 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
968 # we set {-opt}->{quit} too, so ->index_sync callers
969 # can abort multi-inbox loops this way
970 $sync->{quit} = $sync->{-opt}->{quit} = 1;
971 warn "gracefully quitting\n";
975 # indexes all unindexed messages (v1 only)
977 my ($self, $opt) = @_;
978 my $tip = $opt->{ref} || 'HEAD';
979 my $ibx = $self->{ibx};
980 local $self->{current_info} = "$ibx->{inboxdir}";
981 $self->{batch_bytes} = $opt->{batch_size} // $BATCH_BYTES;
982 $ibx->git->batch_prepare;
983 my $pr = $opt->{-progress};
984 my $sync = { reindex => $opt->{reindex}, -opt => $opt, ibx => $ibx };
985 my $quit = quit_cb($sync);
986 local $SIG{QUIT} = $quit;
987 local $SIG{INT} = $quit;
988 local $SIG{TERM} = $quit;
989 my $xdb = $self->begin_txn_lazy;
990 $self->{oidx}->rethread_prepare($opt);
991 my $mm = _msgmap_init($self);
992 if ($sync->{reindex}) {
993 my $last = $mm->last_commit;
997 # somebody just blindly added --reindex when indexing
998 # for the first time, allow it:
999 undef $sync->{reindex};
1002 my $last_commit = _last_x_commit($self, $mm);
1003 my $lx = reindex_from($sync->{reindex}, $last_commit);
1004 my $range = $lx eq '' ? $tip : "$lx..$tip";
1005 $pr->("counting changes\n\t$range ... ") if $pr;
1006 my $stk = prepare_stack($sync, $range);
1007 $sync->{ntodo} = $stk ? $stk->num_records : 0;
1008 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
1009 process_stack($self, $sync, $stk) if !$sync->{quit};
1013 # order matters for unlocking
1014 $_[0]->{xdb} = undef;
1015 $_[0]->{lockfh} = undef;
1020 my $xdb = $self->{xdb} || idx_acquire($self);
1021 $self->{oidx}->begin_lazy if $self->{oidx};
1022 $xdb->begin_transaction if $xdb;
1027 sub begin_txn_lazy {
1029 $self->with_umask(\&_begin_txn, $self) if !$self->{txn};
1032 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
1033 # This metadata is read by Admin::detect_indexlevel:
1034 sub set_metadata_once {
1037 return if $self->{shard}; # only continue if undef or 0, not >0
1038 my $xdb = $self->{xdb};
1040 if (delete($self->{-set_has_threadid_once})) {
1041 $xdb->set_metadata('has_threadid', '1');
1043 if (delete($self->{-set_indexlevel_once})) {
1044 my $level = $xdb->get_metadata('indexlevel');
1045 if (!$level || $level ne 'medium') {
1046 $xdb->set_metadata('indexlevel', 'medium');
1049 if (delete($self->{-set_skip_docdata_once})) {
1050 $xdb->get_metadata('skip_docdata') or
1051 $xdb->set_metadata('skip_docdata', '1');
1057 if (my $eidx = $self->{eidx}) {
1058 $eidx->git->async_wait_all;
1059 $eidx->{transact_bytes} = 0;
1061 if (my $xdb = $self->{xdb}) {
1062 set_metadata_once($self);
1063 $xdb->commit_transaction;
1065 $self->{oidx}->commit_lazy if $self->{oidx};
1068 sub commit_txn_lazy {
1070 delete($self->{txn}) and
1071 $self->with_umask(\&_commit_txn, $self);
1074 sub eidx_shard_new {
1075 my ($class, $eidx, $shard) = @_;
1078 xpfx => $eidx->{xpfx},
1079 indexlevel => $eidx->{indexlevel},
1084 $self->{-set_indexlevel_once} = 1 if $self->{indexlevel} eq 'medium';
1088 # ensure there's no stale Xapian docs by treating $over as canonical
1090 my ($self, $over) = @_;
1091 begin_txn_lazy($self);
1092 my $sth = $over->dbh->prepare(<<'');
1093 SELECT COUNT(*) FROM over WHERE num = ?
1095 my $xdb = $self->{xdb};
1096 my $cur = $xdb->postlist_begin('');
1097 my $end = $xdb->postlist_end('');
1098 my $xdir = $self->xdir;
1099 for (; $cur != $end; $cur++) {
1100 my $docid = $cur->get_docid;
1101 $sth->execute($docid);
1102 my $x = $sth->fetchrow_array;
1104 warn "I: removing $xdir #$docid, not in `over'\n";
1105 $xdb->delete_document($docid);