]> git.cworth.org Git - sup/blob - lib/sup/index.rb
fixes for ruby1.9
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'fileutils'
4 require 'ferret'
5
6 begin
7   require 'chronic'
8   $have_chronic = true
9 rescue LoadError => e
10   Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
11   $have_chronic = false
12 end
13
14 module Redwood
15
16 class Index
17   class LockError < StandardError
18     def initialize h
19       @h = h
20     end
21
22     def method_missing m; @h[m.to_s] end
23   end
24
25   include Singleton
26
27   ## these two accessors should ONLY be used by single-threaded programs.
28   ## otherwise you will have a naughty ferret on your hands.
29   attr_reader :index
30   alias ferret index
31
32   def initialize dir=BASE_DIR
33     @index_mutex = Monitor.new
34
35     @dir = dir
36     @sources = {}
37     @sources_dirty = false
38     @source_mutex = Monitor.new
39
40     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
41     sa = Ferret::Analysis::StandardAnalyzer.new [], true
42     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
43     @analyzer[:body] = sa
44     @analyzer[:subject] = sa
45     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
46     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
47
48     self.class.i_am_the_instance self
49   end
50
51   def lockfile; File.join @dir, "lock" end
52
53   def lock
54     Redwood::log "locking #{lockfile}..."
55     begin
56       @lock.lock
57     rescue Lockfile::MaxTriesLockError
58       raise LockError, @lock.lockinfo_on_disk
59     end
60   end
61
62   def start_lock_update_thread
63     @lock_update_thread = Redwood::reporting_thread("lock update") do
64       while true
65         sleep 30
66         @lock.touch_yourself
67       end
68     end
69   end
70
71   def stop_lock_update_thread
72     @lock_update_thread.kill if @lock_update_thread
73     @lock_update_thread = nil
74   end
75
76   def possibly_pluralize number_of, kind
77     "#{number_of} #{kind}" +
78         if number_of == 1 then "" else "s" end
79   end
80
81   def fancy_lock_error_message_for e
82     secs = (Time.now - e.mtime).to_i
83     mins = secs / 60
84     time =
85       if mins == 0
86         possibly_pluralize secs , "second"
87       else
88         possibly_pluralize mins, "minute"
89       end
90
91     <<EOS
92 Error: the sup index is locked by another process! User '#{e.user}' on
93 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
94 as of #{time} ago.
95 EOS
96   end
97
98   def lock_or_die
99     begin
100       lock
101     rescue LockError => e
102       $stderr.puts fancy_lock_error_message_for(e)
103       $stderr.puts <<EOS
104
105 You can wait for the process to finish, or, if it crashed and left a
106 stale lock file behind, you can manually delete #{@lock.path}.
107 EOS
108       exit
109     end
110   end
111
112   def unlock
113     if @lock && @lock.locked?
114       Redwood::log "unlocking #{lockfile}..."
115       @lock.unlock
116     end
117   end
118
119   def load
120     load_sources
121     load_index
122   end
123
124   def save
125     Redwood::log "saving index and sources..."
126     FileUtils.mkdir_p @dir unless File.exists? @dir
127     save_sources
128     save_index
129   end
130
131   def add_source source
132     @source_mutex.synchronize do
133       raise "duplicate source!" if @sources.include? source
134       @sources_dirty = true
135       max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
136       source.id ||= (max || 0) + 1
137       ##source.id += 1 while @sources.member? source.id
138       @sources[source.id] = source
139     end
140   end
141
142   def sources
143     ## favour the inbox by listing non-archived sources first
144     @source_mutex.synchronize { @sources.values }.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
145   end
146
147   def source_for uri; sources.find { |s| s.is_source_for? uri }; end
148   def usual_sources; sources.find_all { |s| s.usual? }; end
149
150   def load_index dir=File.join(@dir, "ferret")
151     if File.exists? dir
152       Redwood::log "loading index..."
153       @index_mutex.synchronize do
154         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
155         Redwood::log "loaded index of #{@index.size} messages"
156       end
157     else
158       Redwood::log "creating index..."
159       @index_mutex.synchronize do
160         field_infos = Ferret::Index::FieldInfos.new :store => :yes
161         field_infos.add_field :message_id, :index => :untokenized
162         field_infos.add_field :source_id
163         field_infos.add_field :source_info
164         field_infos.add_field :date, :index => :untokenized
165         field_infos.add_field :body
166         field_infos.add_field :label
167         field_infos.add_field :attachments
168         field_infos.add_field :subject
169         field_infos.add_field :from
170         field_infos.add_field :to
171         field_infos.add_field :refs
172         field_infos.add_field :snippet, :index => :no, :term_vector => :no
173         field_infos.create_index dir
174         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
175       end
176     end
177   end
178
179   ## Syncs the message to the index, replacing any previous version.  adding
180   ## either way. Index state will be determined by the message's #labels
181   ## accessor.
182   ##
183   ## if need_load is false, docid and entry are assumed to be set to the
184   ## result of load_entry_for_id (which can be nil).
185   def sync_message m, need_load=true, docid=nil, entry=nil, opts={}
186     docid, entry = load_entry_for_id m.id if need_load
187
188     raise "no source info for message #{m.id}" unless m.source && m.source_info
189     @index_mutex.synchronize do
190       raise "trying to delete non-corresponding entry #{docid} with index message-id #{@index[docid][:message_id].inspect} and parameter message id #{m.id.inspect}" if docid && @index[docid][:message_id] != m.id
191     end
192
193     source_id = if m.source.is_a? Integer
194       m.source
195     else
196       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
197     end
198
199     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
200       ""
201     else
202       m.snippet
203     end
204
205     ## write the new document to the index. if the entry already exists in the
206     ## index, reuse it (which avoids having to reload the entry from the source,
207     ## which can be quite expensive for e.g. large threads of IMAP actions.)
208     ##
209     ## exception: if the index entry belongs to an earlier version of the
210     ## message, use everything from the new message instead, but union the
211     ## flags. this allows messages sent to mailing lists to have their header
212     ## updated and to have flags set properly.
213     ##
214     ## minor hack: messages in sources with lower ids have priority over
215     ## messages in sources with higher ids. so messages in the inbox will
216     ## override everyone, and messages in the sent box will be overridden
217     ## by everyone else.
218     ##
219     ## written in this manner to support previous versions of the index which
220     ## did not keep around the entry body. upgrading is thus seamless.
221     entry ||= {}
222     labels = m.labels.uniq # override because this is the new state, unless...
223
224     ## if we are a later version of a message, ignore what's in the index,
225     ## but merge in the labels.
226     if entry[:source_id] && entry[:source_info] && entry[:label] &&
227       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
228       labels = (entry[:label].symbolistize + m.labels).uniq
229       #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
230       #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
231       #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
232       entry = {}
233     end
234
235     ## if force_overwite is true, ignore what's in the index. this is used
236     ## primarily by sup-sync to force index updates.
237     entry = {} if opts[:force_overwrite]
238
239     d = {
240       :message_id => m.id,
241       :source_id => source_id,
242       :source_info => m.source_info,
243       :date => (entry[:date] || m.date.to_indexable_s),
244       :body => (entry[:body] || m.indexable_content),
245       :snippet => snippet, # always override
246       :label => labels.uniq.join(" "),
247       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
248
249       ## always override :from and :to.
250       ## older versions of Sup would often store the wrong thing in the index
251       ## (because they were canonicalizing email addresses, resulting in the
252       ## wrong name associated with each.) the correct address is read from
253       ## the original header when these messages are opened in thread-view-mode,
254       ## so this allows people to forcibly update the address in the index by
255       ## marking those threads for saving.
256       :from => (m.from ? m.from.indexable_content : ""),
257       :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
258
259       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
260       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
261     }
262
263     @index_mutex.synchronize do
264       @index.delete docid if docid
265       @index.add_document d
266     end
267
268     ## this hasn't been triggered in a long time.
269     ## docid, entry = load_entry_for_id m.id
270     ## raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
271   end
272
273   def save_index fn=File.join(@dir, "ferret")
274     # don't have to do anything, apparently
275   end
276
277   def contains_id? id
278     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
279   end
280   def contains? m; contains_id? m.id end
281   def size; @index_mutex.synchronize { @index.size } end
282   def empty?; size == 0 end
283
284   ## you should probably not call this on a block that doesn't break
285   ## rather quickly because the results can be very large.
286   EACH_BY_DATE_NUM = 100
287   def each_id_by_date opts={}
288     return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
289     query = build_query opts
290     offset = 0
291     while true
292       limit = (opts[:limit])? [EACH_BY_DATE_NUM, opts[:limit] - offset].min : EACH_BY_DATE_NUM
293       results = @index_mutex.synchronize { @index.search query, :sort => "date DESC", :limit => limit, :offset => offset }
294       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
295       results.hits.each do |hit|
296         yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
297       end
298       break if opts[:limit] and offset >= opts[:limit] - limit
299       break if offset >= results.total_hits - limit
300       offset += limit
301     end
302   end
303
304   def num_results_for opts={}
305     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
306
307     q = build_query opts
308     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits }
309   end
310
311   ## yield all messages in the thread containing 'm' by repeatedly
312   ## querying the index. yields pairs of message ids and
313   ## message-building lambdas, so that building an unwanted message
314   ## can be skipped in the block if desired.
315   ##
316   ## only two options, :limit and :skip_killed. if :skip_killed is
317   ## true, stops loading any thread if a message with a :killed flag
318   ## is found.
319   SAME_SUBJECT_DATE_LIMIT = 7
320   MAX_CLAUSES = 1000
321   def each_message_in_thread_for m, opts={}
322     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
323     messages = {}
324     searched = {}
325     num_queries = 0
326
327     pending = [m.id]
328     if $config[:thread_by_subject] # do subject queries
329       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
330       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
331
332       q = Ferret::Search::BooleanQuery.new true
333       sq = Ferret::Search::PhraseQuery.new(:subject)
334       wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
335         sq.add_term t
336       end
337       q.add_query sq, :must
338       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
339
340       q = build_query :qobj => q
341
342       p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
343       Redwood::log "found #{p1.size} results for subject query #{q}"
344
345       p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
346       Redwood::log "found #{p2.size} results in string form"
347
348       pending = (pending + p1 + p2).uniq
349     end
350
351     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
352       q = Ferret::Search::BooleanQuery.new true
353       # this disappeared in newer ferrets... wtf.
354       # q.max_clause_count = 2048
355
356       lim = [MAX_CLAUSES / 2, pending.length].min
357       pending[0 ... lim].each do |id|
358         searched[id] = true
359         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
360         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
361       end
362       pending = pending[lim .. -1]
363
364       q = build_query :qobj => q
365
366       num_queries += 1
367       killed = false
368       @index_mutex.synchronize do
369         @index.search_each(q, :limit => :all) do |docid, score|
370           break if opts[:limit] && messages.size >= opts[:limit]
371           if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
372             killed = true
373             break
374           end
375           mid = @index[docid][:message_id]
376           unless messages.member?(mid)
377             #Redwood::log "got #{mid} as a child of #{id}"
378             messages[mid] ||= lambda { build_message docid }
379             refs = @index[docid][:refs].split
380             pending += refs.select { |id| !searched[id] }
381           end
382         end
383       end
384     end
385
386     if killed
387       Redwood::log "thread for #{m.id} is killed, ignoring"
388       false
389     else
390       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
391       messages.each { |mid, builder| yield mid, builder }
392       true
393     end
394   end
395
396   ## builds a message object from a ferret result
397   def build_message docid
398     @index_mutex.synchronize do
399       doc = @index[docid]
400
401       source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
402       raise "invalid source #{doc[:source_id]}" unless source
403
404       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
405
406       fake_header = {
407         "date" => Time.at(doc[:date].to_i),
408         "subject" => unwrap_subj(doc[:subject]),
409         "from" => doc[:from],
410         "to" => doc[:to].split.join(", "), # reformat
411         "message-id" => doc[:message_id],
412         "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
413       }
414
415       m = Message.new :source => source, :source_info => doc[:source_info].to_i,
416                   :labels => doc[:label].symbolistize,
417                   :snippet => doc[:snippet]
418       m.parse_header fake_header
419       m
420     end
421   end
422
423   def fresh_thread_id; @next_thread_id += 1; end
424   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
425   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
426
427   def drop_entry docno; @index_mutex.synchronize { @index.delete docno } end
428
429   def load_entry_for_id mid
430     @index_mutex.synchronize do
431       results = @index.search Ferret::Search::TermQuery.new(:message_id, mid)
432       return if results.total_hits == 0
433       docid = results.hits[0].doc
434       entry = @index[docid]
435       entry_dup = entry.fields.inject({}) { |h, f| h[f] = entry[f]; h }
436       [docid, entry_dup]
437     end
438   end
439
440   def load_contacts emails, h={}
441     q = Ferret::Search::BooleanQuery.new true
442     emails.each do |e|
443       qq = Ferret::Search::BooleanQuery.new true
444       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
445       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
446       q.add_query qq
447     end
448     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
449     
450     Redwood::log "contact search: #{q}"
451     contacts = {}
452     num = h[:num] || 20
453     @index_mutex.synchronize do
454       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
455         break if contacts.size >= num
456         #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
457         f = @index[docid][:from]
458         t = @index[docid][:to]
459
460         if AccountManager.is_account_email? f
461           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
462         else
463           contacts[Person.from_address(f)] = true
464         end
465       end
466     end
467
468     contacts.keys.compact
469   end
470
471   def load_sources fn=Redwood::SOURCE_FN
472     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
473     @source_mutex.synchronize do
474       @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
475       @sources_dirty = false
476     end
477   end
478
479   def has_any_from_source_with_label? source, label
480     q = Ferret::Search::BooleanQuery.new
481     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
482     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
483     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
484   end
485
486   ## takes a user query string and returns the list of docids for messages
487   ## that match the query.
488   ##
489   ## messages can then be loaded from the index with #build_message.
490   ##
491   ## raises a ParseError if the parsing failed.
492   def run_query query
493     qobj, opts = Redwood::Index.parse_user_query_string query
494     query = Redwood::Index.build_query opts.merge(:qobj => qobj)
495     results = @index.search query, :limit => (opts[:limit] || :all)
496     results.hits.map { |hit| hit.doc }
497   end
498
499 protected
500
501   class ParseError < StandardError; end
502
503   ## parse a query string from the user. returns a query object and a set of
504   ## extra flags; both of these are meant to be passed to #build_query.
505   ##
506   ## raises a ParseError if something went wrong.
507   def parse_user_query_string s
508     extraopts = {}
509
510     subs = s.gsub(/\b(to|from):(\S+)\b/) do
511       field, name = $1, $2
512       if(p = ContactManager.contact_for(name))
513         [field, p.email]
514       elsif name == "me"
515         [field, "(" + AccountManager.user_emails.join("||") + ")"]
516       else
517         [field, name]
518       end.join(":")
519     end
520
521     ## if we see a label:deleted or a label:spam term anywhere in the query
522     ## string, we set the extra load_spam or load_deleted options to true.
523     ## bizarre? well, because the query allows arbitrary parenthesized boolean
524     ## expressions, without fully parsing the query, we can't tell whether
525     ## the user is explicitly directing us to search spam messages or not.
526     ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
527     ## search spam messages or not?
528     ##
529     ## so, we rely on the fact that turning these extra options ON turns OFF
530     ## the adding of "-label:deleted" or "-label:spam" terms at the very
531     ## final stage of query processing. if the user wants to search spam
532     ## messages, not adding that is the right thing; if he doesn't want to
533     ## search spam messages, then not adding it won't have any effect.
534     extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
535     extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
536
537     ## gmail style "is" operator
538     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
539       field, label = $1, $2
540       case label
541       when "read"
542         "-label:unread"
543       when "spam"
544         extraopts[:load_spam] = true
545         "label:spam"
546       when "deleted"
547         extraopts[:load_deleted] = true
548         "label:deleted"
549       else
550         "label:#{$2}"
551       end
552     end
553
554     ## gmail style attachments "filename" and "filetype" searches
555     subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
556       field, name = $1, ($3 || $4)
557       case field
558       when "filename"
559         Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
560         "attachments:(#{name.downcase})"
561       when "filetype"
562         Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
563         "attachments:(*.#{name.downcase})"
564       end
565     end
566
567     if $have_chronic
568       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
569         field, datestr = $1, ($3 || $4)
570         realdate = Chronic.parse datestr, :guess => false, :context => :past
571         if realdate
572           case field
573           when "after"
574             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
575             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
576           when "before"
577             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
578             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
579           else
580             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
581             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
582           end
583         else
584           raise ParseError, "can't understand date #{datestr.inspect}"
585         end
586       end
587     end
588
589     ## limit:42 restrict the search to 42 results
590     subs = subs.gsub(/\blimit:(\S+)\b/) do
591       lim = $1
592       if lim =~ /^\d+$/
593         extraopts[:limit] = lim.to_i
594         ''
595       else
596         raise ParseError, "non-numeric limit #{lim.inspect}"
597       end
598     end
599     
600     begin
601       [@qparser.parse(subs), extraopts]
602     rescue Ferret::QueryParser::QueryParseException => e
603       raise ParseError, e.message
604     end
605   end
606
607   def build_query opts
608     query = Ferret::Search::BooleanQuery.new
609     query.add_query opts[:qobj], :must if opts[:qobj]
610     labels = ([opts[:label]] + (opts[:labels] || [])).compact
611     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
612     if opts[:participants]
613       q2 = Ferret::Search::BooleanQuery.new
614       opts[:participants].each do |p|
615         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
616         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
617       end
618       query.add_query q2, :must
619     end
620         
621     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
622     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
623     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
624     query
625   end
626
627   def save_sources fn=Redwood::SOURCE_FN
628     @source_mutex.synchronize do
629       if @sources_dirty || @sources.any? { |id, s| s.dirty? }
630         bakfn = fn + ".bak"
631         if File.exists? fn
632           File.chmod 0600, fn
633           FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
634         end
635         Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
636         File.chmod 0600, fn
637       end
638       @sources_dirty = false
639     end
640   end
641 end
642
643 end