]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
0b1dc219ba45922334ebc9a4ebdf3722b860cbe7
[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 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                 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                 $tg->index_text($subj, 1, 'S') if $subj;
287                 $tg->increase_termpos;
288
289                 index_users($tg, $smsg);
290
291                 msg_iter($mime, sub {
292                         my ($part, $depth, @idx) = @{$_[0]};
293                         my $ct = $part->content_type || 'text/plain';
294                         my $fn = $part->filename;
295                         if (defined $fn && $fn ne '') {
296                                 $tg->index_text($fn, 1, 'XFN');
297                         }
298
299                         return if $ct =~ m!\btext/x?html\b!i;
300
301                         my $s = eval { $part->body_str };
302                         if ($@) {
303                                 if ($ct =~ m!\btext/plain\b!i) {
304                                         # Try to assume UTF-8 because Alpine
305                                         # seems to do wacky things and set
306                                         # charset=X-UNKNOWN
307                                         $part->charset_set('UTF-8');
308                                         $s = eval { $part->body_str };
309                                         $s = $part->body if $@;
310                                 }
311                         }
312                         defined $s or return;
313
314                         my (@orig, @quot);
315                         my $body = $part->body;
316                         my @lines = split(/\n/, $body);
317                         while (defined(my $l = shift @lines)) {
318                                 if ($l =~ /^>/) {
319                                         index_body($tg, \@orig, $doc) if @orig;
320                                         push @quot, $l;
321                                 } else {
322                                         index_body($tg, \@quot, 0) if @quot;
323                                         push @orig, $l;
324                                 }
325                         }
326                         index_body($tg, \@quot, 0) if @quot;
327                         index_body($tg, \@orig, $doc) if @orig;
328                 });
329
330                 foreach my $mid (@$mids) {
331                         $tg->index_text($mid, 1, 'XM');
332                 }
333                 $smsg->{to} = $smsg->{cc} = '';
334                 PublicInbox::OverIdx::parse_references($smsg, $mid0, $mids);
335                 my $data = $smsg->to_doc_data($oid, $mid0);
336                 $doc->set_data($data);
337                 if (my $altid = $self->{-altid}) {
338                         foreach my $alt (@$altid) {
339                                 my $pfx = $alt->{xprefix};
340                                 foreach my $mid (@$mids) {
341                                         my $id = $alt->mid2alt($mid);
342                                         next unless defined $id;
343                                         $doc->add_boolean_term($pfx . $id);
344                                 }
345                         }
346                 }
347
348                 if (my $over = $self->{over}) {
349                         $over->add_overview($mime, $bytes, $num, $oid, $mid0);
350                 }
351                 $doc->add_boolean_term('Q' . $_) foreach @$mids;
352                 $self->{xdb}->replace_document($doc_id = $num, $doc);
353         };
354
355         if ($@) {
356                 warn "failed to index message <".join('> <',@$mids).">: $@\n";
357                 return undef;
358         }
359         $doc_id;
360 }
361
362 # returns begin and end PostingIterator
363 sub find_doc_ids {
364         my ($self, $termval) = @_;
365         my $db = $self->{xdb};
366
367         ($db->postlist_begin($termval), $db->postlist_end($termval));
368 }
369
370 sub batch_do {
371         my ($self, $termval, $cb) = @_;
372         my $batch_size = 1000; # don't let @ids grow too large to avoid OOM
373         while (1) {
374                 my ($head, $tail) = $self->find_doc_ids($termval);
375                 return if $head == $tail;
376                 my @ids;
377                 for (; $head != $tail && @ids < $batch_size; $head->inc) {
378                         push @ids, $head->get_docid;
379                 }
380                 $cb->(\@ids);
381         }
382 }
383
384 sub remove_message {
385         my ($self, $mid) = @_;
386         my $db = $self->{xdb};
387         my $called;
388         $mid = mid_clean($mid);
389         my $over = $self->{over};
390
391         eval {
392                 batch_do($self, 'Q' . $mid, sub {
393                         my ($ids) = @_;
394                         $db->delete_document($_) for @$ids;
395                         $over->delete_articles($ids) if $over;
396                         $called = 1;
397                 });
398         };
399         if ($@) {
400                 warn "failed to remove message <$mid>: $@\n";
401         } elsif (!$called) {
402                 warn "cannot remove non-existent <$mid>\n";
403         }
404 }
405
406 # MID is a hint in V2
407 sub remove_by_oid {
408         my ($self, $oid, $mid) = @_;
409         my $db = $self->{xdb};
410
411         $self->{over}->remove_oid($oid, $mid) if $self->{over};
412
413         # XXX careful, we cannot use batch_do here since we conditionally
414         # delete documents based on other factors, so we cannot call
415         # find_doc_ids twice.
416         my ($head, $tail) = $self->find_doc_ids('Q' . $mid);
417         return if $head == $tail;
418
419         # there is only ONE element in @delete unless we
420         # have bugs in our v2writable deduplication check
421         my @delete;
422         for (; $head != $tail; $head->inc) {
423                 my $docid = $head->get_docid;
424                 my $doc = $db->get_document($docid);
425                 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
426                 $smsg->load_expand;
427                 if ($smsg->{blob} eq $oid) {
428                         push(@delete, $docid);
429                 }
430         }
431         $db->delete_document($_) foreach @delete;
432         scalar(@delete);
433 }
434
435 sub term_generator { # write-only
436         my ($self) = @_;
437
438         my $tg = $self->{term_generator};
439         return $tg if $tg;
440
441         $tg = Search::Xapian::TermGenerator->new;
442         $tg->set_stemmer($self->stemmer);
443
444         $self->{term_generator} = $tg;
445 }
446
447 sub index_git_blob_id {
448         my ($doc, $pfx, $objid) = @_;
449
450         my $len = length($objid);
451         for (my $len = length($objid); $len >= 7; ) {
452                 $doc->add_term($pfx.$objid);
453                 $objid = substr($objid, 0, --$len);
454         }
455 }
456
457 sub unindex_blob {
458         my ($self, $mime) = @_;
459         my $mid = eval { mid_clean(mid_mime($mime)) };
460         $self->remove_message($mid) if defined $mid;
461 }
462
463 sub index_mm {
464         my ($self, $mime) = @_;
465         my $mid = mid_clean(mid_mime($mime));
466         my $mm = $self->{mm};
467         my $num = $mm->mid_insert($mid);
468         return $num if defined $num;
469
470         # fallback to num_for since filters like RubyLang set the number
471         $mm->num_for($mid);
472 }
473
474 sub unindex_mm {
475         my ($self, $mime) = @_;
476         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
477 }
478
479 sub index_mm2 {
480         my ($self, $mime, $bytes, $blob) = @_;
481         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
482         add_message($self, $mime, $bytes, $num, $blob);
483 }
484
485 sub unindex_mm2 {
486         my ($self, $mime) = @_;
487         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
488         unindex_blob($self, $mime);
489 }
490
491 sub index_both {
492         my ($self, $mime, $bytes, $blob) = @_;
493         my $num = index_mm($self, $mime);
494         add_message($self, $mime, $bytes, $num, $blob);
495 }
496
497 sub unindex_both {
498         my ($self, $mime) = @_;
499         unindex_blob($self, $mime);
500         unindex_mm($self, $mime);
501 }
502
503 sub do_cat_mail {
504         my ($git, $blob, $sizeref) = @_;
505         my $mime = eval {
506                 my $str = $git->cat_file($blob, $sizeref);
507                 # fixup bugs from import:
508                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
509                 PublicInbox::MIME->new($str);
510         };
511         $@ ? undef : $mime;
512 }
513
514 sub index_sync {
515         my ($self, $opts) = @_;
516         $self->{-inbox}->with_umask(sub { $self->_index_sync($opts) })
517 }
518
519 sub batch_adjust ($$$$) {
520         my ($max, $bytes, $batch_cb, $latest) = @_;
521         $$max -= $bytes;
522         if ($$max <= 0) {
523                 $$max = BATCH_BYTES;
524                 $batch_cb->($latest, 1);
525         }
526 }
527
528 # only for v1
529 sub rlog {
530         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
531         my $hex = '[a-f0-9]';
532         my $h40 = $hex .'{40}';
533         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
534         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
535         my $git = $self->{git};
536         my $latest;
537         my $bytes;
538         my $max = BATCH_BYTES;
539         local $/ = "\n";
540         my $line;
541         while (defined($line = <$log>)) {
542                 if ($line =~ /$addmsg/o) {
543                         my $blob = $1;
544                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
545                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
546                         $add_cb->($self, $mime, $bytes, $blob);
547                 } elsif ($line =~ /$delmsg/o) {
548                         my $blob = $1;
549                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
550                         batch_adjust(\$max, $bytes, $batch_cb, $latest);
551                         $del_cb->($self, $mime);
552                 } elsif ($line =~ /^commit ($h40)/o) {
553                         $latest = $1;
554                 }
555         }
556         $batch_cb->($latest, 0);
557 }
558
559 sub _msgmap_init {
560         my ($self) = @_;
561         die "BUG: _msgmap_init is only for v1\n" if $self->{version} != 1;
562         $self->{mm} ||= eval {
563                 require PublicInbox::Msgmap;
564                 PublicInbox::Msgmap->new($self->{mainrepo}, 1);
565         };
566 }
567
568 sub _git_log {
569         my ($self, $range) = @_;
570         $self->{git}->popen(qw/log --reverse --no-notes --no-color
571                                 --raw -r --no-abbrev/, $range);
572 }
573
574 # indexes all unindexed messages (v1 only)
575 sub _index_sync {
576         my ($self, $opts) = @_;
577         my $tip = $opts->{ref} || 'HEAD';
578         my $reindex = $opts->{reindex};
579         my ($mkey, $last_commit, $lx, $xlog);
580         $self->{git}->batch_prepare;
581         my $xdb = $self->begin_txn_lazy;
582         do {
583                 $xlog = undef;
584                 $mkey = 'last_commit';
585                 $last_commit = $xdb->get_metadata('last_commit');
586                 $lx = $last_commit;
587                 if ($reindex) {
588                         $lx = '';
589                         $mkey = undef if $last_commit ne '';
590                 }
591                 $self->{over}->rollback_lazy;
592                 $self->{over}->disconnect;
593                 delete $self->{txn};
594                 $xdb->cancel_transaction;
595                 $xdb = _xdb_release($self);
596
597                 # ensure we leak no FDs to "git log"
598                 my $range = $lx eq '' ? $tip : "$lx..$tip";
599                 $xlog = _git_log($self, $range);
600
601                 $xdb = $self->begin_txn_lazy;
602         } while ($xdb->get_metadata('last_commit') ne $last_commit);
603
604         my $mm = _msgmap_init($self);
605         my $dbh = $mm->{dbh} if $mm;
606         my $mm_only;
607         my $cb = sub {
608                 my ($commit, $more) = @_;
609                 if ($dbh) {
610                         $mm->last_commit($commit) if $commit;
611                         $dbh->commit;
612                 }
613                 if (!$mm_only) {
614                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
615                         $self->commit_txn_lazy;
616                 }
617                 # let another process do some work... <
618                 if ($more) {
619                         if (!$mm_only) {
620                                 $xdb = $self->begin_txn_lazy;
621                         }
622                         $dbh->begin_work if $dbh;
623                 }
624         };
625
626         if ($mm) {
627                 $dbh->begin_work;
628                 my $lm = $mm->last_commit || '';
629                 if ($lm eq $lx) {
630                         # Common case is the indexes are synced,
631                         # we only need to run git-log once:
632                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
633                 } else {
634                         # Uncommon case, msgmap and xapian are out-of-sync
635                         # do not care for performance (but git is fast :>)
636                         # This happens if we have to reindex Xapian since
637                         # msgmap is a frozen format and our Xapian format
638                         # is evolving.
639                         my $r = $lm eq '' ? $tip : "$lm..$tip";
640
641                         # first, ensure msgmap is up-to-date:
642                         my $mkey_prev = $mkey;
643                         $mkey = undef; # ignore xapian, for now
644                         my $mlog = _git_log($self, $r);
645                         $mm_only = 1;
646                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
647                         $mm_only = $mlog = undef;
648
649                         # now deal with Xapian
650                         $mkey = $mkey_prev;
651                         $dbh = undef;
652                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
653                 }
654         } else {
655                 # user didn't install DBD::SQLite and DBI
656                 rlog($self, $xlog, *add_message, *unindex_blob, $cb);
657         }
658 }
659
660 sub DESTROY {
661         # order matters for unlocking
662         $_[0]->{xdb} = undef;
663         $_[0]->{lockfh} = undef;
664 }
665
666 # remote_* subs are only used by SearchIdxPart
667 sub remote_commit {
668         my ($self) = @_;
669         if (my $w = $self->{w}) {
670                 print $w "commit\n" or die "failed to write commit: $!";
671         } else {
672                 $self->commit_txn_lazy;
673         }
674 }
675
676 sub remote_close {
677         my ($self) = @_;
678         if (my $w = delete $self->{w}) {
679                 my $pid = delete $self->{pid} or die "no process to wait on\n";
680                 print $w "close\n" or die "failed to write to pid:$pid: $!\n";
681                 close $w or die "failed to close pipe for pid:$pid: $!\n";
682                 waitpid($pid, 0) == $pid or die "remote process did not finish";
683                 $? == 0 or die ref($self)." pid:$pid exited with: $?";
684         } else {
685                 die "transaction in progress $self\n" if $self->{txn};
686                 $self->_xdb_release if $self->{xdb};
687         }
688 }
689
690 sub remote_remove {
691         my ($self, $oid, $mid) = @_;
692         if (my $w = $self->{w}) {
693                 # triggers remove_by_oid in a partition
694                 print $w "D $oid $mid\n" or die "failed to write remove $!";
695         } else {
696                 $self->begin_txn_lazy;
697                 $self->remove_by_oid($oid, $mid);
698         }
699 }
700
701 sub begin_txn_lazy {
702         my ($self) = @_;
703         return if $self->{txn};
704         my $xdb = $self->{xdb} || $self->_xdb_acquire;
705         $self->{over}->begin_lazy if $self->{over};
706         $xdb->begin_transaction;
707         $self->{txn} = 1;
708         $xdb;
709 }
710
711 sub commit_txn_lazy {
712         my ($self) = @_;
713         delete $self->{txn} or return;
714         $self->{xdb}->commit_transaction;
715         $self->{over}->commit_lazy if $self->{over};
716 }
717
718 sub worker_done {
719         my ($self) = @_;
720         die "$$ $0 xdb not released\n" if $self->{xdb};
721         die "$$ $0 still in transaction\n" if $self->{txn};
722 }
723
724 1;