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