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