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