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