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