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