1 ## the index structure for redwood. interacts with ferret.
10 class LockError < StandardError
15 def method_missing m; @h[m.to_s] end
21 def initialize dir=BASE_DIR
24 @sources_dirty = false
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
30 @analyzer[:subject] = sa
31 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer
32 @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
34 self.class.i_am_the_instance self
37 def lockfile; File.join @dir, "lock" end
40 Redwood::log "locking #{lockfile}..."
43 rescue Lockfile::MaxTriesLockError
44 raise LockError, @lock.lockinfo_on_disk
48 def start_lock_update_thread
49 @lock_update_thread = Redwood::reporting_thread do
57 def stop_lock_update_thread
58 @lock_update_thread.kill if @lock_update_thread
59 @lock_update_thread = nil
62 def fancy_lock_error_message_for e
63 secs = Time.now - e.mtime
67 "#{secs.to_i} seconds"
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
83 $stderr.puts fancy_lock_error_message_for(e)
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}.
94 if @lock && @lock.locked?
95 Redwood::log "unlocking #{lockfile}..."
106 Redwood::log "saving index and sources..."
107 FileUtils.mkdir_p @dir unless File.exists? @dir
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
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
125 def load_index dir=File.join(@dir, "ferret")
127 Redwood::log "loading index..."
128 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
129 Redwood::log "loaded index of #{@index.size} messages"
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)
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.
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
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
160 if m.source.is_a? Integer
161 raise "Debugging: integer source set"
164 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
167 to = (m.to + m.cc + m.bcc).map { |x| x.email }.join(" ")
170 :source_id => source_id,
171 :source_info => m.source_info,
172 :date => m.date.to_indexable_s,
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(" "),
182 @index.delete docid if docid
183 @index.add_document d
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
191 def save_index fn=File.join(@dir, "ferret")
192 # don't have to do anything, apparently
196 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
198 def contains? m; contains_id? m.id; end
199 def size; @index.size; end
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
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
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
221 index.search(q, :limit => 1).total_hits
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.
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}"
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)
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|
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
249 q = build_query :qobj => q
251 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
252 Redwood::log "found #{pending.size} results for subject query #{q}"
257 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
259 next if searched.member? id
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
265 q = build_query :qobj => q, :load_killed => true
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(" ")
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 }
284 ## builds a message object from a ferret result
285 def build_message 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
292 "date" => Time.at(doc[:date].to_i),
293 "subject" => unwrap_subj(doc[:subject]),
294 "from" => doc[:from],
296 "message-id" => doc[:message_id],
297 "references" => doc[:refs],
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
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
309 def drop_entry docno; @index.delete docno; end
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]]
318 def load_contacts emails, h={}
319 q = Ferret::Search::BooleanQuery.new true
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
326 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
328 Redwood::log "contact search: #{q}"
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]
337 if AccountManager.is_account_email? f
338 t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
340 contacts[PersonManager.person_for(f)] = true
344 contacts.keys.compact
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
355 def parse_user_query_string str; @qparser.parse str; end
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
367 query.add_query q2, :must
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)
376 def save_sources fn=Redwood::SOURCE_FN
377 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
381 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
383 Redwood::save_yaml_obj @sources.values.sort_by { |s| s.id.to_i }, fn, true
386 @sources_dirty = false