1 # Copyright (C) 2015-2020 all contributors <meta@public-inbox.org>
2 # License: AGPL-3.0+ <https://www.gnu.org/licenses/agpl-3.0.txt>
3 # based on notmuch, but with no concept of folders, files or flags
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);
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw(mid_mime mids_for_index mids);
16 use PublicInbox::MsgIter;
17 use PublicInbox::IdxStack;
19 use POSIX qw(strftime);
20 use PublicInbox::OverIdx;
21 use PublicInbox::Spawn qw(spawn);
22 use PublicInbox::Git qw(git_unquote);
23 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
24 my $X = \%PublicInbox::Search::X;
25 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
26 our $BATCH_BYTES = defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
27 0x7fffffff : 1_000_000;
28 use constant DEBUG => !!$ENV{DEBUG};
30 my $xapianlevels = qr/\A(?:full|medium)\z/;
32 my $OID = $hex .'{40,}';
33 my $addmsg = qr!^:000000 100644 \S+ ($OID) A\t${hex}{2}/${hex}{38}$!;
34 my $delmsg = qr!^:100644 000000 ($OID) \S+ D\t${hex}{2}/${hex}{38}$!;
37 my ($class, $ibx, $creat, $shard) = @_;
38 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
39 my $levels = qr/\A(?:full|medium|basic)\z/;
40 my $inboxdir = $ibx->{inboxdir};
41 my $version = $ibx->version;
42 my $indexlevel = 'full';
43 my $altid = $ibx->{altid};
45 require PublicInbox::AltId;
46 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
48 if ($ibx->{indexlevel}) {
49 if ($ibx->{indexlevel} =~ $levels) {
50 $indexlevel = $ibx->{indexlevel};
52 die("Invalid indexlevel $ibx->{indexlevel}\n");
55 $ibx = PublicInbox::InboxWritable->new($ibx);
58 xpfx => $inboxdir, # for xpfx_init
61 indexlevel => $indexlevel,
64 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
67 $self->{lock_path} = "$inboxdir/ssoma.lock";
68 my $dir = $self->xdir;
69 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
70 $self->{index_max_size} = $ibx->{index_max_size};
71 } elsif ($version == 2) {
72 defined $shard or die "shard is required for v2\n";
74 $self->{shard} = $shard;
75 $self->{lock_path} = undef;
77 die "unsupported inbox version=$version\n";
79 $self->{creat} = ($creat || 0) == 1;
83 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
86 my ($self, $wake) = @_;
87 if (need_xapian($self)) {
88 my $xdb = delete $self->{xdb} or croak 'not acquired';
91 $self->lock_release($wake) if $self->{creat};
95 sub load_xapian_writable () {
96 return 1 if $X->{WritableDatabase};
97 PublicInbox::Search::load_xapian() or return;
98 my $xap = $PublicInbox::Search::Xap;
99 for (qw(Document TermGenerator WritableDatabase)) {
100 $X->{$_} = $xap.'::'.$_;
102 eval 'require '.$X->{WritableDatabase} or die;
103 *sortable_serialise = $xap.'::sortable_serialise';
104 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
105 $DB_OPEN = eval($xap.'::DB_OPEN()');
112 my $dir = $self->xdir;
113 if (need_xapian($self)) {
114 croak 'already acquired' if $self->{xdb};
115 load_xapian_writable();
116 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
118 if ($self->{creat}) {
122 # don't create empty Xapian directories if we don't need Xapian
123 my $is_shard = defined($self->{shard});
124 if (!$is_shard || ($is_shard && need_xapian($self))) {
125 File::Path::mkpath($dir);
128 return unless defined $flag;
129 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
131 die "Failed opening $dir: ", $@;
137 my ($doc, $col, $num) = @_;
138 $num = sortable_serialise($num);
139 $doc->add_value($col, $num);
142 sub term_generator ($) { # write-only
145 $self->{term_generator} //= do {
146 my $tg = $X->{TermGenerator}->new;
147 $tg->set_stemmer($self->stemmer);
152 sub index_text ($$$$) {
153 my ($self, $text, $wdf_inc, $prefix) = @_;
154 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
156 if ($self->{indexlevel} eq 'full') {
157 $tg->index_text($text, $wdf_inc, $prefix);
158 $tg->increase_termpos;
160 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
164 sub index_headers ($$) {
165 my ($self, $smsg) = @_;
166 my @x = (from => 'A', # Author
167 subject => 'S', to => 'XTO', cc => 'XCC');
168 while (my ($field, $pfx) = splice(@x, 0, 2)) {
169 my $val = $smsg->{$field};
170 index_text($self, $val, 1, $pfx) if $val ne '';
174 sub index_diff_inc ($$$$) {
175 my ($self, $text, $pfx, $xnq) = @_;
177 index_text($self, join("\n", @$xnq), 1, 'XNQ');
180 index_text($self, $text, 1, $pfx);
183 sub index_old_diff_fn {
184 my ($self, $seen, $fa, $fb, $xnq) = @_;
186 # no renames or space support for traditional diffs,
187 # find the number of leading common paths to strip:
188 my @fa = split('/', $fa);
189 my @fb = split('/', $fb);
190 while (scalar(@fa) && scalar(@fb)) {
191 $fa = join('/', @fa);
192 $fb = join('/', @fb);
194 unless ($seen->{$fa}++) {
195 index_diff_inc($self, $fa, 'XDFN', $xnq);
205 sub index_diff ($$$) {
206 my ($self, $txt, $doc) = @_;
211 foreach (split(/\n/, $txt)) {
212 if ($in_diff && s/^ //) { # diff context
213 index_diff_inc($self, $_, 'XDFCTX', $xnq);
214 } elsif (/^-- $/) { # email signature begins
216 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
217 # wait until "---" and "+++" to capture filenames
220 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
221 my ($opt, $fa, $fb) = ($1, $2, $3);
223 # only support unified:
224 next unless $opt =~ /[uU]/;
225 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
227 } elsif (m!^--- ("?[^/]+/.+)!) {
229 $fn = (split('/', git_unquote($fn), 2))[1];
230 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
232 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
234 $fn = (split('/', git_unquote($fn), 2))[1];
235 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
237 } elsif (/^--- (\S+)/) {
240 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
241 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
243 } elsif ($in_diff && s/^\+//) { # diff added
244 index_diff_inc($self, $_, 'XDFB', $xnq);
245 } elsif ($in_diff && s/^-//) { # diff removed
246 index_diff_inc($self, $_, 'XDFA', $xnq);
247 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
248 my ($ba, $bb) = ($1, $2);
249 index_git_blob_id($doc, 'XDFPRE', $ba);
250 index_git_blob_id($doc, 'XDFPOST', $bb);
252 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
253 # traditional diff w/o -p
254 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
255 # hunk header context
256 index_diff_inc($self, $1, 'XDFHH', $xnq);
257 # ignore the following lines:
258 } elsif (/^(?:dis)similarity index/ ||
259 /^(?:old|new) mode/ ||
260 /^(?:deleted|new) file mode/ ||
261 /^(?:copy|rename) (?:from|to) / ||
262 /^(?:dis)?similarity index / ||
263 /^\\ No newline at end of file/ ||
264 /^Binary files .* differ/) {
267 # possible to be in diff context, some mail may be
268 # stripped by MUA or even GNU diff(1). "git apply"
269 # treats a bare "\n" as diff context, too
272 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
277 index_text($self, join("\n", @xnq), 1, 'XNQ');
280 sub index_xapian { # msg_iter callback
281 my $part = $_[0]->[0]; # ignore $depth and $idx
282 my ($self, $doc) = @{$_[1]};
283 my $ct = $part->content_type || 'text/plain';
284 my $fn = $part->filename;
285 if (defined $fn && $fn ne '') {
286 index_text($self, $fn, 1, 'XFN');
288 if ($part->{is_submsg}) {
289 my $mids = mids_for_index($part);
290 index_ids($self, $doc, $part, $mids);
291 my $smsg = bless {}, 'PublicInbox::Smsg';
292 $smsg->populate($part);
293 index_headers($self, $smsg);
296 my ($s, undef) = msg_part_text($part, $ct);
297 defined $s or return;
298 $_[0]->[0] = $part = undef; # free memory
300 # split off quoted and unquoted blocks:
301 my @sections = PublicInbox::MsgIter::split_quotes($s);
302 undef $s; # free memory
303 for my $txt (@sections) {
305 index_text($self, $txt, 0, 'XQUOT');
307 # does it look like a diff?
308 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
309 index_diff($self, $txt, $doc);
311 index_text($self, $txt, 1, 'XNQ');
314 undef $txt; # free memory
318 sub index_ids ($$$$) {
319 my ($self, $doc, $hdr, $mids) = @_;
320 for my $mid (@$mids) {
321 index_text($self, $mid, 1, 'XM');
323 # because too many Message-IDs are prefixed with
325 if ($mid =~ /\w{12,}/) {
326 my @long = ($mid =~ /(\w{3,}+)/g);
327 index_text($self, join(' ', @long), 1, 'XM');
330 $doc->add_boolean_term('Q' . $_) for @$mids;
331 for my $l ($hdr->header_raw('List-Id')) {
332 $l =~ /<([^>]+)>/ or next;
334 $doc->add_boolean_term('G' . $lid);
335 index_text($self, $lid, 1, 'XL'); # probabilistic
339 sub add_xapian ($$$$) {
340 my ($self, $mime, $smsg, $mids) = @_;
341 my $hdr = $mime->header_obj;
342 my $doc = $X->{Document}->new;
343 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
344 my @ds = gmtime($smsg->{ds});
345 my $yyyymmdd = strftime('%Y%m%d', @ds);
346 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
347 my $dt = strftime('%Y%m%d%H%M%S', @ds);
348 add_val($doc, PublicInbox::Search::DT(), $dt);
349 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
350 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
352 my $tg = term_generator($self);
353 $tg->set_document($doc);
354 index_headers($self, $smsg);
356 msg_iter($mime, \&index_xapian, [ $self, $doc ]);
357 index_ids($self, $doc, $hdr, $mids);
358 $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
359 PublicInbox::OverIdx::parse_references($smsg, $hdr, $mids);
360 my $data = $smsg->to_doc_data;
361 $doc->set_data($data);
362 if (my $altid = $self->{-altid}) {
363 foreach my $alt (@$altid) {
364 my $pfx = $alt->{xprefix};
365 foreach my $mid (@$mids) {
366 my $id = $alt->mid2alt($mid);
367 next unless defined $id;
368 $doc->add_boolean_term($pfx . $id);
372 $self->{xdb}->replace_document($smsg->{num}, $doc);
375 sub _msgmap_init ($) {
377 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
378 $self->{mm} //= eval {
379 require PublicInbox::Msgmap;
380 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, 1);
385 # mime = PublicInbox::Eml or Email::MIME object
386 my ($self, $mime, $smsg, $sync) = @_;
387 my $hdr = $mime->header_obj;
388 my $mids = mids_for_index($hdr);
389 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
390 $smsg->{mid} //= $mids->[0]; # v1 compatibility
391 $smsg->{num} //= do { # v1
393 index_mm($self, $mime, $smsg->{blob}, $sync);
397 $smsg->populate($hdr, $sync);
398 $smsg->{bytes} //= length($mime->as_string);
401 # order matters, overview stores every possible piece of
402 # data in doc_data (deflated). Xapian only stores a subset
403 # of the fields which exist in over.sqlite3. We may stop
404 # storing doc_data in Xapian sometime after we get multi-inbox
406 if (my $over = $self->{over}) { # v1 only
407 $over->add_overview($mime, $smsg);
409 if (need_xapian($self)) {
410 add_xapian($self, $mime, $smsg, $mids);
415 warn "failed to index message <".join('> <',@$mids).">: $@\n";
422 my ($self, $oid, @removed) = @_;
423 my $xdb = $self->{xdb} or return;
424 for my $num (@removed) {
425 my $doc = eval { $xdb->get_document($num) };
427 warn "E: $@\n" if $@;
428 warn "E: #$num $oid missing in Xapian\n";
431 my $smsg = bless {}, 'PublicInbox::Smsg';
432 $smsg->load_expand($doc);
433 my $blob = $smsg->{blob} // '(unset)';
435 $xdb->delete_document($num);
437 warn "E: #$num $oid != $blob in Xapian\n";
443 my ($self, $oid, $num) = @_;
444 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
445 $self->begin_txn_lazy;
446 xdb_remove($self, $oid, $num) if need_xapian($self);
449 sub index_git_blob_id {
450 my ($doc, $pfx, $objid) = @_;
452 my $len = length($objid);
453 for (my $len = length($objid); $len >= 7; ) {
454 $doc->add_term($pfx.$objid);
455 $objid = substr($objid, 0, --$len);
461 my ($self, $oid, $eml) = @_;
462 my $mids = mids($eml);
465 for my $mid (@$mids) {
466 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
468 warn "E: failed to remove <$mid> from overview: $@\n";
470 $nr += scalar @removed;
471 $tmp{$_}++ for @removed;
475 $mids = join('> <', @$mids);
476 warn "W: <$mids> missing for removal from overview\n";
478 while (my ($num, $nr) = each %tmp) {
479 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
481 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
485 my ($self, $mime, $oid, $sync) = @_;
486 my $mids = mids($mime);
487 my $mm = $self->{mm};
488 if ($sync->{reindex}) {
489 my $over = $self->{over};
490 for my $mid (@$mids) {
491 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
492 return $num if defined $num;
494 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
496 # fallback to num_for since filters like RubyLang set the number
497 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
502 my ($self, $mime) = @_;
503 $self->{mm}->mid_delete(mid_mime($mime));
506 # returns the number of bytes to add if given a non-CRLF arg
507 sub crlf_adjust ($) {
508 if (index($_[0], "\r\n") < 0) {
509 # common case is LF-only, every \n needs an \r;
510 # so favor a cheap tr// over an expensive m//g
512 } else { # count number of '\n' w/o '\r', expensive:
513 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
517 sub index_both { # git->cat_async callback
518 my ($bref, $oid, $type, $size, $sync) = @_;
519 my ($nr, $max) = @$sync{qw(nr max)};
522 $size += crlf_adjust($$bref);
523 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
524 my $self = $sync->{sidx};
525 my $eml = PublicInbox::Eml->new($bref);
526 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
527 die "E: could not generate NNTP article number for $oid";
528 add_message($self, $eml, $smsg, $sync);
531 sub unindex_both { # git->cat_async callback
532 my ($bref, $oid, $type, $size, $self) = @_;
533 my $eml = PublicInbox::Eml->new($bref);
534 unindex_eml($self, $oid, $eml);
535 unindex_mm($self, $eml);
538 # called by public-inbox-index
540 my ($self, $opts) = @_;
541 delete $self->{lock_path} if $opts->{-skip_lock};
542 $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
543 if ($opts->{reindex}) {
545 delete @again{qw(rethread reindex)};
546 index_sync($self, \%again);
551 my ($self, $oid) = @_;
552 my $max_size = $self->{index_max_size} or return;
553 my (undef, undef, $size) = $self->{ibx}->git->check($oid);
554 die "E: bad $oid in $self->{ibx}->{inboxdir}\n" if !defined($size);
555 return if $size <= $max_size;
556 warn "W: skipping $oid ($size > $max_size)\n";
562 my ($self, $stk, $sync, $batch_cb) = @_;
563 my $git = $self->{ibx}->git;
564 my $max = $BATCH_BYTES;
567 $sync->{max} = \$max;
568 $sync->{sidx} = $self;
570 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
571 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
572 for my $oid (@leftovers) {
573 $oid = unpack('H*', $oid);
574 $git->cat_async($oid, \&unindex_both, $self);
577 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
579 $sync->{autime} = $at;
580 $sync->{cotime} = $ct;
581 next if too_big($self, $oid);
582 $git->cat_async($oid, \&index_both, { %$sync });
584 $git->cat_async_wait;
588 } elsif ($f eq 'd') {
589 $git->cat_async($oid, \&unindex_both, $self);
592 $git->cat_async_wait;
593 $batch_cb->($nr, $stk);
596 sub prepare_stack ($$$) {
597 my ($self, $sync, $range) = @_;
598 my $git = $self->{ibx}->git;
600 if (index($range, '..') < 0) {
601 # don't show annoying git errors to users who run -index
603 $git->qx(qw(rev-parse -q --verify), "$range^0");
604 return PublicInbox::IdxStack->new->read_prepare if $?;
606 my $D = $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
608 # Count the new files so they can be added newest to oldest
609 # and still have numbers increasing from oldest to newest
610 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
611 --no-notes --no-color --no-renames --no-abbrev),
615 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
616 ($at, $ct) = ($1 + 0, $2 + 0);
617 $stk //= PublicInbox::IdxStack->new($3);
618 } elsif (/$delmsg/) {
620 if ($D) { # reindex case
621 $D->{pack('H*', $oid)}++;
622 } else { # non-reindex case:
623 $stk->push_rec('d', $at, $ct, $oid);
625 } elsif (/$addmsg/) {
628 my $oid_bin = pack('H*', $oid);
629 my $nr = --$D->{$oid_bin};
630 delete($D->{$oid_bin}) if $nr <= 0;
632 # nr < 0 (-1) means it never existed
633 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
635 $stk->push_rec('m', $at, $ct, $oid);
639 close $fh or die "git log failed: \$?=$?";
640 $stk //= PublicInbox::IdxStack->new;
644 # --is-ancestor requires git 1.8.0+
645 sub is_ancestor ($$$) {
646 my ($git, $cur, $tip) = @_;
647 return 0 unless $git->check($cur);
648 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
649 qw(merge-base --is-ancestor), $cur, $tip ];
650 my $pid = spawn($cmd);
651 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
655 sub need_update ($$$) {
656 my ($self, $cur, $new) = @_;
657 my $git = $self->{ibx}->git;
658 return 1 if $cur && !is_ancestor($git, $cur, $new);
659 my $range = $cur eq '' ? $new : "$cur..$new";
660 chomp(my $n = $git->qx(qw(rev-list --count), $range));
661 ($n eq '' || $n > 0);
664 # The last git commit we indexed with Xapian or SQLite (msgmap)
665 # This needs to account for cases where Xapian or SQLite is
666 # out-of-date with respect to the other.
668 my ($self, $mm) = @_;
669 my $lm = $mm->last_commit || '';
671 if (need_xapian($self)) {
672 $lx = $self->{xdb}->get_metadata('last_commit') || '';
676 # Use last_commit from msgmap if it is older or unset
677 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
683 sub reindex_from ($$) {
684 my ($reindex, $last_commit) = @_;
685 return $last_commit unless $reindex;
686 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
689 # indexes all unindexed messages (v1 only)
691 my ($self, $opts) = @_;
692 my $tip = $opts->{ref} || 'HEAD';
693 my $git = $self->{ibx}->git;
695 my $pr = $opts->{-progress};
696 my $sync = { reindex => $opts->{reindex} };
697 my $xdb = $self->begin_txn_lazy;
698 $self->{over}->rethread_prepare($opts);
699 my $mm = _msgmap_init($self);
700 if ($sync->{reindex}) {
701 my $last = $mm->last_commit;
705 # somebody just blindly added --reindex when indexing
706 # for the first time, allow it:
707 undef $sync->{reindex};
710 my $last_commit = _last_x_commit($self, $mm);
711 my $lx = reindex_from($sync->{reindex}, $last_commit);
712 my $range = $lx eq '' ? $tip : "$lx..$tip";
713 $pr->("counting changes\n\t$range ... ") if $pr;
714 my $stk = prepare_stack($self, $sync, $range);
715 $sync->{ntodo} = $stk ? $stk->num_records : 0;
716 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
718 my $dbh = $mm->{dbh};
721 # latest_cmt may be undef
722 my $newest = $stk ? $stk->{latest_cmt} : undef;
724 my $cur = $mm->last_commit || '';
725 if (need_update($self, $cur, $newest)) {
726 $mm->last_commit($newest);
730 if ($newest && need_xapian($self)) {
731 my $cur = $xdb->get_metadata('last_commit');
732 if (need_update($self, $cur, $newest)) {
733 $xdb->set_metadata('last_commit', $newest);
737 $self->{over}->rethread_done($opts) if $newest; # all done
738 $self->commit_txn_lazy;
740 $xdb = idx_release($self, $nr);
741 # let another process do some work...
742 $pr->("indexed $nr/$sync->{ntodo}\n") if $pr && $nr;
743 if (!$stk) { # more to come
744 $xdb = $self->begin_txn_lazy;
750 process_stack($self, $stk, $sync, $batch_cb);
754 # order matters for unlocking
755 $_[0]->{xdb} = undef;
756 $_[0]->{lockfh} = undef;
759 # remote_* subs are only used by SearchIdxPart
762 if (my $w = $self->{w}) {
763 print $w "commit\n" or die "failed to write commit: $!";
765 $self->commit_txn_lazy;
771 if (my $w = delete $self->{w}) {
772 my $pid = delete $self->{pid} or die "no process to wait on\n";
773 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
774 close $w or die "failed to close pipe for pid:$pid: $!\n";
775 waitpid($pid, 0) == $pid or die "remote process did not finish";
776 $? == 0 or die ref($self)." pid:$pid exited with: $?";
778 die "transaction in progress $self\n" if $self->{txn};
779 idx_release($self) if $self->{xdb};
784 my ($self, $oid, $num) = @_;
785 if (my $w = $self->{w}) {
786 # triggers remove_by_oid in a shard
787 print $w "D $oid $num\n" or die "failed to write remove $!";
789 $self->remove_by_oid($oid, $num);
795 my $xdb = $self->{xdb} || idx_acquire($self);
796 $self->{over}->begin_lazy if $self->{over};
797 $xdb->begin_transaction if $xdb;
804 $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
807 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
808 # This metadata is read by Admin::detect_indexlevel:
812 if (!$self->{shard} && # undef or 0, not >0
813 delete($self->{-set_indexlevel_once})) {
814 my $xdb = $self->{xdb};
815 my $level = $xdb->get_metadata('indexlevel');
816 if (!$level || $level ne 'medium') {
817 $xdb->set_metadata('indexlevel', 'medium');
824 if (my $xdb = $self->{xdb}) {
825 set_indexlevel($self);
826 $xdb->commit_transaction;
828 $self->{over}->commit_lazy if $self->{over};
831 sub commit_txn_lazy {
833 delete($self->{txn}) and
834 $self->{ibx}->with_umask(\&_commit_txn, $self);
839 if (need_xapian($self)) {
840 die "$$ $0 xdb not released\n" if $self->{xdb};
842 die "$$ $0 still in transaction\n" if $self->{txn};