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 base qw(PublicInbox::Search PublicInbox::Lock);
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw/mid_clean mid_mime mids_for_index/;
16 use PublicInbox::MsgIter;
18 use POSIX qw(strftime);
19 use PublicInbox::OverIdx;
20 use PublicInbox::Spawn qw(spawn);
21 use PublicInbox::Git qw(git_unquote);
22 use PublicInbox::MsgTime qw(msg_timestamp msg_datestamp);
23 my $X = \%PublicInbox::Search::X;
24 my ($DB_CREATE_OR_OPEN, $DB_OPEN);
25 our $BATCH_BYTES = defined($ENV{XAPIAN_FLUSH_THRESHOLD}) ?
26 0x7fffffff : 1_000_000;
27 use constant DEBUG => !!$ENV{DEBUG};
29 my $xapianlevels = qr/\A(?:full|medium)\z/;
32 my ($class, $ibx, $creat, $shard) = @_;
33 ref $ibx or die "BUG: expected PublicInbox::Inbox object: $ibx";
34 my $levels = qr/\A(?:full|medium|basic)\z/;
35 my $inboxdir = $ibx->{inboxdir};
36 my $version = $ibx->version;
37 my $indexlevel = 'full';
38 my $altid = $ibx->{altid};
40 require PublicInbox::AltId;
41 $altid = [ map { PublicInbox::AltId->new($ibx, $_); } @$altid ];
43 if ($ibx->{indexlevel}) {
44 if ($ibx->{indexlevel} =~ $levels) {
45 $indexlevel = $ibx->{indexlevel};
47 die("Invalid indexlevel $ibx->{indexlevel}\n");
50 $ibx = PublicInbox::InboxWritable->new($ibx);
52 inboxdir => $inboxdir,
57 indexlevel => $indexlevel,
59 $self->{-set_indexlevel_once} = 1 if $indexlevel eq 'medium';
62 $self->{lock_path} = "$inboxdir/ssoma.lock";
63 my $dir = $self->xdir;
64 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
65 $self->{index_max_size} = $ibx->{index_max_size};
66 } elsif ($version == 2) {
67 defined $shard or die "shard is required for v2\n";
69 $self->{shard} = $shard;
70 $self->{lock_path} = undef;
72 die "unsupported inbox version=$version\n";
74 $self->{creat} = ($creat || 0) == 1;
78 sub need_xapian ($) { $_[0]->{indexlevel} =~ $xapianlevels }
81 my ($self, $wake) = @_;
82 if (need_xapian($self)) {
83 my $xdb = delete $self->{xdb} or croak 'not acquired';
86 $self->lock_release($wake) if $self->{creat};
90 sub load_xapian_writable () {
91 return 1 if $X->{WritableDatabase};
92 PublicInbox::Search::load_xapian() or return;
93 my $xap = $PublicInbox::Search::Xap;
94 for (qw(Document TermGenerator WritableDatabase)) {
95 $X->{$_} = $xap.'::'.$_;
97 eval 'require '.$X->{WritableDatabase} or die;
98 *sortable_serialise = $xap.'::sortable_serialise';
99 $DB_CREATE_OR_OPEN = eval($xap.'::DB_CREATE_OR_OPEN()');
100 $DB_OPEN = eval($xap.'::DB_OPEN()');
107 my $dir = $self->xdir;
108 if (need_xapian($self)) {
109 croak 'already acquired' if $self->{xdb};
110 load_xapian_writable();
111 $flag = $self->{creat} ? $DB_CREATE_OR_OPEN : $DB_OPEN;
113 if ($self->{creat}) {
117 # don't create empty Xapian directories if we don't need Xapian
118 my $is_shard = defined($self->{shard});
119 if (!$is_shard || ($is_shard && need_xapian($self))) {
120 File::Path::mkpath($dir);
123 return unless defined $flag;
124 my $xdb = eval { ($X->{WritableDatabase})->new($dir, $flag) };
126 die "Failed opening $dir: ", $@;
132 my ($doc, $col, $num) = @_;
133 $num = sortable_serialise($num);
134 $doc->add_value($col, $num);
137 sub term_generator ($) { # write-only
140 $self->{term_generator} //= do {
141 my $tg = $X->{TermGenerator}->new;
142 $tg->set_stemmer($self->stemmer);
147 sub index_text ($$$$) {
148 my ($self, $text, $wdf_inc, $prefix) = @_;
149 my $tg = term_generator($self); # man Search::Xapian::TermGenerator
151 if ($self->{indexlevel} eq 'full') {
152 $tg->index_text($text, $wdf_inc, $prefix);
153 $tg->increase_termpos;
155 $tg->index_text_without_positions($text, $wdf_inc, $prefix);
159 sub index_headers ($$) {
160 my ($self, $smsg) = @_;
161 my @x = (from => 'A', # Author
162 subject => 'S', to => 'XTO', cc => 'XCC');
163 while (my ($field, $pfx) = splice(@x, 0, 2)) {
164 my $val = $smsg->{$field};
165 index_text($self, $val, 1, $pfx) if $val ne '';
169 sub index_diff_inc ($$$$) {
170 my ($self, $text, $pfx, $xnq) = @_;
172 index_text($self, join("\n", @$xnq), 1, 'XNQ');
175 index_text($self, $text, 1, $pfx);
178 sub index_old_diff_fn {
179 my ($self, $seen, $fa, $fb, $xnq) = @_;
181 # no renames or space support for traditional diffs,
182 # find the number of leading common paths to strip:
183 my @fa = split('/', $fa);
184 my @fb = split('/', $fb);
185 while (scalar(@fa) && scalar(@fb)) {
186 $fa = join('/', @fa);
187 $fb = join('/', @fb);
189 unless ($seen->{$fa}++) {
190 index_diff_inc($self, $fa, 'XDFN', $xnq);
200 sub index_diff ($$$) {
201 my ($self, $txt, $doc) = @_;
206 foreach (split(/\n/, $txt)) {
207 if ($in_diff && s/^ //) { # diff context
208 index_diff_inc($self, $_, 'XDFCTX', $xnq);
209 } elsif (/^-- $/) { # email signature begins
211 } elsif (m!^diff --git "?[^/]+/.+ "?[^/]+/.+\z!) {
212 # wait until "---" and "+++" to capture filenames
215 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
216 my ($opt, $fa, $fb) = ($1, $2, $3);
218 # only support unified:
219 next unless $opt =~ /[uU]/;
220 $in_diff = index_old_diff_fn($self, \%seen, $fa, $fb,
222 } elsif (m!^--- ("?[^/]+/.+)!) {
224 $fn = (split('/', git_unquote($fn), 2))[1];
225 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
227 } elsif (m!^\+\+\+ ("?[^/]+/.+)!) {
229 $fn = (split('/', git_unquote($fn), 2))[1];
230 $seen{$fn}++ or index_diff_inc($self, $fn, 'XDFN', $xnq);
232 } elsif (/^--- (\S+)/) {
235 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
236 $in_diff = index_old_diff_fn($self, \%seen, $in_diff,
238 } elsif ($in_diff && s/^\+//) { # diff added
239 index_diff_inc($self, $_, 'XDFB', $xnq);
240 } elsif ($in_diff && s/^-//) { # diff removed
241 index_diff_inc($self, $_, 'XDFA', $xnq);
242 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
243 my ($ba, $bb) = ($1, $2);
244 index_git_blob_id($doc, 'XDFPRE', $ba);
245 index_git_blob_id($doc, 'XDFPOST', $bb);
247 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
248 # traditional diff w/o -p
249 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
250 # hunk header context
251 index_diff_inc($self, $1, 'XDFHH', $xnq);
252 # ignore the following lines:
253 } elsif (/^(?:dis)similarity index/ ||
254 /^(?:old|new) mode/ ||
255 /^(?:deleted|new) file mode/ ||
256 /^(?:copy|rename) (?:from|to) / ||
257 /^(?:dis)?similarity index / ||
258 /^\\ No newline at end of file/ ||
259 /^Binary files .* differ/) {
262 # possible to be in diff context, some mail may be
263 # stripped by MUA or even GNU diff(1). "git apply"
264 # treats a bare "\n" as diff context, too
267 warn "non-diff line: $_\n" if DEBUG && $_ ne '';
272 index_text($self, join("\n", @xnq), 1, 'XNQ');
275 sub index_xapian { # msg_iter callback
276 my $part = $_[0]->[0]; # ignore $depth and $idx
277 my ($self, $doc) = @{$_[1]};
278 my $ct = $part->content_type || 'text/plain';
279 my $fn = $part->filename;
280 if (defined $fn && $fn ne '') {
281 index_text($self, $fn, 1, 'XFN');
283 if ($part->{is_submsg}) {
284 my $mids = mids_for_index($part);
285 index_ids($self, $doc, $part, $mids);
286 my $smsg = bless {}, 'PublicInbox::Smsg';
287 $smsg->populate($part);
288 index_headers($self, $smsg);
291 my ($s, undef) = msg_part_text($part, $ct);
292 defined $s or return;
293 $_[0]->[0] = $part = undef; # free memory
295 # split off quoted and unquoted blocks:
296 my @sections = PublicInbox::MsgIter::split_quotes($s);
297 undef $s; # free memory
298 for my $txt (@sections) {
300 index_text($self, $txt, 0, 'XQUOT');
302 # does it look like a diff?
303 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
304 index_diff($self, $txt, $doc);
306 index_text($self, $txt, 1, 'XNQ');
309 undef $txt; # free memory
313 sub index_ids ($$$$) {
314 my ($self, $doc, $hdr, $mids) = @_;
315 for my $mid (@$mids) {
316 index_text($self, $mid, 1, 'XM');
318 # because too many Message-IDs are prefixed with
320 if ($mid =~ /\w{12,}/) {
321 my @long = ($mid =~ /(\w{3,}+)/g);
322 index_text($self, join(' ', @long), 1, 'XM');
325 $doc->add_boolean_term('Q' . $_) for @$mids;
326 for my $l ($hdr->header_raw('List-Id')) {
327 $l =~ /<([^>]+)>/ or next;
329 $doc->add_boolean_term('G' . $lid);
330 index_text($self, $lid, 1, 'XL'); # probabilistic
334 sub add_xapian ($$$$) {
335 my ($self, $mime, $smsg, $mids) = @_;
336 my $hdr = $mime->header_obj;
337 my $doc = $X->{Document}->new;
338 add_val($doc, PublicInbox::Search::TS(), $smsg->{ts});
339 my @ds = gmtime($smsg->{ds});
340 my $yyyymmdd = strftime('%Y%m%d', @ds);
341 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
342 my $dt = strftime('%Y%m%d%H%M%S', @ds);
343 add_val($doc, PublicInbox::Search::DT(), $dt);
344 add_val($doc, PublicInbox::Search::BYTES(), $smsg->{bytes});
345 add_val($doc, PublicInbox::Search::UID(), $smsg->{num});
347 my $tg = term_generator($self);
348 $tg->set_document($doc);
349 index_headers($self, $smsg);
351 msg_iter($mime, \&index_xapian, [ $self, $doc ]);
352 index_ids($self, $doc, $hdr, $mids);
353 $smsg->{to} = $smsg->{cc} = ''; # WWW doesn't need these, only NNTP
354 PublicInbox::OverIdx::parse_references($smsg, $hdr, $mids);
355 my $data = $smsg->to_doc_data;
356 $doc->set_data($data);
357 if (my $altid = $self->{-altid}) {
358 foreach my $alt (@$altid) {
359 my $pfx = $alt->{xprefix};
360 foreach my $mid (@$mids) {
361 my $id = $alt->mid2alt($mid);
362 next unless defined $id;
363 $doc->add_boolean_term($pfx . $id);
367 $self->{xdb}->replace_document($smsg->{num}, $doc);
370 sub _msgmap_init ($) {
372 die "BUG: _msgmap_init is only for v1\n" if $self->{ibx_ver} != 1;
373 $self->{mm} //= eval {
374 require PublicInbox::Msgmap;
375 PublicInbox::Msgmap->new($self->{inboxdir}, 1);
380 # mime = PublicInbox::Eml or Email::MIME object
381 my ($self, $mime, $smsg, $sync) = @_;
382 my $hdr = $mime->header_obj;
383 my $mids = mids_for_index($hdr);
384 $smsg //= bless { blob => '' }, 'PublicInbox::Smsg'; # test-only compat
385 $smsg->{mid} //= $mids->[0]; # v1 compatibility
386 $smsg->{num} //= do { # v1
388 index_mm($self, $mime);
392 $smsg->populate($hdr, $sync);
393 $smsg->{bytes} //= length($mime->as_string);
396 # order matters, overview stores every possible piece of
397 # data in doc_data (deflated). Xapian only stores a subset
398 # of the fields which exist in over.sqlite3. We may stop
399 # storing doc_data in Xapian sometime after we get multi-inbox
401 if (my $over = $self->{over}) { # v1 only
402 $over->add_overview($mime, $smsg);
404 if (need_xapian($self)) {
405 add_xapian($self, $mime, $smsg, $mids);
410 warn "failed to index message <".join('> <',@$mids).">: $@\n";
416 # returns begin and end PostingIterator
418 my ($self, $termval) = @_;
419 my $db = $self->{xdb};
421 ($db->postlist_begin($termval), $db->postlist_end($termval));
426 my ($self, $termval, $cb) = @_;
427 my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
429 my ($head, $tail) = $self->find_doc_ids($termval);
430 return if $head == $tail;
432 for (; $head != $tail && @ids < $batch_size; $head++) {
433 push @ids, $head->get_docid;
439 # v1 only, where $mid is unique
441 my ($self, $mid) = @_;
442 $mid = mid_clean($mid);
444 if (my $over = $self->{over}) {
445 my $nr = eval { $over->remove_oid(undef, $mid) };
447 warn "failed to remove <$mid> from overview: $@\n";
449 warn "<$mid> missing for removal from overview\n";
452 return unless need_xapian($self);
453 my $db = $self->{xdb};
456 batch_do($self, 'Q' . $mid, sub {
458 $db->delete_document($_) for @$ids;
463 warn "failed to remove <$mid> from Xapian: $@\n";
465 warn "<$mid> missing for removal from Xapian\n";
469 # MID is a hint in V2
471 my ($self, $oid, $mid) = @_;
473 $self->{over}->remove_oid($oid, $mid) if $self->{over};
475 return unless need_xapian($self);
476 my $db = $self->{xdb};
478 # XXX careful, we cannot use batch_do here since we conditionally
479 # delete documents based on other factors, so we cannot call
480 # find_doc_ids twice.
481 my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
482 return if $head == $tail;
484 # there is only ONE element in @delete unless we
485 # have bugs in our v2writable deduplication check
487 for (; $head != $tail; $head++) {
488 my $docid = $head->get_docid;
489 my $doc = $db->get_document($docid);
490 my $smsg = bless { mid => $mid }, 'PublicInbox::Smsg';
491 $smsg->load_expand($doc);
492 if ($smsg->{blob} eq $oid) {
493 push(@delete, $docid);
496 $db->delete_document($_) foreach @delete;
500 sub index_git_blob_id {
501 my ($doc, $pfx, $objid) = @_;
503 my $len = length($objid);
504 for (my $len = length($objid); $len >= 7; ) {
505 $doc->add_term($pfx.$objid);
506 $objid = substr($objid, 0, --$len);
511 my ($self, $mime) = @_;
512 my $mid = eval { mid_mime($mime) };
513 $self->remove_message($mid) if defined $mid;
517 my ($self, $mime) = @_;
518 my $mid = mid_mime($mime);
519 my $mm = $self->{mm};
522 if (defined $self->{regen_down}) {
523 $num = $mm->num_for($mid) and return $num;
525 while (($num = $self->{regen_down}--) > 0) {
526 if ($mm->mid_set($num, $mid) != 0) {
530 } elsif (defined $self->{regen_up}) {
531 $num = $mm->num_for($mid) and return $num;
533 # this is to fixup old bugs due to add-remove-add
534 while (($num = ++$self->{regen_up})) {
535 if ($mm->mid_set($num, $mid) != 0) {
541 $num = $mm->mid_insert($mid) and return $num;
543 # fallback to num_for since filters like RubyLang set the number
548 my ($self, $mime) = @_;
549 $self->{mm}->mid_delete(mid_mime($mime));
552 # returns the number of bytes to add if given a non-CRLF arg
553 sub crlf_adjust ($) {
554 if (index($_[0], "\r\n") < 0) {
555 # common case is LF-only, every \n needs an \r;
556 # so favor a cheap tr// over an expensive m//g
558 } else { # count number of '\n' w/o '\r', expensive:
559 scalar(my @n = ($_[0] =~ m/(?<!\r)\n/g));
563 sub index_both { # git->cat_async callback
564 my ($bref, $oid, $type, $size, $sync) = @_;
565 my ($nr, $max) = @$sync{qw(nr max)};
568 $size += crlf_adjust($$bref);
569 my $smsg = bless { bytes => $size, blob => $oid }, 'PublicInbox::Smsg';
570 my $self = $sync->{sidx};
571 my $eml = PublicInbox::Eml->new($bref);
572 my $num = index_mm($self, $eml);
574 add_message($self, $eml, $smsg, $sync);
577 sub unindex_both { # git->cat_async callback
578 my ($bref, $oid, $type, $size, $self) = @_;
579 my $eml = PublicInbox::Eml->new($bref);
580 unindex_blob($self, $eml);
581 unindex_mm($self, $eml);
584 # called by public-inbox-index
586 my ($self, $opts) = @_;
587 delete $self->{lock_path} if $opts->{-skip_lock};
588 $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
592 my ($self, $git, $oid) = @_;
593 my $max_size = $self->{index_max_size} or return;
594 my (undef, undef, $size) = $git->check($oid);
595 die "E: bad $oid in $git->{git_dir}\n" if !defined($size);
596 return if $size <= $max_size;
597 warn "W: skipping $oid ($size > $max_size)\n";
603 my ($self, $log, $batch_cb) = @_;
604 my $hex = '[a-f0-9]';
605 my $h40 = $hex .'{40}';
606 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
607 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
608 my $git = $self->{git};
610 my $max = $BATCH_BYTES;
616 my $sync = { sidx => $self, nr => \$nr, max => \$max };
617 while (defined($line = <$log>)) {
618 if ($line =~ /$addmsg/o) {
620 if (delete $D{$blob}) {
621 # make sure pending index writes are done
622 # before writing to ->mm
623 $git->cat_async_wait;
625 if (defined $self->{regen_down}) {
626 my $num = $self->{regen_down}--;
627 $self->{mm}->num_highwater($num);
631 next if too_big($self, $git, $blob);
632 $git->cat_async($blob, \&index_both, { %$sync });
634 $git->cat_async_wait;
636 $batch_cb->($nr, $latest);
638 } elsif ($line =~ /$delmsg/o) {
640 $D{$blob} = 1 unless too_big($self, $git, $blob);
641 } elsif ($line =~ /^commit ($h40)/o) {
644 } elsif ($line =~ /^author .*? ([0-9]+) [\-\+][0-9]+$/) {
645 $sync->{autime} = $1;
646 } elsif ($line =~ /^committer .*? ([0-9]+) [\-\+][0-9]+$/) {
647 $sync->{cotime} = $1;
650 close($log) or die "git log failed: \$?=$?";
652 foreach my $blob (keys %D) {
653 $git->cat_async($blob, \&unindex_both, $self);
655 $git->cat_async_wait;
656 $batch_cb->($nr, $latest, $newest);
660 my ($self, $opts, $range) = @_;
661 my $git = $self->{git};
663 if (index($range, '..') < 0) {
664 # don't show annoying git errors to users who run -index
666 $git->qx(qw(rev-parse -q --verify), "$range^0");
668 open my $fh, '<', '/dev/null' or
669 die "failed to open /dev/null: $!\n";
674 # Count the new files so they can be added newest to oldest
675 # and still have numbers increasing from oldest to newest
677 my $pr = $opts->{-progress};
678 $pr->("counting changes\n\t$range ... ") if $pr;
679 # can't use 'rev-list --count' if we use --diff-filter
680 my $fh = $git->popen(qw(log --pretty=tformat:%h
681 --no-notes --no-color --no-renames
682 --diff-filter=AM), $range);
683 ++$fcount while <$fh>;
684 close $fh or die "git log failed: \$?=$?";
685 my $high = $self->{mm}->num_highwater;
686 $pr->("$fcount\n") if $pr; # continue previous line
687 $self->{ntodo} = $fcount;
689 if (index($range, '..') < 0) {
690 if ($high && $high == $fcount) {
691 # fix up old bugs in full indexes which caused messages to
692 # not appear in Msgmap
693 $self->{regen_up} = $high;
695 # normal regen is for for fresh data
696 $self->{regen_down} = $fcount;
697 $self->{regen_down} += $high unless $opts->{reindex};
700 # Give oldest messages the smallest numbers
701 $self->{regen_down} = $high + $fcount;
704 $git->popen(qw/log --pretty=raw --no-notes --no-color --no-renames
705 --raw -r --no-abbrev/, $range);
708 # --is-ancestor requires git 1.8.0+
709 sub is_ancestor ($$$) {
710 my ($git, $cur, $tip) = @_;
711 return 0 unless $git->check($cur);
712 my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
713 qw(merge-base --is-ancestor), $cur, $tip ];
714 my $pid = spawn($cmd);
715 waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
719 sub need_update ($$$) {
720 my ($self, $cur, $new) = @_;
721 my $git = $self->{git};
722 return 1 if $cur && !is_ancestor($git, $cur, $new);
723 my $range = $cur eq '' ? $new : "$cur..$new";
724 chomp(my $n = $git->qx(qw(rev-list --count), $range));
725 ($n eq '' || $n > 0);
728 # The last git commit we indexed with Xapian or SQLite (msgmap)
729 # This needs to account for cases where Xapian or SQLite is
730 # out-of-date with respect to the other.
732 my ($self, $mm) = @_;
733 my $lm = $mm->last_commit || '';
735 if (need_xapian($self)) {
736 $lx = $self->{xdb}->get_metadata('last_commit') || '';
740 # Use last_commit from msgmap if it is older or unset
741 if (!$lm || ($lx && $lm && is_ancestor($self->{git}, $lm, $lx))) {
747 sub reindex_from ($$) {
748 my ($reindex, $last_commit) = @_;
749 return $last_commit unless $reindex;
750 ref($reindex) eq 'HASH' ? $reindex->{from} : '';
753 # indexes all unindexed messages (v1 only)
755 my ($self, $opts) = @_;
756 my $tip = $opts->{ref} || 'HEAD';
757 my ($last_commit, $lx, $xlog);
758 my $git = $self->{git};
760 my $pr = $opts->{-progress};
762 my $xdb = $self->begin_txn_lazy;
763 my $mm = _msgmap_init($self);
765 $xlog = undef; # stop previous git-log via SIGPIPE
766 $last_commit = _last_x_commit($self, $mm);
767 $lx = reindex_from($opts->{reindex}, $last_commit);
769 $self->{over}->rollback_lazy;
770 $self->{over}->disconnect;
773 $xdb->cancel_transaction if $xdb;
774 $xdb = _xdb_release($self);
776 # ensure we leak no FDs to "git log" with Xapian <= 1.2
777 my $range = $lx eq '' ? $tip : "$lx..$tip";
778 $xlog = _git_log($self, $opts, $range);
780 $xdb = $self->begin_txn_lazy;
781 } while (_last_x_commit($self, $mm) ne $last_commit);
783 my $dbh = $mm->{dbh} if $mm;
785 my ($nr, $commit, $newest) = @_;
788 my $cur = $mm->last_commit || '';
789 if (need_update($self, $cur, $newest)) {
790 $mm->last_commit($newest);
795 if ($newest && need_xapian($self)) {
796 my $cur = $xdb->get_metadata('last_commit');
797 if (need_update($self, $cur, $newest)) {
798 $xdb->set_metadata('last_commit', $newest);
801 $self->commit_txn_lazy;
803 $xdb = _xdb_release($self, $nr);
804 # let another process do some work... <
805 $pr->("indexed $nr/$self->{ntodo}\n") if $pr && $nr;
807 $xdb = $self->begin_txn_lazy;
808 $dbh->begin_work if $dbh;
813 read_log($self, $xlog, $batch_cb);
817 # order matters for unlocking
818 $_[0]->{xdb} = undef;
819 $_[0]->{lockfh} = undef;
822 # remote_* subs are only used by SearchIdxPart
825 if (my $w = $self->{w}) {
826 print $w "commit\n" or die "failed to write commit: $!";
828 $self->commit_txn_lazy;
834 if (my $w = delete $self->{w}) {
835 my $pid = delete $self->{pid} or die "no process to wait on\n";
836 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
837 close $w or die "failed to close pipe for pid:$pid: $!\n";
838 waitpid($pid, 0) == $pid or die "remote process did not finish";
839 $? == 0 or die ref($self)." pid:$pid exited with: $?";
841 die "transaction in progress $self\n" if $self->{txn};
842 $self->_xdb_release if $self->{xdb};
847 my ($self, $oid, $mid) = @_;
848 if (my $w = $self->{w}) {
849 # triggers remove_by_oid in a shard
850 print $w "D $oid $mid\n" or die "failed to write remove $!";
852 $self->begin_txn_lazy;
853 $self->remove_by_oid($oid, $mid);
859 return if $self->{txn};
861 $self->{-inbox}->with_umask(sub {
862 my $xdb = $self->{xdb} || $self->_xdb_acquire;
863 $self->{over}->begin_lazy if $self->{over};
864 $xdb->begin_transaction if $xdb;
870 # store 'indexlevel=medium' in v2 shard=0 and v1 (only one shard)
871 # This metadata is read by Admin::detect_indexlevel:
875 if (!$self->{shard} && # undef or 0, not >0
876 delete($self->{-set_indexlevel_once})) {
877 my $xdb = $self->{xdb};
878 my $level = $xdb->get_metadata('indexlevel');
879 if (!$level || $level ne 'medium') {
880 $xdb->set_metadata('indexlevel', 'medium');
885 sub commit_txn_lazy {
887 delete $self->{txn} or return;
888 $self->{-inbox}->with_umask(sub {
889 if (my $xdb = $self->{xdb}) {
890 set_indexlevel($self);
891 $xdb->commit_transaction;
893 $self->{over}->commit_lazy if $self->{over};
899 if (need_xapian($self)) {
900 die "$$ $0 xdb not released\n" if $self->{xdb};
902 die "$$ $0 still in transaction\n" if $self->{txn};