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