6 # This index implementation uses Xapian for searching and GDBM for storage. It
7 # tends to be slightly faster than Ferret for indexing and significantly faster
8 # for searching due to precomputing thread membership.
9 class XapianIndex < BaseIndex
10 STEM_LANGUAGE = "english"
13 ## dates are converted to integers for xapian, and are used for document ids,
14 ## so we must ensure they're reasonably valid. this typically only affect
17 MAX_DATE = Time.at(2**31-1)
19 def initialize dir=BASE_DIR
22 @index_mutex = Monitor.new
26 path = File.join(@dir, 'xapian')
28 @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_OPEN)
29 db_version = @xapian.get_metadata 'version'
30 db_version = '0' if db_version.empty?
31 if db_version != INDEX_VERSION
32 fail "This Sup version expects a v#{INDEX_VERSION} index, but you have an existing v#{db_version} index. Please downgrade to your previous version and dump your labels before upgrading to this version (then run sup-sync --restore)."
35 @xapian = Xapian::WritableDatabase.new(path, Xapian::DB_CREATE)
36 @xapian.set_metadata 'version', INDEX_VERSION
38 @term_generator = Xapian::TermGenerator.new()
39 @term_generator.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
40 @enquire = Xapian::Enquire.new @xapian
41 @enquire.weighting_scheme = Xapian::BoolWeight.new
42 @enquire.docid_order = Xapian::Enquire::ASCENDING
52 synchronize { @xapian.doccount }
56 synchronize { find_docid(id) && true }
60 synchronize { get_entry(id)[:source_id] }
64 synchronize { @xapian.delete_document mkterm(:msgid, id) }
68 entry = synchronize { get_entry id }
71 source = SourceManager[entry[:source_id]]
72 raise "invalid source #{entry[:source_id]}" unless source
74 mk_addrs = lambda { |l| l.map { |e,n| "#{n} <#{e}>" } * ', ' }
75 mk_refs = lambda { |l| l.map { |r| "<#{r}>" } * ' ' }
77 'message-id' => entry[:message_id],
78 'date' => Time.at(entry[:date]),
79 'subject' => entry[:subject],
80 'from' => mk_addrs[[entry[:from]]],
81 'to' => mk_addrs[entry[:to]],
82 'cc' => mk_addrs[entry[:cc]],
83 'bcc' => mk_addrs[entry[:bcc]],
84 'reply-tos' => mk_refs[entry[:replytos]],
85 'references' => mk_refs[entry[:refs]],
88 m = Message.new :source => source, :source_info => entry[:source_info],
89 :labels => entry[:labels],
90 :snippet => entry[:snippet]
91 m.parse_header fake_header
95 def add_message m; sync_message m end
96 def update_message m; sync_message m end
97 def update_message_state m; sync_message m end
99 def sync_message m, opts={}
100 entry = synchronize { get_entry m.id }
104 entry = {} if opts[:force_overwrite]
108 :source_id => m.source.id,
109 :source_info => m.source_info,
110 :date => (entry[:date] || m.date),
113 :from => (entry[:from] || [m.from.email, m.from.name]),
114 :to => (entry[:to] || m.to.map { |p| [p.email, p.name] }),
115 :cc => (entry[:cc] || m.cc.map { |p| [p.email, p.name] }),
116 :bcc => (entry[:bcc] || m.bcc.map { |p| [p.email, p.name] }),
118 :refs => (entry[:refs] || m.refs),
119 :replytos => (entry[:replytos] || m.replytos),
122 labels.each { |l| LabelManager << l }
125 index_message m, d, opts
129 private :sync_message
131 def num_results_for query={}
132 xapian_query = build_xapian_query query
133 matchset = run_query xapian_query, 0, 0, 100
134 matchset.matches_estimated
142 xapian_query = build_xapian_query query
144 ids = run_query_ids xapian_query, offset, (offset+page)
145 ids.each { |id| yield id }
146 break if ids.size < page
151 def each_id_by_date query={}
152 each_id(query) { |id| yield id, lambda { build_message id } }
155 def each_message_in_thread_for m, opts={}
156 # TODO thread by subject
157 # TODO handle killed threads
158 return unless doc = find_doc(m.id)
159 queue = doc.value(THREAD_VALUENO).split(',')
161 seen_threads = Set.new
162 seen_messages = Set.new [m.id]
163 while not queue.empty?
164 thread_id = queue.pop
165 next if seen_threads.member? thread_id
166 return false if thread_killed? thread_id
167 seen_threads << thread_id
168 docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
170 msgid = doc.value MSGID_VALUENO
171 next if seen_messages.member? msgid
173 seen_messages << msgid
174 queue.concat doc.value(THREAD_VALUENO).split(',')
177 msgids.each { |id| yield id, lambda { build_message id } }
181 def load_contacts emails, opts={}
183 num = opts[:num] || 20
184 each_id_by_date :participants => emails do |id,b|
185 break if contacts.size >= num
187 ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
189 contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
192 # TODO share code with the Ferret index
196 subs = s.gsub(/\b(to|from):(\S+)\b/) do
198 if(p = ContactManager.contact_for(name))
201 [field, "(" + AccountManager.user_emails.join("||") + ")"]
207 ## if we see a label:deleted or a label:spam term anywhere in the query
208 ## string, we set the extra load_spam or load_deleted options to true.
209 ## bizarre? well, because the query allows arbitrary parenthesized boolean
210 ## expressions, without fully parsing the query, we can't tell whether
211 ## the user is explicitly directing us to search spam messages or not.
212 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
213 ## search spam messages or not?
215 ## so, we rely on the fact that turning these extra options ON turns OFF
216 ## the adding of "-label:deleted" or "-label:spam" terms at the very
217 ## final stage of query processing. if the user wants to search spam
218 ## messages, not adding that is the right thing; if he doesn't want to
219 ## search spam messages, then not adding it won't have any effect.
220 query[:load_spam] = true if subs =~ /\blabel:spam\b/
221 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
223 ## gmail style "is" operator
224 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
225 field, label = $1, $2
230 query[:load_spam] = true
233 query[:load_deleted] = true
240 ## gmail style attachments "filename" and "filetype" searches
241 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
242 field, name = $1, ($3 || $4)
245 debug "filename: translated #{field}:#{name} to attachment:\"#{name.downcase}\""
246 "attachment:\"#{name.downcase}\""
248 debug "filetype: translated #{field}:#{name} to attachment_extension:#{name.downcase}"
249 "attachment_extension:#{name.downcase}"
256 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
257 field, datestr = $1, ($3 || $4)
258 realdate = Chronic.parse datestr, :guess => false, :context => :past
262 debug "chronic: translated #{field}:#{datestr} to #{realdate.end}"
263 "date:#{realdate.end.to_i}..#{lastdate}"
265 debug "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
266 "date:#{firstdate}..#{realdate.end.to_i}"
268 debug "chronic: translated #{field}:#{datestr} to #{realdate}"
269 "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
272 raise ParseError, "can't understand date #{datestr.inspect}"
277 ## limit:42 restrict the search to 42 results
278 subs = subs.gsub(/\blimit:(\S+)\b/) do
281 query[:limit] = lim.to_i
284 raise ParseError, "non-numeric limit #{lim.inspect}"
288 qp = Xapian::QueryParser.new
289 qp.database = @xapian
290 qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
291 qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
292 qp.default_op = Xapian::Query::OP_AND
293 qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
294 NORMAL_PREFIX.each { |k,v| qp.add_prefix k, v }
295 BOOLEAN_PREFIX.each { |k,v| qp.add_boolean_prefix k, v }
296 xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD, PREFIX['body'])
298 raise ParseError if xapian_query.nil? or xapian_query.empty?
299 query[:qobj] = xapian_query
319 'from_email' => 'FE',
325 'attachment_extension' => 'O',
331 PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
337 MAX_TERM_LENGTH = 245
339 # Xapian can very efficiently sort in ascending docid order. Sup always wants
340 # to sort by descending date, so this method maps between them. In order to
341 # handle multiple messages per second, we use a logistic curve centered
342 # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
343 # period. A docid collision is not an error - the code will pick the next
344 # smallest unused one.
345 DOCID_SCALE = 2.0**32
347 MIDDLE_DATE = Time.gm(2011)
348 def assign_docid m, truncated_date
349 t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
350 docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
351 while docid > 0 and docid_exists? docid
354 docid > 0 ? docid : nil
357 # XXX is there a better way?
358 def docid_exists? docid
360 @xapian.doclength docid
362 rescue RuntimeError #Xapian::DocNotFoundError
363 raise unless $!.message =~ /DocNotFoundError/
369 @xapian.postlist(term).map { |x| x.docid }
373 term_docids(mkterm(:msgid,id)).tap { |x| fail unless x.size <= 1 }.first
377 return unless docid = find_docid(id)
378 @xapian.document docid
382 return unless doc = @xapian.document(docid)
383 doc.value MSGID_VALUENO
387 return unless doc = find_doc(id)
388 Marshal.load doc.data
391 def thread_killed? thread_id
392 not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
396 @index_mutex.synchronize &b
399 def run_query xapian_query, offset, limit, checkatleast=0
401 @enquire.query = xapian_query
402 @enquire.mset(offset, limit-offset, checkatleast)
406 def run_query_ids xapian_query, offset, limit
407 matchset = run_query xapian_query, offset, limit
408 matchset.matches.map { |r| r.document.value MSGID_VALUENO }
412 def build_xapian_query opts
413 labels = ([opts[:label]] + (opts[:labels] || [])).compact
414 neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
415 pos_terms, neg_terms = [], []
417 pos_terms << mkterm(:type, 'mail')
418 pos_terms.concat(labels.map { |l| mkterm(:label,l) })
419 pos_terms << opts[:qobj] if opts[:qobj]
420 pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
422 if opts[:participants]
423 participant_terms = opts[:participants].map { |p| mkterm(:email,:any, (Redwood::Person === p) ? p.email : p) }
424 pos_terms << Q.new(Q::OP_OR, participant_terms)
427 neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
429 pos_query = Q.new(Q::OP_AND, pos_terms)
430 neg_query = Q.new(Q::OP_OR, neg_terms)
435 Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
439 def index_message m, entry, opts
443 subject_text = m.indexable_subject
444 body_text = m.indexable_body
446 # Person names are indexed with several prefixes
447 person_termer = lambda do |d|
449 ["#{d}_name", "name", "body"].each do |x|
450 text << [p.name, PREFIX[x]]
452 [d, :any].each { |x| terms << mkterm(:email, x, p.email) }
456 person_termer[:from][m.from] if m.from
457 (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
459 terms << mkterm(:date,m.date) if m.date
460 m.labels.each { |t| terms << mkterm(:label,t) }
461 terms << mkterm(:type, 'mail')
462 terms << mkterm(:msgid, m.id)
463 terms << mkterm(:source_id, m.source.id)
464 m.attachments.each do |a|
465 a =~ /\.(\w+)$/ or next
466 t = mkterm(:attachment_extension, $1)
471 children = term_docids(mkterm(:ref, m.id)).map { |docid| @xapian.document docid }
472 parent_ids = m.refs + m.replytos
473 parents = parent_ids.map { |id| find_doc id }.compact
474 thread_members = SavingHash.new { [] }
475 (children + parents).each do |doc2|
476 thread_ids = doc2.value(THREAD_VALUENO).split ','
477 thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
480 thread_ids = thread_members.empty? ? [m.id] : thread_members.keys
482 thread_ids.each { |thread_id| terms << mkterm(:thread, thread_id) }
483 parent_ids.each do |ref|
484 terms << mkterm(:ref, ref)
487 # Full text search content
488 text << [subject_text, PREFIX['subject']]
489 text << [subject_text, PREFIX['body']]
490 text << [body_text, PREFIX['body']]
491 m.attachments.each { |a| text << [a, PREFIX['attachment']] }
493 truncated_date = if m.date < MIN_DATE
494 debug "warning: adjusting too-low date #{m.date} for indexing"
496 elsif m.date > MAX_DATE
497 debug "warning: adjusting too-high date #{m.date} for indexing"
503 # Date value for range queries
505 Xapian.sortable_serialise truncated_date.to_i
507 Xapian.sortable_serialise 0
511 unless doc = find_doc(m.id)
512 doc = Xapian::Document.new
513 if not docid = assign_docid(m, truncated_date)
514 # Could be triggered by spam
515 Redwood::log "warning: docid underflow, dropping #{m.id.inspect}"
524 @term_generator.document = doc
525 text.each { |text,prefix| @term_generator.index_text text, 1, prefix }
526 terms.each { |term| doc.add_term term if term.length <= MAX_TERM_LENGTH }
527 doc.add_value MSGID_VALUENO, m.id
528 doc.add_value THREAD_VALUENO, (thread_ids * ',')
529 doc.add_value DATE_VALUENO, date_value
530 doc.data = Marshal.dump entry
532 @xapian.replace_document docid, doc
535 # Construct a Xapian term
536 def mkterm type, *args
539 PREFIX['label'] + args[0].to_s.downcase
541 PREFIX['type'] + args[0].to_s.downcase
543 PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
546 when :from then PREFIX['from_email']
547 when :to then PREFIX['to_email']
548 when :any then PREFIX['email']
549 else raise "Invalid email term type #{args[0]}"
550 end + args[1].to_s.downcase
552 PREFIX['source_id'] + args[0].to_s.downcase
553 when :attachment_extension
554 PREFIX['attachment_extension'] + args[0].to_s.downcase
555 when :msgid, :ref, :thread
556 PREFIX[type.to_s] + args[0][0...(MAX_TERM_LENGTH-1)]
558 raise "Invalid term type #{type}"