]> git.cworth.org Git - sup/blob - lib/sup/index.rb
finally, attachment support\!
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'thread'
4 require 'fileutils'
5 require 'ferret'
6
7 module Redwood
8
9 class Index
10   class LockError < StandardError
11     def initialize h
12       @h = h
13     end
14
15     def method_missing m; @h[m.to_s] end
16   end
17
18   include Singleton
19
20   attr_reader :index
21   def initialize dir=BASE_DIR
22     @dir = dir
23     @sources = {}
24     @sources_dirty = false
25
26     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
27     sa = Ferret::Analysis::StandardAnalyzer.new Ferret::Analysis::FULL_ENGLISH_STOP_WORDS, true
28     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
29     @analyzer[:body] = sa
30     @analyzer[:subject] = sa
31     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
32     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
33
34     self.class.i_am_the_instance self
35   end
36
37   def lockfile; File.join @dir, "lock" end
38
39   def lock
40     Redwood::log "locking #{lockfile}..."
41     begin
42       @lock.lock
43     rescue Lockfile::MaxTriesLockError
44       raise LockError, @lock.lockinfo_on_disk
45     end
46   end
47
48   def start_lock_update_thread
49     @lock_update_thread = Redwood::reporting_thread do
50       while true
51         sleep 30
52         @lock.touch_yourself
53       end
54     end
55   end
56
57   def stop_lock_update_thread
58     @lock_update_thread.kill if @lock_update_thread
59     @lock_update_thread = nil
60   end
61
62   def fancy_lock_error_message_for e
63     secs = Time.now - e.mtime
64     mins = secs.to_i / 60
65     time =
66       if mins == 0
67         "#{secs.to_i} seconds"
68       else
69         "#{mins} minutes"
70       end
71
72     <<EOS
73 Error: the sup index is locked by another process! User '#{e.user}' on
74 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
75 as of #{time} ago.
76 EOS
77   end
78
79   def lock_or_die
80     begin
81       lock
82     rescue LockError => e
83       $stderr.puts fancy_lock_error_message_for(e)
84       $stderr.puts <<EOS
85
86 You can wait for the process to finish, or, if it crashed and left a
87 stale lock file behind, you can manually delete #{@lock.path}.
88 EOS
89       exit
90     end
91   end
92
93   def unlock
94     if @lock && @lock.locked?
95       Redwood::log "unlocking #{lockfile}..."
96       @lock.unlock
97     end
98   end
99
100   def load
101     load_sources
102     load_index
103   end
104
105   def save
106     Redwood::log "saving index and sources..."
107     FileUtils.mkdir_p @dir unless File.exists? @dir
108     save_sources
109     save_index
110   end
111
112   def add_source source
113     raise "duplicate source!" if @sources.include? source
114     @sources_dirty = true
115     source.id ||= @sources.size
116     ##TODO: why was this necessary?
117     ##source.id += 1 while @sources.member? source.id
118     @sources[source.id] = source
119   end
120
121   def source_for uri; @sources.values.find { |s| s.is_source_for? uri }; end
122   def usual_sources; @sources.values.find_all { |s| s.usual? }; end
123   def sources; @sources.values; end
124
125   def load_index dir=File.join(@dir, "ferret")
126     if File.exists? dir
127       Redwood::log "loading index..."
128       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
129       Redwood::log "loaded index of #{@index.size} messages"
130     else
131       Redwood::log "creating index..."
132       field_infos = Ferret::Index::FieldInfos.new :store => :yes
133       field_infos.add_field :message_id
134       field_infos.add_field :source_id
135       field_infos.add_field :source_info
136       field_infos.add_field :date, :index => :untokenized
137       field_infos.add_field :body, :store => :no
138       field_infos.add_field :label
139       field_infos.add_field :subject
140       field_infos.add_field :from
141       field_infos.add_field :to
142       field_infos.add_field :refs
143       field_infos.add_field :snippet, :index => :no, :term_vector => :no
144       field_infos.create_index dir
145       @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
146     end
147   end
148
149   ## Syncs the message to the index: deleting if it's already there,
150   ## and adding either way. Index state will be determined by m.labels.
151   ##
152   ## docid and entry can be specified if they're already known.
153   def sync_message m, docid=nil, entry=nil
154     docid, entry = load_entry_for_id m.id unless docid && entry
155
156     raise "no source info for message #{m.id}" unless m.source && m.source_info
157     raise "trying deleting non-corresponding entry #{docid}" if docid && @index[docid][:message_id] != m.id
158
159     source_id = 
160       if m.source.is_a? Integer
161         raise "Debugging: integer source set"
162         m.source
163       else
164         m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
165       end
166
167     to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
168     d = {
169       :message_id => m.id,
170       :source_id => source_id,
171       :source_info => m.source_info,
172       :date => m.date.to_indexable_s,
173       :body => m.content,
174       :snippet => m.snippet,
175       :label => m.labels.join(" "),
176       :from => m.from ? m.from.email : "",
177       :to => (m.to + m.cc + m.bcc).map { |x| x.email }.join(" "),
178       :subject => wrap_subj(Message.normalize_subj(m.subj)),
179       :refs => (m.refs + m.replytos).uniq.join(" "),
180     }
181
182     @index.delete docid if docid
183     @index.add_document d
184     
185     docid, entry = load_entry_for_id m.id
186     ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
187     raise "just added message #{m.id} but couldn't find it in a search" unless docid
188     true
189   end
190
191   def save_index fn=File.join(@dir, "ferret")
192     # don't have to do anything, apparently
193   end
194
195   def contains_id? id
196     @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
197   end
198   def contains? m; contains_id? m.id; end
199   def size; @index.size; end
200
201   ## you should probably not call this on a block that doesn't break
202   ## rather quickly because the results can be very large.
203   EACH_BY_DATE_NUM = 100
204   def each_id_by_date opts={}
205     return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
206     query = build_query opts
207     offset = 0
208     while true
209       results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
210       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
211       results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
212       break if offset >= results.total_hits - EACH_BY_DATE_NUM
213       offset += EACH_BY_DATE_NUM
214     end
215   end
216
217   def num_results_for opts={}
218     return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
219
220     q = build_query opts
221     index.search(q, :limit => 1).total_hits
222   end
223
224   ## yield all messages in the thread containing 'm' by repeatedly
225   ## querying the index. yields pairs of message ids and
226   ## message-building lambdas, so that building an unwanted message
227   ## can be skipped in the block if desired.
228   ##
229   ## stops loading any thread if a message with a :killed flag is found.
230   SAME_SUBJECT_DATE_LIMIT = 7
231   def each_message_in_thread_for m, opts={}
232     Redwood::log "Building thread for #{m.id}: #{m.subj}"
233     messages = {}
234     searched = {}
235     num_queries = 0
236
237     if $config[:thread_by_subject] # do subject queries
238       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
239       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
240
241       q = Ferret::Search::BooleanQuery.new true
242       sq = Ferret::Search::PhraseQuery.new(:subject)
243       wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
244         sq.add_term t
245       end
246       q.add_query sq, :must
247       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
248
249       q = build_query :qobj => q
250
251       pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
252       Redwood::log "found #{pending.size} results for subject query #{q}"
253     else
254       pending = [m.id]
255     end
256
257     until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
258       id = pending.pop
259       next if searched.member? id
260       searched[id] = true
261       q = Ferret::Search::BooleanQuery.new true
262       q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
263       q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
264
265       q = build_query :qobj => q, :load_killed => true
266
267       num_queries += 1
268       @index.search_each(q, :limit => :all) do |docid, score|
269         break if opts[:limit] && messages.size >= opts[:limit]
270         break if @index[docid][:label].split(/\s+/).include? "killed" unless opts[:load_killed]
271         mid = @index[docid][:message_id]
272         unless messages.member?(mid)
273           Redwood::log "got #{mid} as a child of #{id}"
274           messages[mid] ||= lambda { build_message docid }
275           refs = @index[docid][:refs].split(" ")
276           pending += refs
277         end
278       end
279     end
280     Redwood::log "ran #{num_queries} queries to build thread of #{messages.size + 1} messages for #{m.id}" if num_queries > 0
281     messages.each { |mid, builder| yield mid, builder }
282   end
283
284   ## builds a message object from a ferret result
285   def build_message docid
286     doc = @index[docid]
287     source = @sources[doc[:source_id].to_i]
288     #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
289     raise "invalid source #{doc[:source_id]}" unless source
290
291     fake_header = {
292       "date" => Time.at(doc[:date].to_i),
293       "subject" => unwrap_subj(doc[:subject]),
294       "from" => doc[:from],
295       "to" => doc[:to],
296       "message-id" => doc[:message_id],
297       "references" => doc[:refs],
298     }
299
300     Message.new :source => source, :source_info => doc[:source_info].to_i, 
301                 :labels => doc[:label].split(" ").map { |s| s.intern },
302                 :snippet => doc[:snippet], :header => fake_header
303   end
304
305   def fresh_thread_id; @next_thread_id += 1; end
306   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
307   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
308
309   def drop_entry docno; @index.delete docno; end
310
311   def load_entry_for_id mid
312     results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
313     return if results.total_hits == 0
314     docid = results.hits[0].doc
315     [docid, @index[docid]]
316   end
317
318   def load_contacts emails, h={}
319     q = Ferret::Search::BooleanQuery.new true
320     emails.each do |e|
321       qq = Ferret::Search::BooleanQuery.new true
322       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
323       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
324       q.add_query qq
325     end
326     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
327     
328     Redwood::log "contact search: #{q}"
329     contacts = {}
330     num = h[:num] || 20
331     @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
332       break if contacts.size >= num
333       #Redwood::log "got message with to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
334       f = @index[docid][:from]
335       t = @index[docid][:to]
336
337       if AccountManager.is_account_email? f
338         t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
339       else
340         contacts[PersonManager.person_for(f)] = true
341       end
342     end
343
344     contacts.keys.compact
345   end
346
347   def load_sources fn=Redwood::SOURCE_FN
348     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
349     @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
350     @sources_dirty = false
351   end
352
353 protected
354
355   def parse_user_query_string str; @qparser.parse str; end
356   def build_query opts
357     query = Ferret::Search::BooleanQuery.new
358     query.add_query opts[:qobj], :must if opts[:qobj]
359     labels = ([opts[:label]] + (opts[:labels] || [])).compact
360     labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
361     if opts[:participants]
362       q2 = Ferret::Search::BooleanQuery.new
363       opts[:participants].each do |p|
364         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
365         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
366       end
367       query.add_query q2, :must
368     end
369         
370     query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
371     query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
372     query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not unless opts[:load_killed] || labels.include?(:killed)
373     query
374   end
375
376   def save_sources fn=Redwood::SOURCE_FN
377     if @sources_dirty || @sources.any? { |id, s| s.dirty? }
378       bakfn = fn + ".bak"
379       if File.exists? fn
380         File.chmod 0600, fn
381         FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
382       end
383       Redwood::save_yaml_obj @sources.values.sort_by { |s| s.id.to_i }, fn, true
384       File.chmod 0600, fn
385     end
386     @sources_dirty = false
387   end
388 end
389
390 end