]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
searchidx: regenerate and avoid article number gaps on full index
[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 => 10_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                         }
299
300                         return if $ct =~ m!\btext/x?html\b!i;
301
302                         my $s = eval { $part->body_str };
303                         if ($@) {
304                                 if ($ct =~ m!\btext/plain\b!i) {
305                                         # Try to assume UTF-8 because Alpine
306                                         # seems to do wacky things and set
307                                         # charset=X-UNKNOWN
308                                         $part->charset_set('UTF-8');
309                                         $s = eval { $part->body_str };
310                                         $s = $part->body if $@;
311                                 }
312                         }
313                         defined $s or return;
314
315                         my (@orig, @quot);
316                         my $body = $part->body;
317                         my @lines = split(/\n/, $body);
318                         while (defined(my $l = shift @lines)) {
319                                 if ($l =~ /^>/) {
320                                         index_body($tg, \@orig, $doc) if @orig;
321                                         push @quot, $l;
322                                 } else {
323                                         index_body($tg, \@quot, 0) if @quot;
324                                         push @orig, $l;
325                                 }
326                         }
327                         index_body($tg, \@quot, 0) if @quot;
328                         index_body($tg, \@orig, $doc) if @orig;
329                 });
330
331                 foreach my $mid (@$mids) {
332                         $tg->index_text($mid, 1, 'XM');
333                 }
334                 $smsg->{to} = $smsg->{cc} = '';
335                 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
336                 my $data = $smsg->to_doc_data($oid, $mid0);
337                 $doc->set_data($data);
338                 if (my $altid = $self->{-altid}) {
339                         foreach my $alt (@$altid) {
340                                 my $pfx = $alt->{xprefix};
341                                 foreach my $mid (@$mids) {
342                                         my $id = $alt->mid2alt($mid);
343                                         next unless defined $id;
344                                         $doc->add_boolean_term($pfx . $id);
345                                 }
346                         }
347                 }
348
349                 if (my $over = $self->{over}) {
350                         $over->add_overview($mime, $bytes, $num, $oid, $mid0);
351                 }
352                 $doc->add_boolean_term('Q' . $_) foreach @$mids;
353                 $self->{xdb}->replace_document($doc_id = $num, $doc);
354         };
355
356         if ($@) {
357                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
358                 return undef;
359         }
360         $doc_id;
361 }
362
363 # returns begin and end PostingIterator
364 sub find_doc_ids {
365         my ($self, $termval) = @_;
366         my $db = $self->{xdb};
367
368         ($db->postlist_begin($termval), $db->postlist_end($termval));
369 }
370
371 sub batch_do {
372         my ($self, $termval, $cb) = @_;
373         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
374         while (1) {
375                 my ($head, $tail) = $self->find_doc_ids($termval);
376                 return if $head == $tail;
377                 my @ids;
378                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
379                         push @ids, $head->get_docid;
380                 }
381                 $cb->(\@ids);
382         }
383 }
384
385 sub remove_message {
386         my ($self, $mid) = @_;
387         my $db = $self->{xdb};
388         my $called;
389         $mid = mid_clean($mid);
390         my $over = $self->{over};
391
392         eval {
393                 batch_do($self, 'Q' . $mid, sub {
394                         my ($ids) = @_;
395                         $db->delete_document($_) for @$ids;
396                         $over->delete_articles($ids) if $over;
397                         $called = 1;
398                 });
399         };
400         if ($@) {
401                 warn "failed to remove message <$mid>: $@\n";
402         } elsif (!$called) {
403                 warn "cannot remove non-existent <$mid>\n";
404         }
405 }
406
407 # MID is a hint in V2
408 sub remove_by_oid {
409         my ($self, $oid, $mid) = @_;
410         my $db = $self->{xdb};
411
412         $self->{over}->remove_oid($oid, $mid) if $self->{over};
413
414         # XXX careful, we cannot use batch_do here since we conditionally
415         # delete documents based on other factors, so we cannot call
416         # find_doc_ids twice.
417         my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
418         return if $head == $tail;
419
420         # there is only ONE element in @delete unless we
421         # have bugs in our v2writable deduplication check
422         my @delete;
423         for (; $head != $tail; $head->inc) {
424                 my $docid = $head->get_docid;
425                 my $doc = $db->get_document($docid);
426                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
427                 $smsg->load_expand;
428                 if ($smsg->{blob} eq $oid) {
429                         push(@delete, $docid);
430                 }
431         }
432         $db->delete_document($_) foreach @delete;
433         scalar(@delete);
434 }
435
436 sub term_generator { # write-only
437         my ($self) = @_;
438
439         my $tg = $self->{term_generator};
440         return $tg if $tg;
441
442         $tg = Search::Xapian::TermGenerator->new;
443         $tg->set_stemmer($self->stemmer);
444
445         $self->{term_generator} = $tg;
446 }
447
448 sub index_git_blob_id {
449         my ($doc, $pfx, $objid) = @_;
450
451         my $len = length($objid);
452         for (my $len = length($objid); $len >= 7; ) {
453                 $doc->add_term($pfx.$objid);
454                 $objid = substr($objid, 0, --$len);
455         }
456 }
457
458 sub unindex_blob {
459         my ($self, $mime) = @_;
460         my $mid = eval { mid_clean(mid_mime($mime)) };
461         $self->remove_message($mid) if defined $mid;
462 }
463
464 sub index_mm {
465         my ($self, $mime) = @_;
466         my $mid = mid_clean(mid_mime($mime));
467         my $mm = $self->{mm};
468         my $num;
469
470         if (defined $self->{regen_down}) {
471                 $num = $mm->num_for($mid) and return $num;
472
473                 while (($num = $self->{regen_down}--) > 0) {
474                         if ($mm->mid_set($num, $mid) != 0) {
475                                 return $num;
476                         }
477                 }
478         } elsif (defined $self->{regen_up}) {
479                 $num = $mm->num_for($mid) and return $num;
480
481                 # this is to fixup old bugs due to add-remove-add
482                 while (($num = ++$self->{regen_up})) {
483                         if ($mm->mid_set($num, $mid) != 0) {
484                                 return $num;
485                         }
486                 }
487         }
488
489         $num = $mm->mid_insert($mid) and return $num;
490
491         # fallback to num_for since filters like RubyLang set the number
492         $mm->num_for($mid);
493 }
494
495 sub unindex_mm {
496         my ($self, $mime) = @_;
497         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
498 }
499
500 sub index_both {
501         my ($self, $mime, $bytes, $blob) = @_;
502         my $num = index_mm($self, $mime);
503         add_message($self, $mime, $bytes, $num, $blob);
504 }
505
506 sub unindex_both {
507         my ($self, $mime) = @_;
508         unindex_blob($self, $mime);
509         unindex_mm($self, $mime);
510 }
511
512 sub do_cat_mail {
513         my ($git, $blob, $sizeref) = @_;
514         my $mime = eval {
515                 my $str = $git->cat_file($blob, $sizeref);
516                 # fixup bugs from import:
517                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
518                 PublicInbox::MIME->new($str);
519         };
520         $@ ? undef : $mime;
521 }
522
523 sub index_sync {
524         my ($self, $opts) = @_;
525         $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
526 }
527
528 sub batch_adjust ($$$$) {
529         my ($max, $bytes, $batch_cb, $latest) = @_;
530         $$max -= $bytes;
531         if ($$max <= 0) {
532                 $$max = BATCH_BYTES;
533                 $batch_cb->($latest);
534         }
535 }
536
537 # only for v1
538 sub read_log {
539         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
540         my $hex = '[a-f0-9]';
541         my $h40 = $hex .'{40}';
542         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
543         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
544         my $git = $self->{git};
545         my $latest;
546         my $bytes;
547         my $max = BATCH_BYTES;
548         local $/ = "\n";
549         my %D;
550         my $line;
551         my $newest;
552         my $mid = '20170114215743.5igbjup6qpsh3jfg@genre.crustytoothpaste.net';
553         while (defined($line = <$log>)) {
554                 if ($line =~ /$addmsg/o) {
555                         my $blob = $1;
556                         delete $D{$blob} and next;
557                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
558                         my $mids = mids($mime->header_obj);
559                         foreach (@$mids) {
560                                 warn "ADD $mid\n" if ($_ eq $mid);
561                         }
562                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
563                         $add_cb->($self, $mime, $bytes, $blob);
564                 } elsif ($line =~ /$delmsg/o) {
565                         my $blob = $1;
566                         $D{$blob} = 1;
567                 } elsif ($line =~ /^commit ($h40)/o) {
568                         $latest = $1;
569                         $newest ||= $latest;
570                 }
571         }
572         # get the leftovers
573         foreach my $blob (keys %D) {
574                 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
575                 my $mids = mids($mime->header_obj);
576                 foreach (@$mids) {
577                         warn "DEL $mid\n" if ($_ eq $mid);
578                 }
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                 # let another process do some work... <
700                 if (!$newest) {
701                         $xdb = $self->begin_txn_lazy;
702                         $dbh->begin_work if $dbh;
703                 }
704         };
705
706         $dbh->begin_work;
707         read_log($self, $xlog, *index_both, *unindex_both, $cb);
708 }
709
710 sub DESTROY {
711         # order matters for unlocking
712         $_[0]->{xdb} = undef;
713         $_[0]->{lockfh} = undef;
714 }
715
716 # remote_* subs are only used by SearchIdxPart
717 sub remote_commit {
718         my ($self) = @_;
719         if (my $w = $self->{w}) {
720                 print $w "commit\n" or die "failed to write commit: $!";
721         } else {
722                 $self->commit_txn_lazy;
723         }
724 }
725
726 sub remote_close {
727         my ($self) = @_;
728         if (my $w = delete $self->{w}) {
729                 my $pid = delete $self->{pid} or die "no process to wait on\n";
730                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
731                 close $w or die "failed to close pipe for pid:$pid: $!\n";
732                 waitpid($pid, 0) == $pid or die "remote process did not finish";
733                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
734         } else {
735                 die "transaction in progress $self\n" if $self->{txn};
736                 $self->_xdb_release if $self->{xdb};
737         }
738 }
739
740 sub remote_remove {
741         my ($self, $oid, $mid) = @_;
742         if (my $w = $self->{w}) {
743                 # triggers remove_by_oid in a partition
744                 print $w "D $oid $mid\n" or die "failed to write remove $!";
745         } else {
746                 $self->begin_txn_lazy;
747                 $self->remove_by_oid($oid, $mid);
748         }
749 }
750
751 sub begin_txn_lazy {
752         my ($self) = @_;
753         return if $self->{txn};
754         my $xdb = $self->{xdb} || $self->_xdb_acquire;
755         $self->{over}->begin_lazy if $self->{over};
756         $xdb->begin_transaction;
757         $self->{txn} = 1;
758         $xdb;
759 }
760
761 sub commit_txn_lazy {
762         my ($self) = @_;
763         delete $self->{txn} or return;
764         $self->{xdb}->commit_transaction;
765         $self->{over}->commit_lazy if $self->{over};
766 }
767
768 sub worker_done {
769         my ($self) = @_;
770         die "$$ $0 xdb not released\n" if $self->{xdb};
771         die "$$ $0 still in transaction\n" if $self->{txn};
772 }
773
774 1;