]> git.cworth.org Git - sup/blob - lib/sup/xapian_index.rb
move all GDBM data into Xapian
[sup] / lib / sup / xapian_index.rb
1 require 'xapian'
2 require 'set'
3
4 module Redwood
5
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"
11
12   ## dates are converted to integers for xapian, and are used for document ids,
13   ## so we must ensure they're reasonably valid. this typically only affect
14   ## spam.
15   MIN_DATE = Time.at 0
16   MAX_DATE = Time.at(2**31-1)
17
18   def initialize dir=BASE_DIR
19     super
20
21     @index_mutex = Monitor.new
22   end
23
24   def load_index
25     @xapian = Xapian::WritableDatabase.new(File.join(@dir, "xapian"), Xapian::DB_CREATE_OR_OPEN)
26     @term_generator = Xapian::TermGenerator.new()
27     @term_generator.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
28     @enquire = Xapian::Enquire.new @xapian
29     @enquire.weighting_scheme = Xapian::BoolWeight.new
30     @enquire.docid_order = Xapian::Enquire::ASCENDING
31   end
32
33   def save_index
34   end
35
36   def optimize
37   end
38
39   def size
40     synchronize { @xapian.doccount }
41   end
42
43   def contains_id? id
44     synchronize { find_docid(id) && true }
45   end
46
47   def source_for_id id
48     synchronize { get_entry(id)[:source_id] }
49   end
50
51   def delete id
52     synchronize { @xapian.delete_document mkterm(:msgid, id) }
53   end
54
55   def build_message id
56     entry = synchronize { get_entry id }
57     return unless entry
58
59     source = SourceManager[entry[:source_id]]
60     raise "invalid source #{entry[:source_id]}" unless source
61
62     mk_addrs = lambda { |l| l.map { |e,n| "#{n} <#{e}>" } * ', ' }
63     mk_refs = lambda { |l| l.map { |r| "<#{r}>" } * ' ' }
64     fake_header = {
65       'message-id' => entry[:message_id],
66       'date' => Time.at(entry[:date]),
67       'subject' => entry[:subject],
68       'from' => mk_addrs[[entry[:from]]],
69       'to' => mk_addrs[entry[:to]],
70       'cc' => mk_addrs[entry[:cc]],
71       'bcc' => mk_addrs[entry[:bcc]],
72       'reply-tos' => mk_refs[entry[:replytos]],
73       'references' => mk_refs[entry[:refs]],
74      }
75
76       m = Message.new :source => source, :source_info => entry[:source_info],
77                   :labels => entry[:labels],
78                   :snippet => entry[:snippet]
79       m.parse_header fake_header
80       m
81   end
82
83   def sync_message m, opts={}
84     entry = synchronize { get_entry m.id }
85     snippet = m.snippet
86     entry ||= {}
87     labels = m.labels
88     entry = {} if opts[:force_overwrite]
89
90     d = {
91       :message_id => m.id,
92       :source_id => m.source.id,
93       :source_info => m.source_info,
94       :date => (entry[:date] || m.date),
95       :snippet => snippet,
96       :labels => labels.uniq,
97       :from => (entry[:from] || [m.from.email, m.from.name]),
98       :to => (entry[:to] || m.to.map { |p| [p.email, p.name] }),
99       :cc => (entry[:cc] || m.cc.map { |p| [p.email, p.name] }),
100       :bcc => (entry[:bcc] || m.bcc.map { |p| [p.email, p.name] }),
101       :subject => m.subj,
102       :refs => (entry[:refs] || m.refs),
103       :replytos => (entry[:replytos] || m.replytos),
104     }
105
106     m.labels.each { |l| LabelManager << l }
107
108     synchronize do
109       index_message m, d, opts
110     end
111     true
112   end
113
114   def num_results_for query={}
115     xapian_query = build_xapian_query query
116     matchset = run_query xapian_query, 0, 0, 100
117     matchset.matches_estimated
118   end
119
120   EACH_ID_PAGE = 100
121   def each_id query={}
122     offset = 0
123     page = EACH_ID_PAGE
124
125     xapian_query = build_xapian_query query
126     while true
127       ids = run_query_ids xapian_query, offset, (offset+page)
128       ids.each { |id| yield id }
129       break if ids.size < page
130       offset += page
131     end
132   end
133
134   def each_id_by_date query={}
135     each_id(query) { |id| yield id, lambda { build_message id } }
136   end
137
138   def each_message_in_thread_for m, opts={}
139     # TODO thread by subject
140     # TODO handle killed threads
141     return unless doc = find_doc(m.id)
142     queue = doc.value(THREAD_VALUENO).split(',')
143     msgids = [m.id]
144     seen_threads = Set.new
145     seen_messages = Set.new [m.id]
146     while not queue.empty?
147       thread_id = queue.pop
148       next if seen_threads.member? thread_id
149       return false if thread_killed? thread_id
150       seen_threads << thread_id
151       docs = term_docids(mkterm(:thread, thread_id)).map { |x| @xapian.document x }
152       docs.each do |doc|
153         msgid = doc.value MSGID_VALUENO
154         next if seen_messages.member? msgid
155         msgids << msgid
156         seen_messages << msgid
157         queue.concat doc.value(THREAD_VALUENO).split(',')
158       end
159     end
160     msgids.each { |id| yield id, lambda { build_message id } }
161     true
162   end
163
164   def load_contacts emails, opts={}
165     contacts = Set.new
166     num = opts[:num] || 20
167     each_id_by_date :participants => emails do |id,b|
168       break if contacts.size >= num
169       m = b.call
170       ([m.from]+m.to+m.cc+m.bcc).compact.each { |p| contacts << [p.name, p.email] }
171     end
172     contacts.to_a.compact.map { |n,e| Person.new n, e }[0...num]
173   end
174
175   # TODO share code with the Ferret index
176   def parse_query s
177     query = {}
178
179     subs = s.gsub(/\b(to|from):(\S+)\b/) do
180       field, name = $1, $2
181       if(p = ContactManager.contact_for(name))
182         [field, p.email]
183       elsif name == "me"
184         [field, "(" + AccountManager.user_emails.join("||") + ")"]
185       else
186         [field, name]
187       end.join(":")
188     end
189
190     ## if we see a label:deleted or a label:spam term anywhere in the query
191     ## string, we set the extra load_spam or load_deleted options to true.
192     ## bizarre? well, because the query allows arbitrary parenthesized boolean
193     ## expressions, without fully parsing the query, we can't tell whether
194     ## the user is explicitly directing us to search spam messages or not.
195     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
196     ## search spam messages or not?
197     ##
198     ## so, we rely on the fact that turning these extra options ON turns OFF
199     ## the adding of "-label:deleted" or "-label:spam" terms at the very
200     ## final stage of query processing. if the user wants to search spam
201     ## messages, not adding that is the right thing; if he doesn't want to
202     ## search spam messages, then not adding it won't have any effect.
203     query[:load_spam] = true if subs =~ /\blabel:spam\b/
204     query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
205
206     ## gmail style "is" operator
207     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
208       field, label = $1, $2
209       case label
210       when "read"
211         "-label:unread"
212       when "spam"
213         query[:load_spam] = true
214         "label:spam"
215       when "deleted"
216         query[:load_deleted] = true
217         "label:deleted"
218       else
219         "label:#{$2}"
220       end
221     end
222
223     ## gmail style attachments "filename" and "filetype" searches
224     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
225       field, name = $1, ($3 || $4)
226       case field
227       when "filename"
228         Redwood::log "filename - translated #{field}:#{name} to attachment:\"#{name.downcase}\""
229         "attachment:\"#{name.downcase}\""
230       when "filetype"
231         Redwood::log "filetype - translated #{field}:#{name} to attachment_extension:#{name.downcase}"
232         "attachment_extension:#{name.downcase}"
233       end
234     end
235
236     if $have_chronic
237       lastdate = 2<<32 - 1
238       firstdate = 0
239       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
240         field, datestr = $1, ($3 || $4)
241         realdate = Chronic.parse datestr, :guess => false, :context => :past
242         if realdate
243           case field
244           when "after"
245             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
246             "date:#{realdate.end.to_i}..#{lastdate}"
247           when "before"
248             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
249             "date:#{firstdate}..#{realdate.end.to_i}"
250           else
251             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
252             "date:#{realdate.begin.to_i}..#{realdate.end.to_i}"
253           end
254         else
255           raise ParseError, "can't understand date #{datestr.inspect}"
256         end
257       end
258     end
259
260     ## limit:42 restrict the search to 42 results
261     subs = subs.gsub(/\blimit:(\S+)\b/) do
262       lim = $1
263       if lim =~ /^\d+$/
264         query[:limit] = lim.to_i
265         ''
266       else
267         raise ParseError, "non-numeric limit #{lim.inspect}"
268       end
269     end
270
271     qp = Xapian::QueryParser.new
272     qp.database = @xapian
273     qp.stemmer = Xapian::Stem.new(STEM_LANGUAGE)
274     qp.stemming_strategy = Xapian::QueryParser::STEM_SOME
275     qp.default_op = Xapian::Query::OP_AND
276     qp.add_valuerangeprocessor(Xapian::NumberValueRangeProcessor.new(DATE_VALUENO, 'date:', true))
277     NORMAL_PREFIX.each { |k,v| qp.add_prefix k, v }
278     BOOLEAN_PREFIX.each { |k,v| qp.add_boolean_prefix k, v }
279     xapian_query = qp.parse_query(subs, Xapian::QueryParser::FLAG_PHRASE|Xapian::QueryParser::FLAG_BOOLEAN|Xapian::QueryParser::FLAG_LOVEHATE|Xapian::QueryParser::FLAG_WILDCARD, PREFIX['body'])
280
281     raise ParseError if xapian_query.nil? or xapian_query.empty?
282     query[:qobj] = xapian_query
283     query[:text] = s
284     query
285   end
286
287   private
288
289   # Stemmed
290   NORMAL_PREFIX = {
291     'subject' => 'S',
292     'body' => 'B',
293     'from_name' => 'FN',
294     'to_name' => 'TN',
295     'name' => 'N',
296     'attachment' => 'A',
297   }
298
299   # Unstemmed
300   BOOLEAN_PREFIX = {
301     'type' => 'K',
302     'from_email' => 'FE',
303     'to_email' => 'TE',
304     'email' => 'E',
305     'date' => 'D',
306     'label' => 'L',
307     'source_id' => 'I',
308     'attachment_extension' => 'O',
309     'msgid' => 'Q',
310     'thread' => 'H',
311     'ref' => 'R',
312   }
313
314   PREFIX = NORMAL_PREFIX.merge BOOLEAN_PREFIX
315
316   MSGID_VALUENO = 0
317   THREAD_VALUENO = 1
318   DATE_VALUENO = 2
319
320   MAX_TERM_LENGTH = 245
321
322   # Xapian can very efficiently sort in ascending docid order. Sup always wants
323   # to sort by descending date, so this method maps between them. In order to
324   # handle multiple messages per second, we use a logistic curve centered
325   # around MIDDLE_DATE so that the slope (docid/s) is greatest in this time
326   # period. A docid collision is not an error - the code will pick the next
327   # smallest unused one.
328   DOCID_SCALE = 2.0**32
329   TIME_SCALE = 2.0**27
330   MIDDLE_DATE = Time.gm(2011)
331   def assign_docid m, truncated_date
332     t = (truncated_date.to_i - MIDDLE_DATE.to_i).to_f
333     docid = (DOCID_SCALE - DOCID_SCALE/(Math::E**(-(t/TIME_SCALE)) + 1)).to_i
334     while docid > 0 and docid_exists? docid
335       docid -= 1
336     end
337     docid > 0 ? docid : nil
338   end
339
340   # XXX is there a better way?
341   def docid_exists? docid
342     begin
343       @xapian.doclength docid
344       true
345     rescue RuntimeError #Xapian::DocNotFoundError
346       raise unless $!.message =~ /DocNotFoundError/
347       false
348     end
349   end
350
351   def term_docids term
352     @xapian.postlist(term).map { |x| x.docid }
353   end
354
355   def find_docid id
356     term_docids(mkterm(:msgid,id)).tap { |x| fail unless x.size <= 1 }.first
357   end
358
359   def find_doc id
360     return unless docid = find_docid(id)
361     @xapian.document docid
362   end
363
364   def get_id docid
365     return unless doc = @xapian.document(docid)
366     doc.value MSGID_VALUENO
367   end
368
369   def get_entry id
370     return unless doc = find_doc(id)
371     Marshal.load doc.data
372   end
373
374   def thread_killed? thread_id
375     not run_query(Q.new(Q::OP_AND, mkterm(:thread, thread_id), mkterm(:label, :Killed)), 0, 1).empty?
376   end
377
378   def synchronize &b
379     @index_mutex.synchronize &b
380   end
381
382   def run_query xapian_query, offset, limit, checkatleast=0
383     synchronize do
384       @enquire.query = xapian_query
385       @enquire.mset(offset, limit-offset, checkatleast)
386     end
387   end
388
389   def run_query_ids xapian_query, offset, limit
390     matchset = run_query xapian_query, offset, limit
391     matchset.matches.map { |r| r.document.value MSGID_VALUENO }
392   end
393
394   Q = Xapian::Query
395   def build_xapian_query opts
396     labels = ([opts[:label]] + (opts[:labels] || [])).compact
397     neglabels = [:spam, :deleted, :killed].reject { |l| (labels.include? l) || opts.member?("load_#{l}".intern) }
398     pos_terms, neg_terms = [], []
399
400     pos_terms << mkterm(:type, 'mail')
401     pos_terms.concat(labels.map { |l| mkterm(:label,l) })
402     pos_terms << opts[:qobj] if opts[:qobj]
403     pos_terms << mkterm(:source_id, opts[:source_id]) if opts[:source_id]
404
405     if opts[:participants]
406       participant_terms = opts[:participants].map { |p| mkterm(:email,:any, (Redwood::Person === p) ? p.email : p) }
407       pos_terms << Q.new(Q::OP_OR, participant_terms)
408     end
409
410     neg_terms.concat(neglabels.map { |l| mkterm(:label,l) })
411
412     pos_query = Q.new(Q::OP_AND, pos_terms)
413     neg_query = Q.new(Q::OP_OR, neg_terms)
414
415     if neg_query.empty?
416       pos_query
417     else
418       Q.new(Q::OP_AND_NOT, [pos_query, neg_query])
419     end
420   end
421
422   def index_message m, entry, opts
423     terms = []
424     text = []
425
426     subject_text = m.indexable_subject
427     body_text = m.indexable_body
428
429     # Person names are indexed with several prefixes
430     person_termer = lambda do |d|
431       lambda do |p|
432         ["#{d}_name", "name", "body"].each do |x|
433           text << [p.name, PREFIX[x]]
434         end if p.name
435         [d, :any].each { |x| terms << mkterm(:email, x, p.email) }
436       end
437     end
438
439     person_termer[:from][m.from] if m.from
440     (m.to+m.cc+m.bcc).each(&(person_termer[:to]))
441
442     terms << mkterm(:date,m.date) if m.date
443     m.labels.each { |t| terms << mkterm(:label,t) }
444     terms << mkterm(:type, 'mail')
445     terms << mkterm(:msgid, m.id)
446     terms << mkterm(:source_id, m.source.id)
447     m.attachments.each do |a|
448       a =~ /\.(\w+)$/ or next
449       t = mkterm(:attachment_extension, $1)
450       terms << t
451     end
452
453     ## Thread membership
454     children = term_docids(mkterm(:ref, m.id)).map { |docid| @xapian.document docid }
455     parent_ids = m.refs + m.replytos
456     parents = parent_ids.map { |id| find_doc id }.compact
457     thread_members = SavingHash.new { [] }
458     (children + parents).each do |doc2|
459       thread_ids = doc2.value(THREAD_VALUENO).split ','
460       thread_ids.each { |thread_id| thread_members[thread_id] << doc2 }
461     end
462
463     thread_ids = thread_members.empty? ? [m.id] : thread_members.keys
464
465     thread_ids.each { |thread_id| terms << mkterm(:thread, thread_id) }
466     parent_ids.each do |ref|
467       terms << mkterm(:ref, ref)
468     end
469
470     # Full text search content
471     text << [subject_text, PREFIX['subject']]
472     text << [subject_text, PREFIX['body']]
473     text << [body_text, PREFIX['body']]
474     m.attachments.each { |a| text << [a, PREFIX['attachment']] }
475
476     truncated_date = if m.date < MIN_DATE
477       Redwood::log "warning: adjusting too-low date #{m.date} for indexing"
478       MIN_DATE
479     elsif m.date > MAX_DATE
480       Redwood::log "warning: adjusting too-high date #{m.date} for indexing"
481       MAX_DATE
482     else
483       m.date
484     end
485
486     # Date value for range queries
487     date_value = begin
488       Xapian.sortable_serialise truncated_date.to_i
489     rescue TypeError
490       Xapian.sortable_serialise 0
491     end
492
493     docid = nil
494     unless doc = find_doc(m.id)
495       doc = Xapian::Document.new
496       if not docid = assign_docid(m, truncated_date)
497         # Could be triggered by spam
498         Redwood::log "warning: docid underflow, dropping #{m.id.inspect}"
499         return
500       end
501     else
502       doc.clear_terms
503       doc.clear_values
504       docid = doc.docid
505     end
506
507     @term_generator.document = doc
508     text.each { |text,prefix| @term_generator.index_text text, 1, prefix }
509     terms.each { |term| doc.add_term term if term.length <= MAX_TERM_LENGTH }
510     doc.add_value MSGID_VALUENO, m.id
511     doc.add_value THREAD_VALUENO, (thread_ids * ',')
512     doc.add_value DATE_VALUENO, date_value
513     doc.data = Marshal.dump entry
514
515     @xapian.replace_document docid, doc
516   end
517
518   # Construct a Xapian term
519   def mkterm type, *args
520     case type
521     when :label
522       PREFIX['label'] + args[0].to_s.downcase
523     when :type
524       PREFIX['type'] + args[0].to_s.downcase
525     when :date
526       PREFIX['date'] + args[0].getutc.strftime("%Y%m%d%H%M%S")
527     when :email
528       case args[0]
529       when :from then PREFIX['from_email']
530       when :to then PREFIX['to_email']
531       when :any then PREFIX['email']
532       else raise "Invalid email term type #{args[0]}"
533       end + args[1].to_s.downcase
534     when :source_id
535       PREFIX['source_id'] + args[0].to_s.downcase
536     when :attachment_extension
537       PREFIX['attachment_extension'] + args[0].to_s.downcase
538     when :msgid, :ref, :thread
539       PREFIX[type.to_s] + args[0][0...(MAX_TERM_LENGTH-1)]
540     else
541       raise "Invalid term type #{type}"
542     end
543   end
544
545 end
546
547 end