]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
extmsg: use Xapian only for partial matches
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015-2018 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
4 #
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;
10 use strict;
11 use warnings;
12 use base qw(PublicInbox::Search PublicInbox::Lock);
13 use PublicInbox::MIME;
14 use PublicInbox::InboxWritable;
15 use PublicInbox::MID qw/mid_clean id_compress mid_mime mids/;
16 use PublicInbox::MsgIter;
17 use Carp qw(croak);
18 use POSIX qw(strftime);
19 use PublicInbox::OverIdx;
20 use PublicInbox::Spawn qw(spawn);
21 require PublicInbox::Git;
22 use Compress::Zlib qw(compress);
23
24 use constant {
25         BATCH_BYTES => 1_000_000,
26         DEBUG => !!$ENV{DEBUG},
27 };
28
29 my %GIT_ESC = (
30         a => "\a",
31         b => "\b",
32         f => "\f",
33         n => "\n",
34         r => "\r",
35         t => "\t",
36         v => "\013",
37 );
38
39 sub git_unquote ($) {
40         my ($s) = @_;
41         return $s unless ($s =~ /\A"(.*)"\z/);
42         $s = $1;
43         $s =~ s/\\([abfnrtv])/$GIT_ESC{$1}/g;
44         $s =~ s/\\([0-7]{1,3})/chr(oct($1))/ge;
45         $s;
46 }
47
48 sub new {
49         my ($class, $ibx, $creat, $part) = @_;
50         my $mainrepo = $ibx; # for "public-inbox-index" w/o entry in config
51         my $git_dir = $mainrepo;
52         my ($altid, $git);
53         my $version = 1;
54         if (ref $ibx) {
55                 $mainrepo = $ibx->{mainrepo};
56                 $altid = $ibx->{altid};
57                 $version = $ibx->{version} || 1;
58                 if ($altid) {
59                         require PublicInbox::AltId;
60                         $altid = [ map {
61                                 PublicInbox::AltId->new($ibx, $_);
62                         } @$altid ];
63                 }
64         } else { # v1
65                 $ibx = { mainrepo => $git_dir, version => 1 };
66         }
67         $ibx = PublicInbox::InboxWritable->new($ibx);
68         require Search::Xapian::WritableDatabase;
69         my $self = bless {
70                 mainrepo => $mainrepo,
71                 -inbox => $ibx,
72                 git => $ibx->git,
73                 -altid => $altid,
74                 version => $version,
75         }, $class;
76         $ibx->umask_prepare;
77         if ($version == 1) {
78                 $self->{lock_path} = "$mainrepo/ssoma.lock";
79                 my $dir = $self->xdir;
80                 $self->{over} = PublicInbox::OverIdx->new("$dir/over.sqlite3");
81         } elsif ($version == 2) {
82                 defined $part or die "partition is required for v2\n";
83                 # partition is a number
84                 $self->{partition} = $part;
85                 $self->{lock_path} = undef;
86         } else {
87                 die "unsupported inbox version=$version\n";
88         }
89         $self->{creat} = ($creat || 0) == 1;
90         $self;
91 }
92
93 sub _xdb_release {
94         my ($self) = @_;
95         my $xdb = delete $self->{xdb} or croak 'not acquired';
96         $xdb->close;
97         $self->lock_release if $self->{creat};
98         undef;
99 }
100
101 sub _xdb_acquire {
102         my ($self) = @_;
103         croak 'already acquired' if $self->{xdb};
104         my $dir = $self->xdir;
105         my $flag = Search::Xapian::DB_OPEN;
106         if ($self->{creat}) {
107                 require File::Path;
108                 $self->lock_acquire;
109                 File::Path::mkpath($dir);
110                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
111         }
112         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
113 }
114
115 sub add_val ($$$) {
116         my ($doc, $col, $num) = @_;
117         $num = Search::Xapian::sortable_serialise($num);
118         $doc->add_value($col, $num);
119 }
120
121 sub index_users ($$) {
122         my ($tg, $smsg) = @_;
123
124         my $from = $smsg->from;
125         my $to = $smsg->to;
126         my $cc = $smsg->cc;
127
128         $tg->index_text($from, 1, 'A'); # A - author
129         $tg->increase_termpos;
130         $tg->index_text($to, 1, 'XTO') if $to ne '';
131         $tg->increase_termpos;
132         $tg->index_text($cc, 1, 'XCC') if $cc ne '';
133         $tg->increase_termpos;
134 }
135
136 sub index_diff_inc ($$$$) {
137         my ($tg, $text, $pfx, $xnq) = @_;
138         if (@$xnq) {
139                 $tg->index_text(join("\n", @$xnq), 1, 'XNQ');
140                 $tg->increase_termpos;
141                 @$xnq = ();
142         }
143         $tg->index_text($text, 1, $pfx);
144         $tg->increase_termpos;
145 }
146
147 sub index_old_diff_fn {
148         my ($tg, $seen, $fa, $fb, $xnq) = @_;
149
150         # no renames or space support for traditional diffs,
151         # find the number of leading common paths to strip:
152         my @fa = split('/', $fa);
153         my @fb = split('/', $fb);
154         while (scalar(@fa) && scalar(@fb)) {
155                 $fa = join('/', @fa);
156                 $fb = join('/', @fb);
157                 if ($fa eq $fb) {
158                         unless ($seen->{$fa}++) {
159                                 index_diff_inc($tg, $fa, 'XDFN', $xnq);
160                         }
161                         return 1;
162                 }
163                 shift @fa;
164                 shift @fb;
165         }
166         0;
167 }
168
169 sub index_diff ($$$) {
170         my ($tg, $lines, $doc) = @_;
171         my %seen;
172         my $in_diff;
173         my @xnq;
174         my $xnq = \@xnq;
175         foreach (@$lines) {
176                 if ($in_diff && s/^ //) { # diff context
177                         index_diff_inc($tg, $_, 'XDFCTX', $xnq);
178                 } elsif (/^-- $/) { # email signature begins
179                         $in_diff = undef;
180                 } elsif (m!^diff --git ("?a/.+) ("?b/.+)\z!) {
181                         my ($fa, $fb) = ($1, $2);
182                         my $fn = (split('/', git_unquote($fa), 2))[1];
183                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
184                         $fn = (split('/', git_unquote($fb), 2))[1];
185                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
186                         $in_diff = 1;
187                 # traditional diff:
188                 } elsif (m/^diff -(.+) (\S+) (\S+)$/) {
189                         my ($opt, $fa, $fb) = ($1, $2, $3);
190                         push @xnq, $_;
191                         # only support unified:
192                         next unless $opt =~ /[uU]/;
193                         $in_diff = index_old_diff_fn($tg, \%seen, $fa, $fb,
194                                                         $xnq);
195                 } elsif (m!^--- ("?a/.+)!) {
196                         my $fn = (split('/', git_unquote($1), 2))[1];
197                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
198                         $in_diff = 1;
199                 } elsif (m!^\+\+\+ ("?b/.+)!)  {
200                         my $fn = (split('/', git_unquote($1), 2))[1];
201                         $seen{$fn}++ or index_diff_inc($tg, $fn, 'XDFN', $xnq);
202                         $in_diff = 1;
203                 } elsif (/^--- (\S+)/) {
204                         $in_diff = $1;
205                         push @xnq, $_;
206                 } elsif (defined $in_diff && /^\+\+\+ (\S+)/) {
207                         $in_diff = index_old_diff_fn($tg, \%seen, $in_diff, $1,
208                                                         $xnq);
209                 } elsif ($in_diff && s/^\+//) { # diff added
210                         index_diff_inc($tg, $_, 'XDFB', $xnq);
211                 } elsif ($in_diff && s/^-//) { # diff removed
212                         index_diff_inc($tg, $_, 'XDFA', $xnq);
213                 } elsif (m!^index ([a-f0-9]+)\.\.([a-f0-9]+)!) {
214                         my ($ba, $bb) = ($1, $2);
215                         index_git_blob_id($doc, 'XDFPRE', $ba);
216                         index_git_blob_id($doc, 'XDFPOST', $bb);
217                         $in_diff = 1;
218                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*$/) {
219                         # traditional diff w/o -p
220                 } elsif (/^@@ (?:\S+) (?:\S+) @@\s*(\S+.*)$/) {
221                         # hunk header context
222                         index_diff_inc($tg, $1, 'XDFHH', $xnq);
223                 # ignore the following lines:
224                 } elsif (/^(?:dis)similarity index/ ||
225                                 /^(?:old|new) mode/ ||
226                                 /^(?:deleted|new) file mode/ ||
227                                 /^(?:copy|rename) (?:from|to) / ||
228                                 /^(?:dis)?similarity index / ||
229                                 /^\\ No newline at end of file/ ||
230                                 /^Binary files .* differ/) {
231                         push @xnq, $_;
232                 } elsif ($_ eq '') {
233                         $in_diff = undef;
234                 } else {
235                         push @xnq, $_;
236                         warn "non-diff line: $_\n" if DEBUG && $_ ne '';
237                         $in_diff = undef;
238                 }
239         }
240
241         $tg->index_text(join("\n", @xnq), 1, 'XNQ');
242         $tg->increase_termpos;
243 }
244
245 sub index_body ($$$) {
246         my ($tg, $lines, $doc) = @_;
247         my $txt = join("\n", @$lines);
248         if ($doc) {
249                 # does it look like a diff?
250                 if ($txt =~ /^(?:diff|---|\+\+\+) /ms) {
251                         $txt = undef;
252                         index_diff($tg, $lines, $doc);
253                 } else {
254                         $tg->index_text($txt, 1, 'XNQ');
255                 }
256         } else {
257                 $tg->index_text($txt, 0, 'XQUOT');
258         }
259         $tg->increase_termpos;
260         @$lines = ();
261 }
262
263 sub add_message {
264         # mime = Email::MIME object
265         my ($self, $mime, $bytes, $num, $oid, $mid0) = @_;
266         my $doc_id;
267         my $mids = mids($mime->header_obj);
268         $mid0 = $mids->[0] unless defined $mid0; # v1 compatibility
269         unless (defined $num) { # v1
270                 $self->_msgmap_init;
271                 $num = index_mm($self, $mime);
272         }
273         eval {
274                 my $smsg = PublicInbox::SearchMsg->new($mime);
275                 my $doc = $smsg->{doc};
276                 my $subj = $smsg->subject;
277                 add_val($doc, PublicInbox::Search::TS(), $smsg->ts);
278                 my @ds = gmtime($smsg->ds);
279                 my $yyyymmdd = strftime('%Y%m%d', @ds);
280                 add_val($doc, PublicInbox::Search::YYYYMMDD(), $yyyymmdd);
281                 my $dt = strftime('%Y%m%d%H%M%S', @ds);
282                 add_val($doc, PublicInbox::Search::DT(), $dt);
283
284                 my $tg = $self->term_generator;
285
286                 $tg->set_document($doc);
287                 $tg->index_text($subj, 1, 'S') if $subj;
288                 $tg->increase_termpos;
289
290                 index_users($tg, $smsg);
291
292                 msg_iter($mime, sub {
293                         my ($part, $depth, @idx) = @{$_[0]};
294                         my $ct = $part->content_type || 'text/plain';
295                         my $fn = $part->filename;
296                         if (defined $fn && $fn ne '') {
297                                 $tg->index_text($fn, 1, 'XFN');
298                                 $tg->increase_termpos;
299                         }
300
301                         return if $ct =~ m!\btext/x?html\b!i;
302
303                         my $s = eval { $part->body_str };
304                         if ($@) {
305                                 if ($ct =~ m!\btext/plain\b!i) {
306                                         # Try to assume UTF-8 because Alpine
307                                         # seems to do wacky things and set
308                                         # charset=X-UNKNOWN
309                                         $part->charset_set('UTF-8');
310                                         $s = eval { $part->body_str };
311                                         $s = $part->body if $@;
312                                 }
313                         }
314                         defined $s or return;
315
316                         my (@orig, @quot);
317                         my $body = $part->body;
318                         my @lines = split(/\n/, $body);
319                         while (defined(my $l = shift @lines)) {
320                                 if ($l =~ /^>/) {
321                                         index_body($tg, \@orig, $doc) if @orig;
322                                         push @quot, $l;
323                                 } else {
324                                         index_body($tg, \@quot, 0) if @quot;
325                                         push @orig, $l;
326                                 }
327                         }
328                         index_body($tg, \@quot, 0) if @quot;
329                         index_body($tg, \@orig, $doc) if @orig;
330                 });
331
332                 foreach my $mid (@$mids) {
333                         $tg->index_text($mid, 1, 'XM');
334
335                         # because too many Message-IDs are prefixed with
336                         # "Pine.LNX."...
337                         if ($mid =~ /\w{12,}/) {
338                                 my @long = ($mid =~ /(\w{3,}+)/g);
339                                 $tg->index_text(join(' ', @long), 1, 'XM');
340                         }
341                         $tg->increase_termpos;
342                 }
343                 $smsg->{to} = $smsg->{cc} = '';
344                 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
345                 my $data = $smsg->to_doc_data($oid, $mid0);
346                 $doc->set_data($data);
347                 if (my $altid = $self->{-altid}) {
348                         foreach my $alt (@$altid) {
349                                 my $pfx = $alt->{xprefix};
350                                 foreach my $mid (@$mids) {
351                                         my $id = $alt->mid2alt($mid);
352                                         next unless defined $id;
353                                         $doc->add_boolean_term($pfx . $id);
354                                 }
355                         }
356                 }
357
358                 if (my $over = $self->{over}) {
359                         $over->add_overview($mime, $bytes, $num, $oid, $mid0);
360                 }
361                 $doc->add_boolean_term('Q' . $_) foreach @$mids;
362                 $self->{xdb}->replace_document($doc_id = $num, $doc);
363         };
364
365         if ($@) {
366                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
367                 return undef;
368         }
369         $doc_id;
370 }
371
372 # returns begin and end PostingIterator
373 sub find_doc_ids {
374         my ($self, $termval) = @_;
375         my $db = $self->{xdb};
376
377         ($db->postlist_begin($termval), $db->postlist_end($termval));
378 }
379
380 sub batch_do {
381         my ($self, $termval, $cb) = @_;
382         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
383         while (1) {
384                 my ($head, $tail) = $self->find_doc_ids($termval);
385                 return if $head == $tail;
386                 my @ids;
387                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
388                         push @ids, $head->get_docid;
389                 }
390                 $cb->(\@ids);
391         }
392 }
393
394 sub remove_message {
395         my ($self, $mid) = @_;
396         my $db = $self->{xdb};
397         my $called;
398         $mid = mid_clean($mid);
399         my $over = $self->{over};
400
401         eval {
402                 batch_do($self, 'Q' . $mid, sub {
403                         my ($ids) = @_;
404                         $db->delete_document($_) for @$ids;
405                         $over->delete_articles($ids) if $over;
406                         $called = 1;
407                 });
408         };
409         if ($@) {
410                 warn "failed to remove message <$mid>: $@\n";
411         } elsif (!$called) {
412                 warn "cannot remove non-existent <$mid>\n";
413         }
414 }
415
416 # MID is a hint in V2
417 sub remove_by_oid {
418         my ($self, $oid, $mid) = @_;
419         my $db = $self->{xdb};
420
421         $self->{over}->remove_oid($oid, $mid) if $self->{over};
422
423         # XXX careful, we cannot use batch_do here since we conditionally
424         # delete documents based on other factors, so we cannot call
425         # find_doc_ids twice.
426         my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
427         return if $head == $tail;
428
429         # there is only ONE element in @delete unless we
430         # have bugs in our v2writable deduplication check
431         my @delete;
432         for (; $head != $tail; $head->inc) {
433                 my $docid = $head->get_docid;
434                 my $doc = $db->get_document($docid);
435                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
436                 $smsg->load_expand;
437                 if ($smsg->{blob} eq $oid) {
438                         push(@delete, $docid);
439                 }
440         }
441         $db->delete_document($_) foreach @delete;
442         scalar(@delete);
443 }
444
445 sub term_generator { # write-only
446         my ($self) = @_;
447
448         my $tg = $self->{term_generator};
449         return $tg if $tg;
450
451         $tg = Search::Xapian::TermGenerator->new;
452         $tg->set_stemmer($self->stemmer);
453
454         $self->{term_generator} = $tg;
455 }
456
457 sub index_git_blob_id {
458         my ($doc, $pfx, $objid) = @_;
459
460         my $len = length($objid);
461         for (my $len = length($objid); $len >= 7; ) {
462                 $doc->add_term($pfx.$objid);
463                 $objid = substr($objid, 0, --$len);
464         }
465 }
466
467 sub unindex_blob {
468         my ($self, $mime) = @_;
469         my $mid = eval { mid_clean(mid_mime($mime)) };
470         $self->remove_message($mid) if defined $mid;
471 }
472
473 sub index_mm {
474         my ($self, $mime) = @_;
475         my $mid = mid_clean(mid_mime($mime));
476         my $mm = $self->{mm};
477         my $num;
478
479         if (defined $self->{regen_down}) {
480                 $num = $mm->num_for($mid) and return $num;
481
482                 while (($num = $self->{regen_down}--) > 0) {
483                         if ($mm->mid_set($num, $mid) != 0) {
484                                 return $num;
485                         }
486                 }
487         } elsif (defined $self->{regen_up}) {
488                 $num = $mm->num_for($mid) and return $num;
489
490                 # this is to fixup old bugs due to add-remove-add
491                 while (($num = ++$self->{regen_up})) {
492                         if ($mm->mid_set($num, $mid) != 0) {
493                                 return $num;
494                         }
495                 }
496         }
497
498         $num = $mm->mid_insert($mid) and return $num;
499
500         # fallback to num_for since filters like RubyLang set the number
501         $mm->num_for($mid);
502 }
503
504 sub unindex_mm {
505         my ($self, $mime) = @_;
506         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
507 }
508
509 sub index_both {
510         my ($self, $mime, $bytes, $blob) = @_;
511         my $num = index_mm($self, $mime);
512         add_message($self, $mime, $bytes, $num, $blob);
513 }
514
515 sub unindex_both {
516         my ($self, $mime) = @_;
517         unindex_blob($self, $mime);
518         unindex_mm($self, $mime);
519 }
520
521 sub do_cat_mail {
522         my ($git, $blob, $sizeref) = @_;
523         my $mime = eval {
524                 my $str = $git->cat_file($blob, $sizeref);
525                 # fixup bugs from import:
526                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
527                 PublicInbox::MIME->new($str);
528         };
529         $@ ? undef : $mime;
530 }
531
532 sub index_sync {
533         my ($self, $opts) = @_;
534         $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
535 }
536
537 sub batch_adjust ($$$$) {
538         my ($max, $bytes, $batch_cb, $latest) = @_;
539         $$max -= $bytes;
540         if ($$max <= 0) {
541                 $$max = BATCH_BYTES;
542                 $batch_cb->($latest);
543         }
544 }
545
546 # only for v1
547 sub read_log {
548         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
549         my $hex = '[a-f0-9]';
550         my $h40 = $hex .'{40}';
551         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
552         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
553         my $git = $self->{git};
554         my $latest;
555         my $bytes;
556         my $max = BATCH_BYTES;
557         local $/ = "\n";
558         my %D;
559         my $line;
560         my $newest;
561         while (defined($line = <$log>)) {
562                 if ($line =~ /$addmsg/o) {
563                         my $blob = $1;
564                         delete $D{$blob} and next;
565                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
566                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
567                         $add_cb->($self, $mime, $bytes, $blob);
568                 } elsif ($line =~ /$delmsg/o) {
569                         my $blob = $1;
570                         $D{$blob} = 1;
571                 } elsif ($line =~ /^commit ($h40)/o) {
572                         $latest = $1;
573                         $newest ||= $latest;
574                 }
575         }
576         # get the leftovers
577         foreach my $blob (keys %D) {
578                 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
579                 $del_cb->($self, $mime);
580         }
581         $batch_cb->($latest, $newest);
582 }
583
584 sub _msgmap_init {
585         my ($self) = @_;
586         die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
587         $self->{mm} ||= eval {
588                 require PublicInbox::Msgmap;
589                 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
590         };
591 }
592
593 sub _git_log {
594         my ($self, $range) = @_;
595         my $git = $self->{git};
596
597         if (index($range, '..') < 0) {
598                 my $regen_max = 0;
599                 # can't use 'rev-list --count' if we use --diff-filter
600                 my $fh = $git->popen(qw(log --pretty=tformat:%h
601                                 --no-notes --no-color --no-renames
602                                 --diff-filter=AM), $range);
603                 ++$regen_max while <$fh>;
604                 my (undef, $max) = $self->{mm}->minmax;
605
606                 if ($max && $max == $regen_max) {
607                         # fix up old bugs in full indexes which caused messages to
608                         # not appear in Msgmap
609                         $self->{regen_up} = $max;
610                 } else {
611                         # normal regen is for for fresh data
612                         $self->{regen_down} = $regen_max;
613                 }
614         }
615
616         $git->popen(qw/log --no-notes --no-color --no-renames
617                                 --raw -r --no-abbrev/, $range);
618 }
619
620 sub is_ancestor ($$$) {
621         my ($git, $cur, $tip) = @_;
622         return 0 unless $git->check($cur);
623         my $cmd = [ 'git', "--git-dir=$git->{git_dir}",
624                 qw(merge-base --is-ancestor), $cur, $tip ];
625         my $pid = spawn($cmd);
626         defined $pid or die "spawning ".join(' ', @$cmd)." failed: $!";
627         waitpid($pid, 0) == $pid or die join(' ', @$cmd) .' did not finish';
628         $? == 0;
629 }
630
631 sub need_update ($$$) {
632         my ($self, $cur, $new) = @_;
633         my $git = $self->{git};
634         return 1 if $cur && !is_ancestor($git, $cur, $new);
635         my $range = $cur eq '' ? $new : "$cur..$new";
636         chomp(my $n = $git->qx(qw(rev-list --count), $range));
637         ($n eq '' || $n > 0);
638 }
639
640 # indexes all unindexed messages (v1 only)
641 sub _index_sync {
642         my ($self, $opts) = @_;
643         my $tip = $opts->{ref} || 'HEAD';
644         my $reindex = $opts->{reindex};
645         my ($mkey, $last_commit, $lx, $xlog);
646         my $git = $self->{git};
647         $git->batch_prepare;
648
649         my $xdb = $self->begin_txn_lazy;
650         my $mm = _msgmap_init($self);
651         do {
652                 $xlog = undef;
653                 $mkey = 'last_commit';
654                 $last_commit = $xdb->get_metadata('last_commit');
655                 $lx = $last_commit;
656                 if ($reindex) {
657                         $lx = '';
658                         $mkey = undef if $last_commit ne '';
659                 }
660
661                 # use last_commit from msgmap if it is older or unset
662                 my $lm = $mm->last_commit || '';
663                 if (!$lm || ($lm && $lx && is_ancestor($git, $lm, $lx))) {
664                         $lx = $lm;
665                 }
666
667                 $self->{over}->rollback_lazy;
668                 $self->{over}->disconnect;
669                 delete $self->{txn};
670                 $xdb->cancel_transaction;
671                 $xdb = _xdb_release($self);
672
673                 # ensure we leak no FDs to "git log" with Xapian <= 1.2
674                 my $range = $lx eq '' ? $tip : "$lx..$tip";
675                 $xlog = _git_log($self, $range);
676
677                 $xdb = $self->begin_txn_lazy;
678         } while ($xdb->get_metadata('last_commit') ne $last_commit);
679
680         my $dbh = $mm->{dbh} if $mm;
681         my $cb = sub {
682                 my ($commit, $newest) = @_;
683                 if ($dbh) {
684                         if ($newest) {
685                                 my $cur = $mm->last_commit || '';
686                                 if (need_update($self, $cur, $newest)) {
687                                         $mm->last_commit($newest);
688                                 }
689                         }
690                         $dbh->commit;
691                 }
692                 if ($mkey && $newest) {
693                         my $cur = $xdb->get_metadata($mkey);
694                         if (need_update($self, $cur, $newest)) {
695                                 $xdb->set_metadata($mkey, $newest);
696                         }
697                 }
698                 $self->commit_txn_lazy;
699                 $xdb = _xdb_release($self);
700                 # let another process do some work... <
701                 if (!$newest) {
702                         $xdb = $self->begin_txn_lazy;
703                         $dbh->begin_work if $dbh;
704                 }
705         };
706
707         $dbh->begin_work;
708         read_log($self, $xlog, *index_both, *unindex_both, $cb);
709 }
710
711 sub DESTROY {
712         # order matters for unlocking
713         $_[0]->{xdb} = undef;
714         $_[0]->{lockfh} = undef;
715 }
716
717 # remote_* subs are only used by SearchIdxPart
718 sub remote_commit {
719         my ($self) = @_;
720         if (my $w = $self->{w}) {
721                 print $w "commit\n" or die "failed to write commit: $!";
722         } else {
723                 $self->commit_txn_lazy;
724         }
725 }
726
727 sub remote_close {
728         my ($self) = @_;
729         if (my $w = delete $self->{w}) {
730                 my $pid = delete $self->{pid} or die "no process to wait on\n";
731                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
732                 close $w or die "failed to close pipe for pid:$pid: $!\n";
733                 waitpid($pid, 0) == $pid or die "remote process did not finish";
734                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
735         } else {
736                 die "transaction in progress $self\n" if $self->{txn};
737                 $self->_xdb_release if $self->{xdb};
738         }
739 }
740
741 sub remote_remove {
742         my ($self, $oid, $mid) = @_;
743         if (my $w = $self->{w}) {
744                 # triggers remove_by_oid in a partition
745                 print $w "D $oid $mid\n" or die "failed to write remove $!";
746         } else {
747                 $self->begin_txn_lazy;
748                 $self->remove_by_oid($oid, $mid);
749         }
750 }
751
752 sub begin_txn_lazy {
753         my ($self) = @_;
754         return if $self->{txn};
755         my $xdb = $self->{xdb} || $self->_xdb_acquire;
756         $self->{over}->begin_lazy if $self->{over};
757         $xdb->begin_transaction;
758         $self->{txn} = 1;
759         $xdb;
760 }
761
762 sub commit_txn_lazy {
763         my ($self) = @_;
764         delete $self->{txn} or return;
765         $self->{xdb}->commit_transaction;
766         $self->{over}->commit_lazy if $self->{over};
767 }
768
769 sub worker_done {
770         my ($self) = @_;
771         die "$$ $0 xdb not released\n" if $self->{xdb};
772         die "$$ $0 still in transaction\n" if $self->{txn};
773 }
774
775 1;