]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
search: match the behavior of WWW for indexing text
[public-inbox.git] / lib / PublicInbox / SearchIdx.pm
1 # Copyright (C) 2015 all contributors <meta@public-inbox.org>
2 # License: AGPLv3 or later (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 Mail::Thread.  This writes to the search
8 # index.
9 package PublicInbox::SearchIdx;
10 use strict;
11 use warnings;
12 use Fcntl qw(:flock :DEFAULT);
13 use Email::MIME;
14 use Email::MIME::ContentType;
15 $Email::MIME::ContentType::STRICT_PARAMS = 0;
16 use base qw(PublicInbox::Search);
17 use PublicInbox::MID qw/mid_clean id_compress mid_mime/;
18 use PublicInbox::MsgIter;
19 use Carp qw(croak);
20 use POSIX qw(strftime);
21 require PublicInbox::Git;
22 *xpfx = *PublicInbox::Search::xpfx;
23
24 use constant MAX_MID_SIZE => 244; # max term size - 1 in Xapian
25 use constant {
26         PERM_UMASK => 0,
27         OLD_PERM_GROUP => 1,
28         OLD_PERM_EVERYBODY => 2,
29         PERM_GROUP => 0660,
30         PERM_EVERYBODY => 0664,
31 };
32
33 sub new {
34         my ($class, $inbox, $creat) = @_;
35         my $git_dir = $inbox;
36         my $altid;
37         if (ref $inbox) {
38                 $git_dir = $inbox->{mainrepo};
39                 $altid = $inbox->{altid};
40                 if ($altid) {
41                         require PublicInbox::AltId;
42                         $altid = [ map {
43                                 PublicInbox::AltId->new($inbox, $_);
44                         } @$altid ];
45                 }
46         }
47         require Search::Xapian::WritableDatabase;
48         my $self = bless { git_dir => $git_dir, -altid => $altid }, $class;
49         my $perm = $self->_git_config_perm;
50         my $umask = _umask_for($perm);
51         $self->{umask} = $umask;
52         $self->{lock_path} = "$git_dir/ssoma.lock";
53         $self->{git} = PublicInbox::Git->new($git_dir);
54         $self->{creat} = ($creat || 0) == 1;
55         $self;
56 }
57
58 sub _xdb_release {
59         my ($self) = @_;
60         my $xdb = delete $self->{xdb} or croak 'not acquired';
61         $xdb->close;
62         _lock_release($self) if $self->{creat};
63         undef;
64 }
65
66 sub _xdb_acquire {
67         my ($self) = @_;
68         croak 'already acquired' if $self->{xdb};
69         my $dir = PublicInbox::Search->xdir($self->{git_dir});
70         my $flag = Search::Xapian::DB_OPEN;
71         if ($self->{creat}) {
72                 require File::Path;
73                 _lock_acquire($self);
74                 File::Path::mkpath($dir);
75                 $self->{batch_size} = 100;
76                 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
77         }
78         $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
79 }
80
81 # we only acquire the flock if creating or reindexing;
82 # PublicInbox::Import already has the lock on its own.
83 sub _lock_acquire {
84         my ($self) = @_;
85         croak 'already locked' if $self->{lockfh};
86         sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
87                 die "failed to open lock $self->{lock_path}: $!\n";
88         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
89         $self->{lockfh} = $lockfh;
90 }
91
92 sub _lock_release {
93         my ($self) = @_;
94         my $lockfh = delete $self->{lockfh} or croak 'not locked';
95         flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
96         close $lockfh or die "close failed: $!\n";
97 }
98
99 sub add_val ($$$) {
100         my ($doc, $col, $num) = @_;
101         $num = Search::Xapian::sortable_serialise($num);
102         $doc->add_value($col, $num);
103 }
104
105 sub add_values ($$$) {
106         my ($smsg, $bytes, $num) = @_;
107
108         my $ts = $smsg->ts;
109         my $doc = $smsg->{doc};
110         add_val($doc, &PublicInbox::Search::TS, $ts);
111
112         defined($num) and add_val($doc, &PublicInbox::Search::NUM, $num);
113
114         defined($bytes) and add_val($doc, &PublicInbox::Search::BYTES, $bytes);
115
116         add_val($doc, &PublicInbox::Search::LINES,
117                         $smsg->{mime}->body_raw =~ tr!\n!\n!);
118
119         my $yyyymmdd = strftime('%Y%m%d', gmtime($ts));
120         add_val($doc, PublicInbox::Search::YYYYMMDD, $yyyymmdd);
121 }
122
123 sub index_users ($$) {
124         my ($tg, $smsg) = @_;
125
126         my $from = $smsg->from;
127         my $to = $smsg->to;
128         my $cc = $smsg->cc;
129
130         $tg->index_text($from, 1, 'A'); # A - author
131         $tg->increase_termpos;
132         $tg->index_text($to, 1, 'XTO') if $to ne '';
133         $tg->increase_termpos;
134         $tg->index_text($cc, 1, 'XCC') if $cc ne '';
135         $tg->increase_termpos;
136 }
137
138 sub index_body ($$$) {
139         my ($tg, $lines, $inc) = @_;
140         $tg->index_text(join("\n", @$lines), $inc, $inc ? 'XNQ' : 'XQUOT');
141         @$lines = ();
142         $tg->increase_termpos;
143 }
144
145 sub add_message {
146         my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
147         my $db = $self->{xdb};
148
149         my ($doc_id, $old_tid);
150         my $mid = mid_clean(mid_mime($mime));
151
152         eval {
153                 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
154                 my $smsg = $self->lookup_message($mid);
155                 if ($smsg) {
156                         # convert a ghost to a regular message
157                         # it will also clobber any existing regular message
158                         $doc_id = $smsg->doc_id;
159                         $old_tid = $smsg->thread_id;
160                 }
161                 $smsg = PublicInbox::SearchMsg->new($mime);
162                 my $doc = $smsg->{doc};
163                 $doc->add_term(xpfx('mid') . $mid);
164
165                 my $subj = $smsg->subject;
166                 if ($subj ne '') {
167                         my $path = $self->subject_path($subj);
168                         $doc->add_term(xpfx('path') . id_compress($path));
169                 }
170
171                 add_values($smsg, $bytes, $num);
172
173                 my $tg = $self->term_generator;
174
175                 $tg->set_document($doc);
176                 $tg->index_text($subj, 1, 'S') if $subj;
177                 $tg->increase_termpos;
178
179                 index_users($tg, $smsg);
180
181                 msg_iter($mime, sub {
182                         my ($part, $depth, @idx) = @{$_[0]};
183                         my $ct = $part->content_type || 'text/plain';
184
185                         return if $ct =~ m!\btext/x?html\b!i;
186
187                         my $s = eval { $part->body_str };
188                         if ($@) {
189                                 if ($ct =~ m!\btext/plain\b!i) {
190                                         # Try to assume UTF-8 because Alpine
191                                         # seems to do wacky things and set
192                                         # charset=X-UNKNOWN
193                                         $part->charset_set('UTF-8');
194                                         $s = eval { $part->body_str };
195                                         $s = $part->body if $@;
196                                 }
197                         }
198                         defined $s or return;
199
200                         my (@orig, @quot);
201                         my $body = $part->body;
202                         my @lines = split(/\n/, $body);
203                         while (defined(my $l = shift @lines)) {
204                                 if ($l =~ /^>/) {
205                                         index_body($tg, \@orig, 1) if @orig;
206                                         push @quot, $l;
207                                 } else {
208                                         index_body($tg, \@quot, 0) if @quot;
209                                         push @orig, $l;
210                                 }
211                         }
212                         index_body($tg, \@quot, 0) if @quot;
213                         index_body($tg, \@orig, 1) if @orig;
214                 });
215
216                 link_message($self, $smsg, $old_tid);
217                 $tg->index_text($mid, 1, 'XMID');
218                 $doc->set_data($smsg->to_doc_data($blob));
219
220                 if (my $altid = $self->{-altid}) {
221                         foreach my $alt (@$altid) {
222                                 my $id = $alt->mid2alt($mid);
223                                 next unless defined $id;
224                                 $doc->add_term($alt->{xprefix} . $id);
225                         }
226                 }
227                 if (defined $doc_id) {
228                         $db->replace_document($doc_id, $doc);
229                 } else {
230                         $doc_id = $db->add_document($doc);
231                 }
232         };
233
234         if ($@) {
235                 warn "failed to index message <$mid>: $@\n";
236                 return undef;
237         }
238         $doc_id;
239 }
240
241 # returns deleted doc_id on success, undef on missing
242 sub remove_message {
243         my ($self, $mid) = @_;
244         my $db = $self->{xdb};
245         my $doc_id;
246         $mid = mid_clean($mid);
247
248         eval {
249                 $doc_id = $self->find_unique_doc_id('mid', $mid);
250                 $db->delete_document($doc_id) if defined $doc_id;
251         };
252
253         if ($@) {
254                 warn "failed to remove message <$mid>: $@\n";
255                 return undef;
256         }
257         $doc_id;
258 }
259
260 sub term_generator { # write-only
261         my ($self) = @_;
262
263         my $tg = $self->{term_generator};
264         return $tg if $tg;
265
266         $tg = Search::Xapian::TermGenerator->new;
267         $tg->set_stemmer($self->stemmer);
268
269         $self->{term_generator} = $tg;
270 }
271
272 # increments last_thread_id counter
273 # returns a 64-bit integer represented as a hex string
274 sub next_thread_id {
275         my ($self) = @_;
276         my $db = $self->{xdb};
277         my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
278
279         $db->set_metadata('last_thread_id', ++$last_thread_id);
280
281         $last_thread_id;
282 }
283
284 sub link_message {
285         my ($self, $smsg, $old_tid) = @_;
286         my $doc = $smsg->{doc};
287         my $mid = $smsg->mid;
288         my $mime = $smsg->mime;
289         my $hdr = $mime->header_obj;
290         my $refs = $hdr->header_raw('References');
291         my @refs = $refs ? ($refs =~ /<([^>]+)>/g) : ();
292         if (my $irt = $hdr->header_raw('In-Reply-To')) {
293                 # last References should be $irt
294                 # we will de-dupe later
295                 push @refs, mid_clean($irt);
296         }
297
298         my $tid;
299         if (@refs) {
300                 my %uniq = ($mid => 1);
301                 my @orig_refs = @refs;
302                 @refs = ();
303
304                 # prevent circular references via References: here:
305                 foreach my $ref (@orig_refs) {
306                         if (length($ref) > MAX_MID_SIZE) {
307                                 warn "References: <$ref> too long, ignoring\n";
308                         }
309                         next if $uniq{$ref};
310                         $uniq{$ref} = 1;
311                         push @refs, $ref;
312                 }
313         }
314         if (@refs) {
315                 $smsg->{references} = '<'.join('> <', @refs).'>';
316
317                 # first ref *should* be the thread root,
318                 # but we can never trust clients to do the right thing
319                 my $ref = shift @refs;
320                 $tid = $self->_resolve_mid_to_tid($ref);
321                 $self->merge_threads($tid, $old_tid) if defined $old_tid;
322
323                 # the rest of the refs should point to this tid:
324                 foreach $ref (@refs) {
325                         my $ptid = $self->_resolve_mid_to_tid($ref);
326                         merge_threads($self, $tid, $ptid);
327                 }
328         } else {
329                 $tid = $self->next_thread_id;
330         }
331         $doc->add_term(xpfx('thread') . $tid);
332 }
333
334 sub index_blob {
335         my ($self, $mime, $bytes, $num, $blob) = @_;
336         $self->add_message($mime, $bytes, $num, $blob);
337 }
338
339 sub unindex_blob {
340         my ($self, $mime) = @_;
341         my $mid = eval { mid_clean(mid_mime($mime)) };
342         $self->remove_message($mid) if defined $mid;
343 }
344
345 sub index_mm {
346         my ($self, $mime) = @_;
347         $self->{mm}->mid_insert(mid_clean(mid_mime($mime)));
348 }
349
350 sub unindex_mm {
351         my ($self, $mime) = @_;
352         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
353 }
354
355 sub index_mm2 {
356         my ($self, $mime, $bytes, $blob) = @_;
357         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
358         index_blob($self, $mime, $bytes, $num, $blob);
359 }
360
361 sub unindex_mm2 {
362         my ($self, $mime) = @_;
363         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
364         unindex_blob($self, $mime);
365 }
366
367 sub index_both {
368         my ($self, $mime, $bytes, $blob) = @_;
369         my $num = index_mm($self, $mime);
370         index_blob($self, $mime, $bytes, $num, $blob);
371 }
372
373 sub unindex_both {
374         my ($self, $mime) = @_;
375         unindex_blob($self, $mime);
376         unindex_mm($self, $mime);
377 }
378
379 sub do_cat_mail {
380         my ($git, $blob, $sizeref) = @_;
381         my $mime = eval {
382                 my $str = $git->cat_file($blob, $sizeref);
383                 # fixup bugs from import:
384                 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
385                 Email::MIME->new($str);
386         };
387         $@ ? undef : $mime;
388 }
389
390 sub index_sync {
391         my ($self, $opts) = @_;
392         with_umask($self, sub { $self->_index_sync($opts) });
393 }
394
395 sub rlog {
396         my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
397         my $hex = '[a-f0-9]';
398         my $h40 = $hex .'{40}';
399         my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
400         my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
401         my $git = $self->{git};
402         my $latest;
403         my $bytes;
404         my $max = $self->{batch_size}; # may be undef
405         local $/ = "\n";
406         my $line;
407         while (defined($line = <$log>)) {
408                 if ($line =~ /$addmsg/o) {
409                         my $blob = $1;
410                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
411                         $add_cb->($self, $mime, $bytes, $blob);
412                 } elsif ($line =~ /$delmsg/o) {
413                         my $blob = $1;
414                         my $mime = do_cat_mail($git, $blob) or next;
415                         $del_cb->($self, $mime);
416                 } elsif ($line =~ /^commit ($h40)/o) {
417                         if (defined $max && --$max <= 0) {
418                                 $max = $self->{batch_size};
419                                 $batch_cb->($latest, 1);
420                         }
421                         $latest = $1;
422                 }
423         }
424         $batch_cb->($latest, 0);
425 }
426
427 sub _msgmap_init {
428         my ($self) = @_;
429         $self->{mm} = eval {
430                 require PublicInbox::Msgmap;
431                 PublicInbox::Msgmap->new($self->{git_dir}, 1);
432         };
433 }
434
435 sub _git_log {
436         my ($self, $range) = @_;
437         $self->{git}->popen(qw/log --reverse --no-notes --no-color
438                                 --raw -r --no-abbrev/, $range);
439 }
440
441 # indexes all unindexed messages
442 sub _index_sync {
443         my ($self, $opts) = @_;
444         my $tip = $opts->{ref} || 'HEAD';
445         my $reindex = $opts->{reindex};
446         my ($mkey, $last_commit, $lx, $xlog);
447         $self->{git}->batch_prepare;
448         my $xdb = _xdb_acquire($self);
449         $xdb->begin_transaction;
450         do {
451                 $xlog = undef;
452                 $mkey = 'last_commit';
453                 $last_commit = $xdb->get_metadata('last_commit');
454                 $lx = $last_commit;
455                 if ($reindex) {
456                         $lx = '';
457                         $mkey = undef if $last_commit ne '';
458                 }
459                 $xdb->cancel_transaction;
460                 $xdb = _xdb_release($self);
461
462                 # ensure we leak no FDs to "git log"
463                 my $range = $lx eq '' ? $tip : "$lx..$tip";
464                 $xlog = _git_log($self, $range);
465
466                 $xdb = _xdb_acquire($self);
467                 $xdb->begin_transaction;
468         } while ($xdb->get_metadata('last_commit') ne $last_commit);
469
470         my $mm = _msgmap_init($self);
471         my $dbh = $mm->{dbh} if $mm;
472         my $mm_only;
473         my $cb = sub {
474                 my ($commit, $more) = @_;
475                 if ($dbh) {
476                         $mm->last_commit($commit) if $commit;
477                         $dbh->commit;
478                 }
479                 if (!$mm_only) {
480                         $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
481                         $xdb->commit_transaction;
482                         $xdb = _xdb_release($self);
483                 }
484                 # let another process do some work... <
485                 if ($more) {
486                         if (!$mm_only) {
487                                 $xdb = _xdb_acquire($self);
488                                 $xdb->begin_transaction;
489                         }
490                         $dbh->begin_work if $dbh;
491                 }
492         };
493
494         if ($mm) {
495                 $dbh->begin_work;
496                 my $lm = $mm->last_commit || '';
497                 if ($lm eq $lx) {
498                         # Common case is the indexes are synced,
499                         # we only need to run git-log once:
500                         rlog($self, $xlog, *index_both, *unindex_both, $cb);
501                 } else {
502                         # Uncommon case, msgmap and xapian are out-of-sync
503                         # do not care for performance (but git is fast :>)
504                         # This happens if we have to reindex Xapian since
505                         # msgmap is a frozen format and our Xapian format
506                         # is evolving.
507                         my $r = $lm eq '' ? $tip : "$lm..$tip";
508
509                         # first, ensure msgmap is up-to-date:
510                         my $mkey_prev = $mkey;
511                         $mkey = undef; # ignore xapian, for now
512                         my $mlog = _git_log($self, $r);
513                         $mm_only = 1;
514                         rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
515                         $mm_only = $mlog = undef;
516
517                         # now deal with Xapian
518                         $mkey = $mkey_prev;
519                         $dbh = undef;
520                         rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
521                 }
522         } else {
523                 # user didn't install DBD::SQLite and DBI
524                 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
525         }
526 }
527
528 # this will create a ghost as necessary
529 sub _resolve_mid_to_tid {
530         my ($self, $mid) = @_;
531
532         my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
533         $smsg->thread_id;
534 }
535
536 sub create_ghost {
537         my ($self, $mid) = @_;
538
539         my $tid = $self->next_thread_id;
540         my $doc = Search::Xapian::Document->new;
541         $doc->add_term(xpfx('mid') . $mid);
542         $doc->add_term(xpfx('thread') . $tid);
543         $doc->add_term(xpfx('type') . 'ghost');
544
545         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
546         $self->{xdb}->add_document($doc);
547
548         $smsg;
549 }
550
551 sub merge_threads {
552         my ($self, $winner_tid, $loser_tid) = @_;
553         return if $winner_tid == $loser_tid;
554         my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
555         my $thread_pfx = xpfx('thread');
556         my $db = $self->{xdb};
557
558         for (; $head != $tail; $head->inc) {
559                 my $docid = $head->get_docid;
560                 my $doc = $db->get_document($docid);
561                 $doc->remove_term($thread_pfx . $loser_tid);
562                 $doc->add_term($thread_pfx . $winner_tid);
563                 $db->replace_document($docid, $doc);
564         }
565 }
566
567 sub _read_git_config_perm {
568         my ($self) = @_;
569         my @cmd = qw(config core.sharedRepository);
570         my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
571         local $/ = "\n";
572         my $perm = <$fh>;
573         chomp $perm if defined $perm;
574         $perm;
575 }
576
577 sub _git_config_perm {
578         my $self = shift;
579         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
580         return PERM_GROUP if (!defined($perm) || $perm eq '');
581         return PERM_UMASK if ($perm eq 'umask');
582         return PERM_GROUP if ($perm eq 'group');
583         if ($perm =~ /\A(?:all|world|everybody)\z/) {
584                 return PERM_EVERYBODY;
585         }
586         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
587         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
588
589         my $i = oct($perm);
590         return PERM_UMASK if ($i == PERM_UMASK);
591         return PERM_GROUP if ($i == OLD_PERM_GROUP);
592         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
593
594         if (($i & 0600) != 0600) {
595                 die "core.sharedRepository mode invalid: ".
596                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
597         }
598         ($i & 0666);
599 }
600
601 sub _umask_for {
602         my ($perm) = @_; # _git_config_perm return value
603         my $rv = $perm;
604         return umask if $rv == 0;
605
606         # set +x bit if +r or +w were set
607         $rv |= 0100 if ($rv & 0600);
608         $rv |= 0010 if ($rv & 0060);
609         $rv |= 0001 if ($rv & 0006);
610         (~$rv & 0777);
611 }
612
613 sub with_umask {
614         my ($self, $cb) = @_;
615         my $old = umask $self->{umask};
616         my $rv = eval { $cb->() };
617         my $err = $@;
618         umask $old;
619         die $err if $@;
620         $rv;
621 }
622
623 sub DESTROY {
624         # order matters for unlocking
625         $_[0]->{xdb} = undef;
626         $_[0]->{lockfh} = undef;
627 }
628
629 1;