1 ## the index structure for redwood. interacts with ferret.
9 Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
16 class LockError < StandardError
21 def method_missing m; @h[m.to_s] end
28 def initialize dir=BASE_DIR
31 @sources_dirty = false
33 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
34 sa = Ferret::Analysis::StandardAnalyzer.new [], true
35 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
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
41 self.class.i_am_the_instance self
44 def lockfile; File.join @dir, "lock" end
47 Redwood::log "locking #{lockfile}..."
50 rescue Lockfile::MaxTriesLockError
51 raise LockError, @lock.lockinfo_on_disk
55 def start_lock_update_thread
56 @lock_update_thread = Redwood::reporting_thread("lock update") do
64 def stop_lock_update_thread
65 @lock_update_thread.kill if @lock_update_thread
66 @lock_update_thread = nil
69 def fancy_lock_error_message_for e
70 secs = Time.now - e.mtime
74 "#{secs.to_i} seconds"
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
90 $stderr.puts fancy_lock_error_message_for(e)
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}.
101 if @lock && @lock.locked?
102 Redwood::log "unlocking #{lockfile}..."
113 Redwood::log "saving index and sources..."
114 FileUtils.mkdir_p @dir unless File.exists? @dir
119 def add_source source
120 raise "duplicate source!" if @sources.include? source
121 @sources_dirty = true
122 max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
123 source.id ||= (max || 0) + 1
124 ##source.id += 1 while @sources.member? source.id
125 @sources[source.id] = source
129 ## favour the inbox by listing non-archived sources first
130 @sources.values.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
133 def source_for uri; sources.find { |s| s.is_source_for? uri }; end
134 def usual_sources; sources.find_all { |s| s.usual? }; end
136 def load_index dir=File.join(@dir, "ferret")
138 Redwood::log "loading index..."
139 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
140 Redwood::log "loaded index of #{@index.size} messages"
142 Redwood::log "creating index..."
143 field_infos = Ferret::Index::FieldInfos.new :store => :yes
144 field_infos.add_field :message_id
145 field_infos.add_field :source_id
146 field_infos.add_field :source_info
147 field_infos.add_field :date, :index => :untokenized
148 field_infos.add_field :body
149 field_infos.add_field :label
150 field_infos.add_field :subject
151 field_infos.add_field :from
152 field_infos.add_field :to
153 field_infos.add_field :refs
154 field_infos.add_field :snippet, :index => :no, :term_vector => :no
155 field_infos.create_index dir
156 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
160 ## Syncs the message to the index: deleting if it's already there,
161 ## and adding either way. Index state will be determined by m.labels.
163 ## docid and entry can be specified if they're already known.
164 def sync_message m, docid=nil, entry=nil
165 docid, entry = load_entry_for_id m.id unless docid && entry
167 raise "no source info for message #{m.id}" unless m.source && m.source_info
168 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
171 if m.source.is_a? Integer
174 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
178 if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
184 ## write the new document to the index. if the entry already exists in the
185 ## index, reuse it (which avoids having to reload the entry from the source,
186 ## which can be quite expensive for e.g. large threads of IMAP actions.)
188 ## exception: if the index entry belongs to an earlier version of the
189 ## message, use everything from the new message instead, but union the
190 ## flags. this allows messages sent to mailing lists to have their header
191 ## updated and to have flags set properly.
193 ## written in this manner to support previous versions of the index which
194 ## did not keep around the entry body. upgrading is thus seamless.
196 labels = m.labels.uniq # override because this is the new state, unless...
198 ## if we are a later version of a message, ignore what's in the index,
199 ## but merge in the labels.
200 if entry[:source_id] && entry[:source_info] && entry[:label] &&
201 ((entry[:source_id].to_i != source_id) || (entry[:source_info].to_i < m.source_info))
202 labels = (entry[:label].split(/\s+/).map { |l| l.intern } + m.labels).uniq
203 Redwood::log "found updated version of message #{m.id}: #{m.subj}"
204 Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
205 Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
210 :message_id => (entry[:message_id] || m.id),
211 :source_id => (entry[:source_id] || source_id),
212 :source_info => (entry[:source_info] || m.source_info),
213 :date => (entry[:date] || m.date.to_indexable_s),
214 :body => (entry[:body] || m.indexable_content),
215 :snippet => snippet, # always override
216 :label => labels.uniq.join(" "),
217 :from => (entry[:from] || (m.from ? m.from.indexable_content : "")),
218 :to => (entry[:to] || (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" ")),
219 :subject => (entry[:subject] || wrap_subj(m.subj)),
220 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
223 @index.delete docid if docid
224 @index.add_document d
226 docid, entry = load_entry_for_id m.id
227 ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
228 raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
232 def save_index fn=File.join(@dir, "ferret")
233 # don't have to do anything, apparently
237 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
239 def contains? m; contains_id? m.id; end
240 def size; @index.size; end
242 ## you should probably not call this on a block that doesn't break
243 ## rather quickly because the results can be very large.
244 EACH_BY_DATE_NUM = 100
245 def each_id_by_date opts={}
246 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
247 query = build_query opts
250 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
251 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
252 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
253 break if offset >= results.total_hits - EACH_BY_DATE_NUM
254 offset += EACH_BY_DATE_NUM
258 def num_results_for opts={}
259 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
262 index.search(q, :limit => 1).total_hits
265 ## yield all messages in the thread containing 'm' by repeatedly
266 ## querying the index. yields pairs of message ids and
267 ## message-building lambdas, so that building an unwanted message
268 ## can be skipped in the block if desired.
270 ## only two options, :limit and :skip_killed. if :skip_killed is
271 ## true, stops loading any thread if a message with a :killed flag
273 SAME_SUBJECT_DATE_LIMIT = 7
275 def each_message_in_thread_for m, opts={}
276 #Redwood::log "Building thread for #{m.id}: #{m.subj}"
281 if $config[:thread_by_subject] # do subject queries
282 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
283 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
285 q = Ferret::Search::BooleanQuery.new true
286 sq = Ferret::Search::PhraseQuery.new(:subject)
287 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
290 q.add_query sq, :must
291 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
293 q = build_query :qobj => q
295 pending = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
296 Redwood::log "found #{pending.size} results for subject query #{q}"
301 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
302 q = Ferret::Search::BooleanQuery.new true
303 # this disappeared in newer ferrets... wtf.
304 # q.max_clause_count = 2048
306 lim = [MAX_CLAUSES / 2, pending.length].min
307 pending[0 ... lim].each do |id|
309 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
310 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
312 pending = pending[lim .. -1]
314 q = build_query :qobj => q
318 @index.search_each(q, :limit => :all) do |docid, score|
319 break if opts[:limit] && messages.size >= opts[:limit]
320 if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
324 mid = @index[docid][:message_id]
325 unless messages.member?(mid)
326 #Redwood::log "got #{mid} as a child of #{id}"
327 messages[mid] ||= lambda { build_message docid }
328 refs = @index[docid][:refs].split(" ")
329 pending += refs.select { |id| !searched[id] }
335 Redwood::log "thread for #{m.id} is killed, ignoring"
338 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size + 1} messages for #{m.id}: #{m.subj}" if num_queries > 0
339 messages.each { |mid, builder| yield mid, builder }
344 ## builds a message object from a ferret result
345 def build_message docid
347 source = @sources[doc[:source_id].to_i]
348 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
349 raise "invalid source #{doc[:source_id]}" unless source
352 "date" => Time.at(doc[:date].to_i),
353 "subject" => unwrap_subj(doc[:subject]),
354 "from" => doc[:from],
355 "to" => doc[:to].split(/\s+/).join(", "), # reformat
356 "message-id" => doc[:message_id],
357 "references" => doc[:refs].split(/\s+/).map { |x| "<#{x}>" }.join(" "),
360 Message.new :source => source, :source_info => doc[:source_info].to_i,
361 :labels => doc[:label].split(" ").map { |s| s.intern },
362 :snippet => doc[:snippet], :header => fake_header
365 def fresh_thread_id; @next_thread_id += 1; end
366 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
367 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
369 def drop_entry docno; @index.delete docno; end
371 def load_entry_for_id mid
372 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
373 return if results.total_hits == 0
374 docid = results.hits[0].doc
375 [docid, @index[docid]]
378 def load_contacts emails, h={}
379 q = Ferret::Search::BooleanQuery.new true
381 qq = Ferret::Search::BooleanQuery.new true
382 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
383 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
386 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
388 Redwood::log "contact search: #{q}"
391 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
392 break if contacts.size >= num
393 #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
394 f = @index[docid][:from]
395 t = @index[docid][:to]
397 if AccountManager.is_account_email? f
398 t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
400 contacts[PersonManager.person_for(f)] = true
404 contacts.keys.compact
407 def load_sources fn=Redwood::SOURCE_FN
408 source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
409 @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
410 @sources_dirty = false
413 def has_any_from_source_with_label? source, label
414 q = Ferret::Search::BooleanQuery.new
415 q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
416 q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
417 index.search(q, :limit => 1).total_hits > 0
422 ## do any specialized parsing
423 ## returns nil and flashes error message if parsing failed
424 def parse_user_query_string s
427 ## this is a little hacky, but it works, at least until ferret changes
428 ## its api. we parse the user query string with ferret twice: the first
429 ## time we just turn the resulting object back into a string, which has
430 ## the next effect of transforming the original string into a nice
431 ## normalized form with + and - instead of AND, OR, etc. then we do some
432 ## string substitutions which depend on this normalized form, re-parse
433 ## the string with Ferret, and return the resulting query object.
435 norms = @qparser.parse(s).to_s
436 Redwood::log "normalized #{s.inspect} to #{norms.inspect}" unless s == norms
438 subs = norms.gsub(/\b(to|from):(\S+)\b/) do
440 if(p = ContactManager.contact_for(name))
443 [field, "(" + AccountManager.user_emails.join("||") + ")"]
449 ## if we see a label:deleted or a label:spam term anywhere in the query
450 ## string, we set the extra load_spam or load_deleted options to true.
451 ## bizarre? well, because the query allows arbitrary parenthesized boolean
452 ## expressions, without fully parsing the query, we can't tell whether
453 ## the user is explicitly directing us to search spam messages or not.
454 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
455 ## search spam messages or not?
457 ## so, we rely on the fact that turning these extra options ON turns OFF
458 ## the adding of "-label:deleted" or "-label:spam" terms at the very
459 ## final stage of query processing. if the user wants to search spam
460 ## messages, not adding that is the right thing; if he doesn't want to
461 ## search spam messages, then not adding it won't have any effect.
462 extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
463 extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
465 ## gmail style "is" operator
466 subs = subs.gsub(/\b(is):(\S+)\b/) do
467 field, label = $1, $2
472 extraopts[:load_spam] = true
475 extraopts[:load_deleted] = true
483 chronic_failure = false
484 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
485 break if chronic_failure
486 field, datestr = $1, ($3 || $4)
487 realdate = Chronic.parse(datestr, :guess => false, :context => :none)
491 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
492 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
494 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
495 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
497 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
498 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
501 BufferManager.flash "Can't understand date #{datestr.inspect}!"
502 chronic_failure = true
505 subs = nil if chronic_failure
508 Redwood::log "translated #{norms.inspect} to #{subs.inspect}" unless subs == norms
510 [@qparser.parse(subs), extraopts]
517 query = Ferret::Search::BooleanQuery.new
518 query.add_query opts[:qobj], :must if opts[:qobj]
519 labels = ([opts[:label]] + (opts[:labels] || [])).compact
520 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
521 if opts[:participants]
522 q2 = Ferret::Search::BooleanQuery.new
523 opts[:participants].each do |p|
524 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
525 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
527 query.add_query q2, :must
530 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
531 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
532 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
536 def save_sources fn=Redwood::SOURCE_FN
537 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
541 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
543 Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
546 @sources_dirty = false