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