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
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
9 package PublicInbox::SearchIdx;
12 use Fcntl qw(:flock :DEFAULT);
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;
20 require PublicInbox::Git;
21 *xpfx = *PublicInbox::Search::xpfx;
23 use constant MAX_MID_SIZE => 244; # max term size - 1 in Xapian
27 OLD_PERM_EVERYBODY => 2,
29 PERM_EVERYBODY => 0664,
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;
47 my $xdb = delete $self->{xdb} or croak 'not acquired';
49 _lock_release($self) if $self->{creat};
55 croak 'already acquired' if $self->{xdb};
56 my $dir = PublicInbox::Search->xdir($self->{git_dir});
57 my $flag = Search::Xapian::DB_OPEN;
61 File::Path::mkpath($dir);
62 $self->{batch_size} = 100;
63 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
65 $self->{xdb} = Search::Xapian::WritableDatabase->new($dir, $flag);
68 # we only acquire the flock if creating or reindexing;
69 # PublicInbox::Import already has the lock on its own.
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;
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";
87 my ($doc, $col, $num) = @_;
88 $num = Search::Xapian::sortable_serialise($num);
89 $doc->add_value($col, $num);
93 my ($self, $mime, $bytes, $num, $blob) = @_; # mime = Email::MIME object
94 my $db = $self->{xdb};
96 my ($doc_id, $old_tid);
97 my $mid = mid_clean(mid_mime($mime));
98 my $ct_msg = $mime->header('Content-Type') || 'text/plain';
101 die 'Message-ID too long' if length($mid) > MAX_MID_SIZE;
102 my $smsg = $self->lookup_message($mid);
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;
109 $smsg = PublicInbox::SearchMsg->new($mime);
110 my $doc = $smsg->{doc};
111 $doc->add_term(xpfx('mid') . $mid);
113 my $subj = $smsg->subject;
115 my $path = $self->subject_path($subj);
116 $doc->add_term(xpfx('path') . id_compress($path));
119 add_val($doc, &PublicInbox::Search::TS, $smsg->ts);
122 add_val($doc, &PublicInbox::Search::NUM, $num);
125 add_val($doc, &PublicInbox::Search::BYTES, $bytes);
127 add_val($doc, &PublicInbox::Search::LINES,
128 $mime->body_raw =~ tr!\n!\n!);
130 my $tg = $self->term_generator;
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;
138 $tg->index_text($smsg->from);
139 $tg->increase_termpos;
141 msg_iter($mime, sub {
142 my ($part, $depth, @idx) = @{$_[0]};
143 my $ct = $part->content_type || $ct_msg;
145 # account for filter bugs...
146 $ct =~ m!\btext/plain\b!i or return;
149 my $body = $part->body;
151 my @lines = split(/\n/, $body);
152 while (defined(my $l = shift @lines)) {
160 $tg->index_text(join("\n", @quot), 0);
162 $tg->increase_termpos;
165 $tg->index_text(join("\n", @orig));
167 $tg->increase_termpos;
171 link_message($self, $smsg, $old_tid);
172 $doc->set_data($smsg->to_doc_data($blob));
173 if (defined $doc_id) {
174 $db->replace_document($doc_id, $doc);
176 $doc_id = $db->add_document($doc);
181 warn "failed to index message <$mid>: $@\n";
187 # returns deleted doc_id on success, undef on missing
189 my ($self, $mid) = @_;
190 my $db = $self->{xdb};
192 $mid = mid_clean($mid);
195 $doc_id = $self->find_unique_doc_id('mid', $mid);
196 $db->delete_document($doc_id) if defined $doc_id;
200 warn "failed to remove message <$mid>: $@\n";
206 sub term_generator { # write-only
209 my $tg = $self->{term_generator};
212 $tg = Search::Xapian::TermGenerator->new;
213 $tg->set_stemmer($self->stemmer);
215 $self->{term_generator} = $tg;
218 # increments last_thread_id counter
219 # returns a 64-bit integer represented as a hex string
222 my $db = $self->{xdb};
223 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
225 $db->set_metadata('last_thread_id', ++$last_thread_id);
231 my ($self, $smsg, $old_tid) = @_;
232 my $doc = $smsg->{doc};
233 my $mid = $smsg->mid;
234 my $mime = $smsg->mime;
235 my $hdr = $mime->header_obj;
236 my $refs = $hdr->header_raw('References');
237 my @refs = $refs ? ($refs =~ /<([^>]+)>/g) : ();
238 if (my $irt = $hdr->header_raw('In-Reply-To')) {
239 # last References should be $irt
240 # we will de-dupe later
241 push @refs, mid_clean($irt);
246 my %uniq = ($mid => 1);
247 my @orig_refs = @refs;
250 # prevent circular references via References: here:
251 foreach my $ref (@orig_refs) {
252 if (length($ref) > MAX_MID_SIZE) {
253 warn "References: <$ref> too long, ignoring\n";
261 $smsg->{references} = '<'.join('> <', @refs).'>';
263 # first ref *should* be the thread root,
264 # but we can never trust clients to do the right thing
265 my $ref = shift @refs;
266 $tid = $self->_resolve_mid_to_tid($ref);
267 $self->merge_threads($tid, $old_tid) if defined $old_tid;
269 # the rest of the refs should point to this tid:
270 foreach $ref (@refs) {
271 my $ptid = $self->_resolve_mid_to_tid($ref);
272 merge_threads($self, $tid, $ptid);
275 $tid = $self->next_thread_id;
277 $doc->add_term(xpfx('thread') . $tid);
281 my ($self, $mime, $bytes, $num, $blob) = @_;
282 $self->add_message($mime, $bytes, $num, $blob);
286 my ($self, $mime) = @_;
287 my $mid = eval { mid_clean(mid_mime($mime)) };
288 $self->remove_message($mid) if defined $mid;
292 my ($self, $mime) = @_;
293 $self->{mm}->mid_insert(mid_clean(mid_mime($mime)));
297 my ($self, $mime) = @_;
298 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
302 my ($self, $mime, $bytes, $blob) = @_;
303 my $num = $self->{mm}->num_for(mid_clean(mid_mime($mime)));
304 index_blob($self, $mime, $bytes, $num, $blob);
308 my ($self, $mime) = @_;
309 $self->{mm}->mid_delete(mid_clean(mid_mime($mime)));
310 unindex_blob($self, $mime);
314 my ($self, $mime, $bytes, $blob) = @_;
315 my $num = index_mm($self, $mime);
316 index_blob($self, $mime, $bytes, $num, $blob);
320 my ($self, $mime) = @_;
321 unindex_blob($self, $mime);
322 unindex_mm($self, $mime);
326 my ($git, $blob, $sizeref) = @_;
328 my $str = $git->cat_file($blob, $sizeref);
329 # fixup bugs from import:
330 $$str =~ s/\A[\r\n]*From [^\r\n]*\r?\n//s;
331 Email::MIME->new($str);
337 my ($self, $opts) = @_;
338 with_umask($self, sub { $self->_index_sync($opts) });
342 my ($self, $log, $add_cb, $del_cb, $batch_cb) = @_;
343 my $hex = '[a-f0-9]';
344 my $h40 = $hex .'{40}';
345 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
346 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
347 my $git = $self->{git};
350 my $max = $self->{batch_size}; # may be undef
353 while (defined($line = <$log>)) {
354 if ($line =~ /$addmsg/o) {
356 my $mime = do_cat_mail($git, $blob, \$bytes) or next;
357 $add_cb->($self, $mime, $bytes, $blob);
358 } elsif ($line =~ /$delmsg/o) {
360 my $mime = do_cat_mail($git, $blob) or next;
361 $del_cb->($self, $mime);
362 } elsif ($line =~ /^commit ($h40)/o) {
363 if (defined $max && --$max <= 0) {
364 $max = $self->{batch_size};
365 $batch_cb->($latest, 1);
370 $batch_cb->($latest, 0);
376 require PublicInbox::Msgmap;
377 PublicInbox::Msgmap->new($self->{git_dir}, 1);
382 my ($self, $range) = @_;
383 $self->{git}->popen(qw/log --reverse --no-notes --no-color
384 --raw -r --no-abbrev/, $range);
387 # indexes all unindexed messages
389 my ($self, $opts) = @_;
390 my $tip = $opts->{ref} || 'HEAD';
391 my $reindex = $opts->{reindex};
392 my ($mkey, $last_commit, $lx, $xlog);
393 $self->{git}->batch_prepare;
394 my $xdb = _xdb_acquire($self);
395 $xdb->begin_transaction;
398 $mkey = 'last_commit';
399 $last_commit = $xdb->get_metadata('last_commit');
403 $mkey = undef if $last_commit ne '';
405 $xdb->cancel_transaction;
406 $xdb = _xdb_release($self);
408 # ensure we leak no FDs to "git log"
409 my $range = $lx eq '' ? $tip : "$lx..$tip";
410 $xlog = _git_log($self, $range);
412 $xdb = _xdb_acquire($self);
413 $xdb->begin_transaction;
414 } while ($xdb->get_metadata('last_commit') ne $last_commit);
416 my $mm = _msgmap_init($self);
417 my $dbh = $mm->{dbh} if $mm;
419 my ($commit, $more) = @_;
421 $mm->last_commit($commit) if $commit;
424 $xdb->set_metadata($mkey, $commit) if $mkey && $commit;
425 $xdb->commit_transaction;
426 $xdb = _xdb_release($self);
427 # let another process do some work... <
429 $xdb = _xdb_acquire($self);
430 $xdb->begin_transaction;
431 $dbh->begin_work if $dbh;
437 my $lm = $mm->last_commit || '';
439 # Common case is the indexes are synced,
440 # we only need to run git-log once:
441 rlog($self, $xlog, *index_both, *unindex_both, $cb);
443 # Uncommon case, msgmap and xapian are out-of-sync
444 # do not care for performance (but git is fast :>)
445 # This happens if we have to reindex Xapian since
446 # msgmap is a frozen format and our Xapian format
448 my $r = $lm eq '' ? $tip : "$lm..$tip";
450 # first, ensure msgmap is up-to-date:
451 my $mkey_prev = $mkey;
452 $mkey = undef; # ignore xapian, for now
453 my $mlog = _git_log($self, $r);
454 rlog($self, $mlog, *index_mm, *unindex_mm, $cb);
457 # now deal with Xapian
460 $xdb = _xdb_acquire($self);
461 $xdb->begin_transaction;
462 rlog($self, $xlog, *index_mm2, *unindex_mm2, $cb);
465 # user didn't install DBD::SQLite and DBI
466 rlog($self, $xlog, *index_blob, *unindex_blob, $cb);
470 # this will create a ghost as necessary
471 sub _resolve_mid_to_tid {
472 my ($self, $mid) = @_;
474 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
479 my ($self, $mid) = @_;
481 my $tid = $self->next_thread_id;
482 my $doc = Search::Xapian::Document->new;
483 $doc->add_term(xpfx('mid') . $mid);
484 $doc->add_term(xpfx('thread') . $tid);
485 $doc->add_term(xpfx('type') . 'ghost');
487 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
488 $self->{xdb}->add_document($doc);
494 my ($self, $winner_tid, $loser_tid) = @_;
495 return if $winner_tid == $loser_tid;
496 my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
497 my $thread_pfx = xpfx('thread');
498 my $db = $self->{xdb};
500 for (; $head != $tail; $head->inc) {
501 my $docid = $head->get_docid;
502 my $doc = $db->get_document($docid);
503 $doc->remove_term($thread_pfx . $loser_tid);
504 $doc->add_term($thread_pfx . $winner_tid);
505 $db->replace_document($docid, $doc);
509 sub _read_git_config_perm {
511 my @cmd = qw(config core.sharedRepository);
512 my $fh = PublicInbox::Git->new($self->{git_dir})->popen(@cmd);
515 chomp $perm if defined $perm;
519 sub _git_config_perm {
521 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
522 return PERM_GROUP if (!defined($perm) || $perm eq '');
523 return PERM_UMASK if ($perm eq 'umask');
524 return PERM_GROUP if ($perm eq 'group');
525 if ($perm =~ /\A(?:all|world|everybody)\z/) {
526 return PERM_EVERYBODY;
528 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
529 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
532 return PERM_UMASK if ($i == PERM_UMASK);
533 return PERM_GROUP if ($i == OLD_PERM_GROUP);
534 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
536 if (($i & 0600) != 0600) {
537 die "core.sharedRepository mode invalid: ".
538 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
544 my ($perm) = @_; # _git_config_perm return value
546 return umask if $rv == 0;
548 # set +x bit if +r or +w were set
549 $rv |= 0100 if ($rv & 0600);
550 $rv |= 0010 if ($rv & 0060);
551 $rv |= 0001 if ($rv & 0006);
556 my ($self, $cb) = @_;
557 my $old = umask $self->{umask};
558 my $rv = eval { $cb->() };
566 # order matters for unlocking
567 $_[0]->{xdb} = undef;
568 $_[0]->{lockfh} = undef;