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);
27 our $BATCH_BYTES = defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
28 0x7fffffff : 1_000_000;
29 use constant DEBUG => !!$ENV{DEBUG};
31 my $xapianlevels = qr/\A(?:full|medium)\z/;
33 my $OID = $hex .'{40,}';
34 my $addmsg = qr!^:000000 100644 \S+ ($OID) A\t${hex}{2}/${hex}{38}$!;
35 my $delmsg = qr!^:100644 000000 ($OID) \S+ D\t${hex}{2}/${hex}{38}$!;
38 my ($class, $ibx, $creat, $shard) = @_;
39 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
40 my $levels = qr/\A(?:full|medium|basic)\z/;
41 my $inboxdir = $ibx->{inboxdir};
42 my $version = $ibx->version;
43 my $indexlevel = 'full';
44 my $altid = $ibx->{altid};
46 require PublicInbox::AltId;
47 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
49 if ($ibx->{indexlevel}) {
50 if ($ibx->{indexlevel} =~ $levels) {
51 $indexlevel = $ibx->{indexlevel};
53 die("Invalid indexlevel $ibx->{indexlevel}\n");
56 $ibx = PublicInbox::InboxWritable->new($ibx);
59 xpfx => $inboxdir, # for xpfx_init
62 indexlevel => $indexlevel,
65 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
68 $self->{lock_path} = "$inboxdir/ssoma.lock";
69 my $dir = $self->xdir;
70 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
71 $self->{over}->{-no_sync} = 1 if $ibx->{-no_sync};
72 $self->{index_max_size} = $ibx->{index_max_size};
73 } elsif ($version == 2) {
74 defined $shard or die "shard is required for v2\n";
76 $self->{shard} = $shard;
77 $self->{lock_path} = undef;
79 die "unsupported inbox version=$version\n";
81 $self->{creat} = ($creat || 0) == 1;
85 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
88 my ($self, $wake) = @_;
89 if (need_xapian($self)) {
90 my $xdb = delete $self->{xdb} or croak 'not acquired';
93 $self->lock_release($wake) if $self->{creat};
97 sub load_xapian_writable () {
98 return 1 if $X->{WritableDatabase};
99 PublicInbox::Search::load_xapian() or return;
100 my $xap = $PublicInbox::Search::Xap;
101 for (qw(Document TermGenerator WritableDatabase)) {
102 $X->{$_} = $xap.'::'.$_;
104 eval 'require '.$X->{WritableDatabase} or die;
105 *sortable_serialise = $xap.'::sortable_serialise';
106 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
107 $DB_OPEN = eval($xap.'::DB_OPEN()');
108 my $ver = (eval($xap.'::major_version()') << 16) |
109 (eval($xap.'::minor_version()') << 8);
110 $DB_NO_SYNC = 0x4 if $ver >= 0x10400;
117 my $dir = $self->xdir;
118 if (need_xapian($self)) {
119 croak 'already acquired' if $self->{xdb};
120 load_xapian_writable();
121 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
123 if ($self->{creat}) {
127 # don't create empty Xapian directories if we don't need Xapian
128 my $is_shard = defined($self->{shard});
129 if (!$is_shard || ($is_shard && need_xapian($self))) {
130 File::Path::mkpath($dir);
133 return unless defined $flag;
134 $flag |= $DB_NO_SYNC if $self->{ibx}->{-no_sync};
135 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
137 die "Failed opening $dir: ", $@;
143 my ($doc, $col, $num) = @_;
144 $num = sortable_serialise($num);
145 $doc->add_value($col, $num);
148 sub term_generator ($) { # write-only
151 $self->{term_generator} //= do {
152 my $tg = $X->{TermGenerator}->new;
153 $tg->set_stemmer($self->stemmer);
158 sub index_text ($$$$) {
159 my ($self, $text, $wdf_inc, $prefix) = @_;
160 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
162 if ($self->{indexlevel} eq 'full') {
163 $tg->index_text($text, $wdf_inc, $prefix);
164 $tg->increase_termpos;
166 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
170 sub index_headers ($$) {
171 my ($self, $smsg) = @_;
172 my @x = (from => 'A', # Author
173 subject => 'S', to => 'XTO', cc => 'XCC');
174 while (my ($field, $pfx) = splice(@x, 0, 2)) {
175 my $val = $smsg->{$field};
176 index_text($self, $val, 1, $pfx) if $val ne '';
180 sub index_diff_inc ($$$$) {
181 my ($self, $text, $pfx, $xnq) = @_;
183 index_text($self, join("\n", @$xnq), 1, 'XNQ');
186 index_text($self, $text, 1, $pfx);
189 sub index_old_diff_fn {
190 my ($self, $seen, $fa, $fb, $xnq) = @_;
192 # no renames or space support for traditional diffs,
193 # find the number of leading common paths to strip:
194 my @fa = split('/', $fa);
195 my @fb = split('/', $fb);
196 while (scalar(@fa) && scalar(@fb)) {
197 $fa = join('/', @fa);
198 $fb = join('/', @fb);
200 unless ($seen->{$fa}++) {
201 index_diff_inc($self, $fa, 'XDFN', $xnq);
211 sub index_diff ($$$) {
212 my ($self, $txt, $doc) = @_;
217 foreach (split(/\n/, $txt)) {
218 if ($in_diff && s/^ //) { # diff context
219 index_diff_inc($self, $_, 'XDFCTX', $xnq);
220 } elsif (/^-- $/) { # email signature begins
222 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
223 # wait until "---" and "+++" to capture filenames
226 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
227 my ($opt, $fa, $fb) = ($1, $2, $3);
229 # only support unified:
230 next unless $opt =~ /[uU]/;
231 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
233 } elsif (m!^--- ("?[^/]+/.+)!) {
235 $fn = (split('/', git_unquote($fn), 2))[1];
236 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
238 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
240 $fn = (split('/', git_unquote($fn), 2))[1];
241 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
243 } elsif (/^--- (\S+)/) {
246 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
247 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
249 } elsif ($in_diff && s/^\+//) { # diff added
250 index_diff_inc($self, $_, 'XDFB', $xnq);
251 } elsif ($in_diff && s/^-//) { # diff removed
252 index_diff_inc($self, $_, 'XDFA', $xnq);
253 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
254 my ($ba, $bb) = ($1, $2);
255 index_git_blob_id($doc, 'XDFPRE', $ba);
256 index_git_blob_id($doc, 'XDFPOST', $bb);
258 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
259 # traditional diff w/o -p
260 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
261 # hunk header context
262 index_diff_inc($self, $1, 'XDFHH', $xnq);
263 # ignore the following lines:
264 } elsif (/^(?:dis)similarity index/ ||
265 /^(?:old|new) mode/ ||
266 /^(?:deleted|new) file mode/ ||
267 /^(?:copy|rename) (?:from|to) / ||
268 /^(?:dis)?similarity index / ||
269 /^\\ No newline at end of file/ ||
270 /^Binary files .* differ/) {
273 # possible to be in diff context, some mail may be
274 # stripped by MUA or even GNU diff(1). "git apply"
275 # treats a bare "\n" as diff context, too
278 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
283 index_text($self, join("\n", @xnq), 1, 'XNQ');
286 sub index_xapian { # msg_iter callback
287 my $part = $_[0]->[0]; # ignore $depth and $idx
288 my ($self, $doc) = @{$_[1]};
289 my $ct = $part->content_type || 'text/plain';
290 my $fn = $part->filename;
291 if (defined $fn && $fn ne '') {
292 index_text($self, $fn, 1, 'XFN');
294 if ($part->{is_submsg}) {
295 my $mids = mids_for_index($part);
296 index_ids($self, $doc, $part, $mids);
297 my $smsg = bless {}, 'PublicInbox::Smsg';
298 $smsg->populate($part);
299 index_headers($self, $smsg);
302 my ($s, undef) = msg_part_text($part, $ct);
303 defined $s or return;
304 $_[0]->[0] = $part = undef; # free memory
306 # split off quoted and unquoted blocks:
307 my @sections = PublicInbox::MsgIter::split_quotes($s);
308 undef $s; # free memory
309 for my $txt (@sections) {
311 index_text($self, $txt, 0, 'XQUOT');
313 # does it look like a diff?
314 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
315 index_diff($self, $txt, $doc);
317 index_text($self, $txt, 1, 'XNQ');
320 undef $txt; # free memory
324 sub index_ids ($$$$) {
325 my ($self, $doc, $hdr, $mids) = @_;
326 for my $mid (@$mids) {
327 index_text($self, $mid, 1, 'XM');
329 # because too many Message-IDs are prefixed with
331 if ($mid =~ /\w{12,}/) {
332 my @long = ($mid =~ /(\w{3,}+)/g);
333 index_text($self, join(' ', @long), 1, 'XM');
336 $doc->add_boolean_term('Q' . $_) for @$mids;
337 for my $l ($hdr->header_raw('List-Id')) {
338 $l =~ /<([^>]+)>/ or next;
340 $doc->add_boolean_term('G' . $lid);
341 index_text($self, $lid, 1, 'XL'); # probabilistic
345 sub add_xapian ($$$$) {
346 my ($self, $mime, $smsg, $mids) = @_;
347 my $hdr = $mime->header_obj;
348 my $doc = $X->{Document}->new;
349 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
350 my @ds = gmtime($smsg->{ds});
351 my $yyyymmdd = strftime('%Y%m%d', @ds);
352 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
353 my $dt = strftime('%Y%m%d%H%M%S', @ds);
354 add_val($doc, PublicInbox::Search::DT(), $dt);
355 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
356 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
358 my $tg = term_generator($self);
359 $tg->set_document($doc);
360 index_headers($self, $smsg);
362 msg_iter($mime, \&index_xapian, [ $self, $doc ]);
363 index_ids($self, $doc, $hdr, $mids);
364 $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
365 PublicInbox::OverIdx::parse_references($smsg, $hdr, $mids);
366 my $data = $smsg->to_doc_data;
367 $doc->set_data($data);
368 if (my $altid = $self->{-altid}) {
369 foreach my $alt (@$altid) {
370 my $pfx = $alt->{xprefix};
371 foreach my $mid (@$mids) {
372 my $id = $alt->mid2alt($mid);
373 next unless defined $id;
374 $doc->add_boolean_term($pfx . $id);
378 $self->{xdb}->replace_document($smsg->{num}, $doc);
381 sub _msgmap_init ($) {
383 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
384 $self->{mm} //= eval {
385 require PublicInbox::Msgmap;
386 my $rw = $self->{ibx}->{-no_sync} ? 2 : 1;
387 PublicInbox::Msgmap->new($self->{ibx}->{inboxdir}, $rw);
392 # mime = PublicInbox::Eml or Email::MIME object
393 my ($self, $mime, $smsg, $sync) = @_;
394 my $hdr = $mime->header_obj;
395 my $mids = mids_for_index($hdr);
396 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
397 $smsg->{mid} //= $mids->[0]; # v1 compatibility
398 $smsg->{num} //= do { # v1
400 index_mm($self, $mime, $smsg->{blob}, $sync);
404 $smsg->populate($hdr, $sync);
405 $smsg->{bytes} //= length($mime->as_string);
408 # order matters, overview stores every possible piece of
409 # data in doc_data (deflated). Xapian only stores a subset
410 # of the fields which exist in over.sqlite3. We may stop
411 # storing doc_data in Xapian sometime after we get multi-inbox
413 if (my $over = $self->{over}) { # v1 only
414 $over->add_overview($mime, $smsg);
416 if (need_xapian($self)) {
417 add_xapian($self, $mime, $smsg, $mids);
422 warn "failed to index message <".join('> <',@$mids).">: $@\n";
429 my ($self, $oid, @removed) = @_;
430 my $xdb = $self->{xdb} or return;
431 for my $num (@removed) {
432 my $doc = eval { $xdb->get_document($num) };
434 warn "E: $@\n" if $@;
435 warn "E: #$num $oid missing in Xapian\n";
438 my $smsg = bless {}, 'PublicInbox::Smsg';
439 $smsg->load_expand($doc);
440 my $blob = $smsg->{blob} // '(unset)';
442 $xdb->delete_document($num);
444 warn "E: #$num $oid != $blob in Xapian\n";
450 my ($self, $oid, $num) = @_;
451 die "BUG: remove_by_oid is v2-only\n" if $self->{over};
452 $self->begin_txn_lazy;
453 xdb_remove($self, $oid, $num) if need_xapian($self);
456 sub index_git_blob_id {
457 my ($doc, $pfx, $objid) = @_;
459 my $len = length($objid);
460 for (my $len = length($objid); $len >= 7; ) {
461 $doc->add_term($pfx.$objid);
462 $objid = substr($objid, 0, --$len);
468 my ($self, $oid, $eml) = @_;
469 my $mids = mids($eml);
472 for my $mid (@$mids) {
473 my @removed = eval { $self->{over}->remove_oid($oid, $mid) };
475 warn "E: failed to remove <$mid> from overview: $@\n";
477 $nr += scalar @removed;
478 $tmp{$_}++ for @removed;
482 $mids = join('> <', @$mids);
483 warn "W: <$mids> missing for removal from overview\n";
485 while (my ($num, $nr) = each %tmp) {
486 warn "BUG: $num appears >1 times ($nr) for $oid\n" if $nr != 1;
488 xdb_remove($self, $oid, keys %tmp) if need_xapian($self);
492 my ($self, $mime, $oid, $sync) = @_;
493 my $mids = mids($mime);
494 my $mm = $self->{mm};
495 if ($sync->{reindex}) {
496 my $over = $self->{over};
497 for my $mid (@$mids) {
498 my ($num, undef) = $over->num_mid0_for_oid($oid, $mid);
499 return $num if defined $num;
501 $mm->num_for($mids->[0]) // $mm->mid_insert($mids->[0]);
503 # fallback to num_for since filters like RubyLang set the number
504 $mm->mid_insert($mids->[0]) // $mm->num_for($mids->[0]);
509 my ($self, $mime) = @_;
510 $self->{mm}->mid_delete(mid_mime($mime));
513 # returns the number of bytes to add if given a non-CRLF arg
514 sub crlf_adjust ($) {
515 if (index($_[0], "\r\n") < 0) {
516 # common case is LF-only, every \n needs an \r;
517 # so favor a cheap tr// over an expensive m//g
519 } else { # count number of '\n' w/o '\r', expensive:
520 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
524 sub index_both { # git->cat_async callback
525 my ($bref, $oid, $type, $size, $sync) = @_;
526 my ($nr, $max) = @$sync{qw(nr max)};
529 $size += crlf_adjust($$bref);
530 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
531 my $self = $sync->{sidx};
532 my $eml = PublicInbox::Eml->new($bref);
533 $smsg->{num} = index_mm($self, $eml, $oid, $sync) or
534 die "E: could not generate NNTP article number for $oid";
535 add_message($self, $eml, $smsg, $sync);
538 sub unindex_both { # git->cat_async callback
539 my ($bref, $oid, $type, $size, $self) = @_;
540 my $eml = PublicInbox::Eml->new($bref);
541 unindex_eml($self, $oid, $eml);
542 unindex_mm($self, $eml);
545 # called by public-inbox-index
547 my ($self, $opts) = @_;
548 delete $self->{lock_path} if $opts->{-skip_lock};
549 $self->{ibx}->with_umask(\&_index_sync, $self, $opts);
550 if ($opts->{reindex}) {
552 delete @again{qw(rethread reindex)};
553 index_sync($self, \%again);
558 my ($self, $oid) = @_;
559 my $max_size = $self->{index_max_size} or return;
560 my (undef, undef, $size) = $self->{ibx}->git->check($oid);
561 die "E: bad $oid in $self->{ibx}->{inboxdir}\n" if !defined($size);
562 return if $size <= $max_size;
563 warn "W: skipping $oid ($size > $max_size)\n";
569 my ($self, $stk, $sync, $batch_cb) = @_;
570 my $git = $self->{ibx}->git;
571 my $max = $BATCH_BYTES;
574 $sync->{max} = \$max;
575 $sync->{sidx} = $self;
577 if (my @leftovers = keys %{delete($sync->{D}) // {}}) {
578 warn('W: unindexing '.scalar(@leftovers)." leftovers\n");
579 for my $oid (@leftovers) {
580 $oid = unpack('H*', $oid);
581 $git->cat_async($oid, \&unindex_both, $self);
584 while (my ($f, $at, $ct, $oid) = $stk->pop_rec) {
586 $sync->{autime} = $at;
587 $sync->{cotime} = $ct;
588 next if too_big($self, $oid);
589 $git->cat_async($oid, \&index_both, { %$sync });
591 $git->cat_async_wait;
595 } elsif ($f eq 'd') {
596 $git->cat_async($oid, \&unindex_both, $self);
599 $git->cat_async_wait;
600 $batch_cb->($nr, $stk);
603 sub prepare_stack ($$$) {
604 my ($self, $sync, $range) = @_;
605 my $git = $self->{ibx}->git;
607 if (index($range, '..') < 0) {
608 # don't show annoying git errors to users who run -index
610 $git->qx(qw(rev-parse -q --verify), "$range^0");
611 return PublicInbox::IdxStack->new->read_prepare if $?;
613 my $D = $sync->{D} = $sync->{reindex} ? {} : undef; # OID_BIN => NR
615 # Count the new files so they can be added newest to oldest
616 # and still have numbers increasing from oldest to newest
617 my $fh = $git->popen(qw(log --raw -r --pretty=tformat:%at-%ct-%H
618 --no-notes --no-color --no-renames --no-abbrev),
622 if (/\A([0-9]+)-([0-9]+)-($OID)$/o) {
623 ($at, $ct) = ($1 + 0, $2 + 0);
624 $stk //= PublicInbox::IdxStack->new($3);
625 } elsif (/$delmsg/) {
627 if ($D) { # reindex case
628 $D->{pack('H*', $oid)}++;
629 } else { # non-reindex case:
630 $stk->push_rec('d', $at, $ct, $oid);
632 } elsif (/$addmsg/) {
635 my $oid_bin = pack('H*', $oid);
636 my $nr = --$D->{$oid_bin};
637 delete($D->{$oid_bin}) if $nr <= 0;
639 # nr < 0 (-1) means it never existed
640 $stk->push_rec('m', $at, $ct, $oid) if $nr < 0;
642 $stk->push_rec('m', $at, $ct, $oid);
646 close $fh or die "git log failed: \$?=$?";
647 $stk //= PublicInbox::IdxStack->new;
651 # --is-ancestor requires git 1.8.0+
652 sub is_ancestor ($$$) {
653 my ($git, $cur, $tip) = @_;
654 return 0 unless $git->check($cur);
655 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
656 qw(merge-base --is-ancestor), $cur, $tip ];
657 my $pid = spawn($cmd);
658 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
662 sub need_update ($$$) {
663 my ($self, $cur, $new) = @_;
664 my $git = $self->{ibx}->git;
665 return 1 if $cur && !is_ancestor($git, $cur, $new);
666 my $range = $cur eq '' ? $new : "$cur..$new";
667 chomp(my $n = $git->qx(qw(rev-list --count), $range));
668 ($n eq '' || $n > 0);
671 # The last git commit we indexed with Xapian or SQLite (msgmap)
672 # This needs to account for cases where Xapian or SQLite is
673 # out-of-date with respect to the other.
675 my ($self, $mm) = @_;
676 my $lm = $mm->last_commit || '';
678 if (need_xapian($self)) {
679 $lx = $self->{xdb}->get_metadata('last_commit') || '';
683 # Use last_commit from msgmap if it is older or unset
684 if (!$lm || ($lx && $lm && is_ancestor($self->{ibx}->git, $lm, $lx))) {
690 sub reindex_from ($$) {
691 my ($reindex, $last_commit) = @_;
692 return $last_commit unless $reindex;
693 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
696 # indexes all unindexed messages (v1 only)
698 my ($self, $opts) = @_;
699 my $tip = $opts->{ref} || 'HEAD';
700 my $git = $self->{ibx}->git;
702 my $pr = $opts->{-progress};
703 my $sync = { reindex => $opts->{reindex} };
704 my $xdb = $self->begin_txn_lazy;
705 $self->{over}->rethread_prepare($opts);
706 my $mm = _msgmap_init($self);
707 if ($sync->{reindex}) {
708 my $last = $mm->last_commit;
712 # somebody just blindly added --reindex when indexing
713 # for the first time, allow it:
714 undef $sync->{reindex};
717 my $last_commit = _last_x_commit($self, $mm);
718 my $lx = reindex_from($sync->{reindex}, $last_commit);
719 my $range = $lx eq '' ? $tip : "$lx..$tip";
720 $pr->("counting changes\n\t$range ... ") if $pr;
721 my $stk = prepare_stack($self, $sync, $range);
722 $sync->{ntodo} = $stk ? $stk->num_records : 0;
723 $pr->("$sync->{ntodo}\n") if $pr; # continue previous line
725 my $dbh = $mm->{dbh};
728 # latest_cmt may be undef
729 my $newest = $stk ? $stk->{latest_cmt} : undef;
731 my $cur = $mm->last_commit || '';
732 if (need_update($self, $cur, $newest)) {
733 $mm->last_commit($newest);
737 if ($newest && need_xapian($self)) {
738 my $cur = $xdb->get_metadata('last_commit');
739 if (need_update($self, $cur, $newest)) {
740 $xdb->set_metadata('last_commit', $newest);
744 $self->{over}->rethread_done($opts) if $newest; # all done
745 $self->commit_txn_lazy;
747 $xdb = idx_release($self, $nr);
748 # let another process do some work...
749 $pr->("indexed $nr/$sync->{ntodo}\n") if $pr && $nr;
750 if (!$stk) { # more to come
751 $xdb = $self->begin_txn_lazy;
757 process_stack($self, $stk, $sync, $batch_cb);
761 # order matters for unlocking
762 $_[0]->{xdb} = undef;
763 $_[0]->{lockfh} = undef;
766 # remote_* subs are only used by SearchIdxPart
769 if (my $w = $self->{w}) {
770 print $w "commit\n" or die "failed to write commit: $!";
772 $self->commit_txn_lazy;
778 if (my $w = delete $self->{w}) {
779 my $pid = delete $self->{pid} or die "no process to wait on\n";
780 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
781 close $w or die "failed to close pipe for pid:$pid: $!\n";
782 waitpid($pid, 0) == $pid or die "remote process did not finish";
783 $? == 0 or die ref($self)." pid:$pid exited with: $?";
785 die "transaction in progress $self\n" if $self->{txn};
786 idx_release($self) if $self->{xdb};
791 my ($self, $oid, $num) = @_;
792 if (my $w = $self->{w}) {
793 # triggers remove_by_oid in a shard
794 print $w "D $oid $num\n" or die "failed to write remove $!";
796 $self->remove_by_oid($oid, $num);
802 my $xdb = $self->{xdb} || idx_acquire($self);
803 $self->{over}->begin_lazy if $self->{over};
804 $xdb->begin_transaction if $xdb;
811 $self->{ibx}->with_umask(\&_begin_txn, $self) if !$self->{txn};
814 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
815 # This metadata is read by Admin::detect_indexlevel:
819 if (!$self->{shard} && # undef or 0, not >0
820 delete($self->{-set_indexlevel_once})) {
821 my $xdb = $self->{xdb};
822 my $level = $xdb->get_metadata('indexlevel');
823 if (!$level || $level ne 'medium') {
824 $xdb->set_metadata('indexlevel', 'medium');
831 if (my $xdb = $self->{xdb}) {
832 set_indexlevel($self);
833 $xdb->commit_transaction;
835 $self->{over}->commit_lazy if $self->{over};
838 sub commit_txn_lazy {
840 delete($self->{txn}) and
841 $self->{ibx}->with_umask(\&_commit_txn, $self);
846 if (need_xapian($self)) {
847 die "$$ $0 xdb not released\n" if $self->{xdb};
849 die "$$ $0 still in transaction\n" if $self->{txn};