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