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