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