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