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
178 ## if need_load is false, docid and entry are assumed to be set to the
179 ## result of load_entry_for_id (which can be nil).
180 def sync_message m, need_load=true, docid=nil, entry=nil, opts={}
181 docid, entry = load_entry_for_id m.id if need_load
183 raise "no source info for message #{m.id}" unless m.source && m.source_info
184 @index_mutex.synchronize do
185 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
188 source_id = if m.source.is_a? Integer
191 m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
194 snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
200 ## write the new document to the index. if the entry already exists in the
201 ## index, reuse it (which avoids having to reload the entry from the source,
202 ## which can be quite expensive for e.g. large threads of IMAP actions.)
204 ## exception: if the index entry belongs to an earlier version of the
205 ## message, use everything from the new message instead, but union the
206 ## flags. this allows messages sent to mailing lists to have their header
207 ## updated and to have flags set properly.
209 ## minor hack: messages in sources with lower ids have priority over
210 ## messages in sources with higher ids. so messages in the inbox will
211 ## override everyone, and messages in the sent box will be overridden
214 ## written in this manner to support previous versions of the index which
215 ## did not keep around the entry body. upgrading is thus seamless.
217 labels = m.labels.uniq # override because this is the new state, unless...
219 ## if we are a later version of a message, ignore what's in the index,
220 ## but merge in the labels.
221 if entry[:source_id] && entry[:source_info] && entry[:label] &&
222 ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
223 labels = (entry[:label].symbolistize + m.labels).uniq
224 #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
225 #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
226 #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
230 ## if force_overwite is true, ignore what's in the index. this is used
231 ## primarily by sup-sync to force index updates.
232 entry = {} if opts[:force_overwrite]
236 :source_id => source_id,
237 :source_info => m.source_info,
238 :date => (entry[:date] || m.date.to_indexable_s),
239 :body => (entry[:body] || m.indexable_content),
240 :snippet => snippet, # always override
241 :label => labels.uniq.join(" "),
242 :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
244 ## always override :from and :to.
245 ## older versions of Sup would often store the wrong thing in the index
246 ## (because they were canonicalizing email addresses, resulting in the
247 ## wrong name associated with each.) the correct address is read from
248 ## the original header when these messages are opened in thread-view-mode,
249 ## so this allows people to forcibly update the address in the index by
250 ## marking those threads for saving.
251 :from => (m.from ? m.from.indexable_content : ""),
252 :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
254 :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
255 :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
258 @index_mutex.synchronize do
259 @index.delete docid if docid
260 @index.add_document d
263 ## this hasn't been triggered in a long time.
264 ## docid, entry = load_entry_for_id m.id
265 ## raise "just added message #{m.id.inspect} but couldn't find it in a search" unless docid
268 def save_index fn=File.join(@dir, "ferret")
269 # don't have to do anything, apparently
273 @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
275 def contains? m; contains_id? m.id end
276 def size; @index_mutex.synchronize { @index.size } end
277 def empty?; size == 0 end
279 ## you should probably not call this on a block that doesn't break
280 ## rather quickly because the results can be very large.
281 EACH_BY_DATE_NUM = 100
282 def each_id_by_date query={}
283 return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
284 ferret_query = build_ferret_query query
287 limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
288 results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
289 Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
290 results.hits.each do |hit|
291 yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
293 break if query[:limit] and offset >= query[:limit] - limit
294 break if offset >= results.total_hits - limit
299 def num_results_for query={}
300 return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
302 ferret_query = build_ferret_query query
303 @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
306 ## yield all messages in the thread containing 'm' by repeatedly
307 ## querying the index. yields pairs of message ids and
308 ## message-building lambdas, so that building an unwanted message
309 ## can be skipped in the block if desired.
311 ## only two options, :limit and :skip_killed. if :skip_killed is
312 ## true, stops loading any thread if a message with a :killed flag
314 SAME_SUBJECT_DATE_LIMIT = 7
316 def each_message_in_thread_for m, query={}
317 #Redwood::log "Building thread for #{m.id}: #{m.subj}"
323 if $config[:thread_by_subject] # do subject queries
324 date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
325 date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
327 q = Ferret::Search::BooleanQuery.new true
328 sq = Ferret::Search::PhraseQuery.new(:subject)
329 wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
332 q.add_query sq, :must
333 q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
335 q = build_ferret_query :qobj => q
337 p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
338 Redwood::log "found #{p1.size} results for subject query #{q}"
340 p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
341 Redwood::log "found #{p2.size} results in string form"
343 pending = (pending + p1 + p2).uniq
346 until pending.empty? || (query[:limit] && messages.size >= query[:limit])
347 q = Ferret::Search::BooleanQuery.new true
348 # this disappeared in newer ferrets... wtf.
349 # q.max_clause_count = 2048
351 lim = [MAX_CLAUSES / 2, pending.length].min
352 pending[0 ... lim].each do |id|
354 q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
355 q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
357 pending = pending[lim .. -1]
359 q = build_ferret_query :qobj => q
363 @index_mutex.synchronize do
364 @index.search_each(q, :limit => :all) do |docid, score|
365 break if query[:limit] && messages.size >= query[:limit]
366 if @index[docid][:label].split(/\s+/).include?("killed") && query[:skip_killed]
370 mid = @index[docid][:message_id]
371 unless messages.member?(mid)
372 #Redwood::log "got #{mid} as a child of #{id}"
373 messages[mid] ||= lambda { build_message docid }
374 refs = @index[docid][:refs].split
375 pending += refs.select { |id| !searched[id] }
382 Redwood::log "thread for #{m.id} is killed, ignoring"
385 Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
386 messages.each { |mid, builder| yield mid, builder }
391 ## builds a message object from a ferret result
392 def build_message docid
393 @index_mutex.synchronize do
396 source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
397 raise "invalid source #{doc[:source_id]}" unless source
399 #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
402 "date" => Time.at(doc[:date].to_i),
403 "subject" => unwrap_subj(doc[:subject]),
404 "from" => doc[:from],
405 "to" => doc[:to].split.join(", "), # reformat
406 "message-id" => doc[:message_id],
407 "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
410 m = Message.new :source => source, :source_info => doc[:source_info].to_i,
411 :labels => doc[:label].symbolistize,
412 :snippet => doc[:snippet]
413 m.parse_header fake_header
418 def fresh_thread_id; @next_thread_id += 1; end
419 def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
420 def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
422 def delete id; @index_mutex.synchronize { @index.delete id } end
424 def load_entry_for_id mid
425 @index_mutex.synchronize do
426 results = @index.search Ferret::Search::TermQuery.new(:message_id, mid)
427 return if results.total_hits == 0
428 docid = results.hits[0].doc
429 entry = @index[docid]
430 entry_dup = entry.fields.inject({}) { |h, f| h[f] = entry[f]; h }
435 def load_contacts emails, h={}
436 q = Ferret::Search::BooleanQuery.new true
438 qq = Ferret::Search::BooleanQuery.new true
439 qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
440 qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
443 q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
445 Redwood::log "contact search: #{q}"
448 @index_mutex.synchronize do
449 @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
450 break if contacts.size >= num
451 #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
452 f = @index[docid][:from]
453 t = @index[docid][:to]
455 if AccountManager.is_account_email? f
456 t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
458 contacts[Person.from_address(f)] = true
463 contacts.keys.compact
466 def load_sources fn=Redwood::SOURCE_FN
467 source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
468 @source_mutex.synchronize do
469 @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
470 @sources_dirty = false
474 def has_any_from_source_with_label? source, label
475 q = Ferret::Search::BooleanQuery.new
476 q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
477 q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
478 @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
481 def each_docid query={}
482 ferret_query = build_ferret_query query
483 results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
484 results.hits.map { |hit| yield hit.doc }
487 def each_message query={}
488 each_docid query do |docid|
489 yield build_message(docid)
494 @index_mutex.synchronize { @index.optimize }
500 entry[:source_id].to_i
503 class ParseError < StandardError; end
505 ## parse a query string from the user. returns a query object
506 ## that can be passed to any index method with a 'query'
507 ## argument, as well as build_ferret_query.
509 ## raises a ParseError if something went wrong.
513 subs = s.gsub(/\b(to|from):(\S+)\b/) do
515 if(p = ContactManager.contact_for(name))
518 [field, "(" + AccountManager.user_emails.join("||") + ")"]
524 ## if we see a label:deleted or a label:spam term anywhere in the query
525 ## string, we set the extra load_spam or load_deleted options to true.
526 ## bizarre? well, because the query allows arbitrary parenthesized boolean
527 ## expressions, without fully parsing the query, we can't tell whether
528 ## the user is explicitly directing us to search spam messages or not.
529 ## e.g. if the string is -(-(-(-(-label:spam)))), does the user want to
530 ## search spam messages or not?
532 ## so, we rely on the fact that turning these extra options ON turns OFF
533 ## the adding of "-label:deleted" or "-label:spam" terms at the very
534 ## final stage of query processing. if the user wants to search spam
535 ## messages, not adding that is the right thing; if he doesn't want to
536 ## search spam messages, then not adding it won't have any effect.
537 query[:load_spam] = true if subs =~ /\blabel:spam\b/
538 query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
540 ## gmail style "is" operator
541 subs = subs.gsub(/\b(is|has):(\S+)\b/) do
542 field, label = $1, $2
547 query[:load_spam] = true
550 query[:load_deleted] = true
557 ## gmail style attachments "filename" and "filetype" searches
558 subs = subs.gsub(/\b(filename|filetype):(\((.+?)\)\B|(\S+)\b)/) do
559 field, name = $1, ($3 || $4)
562 Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
563 "attachments:(#{name.downcase})"
565 Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
566 "attachments:(*.#{name.downcase})"
571 subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
572 field, datestr = $1, ($3 || $4)
573 realdate = Chronic.parse datestr, :guess => false, :context => :past
577 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
578 "date:(>= #{sprintf "%012d", realdate.end.to_i})"
580 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
581 "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
583 Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
584 "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
587 raise ParseError, "can't understand date #{datestr.inspect}"
592 ## limit:42 restrict the search to 42 results
593 subs = subs.gsub(/\blimit:(\S+)\b/) do
596 query[:limit] = lim.to_i
599 raise ParseError, "non-numeric limit #{lim.inspect}"
604 query[:qobj] = @qparser.parse(subs)
607 rescue Ferret::QueryParser::QueryParseException => e
608 raise ParseError, e.message
614 def build_ferret_query query
615 q = Ferret::Search::BooleanQuery.new
616 q.add_query query[:qobj], :must if query[:qobj]
617 labels = ([query[:label]] + (query[:labels] || [])).compact
618 labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
619 if query[:participants]
620 q2 = Ferret::Search::BooleanQuery.new
621 query[:participants].each do |p|
622 q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
623 q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
625 q.add_query q2, :must
628 q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
629 q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
630 q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
632 q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
636 def save_sources fn=Redwood::SOURCE_FN
637 @source_mutex.synchronize do
638 if @sources_dirty || @sources.any? { |id, s| s.dirty? }
642 FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
644 Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
647 @sources_dirty = false