]> Sergey Matveev's repositories - public-inbox.git/blob - lib/PublicInbox/SearchIdx.pm
searchmsg: add git object ID to doc_data
[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 require PublicInbox::Git;
20 *xpfx = *PublicInbox::Search::xpfx;
21
22 use constant MAX_MID_SIZE => 244; # max term size - 1 in Xapian
23 use constant {
24         PERM_UMASK => 0,
25         OLD_PERM_GROUP => 1,
26         OLD_PERM_EVERYBODY => 2,
27         PERM_GROUP => 0660,
28         PERM_EVERYBODY => 0664,
29 };
30
31 sub new {
32         my ($class, $git_dir, $writable) = @_;
33         my $dir = PublicInbox::Search->xdir($git_dir);
34         require Search::Xapian::WritableDatabase;
35         my $flag = Search::Xapian::DB_OPEN;
36         my $self = bless { git_dir => $git_dir }, $class;
37         my $perm = $self->_git_config_perm;
38         my $umask = _umask_for($perm);
39         $self->{umask} = $umask;
40         $self->{lock_path} = "$git_dir/ssoma.lock";
41         $self->{xdb} = $self->with_umask(sub {
42                 if ($writable == 1) {
43                         require File::Path;
44                         File::Path::mkpath($dir);
45                         $self->{batch_size} = 100;
46                         $flag = Search::Xapian::DB_CREATE_OR_OPEN;
47                         _lock_acquire($self);
48                 }
49                 Search::Xapian::WritableDatabase->new($dir, $flag);
50         });
51         $self;
52 }
53
54 sub _xdb_release {
55         my ($self) = @_;
56         my $xdb = delete $self->{xdb};
57         $xdb->commit_transaction;
58         $xdb->close;
59         _lock_release($self);
60 }
61
62 sub _xdb_acquire {
63         my ($self) = @_;
64         _lock_acquire($self);
65         my $dir = PublicInbox::Search->xdir($self->{git_dir});
66         my $flag = Search::Xapian::DB_OPEN;
67         my $xdb = Search::Xapian::WritableDatabase->new($dir, $flag);
68         $xdb->begin_transaction;
69         $self->{xdb} = $xdb;
70 }
71
72 sub _lock_acquire {
73         my ($self) = @_;
74         sysopen(my $lockfh, $self->{lock_path}, O_WRONLY|O_CREAT) or
75                 die "failed to open lock $self->{lock_path}: $!\n";
76         flock($lockfh, LOCK_EX) or die "lock failed: $!\n";
77         $self->{lockfh} = $lockfh;
78 }
79
80 sub _lock_release {
81         my ($self) = @_;
82         my $lockfh = delete $self->{lockfh};
83         flock($lockfh, LOCK_UN) or die "unlock failed: $!\n";
84         close $lockfh or die "close failed: $!\n";
85 }
86
87 sub add_val {
88         my ($doc, $col, $num) = @_;
89         $num = Search::Xapian::sortable_serialise($num);
90         $doc->add_value($col, $num);
91 }
92
93 sub add_message {
94         my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
95         my $db = $self->{xdb};
96
97         my ($doc_id, $old_tid);
98         my $mid = mid_clean(mid_mime($mime));
99         my $ct_msg = $mime->header('Content-Type') || 'text/plain';
100
101         eval {
102                 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
103                 my $smsg = $self->lookup_message($mid);
104                 if ($smsg) {
105                         # convert a ghost to a regular message
106                         # it will also clobber any existing regular message
107                         $doc_id = $smsg->doc_id;
108                         $old_tid = $smsg->thread_id;
109                 }
110                 $smsg = PublicInbox::SearchMsg->new($mime);
111                 my $doc = $smsg->{doc};
112                 $doc->add_term(xpfx('mid') . $mid);
113
114                 my $subj = $smsg->subject;
115                 if ($subj ne '') {
116                         my $path = $self->subject_path($subj);
117                         $doc->add_term(xpfx('path') . id_compress($path));
118                 }
119
120                 add_val($doc, &PublicInbox::Search::TS, $smsg->ts);
121
122                 defined($num) and
123                         add_val($doc, &PublicInbox::Search::NUM, $num);
124
125                 defined($bytes) and
126                         add_val($doc, &PublicInbox::Search::BYTES, $bytes);
127
128                 add_val($doc, &PublicInbox::Search::LINES,
129                                 $mime->body_raw =~ tr!\n!\n!);
130
131                 my $tg = $self->term_generator;
132
133                 $tg->set_document($doc);
134                 $tg->index_text($subj, 1, 'S') if $subj;
135                 $tg->increase_termpos;
136                 $tg->index_text($subj) if $subj;
137                 $tg->increase_termpos;
138
139                 $tg->index_text($smsg->from);
140                 $tg->increase_termpos;
141
142                 msg_iter($mime, sub {
143                         my ($part, $depth, @idx) = @{$_[0]};
144                         my $ct = $part->content_type || $ct_msg;
145
146                         # account for filter bugs...
147                         $ct =~ m!\btext/plain\b!i or return;
148
149                         my (@orig, @quot);
150                         my $body = $part->body;
151                         $part->body_set('');
152                         my @lines = split(/\n/, $body);
153                         while (defined(my $l = shift @lines)) {
154                                 if ($l =~ /^\s*>/) {
155                                         push @quot, $l;
156                                 } else {
157                                         push @orig, $l;
158                                 }
159                         }
160                         if (@quot) {
161                                 $tg->index_text(join("\n", @quot), 0);
162                                 @quot = ();
163                                 $tg->increase_termpos;
164                         }
165                         if (@orig) {
166                                 $tg->index_text(join("\n", @orig));
167                                 @orig = ();
168                                 $tg->increase_termpos;
169                         }
170                 });
171
172                 link_message($self, $smsg, $old_tid);
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, $git, $mime, $bytes, $num, $blob) = @_;
283         $self->add_message($mime, $bytes, $num, $blob);
284 }
285
286 sub unindex_blob {
287         my ($self, $git, $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, $git, $mime) = @_;
294         $self->{mm}->mid_insert(mid_clean(mid_mime($mime)));
295 }
296
297 sub unindex_mm {
298         my ($self, $git, $mime) = @_;
299         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
300 }
301
302 sub index_mm2 {
303         my ($self, $git, $mime, $bytes, $blob) = @_;
304         my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
305         index_blob($self, $git, $mime, $bytes, $num, $blob);
306 }
307
308 sub unindex_mm2 {
309         my ($self, $git, $mime) = @_;
310         $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
311         unindex_blob($self, $git, $mime);
312 }
313
314 sub index_both {
315         my ($self, $git, $mime, $bytes, $blob) = @_;
316         my $num = index_mm($self, $git, $mime);
317         index_blob($self, $git, $mime, $bytes, $num, $blob);
318 }
319
320 sub unindex_both {
321         my ($self, $git, $mime) = @_;
322         unindex_blob($self, $git, $mime);
323         unindex_mm($self, $git, $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, $range, $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 = PublicInbox::Git->new($self->{git_dir});
349         my $log = $git->popen(qw/log --reverse --no-notes --no-color
350                                 --raw -r --no-abbrev/, $range);
351         my $latest;
352         my $bytes;
353         my $max = $self->{batch_size}; # may be undef
354         local $/ = "\n";
355         my $line;
356         while (defined($line = <$log>)) {
357                 if ($line =~ /$addmsg/o) {
358                         my $blob = $1;
359                         my $mime = do_cat_mail($git, $blob, \$bytes) or next;
360                         $add_cb->($self, $git, $mime, $bytes, $blob);
361                 } elsif ($line =~ /$delmsg/o) {
362                         my $blob = $1;
363                         my $mime = do_cat_mail($git, $blob) or next;
364                         $del_cb->($self, $git, $mime);
365                 } elsif ($line =~ /^commit ($h40)/o) {
366                         if (defined $max && --$max <= 0) {
367                                 $max = $self->{batch_size};
368                                 $batch_cb->($latest, 1);
369                         }
370                         $latest = $1;
371                 }
372         }
373         $batch_cb->($latest, 0);
374 }
375
376 # indexes all unindexed messages
377 sub _index_sync {
378         my ($self, $opts) = @_;
379         my $tip = $opts->{ref} || 'HEAD';
380         my $mm = $self->{mm} = eval {
381                 require PublicInbox::Msgmap;
382                 PublicInbox::Msgmap->new($self->{git_dir}, 1);
383         };
384         my $xdb = $self->{xdb};
385         $xdb->begin_transaction;
386         my $reindex = $opts->{reindex};
387         my $mkey = 'last_commit';
388         my $last_commit = $xdb->get_metadata($mkey);
389         my $lx = $last_commit;
390         if ($reindex) {
391                 $lx = '';
392                 $mkey = undef if $last_commit ne '';
393         }
394         my $dbh;
395         my $cb = sub {
396                 my ($commit, $more) = @_;
397                 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
398                 if ($dbh) {
399                         $mm->last_commit($commit) if $commit;
400                         $dbh->commit;
401                 }
402                 _xdb_release($self);
403                 # let another process do some work...
404                 $dbh->begin_work if $dbh && $more;
405                 $xdb = _xdb_acquire($self);
406         };
407
408         my $range = $lx eq '' ? $tip : "$lx..$tip";
409         if ($mm) {
410                 $dbh = $mm->{dbh};
411                 $dbh->begin_work;
412                 my $lm = $mm->last_commit || '';
413                 if ($lm eq $lx) {
414                         # Common case is the indexes are synced,
415                         # we only need to run git-log once:
416                         rlog($self, $range, *index_both, *unindex_both, $cb);
417                 } else {
418                         # Uncommon case, msgmap and xapian are out-of-sync
419                         # do not care for performance (but git is fast :>)
420                         # This happens if we have to reindex Xapian since
421                         # msgmap is a frozen format and our Xapian format
422                         # is evolving.
423                         my $r = $lm eq '' ? $tip : "$lm..$tip";
424
425                         # first, ensure msgmap is up-to-date:
426                         my $mkey_prev = $mkey;
427                         $mkey = undef; # ignore xapian, for now
428                         rlog($self, $r, *index_mm, *unindex_mm, $cb);
429
430                         # now deal with Xapian
431                         $mkey = $mkey_prev;
432                         $dbh = undef;
433                         rlog($self, $range, *index_mm2, *unindex_mm2, $cb);
434                 }
435         } else {
436                 # user didn't install DBD::SQLite and DBI
437                 rlog($self, $range, *index_blob, *unindex_blob, $cb);
438         }
439 }
440
441 # this will create a ghost as necessary
442 sub _resolve_mid_to_tid {
443         my ($self, $mid) = @_;
444
445         my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
446         $smsg->thread_id;
447 }
448
449 sub create_ghost {
450         my ($self, $mid) = @_;
451
452         my $tid = $self->next_thread_id;
453         my $doc = Search::Xapian::Document->new;
454         $doc->add_term(xpfx('mid') . $mid);
455         $doc->add_term(xpfx('thread') . $tid);
456         $doc->add_term(xpfx('type') . 'ghost');
457
458         my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
459         $self->{xdb}->add_document($doc);
460
461         $smsg;
462 }
463
464 sub merge_threads {
465         my ($self, $winner_tid, $loser_tid) = @_;
466         return if $winner_tid == $loser_tid;
467         my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
468         my $thread_pfx = xpfx('thread');
469         my $db = $self->{xdb};
470
471         for (; $head != $tail; $head->inc) {
472                 my $docid = $head->get_docid;
473                 my $doc = $db->get_document($docid);
474                 $doc->remove_term($thread_pfx . $loser_tid);
475                 $doc->add_term($thread_pfx . $winner_tid);
476                 $db->replace_document($docid, $doc);
477         }
478 }
479
480 sub _read_git_config_perm {
481         my ($self) = @_;
482         my @cmd = qw(config core.sharedRepository);
483         my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
484         local $/ = "\n";
485         my $perm = <$fh>;
486         chomp $perm if defined $perm;
487         $perm;
488 }
489
490 sub _git_config_perm {
491         my $self = shift;
492         my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
493         return PERM_GROUP if (!defined($perm) || $perm eq '');
494         return PERM_UMASK if ($perm eq 'umask');
495         return PERM_GROUP if ($perm eq 'group');
496         if ($perm =~ /\A(?:all|world|everybody)\z/) {
497                 return PERM_EVERYBODY;
498         }
499         return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
500         return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
501
502         my $i = oct($perm);
503         return PERM_UMASK if ($i == PERM_UMASK);
504         return PERM_GROUP if ($i == OLD_PERM_GROUP);
505         return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
506
507         if (($i & 0600) != 0600) {
508                 die "core.sharedRepository mode invalid: ".
509                     sprintf('%.3o', $i) . "\nOwner must have permissions\n";
510         }
511         ($i & 0666);
512 }
513
514 sub _umask_for {
515         my ($perm) = @_; # _git_config_perm return value
516         my $rv = $perm;
517         return umask if $rv == 0;
518
519         # set +x bit if +r or +w were set
520         $rv |= 0100 if ($rv & 0600);
521         $rv |= 0010 if ($rv & 0060);
522         $rv |= 0001 if ($rv & 0006);
523         (~$rv & 0777);
524 }
525
526 sub with_umask {
527         my ($self, $cb) = @_;
528         my $old = umask $self->{umask};
529         my $rv = eval { $cb->() };
530         my $err = $@;
531         umask $old;
532         die $err if $@;
533         $rv;
534 }
535
536 sub DESTROY {
537         # order matters for unlocking
538         $_[0]->{xdb} = undef;
539         $_[0]->{lockfh} = undef;
540 }
541
542 1;