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