]> git.notmuchmail.org Git - sup/blob - lib/sup/index.rb
367829533581323e28b91ff59bec4449e37609af
[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 "'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 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 fancy_lock_error_message_for e
70     secs = Time.now - e.mtime
71     mins = secs.to_i / 60
72     time =
73       if mins == 0
74         "#{secs.to_i} seconds"
75       else
76         "#{mins} minutes"
77       end
78
79     <<EOS
80 Error: the sup index is locked by another process! User '#{e.user}' on
81 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
82 as of #{time} ago.
83 EOS
84   end
85
86   def lock_or_die
87     begin
88       lock
89     rescue LockError => e
90       $stderr.puts fancy_lock_error_message_for(e)
91       $stderr.puts <<EOS
92
93 You can wait for the process to finish, or, if it crashed and left a
94 stale lock file behind, you can manually delete #{@lock.path}.
95 EOS
96       exit
97     end
98   end
99
100   def unlock
101     if @lock && @lock.locked?
102       Redwood::log "unlocking #{lockfile}..."
103       @lock.unlock
104     end
105   end
106
107   def load
108     load_sources
109     load_index
110   end
111
112   def save
113     Redwood::log "saving index and sources..."
114     FileUtils.mkdir_p @dir unless File.exists? @dir
115     save_sources
116     save_index
117   end
118
119   def add_source source
120     raise "duplicate source!" if @sources.include? source
121     @sources_dirty = true
122     source.id ||= @sources.size
123     ##TODO: why was this necessary?
124     ##source.id += 1 while @sources.member? source.id
125     @sources[source.id] = source
126   end
127
128   def source_for uri; @sources.values.find { |s| s.is_source_for? uri }; end
129   def usual_sources; @sources.values.find_all { |s| s.usual? }; end
130   def sources; @sources.values; end
131
132   def load_index dir=File.join(@dir, "ferret")
133     if File.exists? dir
134       Redwood::log "loading index..."
135       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
136       Redwood::log "loaded index of #{@index.size} messages"
137     else
138       Redwood::log "creating index..."
139       field_infos = Ferret::Index::FieldInfos.new :store => :yes
140       field_infos.add_field :message_id
141       field_infos.add_field :source_id
142       field_infos.add_field :source_info
143       field_infos.add_field :date, :index => :untokenized
144       field_infos.add_field :body, :store => :no
145       field_infos.add_field :label
146       field_infos.add_field :subject
147       field_infos.add_field :from
148       field_infos.add_field :to
149       field_infos.add_field :refs
150       field_infos.add_field :snippet, :index => :no, :term_vector => :no
151       field_infos.create_index dir
152       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
153     end
154   end
155
156   ## Syncs the message to the index: deleting if it's already there,
157   ## and adding either way. Index state will be determined by m.labels.
158   ##
159   ## docid and entry can be specified if they're already known.
160   def sync_message m, docid=nil, entry=nil
161     docid, entry = load_entry_for_id m.id unless docid && entry
162
163     raise "no source info for message #{m.id}" unless m.source && m.source_info
164     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
165
166     source_id = 
167       if m.source.is_a? Integer
168         m.source
169       else
170         m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
171       end
172
173     to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
174     d = {
175       :message_id => m.id,
176       :source_id => source_id,
177       :source_info => m.source_info,
178       :date => m.date.to_indexable_s,
179       :body => m.content,
180       :snippet => m.snippet,
181       :label => m.labels.uniq.join(" "),
182       :from => m.from ? m.from.email : "",
183       :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
184       :subject => wrap_subj(Message.normalize_subj(m.subj)),
185       :refs => (m.refs + m.replytos).uniq.join(" "),
186     }
187
188     @index.delete docid if docid
189     @index.add_document d
190     
191     docid, entry = load_entry_for_id m.id
192     ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
193     raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
194     true
195   end
196
197   def save_index fn=File.join(@dir, "ferret")
198     # don't have to do anything, apparently
199   end
200
201   def contains_id? id
202     @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
203   end
204   def contains? m; contains_id? m.id; end
205   def size; @index.size; end
206
207   ## you should probably not call this on a block that doesn't break
208   ## rather quickly because the results can be very large.
209   EACH_BY_DATE_NUM = 100
210   def each_id_by_date opts={}
211     return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
212     query = build_query opts
213     offset = 0
214     while true
215       results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
216       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
217       results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
218       break if offset >= results.total_hits - EACH_BY_DATE_NUM
219       offset += EACH_BY_DATE_NUM
220     end
221   end
222
223   def num_results_for opts={}
224     return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
225
226     q = build_query opts
227     index.search(q, :limit => 1).total_hits
228   end
229
230   ## yield all messages in the thread containing 'm' by repeatedly
231   ## querying the index. yields pairs of message ids and
232   ## message-building lambdas, so that building an unwanted message
233   ## can be skipped in the block if desired.
234   ##
235   ## only two options, :limit and :skip_killed. if :skip_killed is
236   ## true, stops loading any thread if a message with a :killed flag
237   ## is found.
238   SAME_SUBJECT_DATE_LIMIT = 7
239   def each_message_in_thread_for m, opts={}
240     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
241     messages = {}
242     searched = {}
243     num_queries = 0
244
245     if $config[:thread_by_subject] # do subject queries
246       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
247       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
248
249       q = Ferret::Search::BooleanQuery.new true
250       sq = Ferret::Search::PhraseQuery.new(:subject)
251       wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
252         sq.add_term t
253       end
254       q.add_query sq, :must
255       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
256
257       q = build_query :qobj => q
258
259       pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
260       Redwood::log "found #{pending.size} results for subject query #{q}"
261     else
262       pending = [m.id]
263     end
264
265     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
266       id = pending.pop
267       next if searched.member? id
268       searched[id] = true
269       q = Ferret::Search::BooleanQuery.new true
270       q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
271       q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
272
273       q = build_query :qobj => q
274
275       num_queries += 1
276       killed = false
277       @index.search_each(q, :limit => :all) do |docid, score|
278         break if opts[:limit] && messages.size >= opts[:limit]
279         if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
280           killed = true
281           break
282         end
283         mid = @index[docid][:message_id]
284         unless messages.member?(mid)
285           #Redwood::log "got #{mid} as a child of #{id}"
286           messages[mid] ||= lambda { build_message docid }
287           refs = @index[docid][:refs].split(" ")
288           pending += refs
289         end
290       end
291     end
292     if killed
293       Redwood::log "thread for #{m.id} is killed, ignoring"
294       false
295     else
296       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size + 1} messages for #{m.id}: #{m.subj}" if num_queries > 0
297       messages.each { |mid, builder| yield mid, builder }
298       true
299     end
300   end
301
302   ## builds a message object from a ferret result
303   def build_message docid
304     doc = @index[docid]
305     source = @sources[doc[:source_id].to_i]
306     #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
307     raise "invalid source #{doc[:source_id]}" unless source
308
309     fake_header = {
310       "date" => Time.at(doc[:date].to_i),
311       "subject" => unwrap_subj(doc[:subject]),
312       "from" => doc[:from],
313       "to" => doc[:to],
314       "message-id" => doc[:message_id],
315       "references" => doc[:refs].split(/\s+/).map { |x| "<#{x}>" }.join(" "),
316     }
317
318     Message.new :source => source, :source_info => doc[:source_info].to_i, 
319                 :labels => doc[:label].split(" ").map { |s| s.intern },
320                 :snippet => doc[:snippet], :header => fake_header
321   end
322
323   def fresh_thread_id; @next_thread_id += 1; end
324   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
325   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
326
327   def drop_entry docno; @index.delete docno; end
328
329   def load_entry_for_id mid
330     results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
331     return if results.total_hits == 0
332     docid = results.hits[0].doc
333     [docid, @index[docid]]
334   end
335
336   def load_contacts emails, h={}
337     q = Ferret::Search::BooleanQuery.new true
338     emails.each do |e|
339       qq = Ferret::Search::BooleanQuery.new true
340       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
341       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
342       q.add_query qq
343     end
344     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
345     
346     Redwood::log "contact search: #{q}"
347     contacts = {}
348     num = h[:num] || 20
349     @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
350       break if contacts.size >= num
351       #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
352       f = @index[docid][:from]
353       t = @index[docid][:to]
354
355       if AccountManager.is_account_email? f
356         t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
357       else
358         contacts[PersonManager.person_for(f)] = true
359       end
360     end
361
362     contacts.keys.compact
363   end
364
365   def load_sources fn=Redwood::SOURCE_FN
366     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
367     @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
368     @sources_dirty = false
369   end
370
371   def has_any_from_source_with_label? source, label
372     q = Ferret::Search::BooleanQuery.new
373     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
374     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
375     index.search(q, :limit => 1).total_hits > 0
376   end
377
378 protected
379
380   ## do any specialized parsing
381   ## returns nil and flashes error message if parsing failed
382   def parse_user_query_string str
383     result = str.gsub(/\b(to|from):(\S+)\b/) do
384       field, name = $1, $2
385       if(p = ContactManager.contact_for(name))
386         [field, p.email]
387       else
388         [field, name]
389       end.join(":")
390     end
391     
392     if $have_chronic
393       chronic_failure = false
394       result = result.gsub(/\b(before|on|in|after):(\((.+?)\)\B|(\S+)\b)/) do
395         break if chronic_failure
396         field, datestr = $1, ($3 || $4)
397         realdate = Chronic.parse(datestr, :guess => false, :context => :none)
398         if realdate
399           case field
400           when "after"
401             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
402             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
403           when "before"
404             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
405             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
406           else
407             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
408             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
409           end
410         else
411           BufferManager.flash "Don't understand date #{datestr.inspect}!"
412           chronic_failure = true
413         end
414       end
415       result = nil if chronic_failure
416     end
417     
418     Redwood::log "translated #{str.inspect} to #{result}" unless result == str
419     @qparser.parse result if result
420   end
421
422   def build_query opts
423     query = Ferret::Search::BooleanQuery.new
424     query.add_query opts[:qobj], :must if opts[:qobj]
425     labels = ([opts[:label]] + (opts[:labels] || [])).compact
426     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
427     if opts[:participants]
428       q2 = Ferret::Search::BooleanQuery.new
429       opts[:participants].each do |p|
430         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
431         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
432       end
433       query.add_query q2, :must
434     end
435         
436     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
437     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
438     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
439     query
440   end
441
442   def save_sources fn=Redwood::SOURCE_FN
443     if @sources_dirty || @sources.any? { |id, s| s.dirty? }
444       bakfn = fn + ".bak"
445       if File.exists? fn
446         File.chmod 0600, fn
447         FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
448       end
449       Redwood::save_yaml_obj @sources.values.sort_by { |s| s.id.to_i }, fn, true
450       File.chmod 0600, fn
451     end
452     @sources_dirty = false
453   end
454 end
455
456 end