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