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