1 ## the index structure for redwood. interacts with ferret.
11 Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
18 class LockError < StandardError
23 def method_missing m; @h[m.to_s] end
30 def initialize dir=BASE_DIR
33 @sources_dirty = false
34 @source_mutex = Monitor.new
36 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
37 sa = Ferret::Analysis::StandardAnalyzer.new [], true
38 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
40 @analyzer[:subject] = sa
41 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
42 @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
44 self.class.i_am_the_instance self
47 def lockfile; File.join @dir, "lock" end
50 Redwood::log "locking #{lockfile}..."
53 rescue Lockfile::MaxTriesLockError
54 raise LockError, @lock.lockinfo_on_disk
58 def start_lock_update_thread
59 @lock_update_thread = Redwood::reporting_thread("lock update") do
67 def stop_lock_update_thread
68 @lock_update_thread.kill if @lock_update_thread
69 @lock_update_thread = nil
72 def possibly_pluralize number_of, kind
73 "#{number_of} #{kind}" +
74 if number_of == 1 then "" else "s" end
77 def fancy_lock_error_message_for e
78 secs = (Time.now - e.mtime).to_i
82 possibly_pluralize secs , "second"
84 possibly_pluralize mins, "minute"
88 Error: the sup index is locked by another process! User '#{e.user}' on
89 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
98 $stderr.puts fancy_lock_error_message_for(e)
101 You can wait for the process to finish, or, if it crashed and left a
102 stale lock file behind, you can manually delete #{@lock.path}.
109 if @lock && @lock.locked?
110 Redwood::log "unlocking #{lockfile}..."
121 Redwood::log "saving index and sources..."
122 FileUtils.mkdir_p @dir unless File.exists? @dir
127 def add_source source
128 @source_mutex.synchronize do
129 raise "duplicate source!" if @sources.include? source
130 @sources_dirty = true
131 max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
132 source.id ||= (max || 0) + 1
133 ##source.id += 1 while @sources.member? source.id
134 @sources[source.id] = source
139 ## favour the inbox by listing non-archived sources first
140 @source_mutex.synchronize { @sources.values }.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
143 def source_for uri; sources.find { |s| s.is_source_for? uri }; end
144 def usual_sources; sources.find_all { |s| s.usual? }; end
146 def load_index dir=File.join(@dir, "ferret")
148 Redwood::log "loading index..."
149 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
150 Redwood::log "loaded index of #{@index.size} messages"
152 Redwood::log "creating index..."
153 field_infos = Ferret::Index::FieldInfos.new :store => :yes
154 field_infos.add_field :message_id, :index => :untokenized
155 field_infos.add_field :source_id
156 field_infos.add_field :source_info
157 field_infos.add_field :date, :index => :untokenized
158 field_infos.add_field :body
159 field_infos.add_field :label
160 field_infos.add_field :attachments
161 field_infos.add_field :subject
162 field_infos.add_field :from
163 field_infos.add_field :to
164 field_infos.add_field :refs
165 field_infos.add_field :snippet, :index => :no, :term_vector => :no
166 field_infos.create_index dir
167 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer)
171 ## Syncs the message to the index: deleting if it's already there,
172 ## and adding either way. Index state will be determined by m.labels.
174 ## docid and entry can be specified if they're already known.
175 def sync_message m, docid=nil, entry=nil, opts={}
176 docid, entry = load_entry_for_id m.id unless docid && entry
178 raise "no source info for message #{m.id}" unless m.source && m.source_info
179 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
182 if m.source.is_a? Integer
185 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
189 if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
195 ## write the new document to the index. if the entry already exists in the
196 ## index, reuse it (which avoids having to reload the entry from the source,
197 ## which can be quite expensive for e.g. large threads of IMAP actions.)
199 ## exception: if the index entry belongs to an earlier version of the
200 ## message, use everything from the new message instead, but union the
201 ## flags. this allows messages sent to mailing lists to have their header
202 ## updated and to have flags set properly.
204 ## minor hack: messages in sources with lower ids have priority over
205 ## messages in sources with higher ids. so messages in the inbox will
206 ## override everyone, and messages in the sent box will be overridden
209 ## written in this manner to support previous versions of the index which
210 ## did not keep around the entry body. upgrading is thus seamless.
212 labels = m.labels.uniq # override because this is the new state, unless...
214 ## if we are a later version of a message, ignore what's in the index,
215 ## but merge in the labels.
216 if entry[:source_id] && entry[:source_info] && entry[:label] &&
217 ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
218 labels = (entry[:label].split(/\s+/).map { |l| l.intern } + m.labels).uniq
219 #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
220 #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
221 #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
225 ## if force_overwite is true, ignore what's in the index. this is used
226 ## primarily by sup-sync to force index updates.
227 entry = {} if opts[:force_overwrite]
231 :source_id => source_id,
232 :source_info => m.source_info,
233 :date => (entry[:date] || m.date.to_indexable_s),
234 :body => (entry[:body] || m.indexable_content),
235 :snippet => snippet, # always override
236 :label => labels.uniq.join(" "),
237 :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
238 :from => (entry[:from] || (m.from ? m.from.indexable_content : "")),
239 :to => (entry[:to] || (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" ")),
240 :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
241 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
244 @index.delete docid if docid
245 @index.add_document d
247 docid, entry = load_entry_for_id m.id
248 ## this hasn't been triggered in a long time. TODO: decide whether it's still a problem.
249 raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
253 def save_index fn=File.join(@dir, "ferret")
254 # don't have to do anything, apparently
258 @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0
260 def contains? m; contains_id? m.id; end
261 def size; @index.size; end
263 ## you should probably not call this on a block that doesn't break
264 ## rather quickly because the results can be very large.
265 EACH_BY_DATE_NUM = 100
266 def each_id_by_date opts={}
267 return if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
268 query = build_query opts
271 results = @index.search(query, :sort => "date DESC", :limit => EACH_BY_DATE_NUM, :offset => offset)
272 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{query.inspect}"
273 results.hits.each { |hit| yield @index[hit.doc][:message_id], lambda { build_message hit.doc } }
274 break if offset >= results.total_hits - EACH_BY_DATE_NUM
275 offset += EACH_BY_DATE_NUM
279 def num_results_for opts={}
280 return 0 if @index.size == 0 # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
283 index.search(q, :limit => 1).total_hits
286 ## yield all messages in the thread containing 'm' by repeatedly
287 ## querying the index. yields pairs of message ids and
288 ## message-building lambdas, so that building an unwanted message
289 ## can be skipped in the block if desired.
291 ## only two options, :limit and :skip_killed. if :skip_killed is
292 ## true, stops loading any thread if a message with a :killed flag
294 SAME_SUBJECT_DATE_LIMIT = 7
296 def each_message_in_thread_for m, opts={}
297 #Redwood::log "Building thread for #{m.id}: #{m.subj}"
303 if $config[:thread_by_subject] # do subject queries
304 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
305 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
307 q = Ferret::Search::BooleanQuery.new true
308 sq = Ferret::Search::PhraseQuery.new(:subject)
309 wrap_subj(Message.normalize_subj(m.subj)).split(/\s+/).each do |t|
312 q.add_query sq, :must
313 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
315 q = build_query :qobj => q
317 p1 = @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] }
318 Redwood::log "found #{p1.size} results for subject query #{q}"
320 p2 = @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] }
321 Redwood::log "found #{p2.size} results in string form"
323 pending = (pending + p1 + p2).uniq
326 until pending.empty? || (opts[:limit] && messages.size >= opts[:limit])
327 q = Ferret::Search::BooleanQuery.new true
328 # this disappeared in newer ferrets... wtf.
329 # q.max_clause_count = 2048
331 lim = [MAX_CLAUSES / 2, pending.length].min
332 pending[0 ... lim].each do |id|
334 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
335 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
337 pending = pending[lim .. -1]
339 q = build_query :qobj => q
343 @index.search_each(q, :limit => :all) do |docid, score|
344 break if opts[:limit] && messages.size >= opts[:limit]
345 if @index[docid][:label].split(/\s+/).include?("killed") && opts[:skip_killed]
349 mid = @index[docid][:message_id]
350 unless messages.member?(mid)
351 #Redwood::log "got #{mid} as a child of #{id}"
352 messages[mid] ||= lambda { build_message docid }
353 refs = @index[docid][:refs].split(" ")
354 pending += refs.select { |id| !searched[id] }
360 Redwood::log "thread for #{m.id} is killed, ignoring"
363 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size + 1} messages for #{m.id}: #{m.subj}" if num_queries > 0
364 messages.each { |mid, builder| yield mid, builder }
369 ## builds a message object from a ferret result
370 def build_message docid
372 source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
373 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
374 raise "invalid source #{doc[:source_id]}" unless source
377 "date" => Time.at(doc[:date].to_i),
378 "subject" => unwrap_subj(doc[:subject]),
379 "from" => doc[:from],
380 "to" => doc[:to].split(/\s+/).join(", "), # reformat
381 "message-id" => doc[:message_id],
382 "references" => doc[:refs].split(/\s+/).map { |x| "<#{x}>" }.join(" "),
385 Message.new :source => source, :source_info => doc[:source_info].to_i,
386 :labels => doc[:label].split(" ").map { |s| s.intern },
387 :snippet => doc[:snippet], :header => fake_header
390 def fresh_thread_id; @next_thread_id += 1; end
391 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
392 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
394 def drop_entry docno; @index.delete docno; end
396 def load_entry_for_id mid
397 results = @index.search(Ferret::Search::TermQuery.new(:message_id, mid))
398 return if results.total_hits == 0
399 docid = results.hits[0].doc
400 [docid, @index[docid]]
403 def load_contacts emails, h={}
404 q = Ferret::Search::BooleanQuery.new true
406 qq = Ferret::Search::BooleanQuery.new true
407 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
408 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
411 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
413 Redwood::log "contact search: #{q}"
416 @index.search_each(q, :sort => "date DESC", :limit => :all) do |docid, score|
417 break if contacts.size >= num
418 #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
419 f = @index[docid][:from]
420 t = @index[docid][:to]
422 if AccountManager.is_account_email? f
423 t.split(" ").each { |e| contacts[PersonManager.person_for(e)] = true }
425 contacts[PersonManager.person_for(f)] = true
429 contacts.keys.compact
432 def load_sources fn=Redwood::SOURCE_FN
433 source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
434 @source_mutex.synchronize do
435 @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
436 @sources_dirty = false
440 def has_any_from_source_with_label? source, label
441 q = Ferret::Search::BooleanQuery.new
442 q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
443 q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
444 index.search(q, :limit => 1).total_hits > 0
449 ## do any specialized parsing
450 ## returns nil and flashes error message if parsing failed
451 def parse_user_query_string s
454 subs = s.gsub(/\b(to|from):(\S+)\b/) do
456 if(p = ContactManager.contact_for(name))
459 [field, "(" + AccountManager.user_emails.join("||") + ")"]
465 ## if we see a label:deleted or a label:spam term anywhere in the query
466 ## string, we set the extra load_spam or load_deleted options to true.
467 ## bizarre? well, because the query allows arbitrary parenthesized boolean
468 ## expressions, without fully parsing the query, we can't tell whether
469 ## the user is explicitly directing us to search spam messages or not.
470 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
471 ## search spam messages or not?
473 ## so, we rely on the fact that turning these extra options ON turns OFF
474 ## the adding of "-label:deleted" or "-label:spam" terms at the very
475 ## final stage of query processing. if the user wants to search spam
476 ## messages, not adding that is the right thing; if he doesn't want to
477 ## search spam messages, then not adding it won't have any effect.
478 extraopts[:load_spam] = true if subs =~ /\blabel:spam\b/
479 extraopts[:load_deleted] = true if subs =~ /\blabel:deleted\b/
481 ## gmail style "is" operator
482 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
483 field, label = $1, $2
488 extraopts[:load_spam] = true
491 extraopts[:load_deleted] = true
498 ## gmail style attachments "filename" and "filetype" searches
499 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
500 field, name = $1, ($3 || $4)
503 Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
504 "attachments:(#{name.downcase})"
506 Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
507 "attachments:(*.#{name.downcase})"
512 chronic_failure = false
513 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
514 break if chronic_failure
515 field, datestr = $1, ($3 || $4)
516 realdate = Chronic.parse(datestr, :guess => false, :context => :none)
520 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
521 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
523 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
524 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
526 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
527 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
530 BufferManager.flash "Can't understand date #{datestr.inspect}!"
531 chronic_failure = true
534 subs = nil if chronic_failure
538 [@qparser.parse(subs), extraopts]
545 query = Ferret::Search::BooleanQuery.new
546 query.add_query opts[:qobj], :must if opts[:qobj]
547 labels = ([opts[:label]] + (opts[:labels] || [])).compact
548 labels.each { |t| query.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
549 if opts[:participants]
550 q2 = Ferret::Search::BooleanQuery.new
551 opts[:participants].each do |p|
552 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
553 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
555 query.add_query q2, :must
558 query.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless opts[:load_spam] || labels.include?(:spam)
559 query.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless opts[:load_deleted] || labels.include?(:deleted)
560 query.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if opts[:skip_killed]
564 def save_sources fn=Redwood::SOURCE_FN
565 @source_mutex.synchronize do
566 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
570 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
572 Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
575 @sources_dirty = false