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 package PublicInbox::SearchIdx;
7 use base qw(PublicInbox::Search);
8 use PublicInbox::MID qw/mid_clean mid_compressed/;
9 *xpfx = *PublicInbox::Search::xpfx;
14 OLD_PERM_EVERYBODY => 2,
16 PERM_EVERYBODY => 0664,
20 my ($class, $git_dir, $writable) = @_;
21 my $dir = $class->xdir($git_dir);
22 require Search::Xapian::WritableDatabase;
23 my $flag = Search::Xapian::DB_OPEN;
24 my $self = bless { git_dir => $git_dir }, $class;
25 my $perm = $self->_git_config_perm;
26 my $umask = _umask_for($perm);
27 $self->{umask} = $umask;
28 $self->{xdb} = $self->with_umask(sub {
31 File::Path::mkpath($dir);
32 $flag = Search::Xapian::DB_CREATE_OR_OPEN;
34 Search::Xapian::WritableDatabase->new($dir, $flag);
40 my ($self, $mime) = @_; # mime = Email::MIME object
41 my $db = $self->{xdb};
44 my $mid_orig = mid_clean($mime->header_obj->header('Message-ID'));
45 my $mid = mid_compressed($mid_orig);
47 my $ct_msg = $mime->header('Content-Type') || 'text/plain';
50 my $smsg = $self->lookup_message($mid);
54 $smsg->ensure_metadata;
55 # convert a ghost to a regular message
56 # it will also clobber any existing regular message
60 my $type = xpfx('type');
62 $doc->remove_term($type . 'ghost');
66 # probably does not exist:
67 eval { $doc->remove_term($type . 'mail') };
68 $doc->add_term($type . 'mail');
70 $smsg = PublicInbox::SearchMsg->new($mime);
72 $doc->add_term(xpfx('mid') . $mid);
75 my $subj = $smsg->subject;
78 $doc->add_term(xpfx('subject') . $subj);
80 my $path = $self->subject_path($subj);
81 $doc->add_term(xpfx('path') . mid_compressed($path));
84 my $from = $smsg->from_name;
85 my $date = $smsg->date;
86 my $ts = Search::Xapian::sortable_serialise($smsg->ts);
87 $doc->add_value(PublicInbox::Search::TS, $ts);
89 my $tg = $self->term_generator;
91 $tg->set_document($doc);
92 $tg->index_text($subj, 1, 'S') if $subj;
93 $tg->increase_termpos;
94 $tg->index_text($subj) if $subj;
95 $tg->increase_termpos;
97 $tg->index_text($smsg->from->format);
98 $tg->increase_termpos;
100 $mime->walk_parts(sub {
102 return if $part->subparts; # walk_parts already recurses
103 my $ct = $part->content_type || $ct_msg;
105 # account for filter bugs...
106 $ct =~ m!\btext/plain\b!i or return;
109 my $body = $part->body;
111 my @lines = split(/\n/, $body);
112 while (defined(my $l = shift @lines)) {
120 $tg->index_text(join("\n", @quot), 0);
122 $tg->increase_termpos;
125 $tg->index_text(join("\n", @orig));
127 $tg->increase_termpos;
132 $doc_id = $smsg->doc_id;
133 $self->link_message($smsg, 0);
134 $doc->set_data($smsg->to_doc_data);
135 $db->replace_document($doc_id, $doc);
137 $self->link_message($smsg, 0);
138 $doc->set_data($smsg->to_doc_data);
139 $doc_id = $db->add_document($doc);
144 warn "failed to index message <$mid_orig>: $@\n";
150 # returns deleted doc_id on success, undef on missing
152 my ($self, $mid_orig) = @_;
153 my $db = $self->{xdb};
155 $mid_orig = mid_clean($mid_orig);
156 my $mid = mid_compressed($mid_orig);
159 $doc_id = $self->find_unique_doc_id('mid', $mid);
160 $db->delete_document($doc_id) if defined $doc_id;
164 warn "failed to remove message <$mid_orig>: $@\n";
170 sub term_generator { # write-only
173 my $tg = $self->{term_generator};
176 $tg = Search::Xapian::TermGenerator->new;
177 $tg->set_stemmer($self->stemmer);
179 $self->{term_generator} = $tg;
182 sub next_doc_id { $_[0]->{xdb}->get_lastdocid + 1 }
184 # increments last_thread_id counter
185 # returns a 64-bit integer represented as a hex string
188 my $db = $self->{xdb};
189 my $last_thread_id = int($db->get_metadata('last_thread_id') || 0);
191 $db->set_metadata('last_thread_id', ++$last_thread_id);
197 my ($self, $smsg, $is_ghost) = @_;
200 $smsg->ensure_metadata;
202 $self->link_message_to_parents($smsg);
206 sub link_message_to_parents {
207 my ($self, $smsg) = @_;
208 my $doc = $smsg->{doc};
209 my $mid = mid_compressed($smsg->mid);
210 my $mime = $smsg->mime;
211 my $refs = $mime->header_obj->header('References');
212 my @refs = $refs ? ($refs =~ /<([^>]+)>/g) : ();
213 my $irt = $mime->header_obj->header('In-Reply-To');
215 $irt = mid_compressed(mid_clean($irt));
217 # maybe some crazies will try to make a circular reference:
221 # last References should be $irt
222 # we will de-dupe later
229 my @crefs = map { mid_compressed($_) } @refs;
230 my %uniq = ($mid => 1);
232 # prevent circular references via References: here:
234 foreach my $ref (@crefs) {
241 $doc->add_term(xpfx('inreplyto') . $irt) if defined $irt;
242 $smsg->{references_sorted} = '<'.join('><', @refs).'>';
244 my $ref_pfx = xpfx('references');
246 # first ref *should* be the thread root,
247 # but we can never trust clients to do the right thing
248 my $ref = shift @refs;
249 $doc->add_term($ref_pfx . $ref);
250 $tid = $self->_resolve_mid_to_tid($ref);
252 # the rest of the refs should point to this tid:
253 foreach $ref (@refs) {
254 $doc->add_term($ref_pfx . $ref);
255 my $ptid = $self->_resolve_mid_to_tid($ref);
257 $self->merge_threads($tid, $ptid);
261 $tid = $self->next_thread_id;
263 $doc->add_term(xpfx('thread') . $tid);
267 my ($self, $git, $blob) = @_;
268 my $mime = do_cat_mail($git, $blob) or return;
269 eval { $self->add_message($mime) };
270 warn "W: index_blob $blob: $@\n" if $@;
274 my ($self, $git, $blob) = @_;
275 my $mime = do_cat_mail($git, $blob) or return;
276 my $mid = $mime->header_obj->header('Message-ID');
277 eval { $self->remove_message($mid) } if defined $mid;
278 warn "W: unindex_blob $blob: $@\n" if $@;
282 my ($git, $blob) = @_;
284 my $str = $git->cat_file($blob);
285 Email::MIME->new($str);
291 my ($self, $head) = @_;
292 $self->with_umask(sub { $self->_index_sync($head) });
295 # indexes all unindexed messages
297 my ($self, $head) = @_;
298 require PublicInbox::GitCatFile;
299 my $db = $self->{xdb};
300 my $hex = '[a-f0-9]';
301 my $h40 = $hex .'{40}';
302 my $addmsg = qr!^:000000 100644 \S+ ($h40) A\t${hex}{2}/${hex}{38}$!;
303 my $delmsg = qr!^:100644 000000 ($h40) \S+ D\t${hex}{2}/${hex}{38}$!;
306 $db->begin_transaction;
308 my $git = PublicInbox::GitCatFile->new($self->{git_dir});
310 my $latest = $db->get_metadata('last_commit');
311 my $range = length $latest ? "$latest..$head" : $head;
314 # get indexed messages
315 my @cmd = ('git', "--git-dir=$self->{git_dir}", "log",
316 qw/--reverse --no-notes --no-color --raw -r
317 --no-abbrev/, $range);
318 my $pid = open(my $log, '-|', @cmd) or
319 die('open` '.join(' ', @cmd) . " pipe failed: $!\n");
321 while (my $line = <$log>) {
322 if ($line =~ /$addmsg/o) {
323 $self->index_blob($git, $1);
324 } elsif ($line =~ /$delmsg/o) {
325 $self->unindex_blob($git, $1);
326 } elsif ($line =~ /^commit ($h40)/o) {
331 $db->set_metadata('last_commit', $latest) if defined $latest;
334 warn "indexing failed: $@\n";
335 $db->cancel_transaction;
337 $db->commit_transaction;
341 # this will create a ghost as necessary
342 sub _resolve_mid_to_tid {
343 my ($self, $mid) = @_;
345 my $smsg = $self->lookup_message($mid) || $self->create_ghost($mid);
350 my ($self, $mid, $tid) = @_;
352 $mid = mid_compressed($mid);
353 $tid = $self->next_thread_id unless defined $tid;
355 my $doc = Search::Xapian::Document->new;
356 $doc->add_term(xpfx('mid') . $mid);
357 $doc->add_term(xpfx('thread') . $tid);
358 $doc->add_term(xpfx('type') . 'ghost');
360 my $smsg = PublicInbox::SearchMsg->wrap($doc, $mid);
361 $self->link_message($smsg, 1);
362 $self->{xdb}->add_document($doc);
368 my ($self, $winner_tid, $loser_tid) = @_;
369 my ($head, $tail) = $self->find_doc_ids('thread', $loser_tid);
370 my $thread_pfx = xpfx('thread');
371 my $db = $self->{xdb};
373 for (; $head != $tail; $head->inc) {
374 my $docid = $head->get_docid;
375 my $doc = $db->get_document($docid);
376 $doc->remove_term($thread_pfx . $loser_tid);
377 $doc->add_term($thread_pfx . $winner_tid);
378 $db->replace_document($docid, $doc);
382 sub _read_git_config_perm {
384 my @cmd = ('git', "--git-dir=$self->{git_dir}",
385 qw(config core.sharedRepository));
386 my $pid = open(my $fh, '-|', @cmd) or
387 die('open `'.join(' ', @cmd) . " pipe failed: $!\n");
390 chomp $perm if defined $perm;
394 sub _git_config_perm {
396 my $perm = scalar @_ ? $_[0] : _read_git_config_perm($self);
397 return PERM_GROUP if (!defined($perm) || !length($perm));
398 return PERM_UMASK if ($perm eq 'umask');
399 return PERM_GROUP if ($perm eq 'group');
400 if ($perm =~ /\A(?:all|world|everybody)\z/) {
401 return PERM_EVERYBODY;
403 return PERM_GROUP if ($perm =~ /\A(?:true|yes|on|1)\z/);
404 return PERM_UMASK if ($perm =~ /\A(?:false|no|off|0)\z/);
407 return PERM_UMASK if ($i == PERM_UMASK);
408 return PERM_GROUP if ($i == OLD_PERM_GROUP);
409 return PERM_EVERYBODY if ($i == OLD_PERM_EVERYBODY);
411 if (($i & 0600) != 0600) {
412 die "core.sharedRepository mode invalid: ".
413 sprintf('%.3o', $i) . "\nOwner must have permissions\n";
419 my ($perm) = @_; # _git_config_perm return value
421 return umask if $rv == 0;
423 # set +x bit if +r or +w were set
424 $rv |= 0100 if ($rv & 0600);
425 $rv |= 0010 if ($rv & 0060);
426 $rv |= 0001 if ($rv & 0006);
431 my ($self, $cb) = @_;
432 my $old = umask $self->{umask};
433 my $rv = eval { $cb->() };