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