1 ## the index structure for redwood. interacts with ferret.
10 Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
17 class LockError < StandardError
22 def method_missing m; @h[m.to_s] end
27 def initialize dir=BASE_DIR
28 @index_mutex = Monitor.new
32 @sources_dirty = false
33 @source_mutex = Monitor.new
35 wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
36 sa = Ferret::Analysis::StandardAnalyzer.new [], true
37 @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
39 @analyzer[:subject] = sa
40 @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
41 @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
43 self.class.i_am_the_instance self
46 def lockfile; File.join @dir, "lock" end
49 Redwood::log "locking #{lockfile}..."
52 rescue Lockfile::MaxTriesLockError
53 raise LockError, @lock.lockinfo_on_disk
57 def start_lock_update_thread
58 @lock_update_thread = Redwood::reporting_thread("lock update") do
66 def stop_lock_update_thread
67 @lock_update_thread.kill if @lock_update_thread
68 @lock_update_thread = nil
71 def possibly_pluralize number_of, kind
72 "#{number_of} #{kind}" +
73 if number_of == 1 then "" else "s" end
76 def fancy_lock_error_message_for e
77 secs = (Time.now - e.mtime).to_i
81 possibly_pluralize secs , "second"
83 possibly_pluralize mins, "minute"
87 Error: the sup index is locked by another process! User '#{e.user}' on
88 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
97 $stderr.puts fancy_lock_error_message_for(e)
100 You can wait for the process to finish, or, if it crashed and left a
101 stale lock file behind, you can manually delete #{@lock.path}.
108 if @lock && @lock.locked?
109 Redwood::log "unlocking #{lockfile}..."
120 Redwood::log "saving index and sources..."
121 FileUtils.mkdir_p @dir unless File.exists? @dir
126 def add_source source
127 @source_mutex.synchronize do
128 raise "duplicate source!" if @sources.include? source
129 @sources_dirty = true
130 max = @sources.max_of { |id, s| s.is_a?(DraftLoader) || s.is_a?(SentLoader) ? 0 : id }
131 source.id ||= (max || 0) + 1
132 ##source.id += 1 while @sources.member? source.id
133 @sources[source.id] = source
138 ## favour the inbox by listing non-archived sources first
139 @source_mutex.synchronize { @sources.values }.sort_by { |s| s.id }.partition { |s| !s.archived? }.flatten
142 def source_for uri; sources.find { |s| s.is_source_for? uri }; end
143 def usual_sources; sources.find_all { |s| s.usual? }; end
145 def load_index dir=File.join(@dir, "ferret")
147 Redwood::log "loading index..."
148 @index_mutex.synchronize do
149 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
150 Redwood::log "loaded index of #{@index.size} messages"
153 Redwood::log "creating index..."
154 @index_mutex.synchronize do
155 field_infos = Ferret::Index::FieldInfos.new :store => :yes
156 field_infos.add_field :message_id, :index => :untokenized
157 field_infos.add_field :source_id
158 field_infos.add_field :source_info
159 field_infos.add_field :date, :index => :untokenized
160 field_infos.add_field :body
161 field_infos.add_field :label
162 field_infos.add_field :attachments
163 field_infos.add_field :subject
164 field_infos.add_field :from
165 field_infos.add_field :to
166 field_infos.add_field :refs
167 field_infos.add_field :snippet, :index => :no, :term_vector => :no
168 field_infos.create_index dir
169 @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
174 ## Syncs the message to the index, replacing any previous version. adding
175 ## either way. Index state will be determined by the message's #labels
177 def sync_message m, opts={}
180 raise "no source info for message #{m.id}" unless m.source && m.source_info
182 source_id = if m.source.is_a? Integer
185 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
188 snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
194 ## write the new document to the index. if the entry already exists in the
195 ## index, reuse it (which avoids having to reload the entry from the source,
196 ## which can be quite expensive for e.g. large threads of IMAP actions.)
198 ## exception: if the index entry belongs to an earlier version of the
199 ## message, use everything from the new message instead, but union the
200 ## flags. this allows messages sent to mailing lists to have their header
201 ## updated and to have flags set properly.
203 ## minor hack: messages in sources with lower ids have priority over
204 ## messages in sources with higher ids. so messages in the inbox will
205 ## override everyone, and messages in the sent box will be overridden
208 ## written in this manner to support previous versions of the index which
209 ## did not keep around the entry body. upgrading is thus seamless.
211 labels = m.labels.uniq # override because this is the new state, unless...
213 ## if we are a later version of a message, ignore what's in the index,
214 ## but merge in the labels.
215 if entry[:source_id] && entry[:source_info] && entry[:label] &&
216 ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
217 labels = (entry[:label].symbolistize + m.labels).uniq
218 #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
219 #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
220 #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
224 ## if force_overwite is true, ignore what's in the index. this is used
225 ## primarily by sup-sync to force index updates.
226 entry = {} if opts[:force_overwrite]
230 :source_id => source_id,
231 :source_info => m.source_info,
232 :date => (entry[:date] || m.date.to_indexable_s),
233 :body => (entry[:body] || m.indexable_content),
234 :snippet => snippet, # always override
235 :label => labels.uniq.join(" "),
236 :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
238 ## always override :from and :to.
239 ## older versions of Sup would often store the wrong thing in the index
240 ## (because they were canonicalizing email addresses, resulting in the
241 ## wrong name associated with each.) the correct address is read from
242 ## the original header when these messages are opened in thread-view-mode,
243 ## so this allows people to forcibly update the address in the index by
244 ## marking those threads for saving.
245 :from => (m.from ? m.from.indexable_content : ""),
246 :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
248 :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
249 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
252 @index_mutex.synchronize do
254 @index.add_document d
258 def save_index fn=File.join(@dir, "ferret")
259 # don't have to do anything, apparently
263 @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
265 def contains? m; contains_id? m.id end
266 def size; @index_mutex.synchronize { @index.size } end
267 def empty?; size == 0 end
269 ## you should probably not call this on a block that doesn't break
270 ## rather quickly because the results can be very large.
271 EACH_BY_DATE_NUM = 100
272 def each_id_by_date query={}
273 return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
274 ferret_query = build_ferret_query query
277 limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
278 results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
279 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
280 results.hits.each do |hit|
281 yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
283 break if query[:limit] and offset >= query[:limit] - limit
284 break if offset >= results.total_hits - limit
289 def num_results_for query={}
290 return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
292 ferret_query = build_ferret_query query
293 @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
296 ## yield all messages in the thread containing 'm' by repeatedly
297 ## querying the index. yields pairs of message ids and
298 ## message-building lambdas, so that building an unwanted message
299 ## can be skipped in the block if desired.
301 ## only two options, :limit and :skip_killed. if :skip_killed is
302 ## true, stops loading any thread if a message with a :killed flag
304 SAME_SUBJECT_DATE_LIMIT = 7
306 def each_message_in_thread_for m, query={}
307 #Redwood::log "Building thread for #{m.id}: #{m.subj}"
313 if $config[:thread_by_subject] # do subject queries
314 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
315 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
317 q = Ferret::Search::BooleanQuery.new true
318 sq = Ferret::Search::PhraseQuery.new(:subject)
319 wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
322 q.add_query sq, :must
323 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
325 q = build_ferret_query :qobj => q
327 p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
328 Redwood::log "found #{p1.size} results for subject query #{q}"
330 p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
331 Redwood::log "found #{p2.size} results in string form"
333 pending = (pending + p1 + p2).uniq
336 until pending.empty? || (query[:limit] && messages.size >= query[:limit])
337 q = Ferret::Search::BooleanQuery.new true
338 # this disappeared in newer ferrets... wtf.
339 # q.max_clause_count = 2048
341 lim = [MAX_CLAUSES / 2, pending.length].min
342 pending[0 ... lim].each do |id|
344 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
345 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
347 pending = pending[lim .. -1]
349 q = build_ferret_query :qobj => q
353 @index_mutex.synchronize do
354 @index.search_each(q, :limit => :all) do |docid, score|
355 break if query[:limit] && messages.size >= query[:limit]
356 if @index[docid][:label].split(/\s+/).include?("killed") && query[:skip_killed]
360 mid = @index[docid][:message_id]
361 unless messages.member?(mid)
362 #Redwood::log "got #{mid} as a child of #{id}"
363 messages[mid] ||= lambda { build_message docid }
364 refs = @index[docid][:refs].split
365 pending += refs.select { |id| !searched[id] }
372 Redwood::log "thread for #{m.id} is killed, ignoring"
375 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
376 messages.each { |mid, builder| yield mid, builder }
381 ## builds a message object from a ferret result
382 def build_message docid
383 @index_mutex.synchronize do
384 doc = @index[docid] or return
386 source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
387 raise "invalid source #{doc[:source_id]}" unless source
389 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
392 "date" => Time.at(doc[:date].to_i),
393 "subject" => unwrap_subj(doc[:subject]),
394 "from" => doc[:from],
395 "to" => doc[:to].split.join(", "), # reformat
396 "message-id" => doc[:message_id],
397 "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
400 m = Message.new :source => source, :source_info => doc[:source_info].to_i,
401 :labels => doc[:label].symbolistize,
402 :snippet => doc[:snippet]
403 m.parse_header fake_header
408 def fresh_thread_id; @next_thread_id += 1; end
409 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
410 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
412 def delete id; @index_mutex.synchronize { @index.delete id } end
414 def load_entry_for_id mid
415 @index_mutex.synchronize do
416 results = @index.search Ferret::Search::TermQuery.new(:message_id, mid)
417 return if results.total_hits == 0
418 docid = results.hits[0].doc
419 entry = @index[docid]
420 entry_dup = entry.fields.inject({}) { |h, f| h[f] = entry[f]; h }
425 def load_contacts emails, h={}
426 q = Ferret::Search::BooleanQuery.new true
428 qq = Ferret::Search::BooleanQuery.new true
429 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
430 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
433 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
435 Redwood::log "contact search: #{q}"
438 @index_mutex.synchronize do
439 @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
440 break if contacts.size >= num
441 #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
442 f = @index[docid][:from]
443 t = @index[docid][:to]
445 if AccountManager.is_account_email? f
446 t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
448 contacts[Person.from_address(f)] = true
453 contacts.keys.compact
456 def load_sources fn=Redwood::SOURCE_FN
457 source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
458 @source_mutex.synchronize do
459 @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
460 @sources_dirty = false
464 def has_any_from_source_with_label? source, label
465 q = Ferret::Search::BooleanQuery.new
466 q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
467 q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
468 @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
471 def each_docid query={}
472 ferret_query = build_ferret_query query
473 results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
474 results.hits.map { |hit| yield hit.doc }
477 def each_message query={}
478 each_docid query do |docid|
479 yield build_message(docid)
484 @index_mutex.synchronize { @index.optimize }
490 entry[:source_id].to_i
493 class ParseError < StandardError; end
495 ## parse a query string from the user. returns a query object
496 ## that can be passed to any index method with a 'query'
497 ## argument, as well as build_ferret_query.
499 ## raises a ParseError if something went wrong.
503 subs = s.gsub(/\b(to|from):(\S+)\b/) do
505 if(p = ContactManager.contact_for(name))
508 [field, "(" + AccountManager.user_emails.join("||") + ")"]
514 ## if we see a label:deleted or a label:spam term anywhere in the query
515 ## string, we set the extra load_spam or load_deleted options to true.
516 ## bizarre? well, because the query allows arbitrary parenthesized boolean
517 ## expressions, without fully parsing the query, we can't tell whether
518 ## the user is explicitly directing us to search spam messages or not.
519 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
520 ## search spam messages or not?
522 ## so, we rely on the fact that turning these extra options ON turns OFF
523 ## the adding of "-label:deleted" or "-label:spam" terms at the very
524 ## final stage of query processing. if the user wants to search spam
525 ## messages, not adding that is the right thing; if he doesn't want to
526 ## search spam messages, then not adding it won't have any effect.
527 query[:load_spam] = true if subs =~ /\blabel:spam\b/
528 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
530 ## gmail style "is" operator
531 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
532 field, label = $1, $2
537 query[:load_spam] = true
540 query[:load_deleted] = true
547 ## gmail style attachments "filename" and "filetype" searches
548 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
549 field, name = $1, ($3 || $4)
552 Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
553 "attachments:(#{name.downcase})"
555 Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
556 "attachments:(*.#{name.downcase})"
561 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
562 field, datestr = $1, ($3 || $4)
563 realdate = Chronic.parse datestr, :guess => false, :context => :past
567 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
568 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
570 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
571 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
573 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
574 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
577 raise ParseError, "can't understand date #{datestr.inspect}"
582 ## limit:42 restrict the search to 42 results
583 subs = subs.gsub(/\blimit:(\S+)\b/) do
586 query[:limit] = lim.to_i
589 raise ParseError, "non-numeric limit #{lim.inspect}"
594 query[:qobj] = @qparser.parse(subs)
597 rescue Ferret::QueryParser::QueryParseException => e
598 raise ParseError, e.message
604 def build_ferret_query query
605 q = Ferret::Search::BooleanQuery.new
606 q.add_query query[:qobj], :must if query[:qobj]
607 labels = ([query[:label]] + (query[:labels] || [])).compact
608 labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
609 if query[:participants]
610 q2 = Ferret::Search::BooleanQuery.new
611 query[:participants].each do |p|
612 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
613 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
615 q.add_query q2, :must
618 q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
619 q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
620 q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
622 q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
626 def save_sources fn=Redwood::SOURCE_FN
627 @source_mutex.synchronize do
628 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
632 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
634 Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
637 @sources_dirty = false