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