]> git.cworth.org Git - sup/blob - lib/sup/index.rb
move source-related methods to SourceManager
[sup] / lib / sup / index.rb
1 ## the index structure for redwood. interacts with ferret.
2
3 require 'fileutils'
4 require 'ferret'
5
6 begin
7   require 'chronic'
8   $have_chronic = true
9 rescue LoadError => e
10   Redwood::log "optional 'chronic' library not found (run 'gem install chronic' to install)"
11   $have_chronic = false
12 end
13
14 module Redwood
15
16 class Index
17   class LockError < StandardError
18     def initialize h
19       @h = h
20     end
21
22     def method_missing m; @h[m.to_s] end
23   end
24
25   include Singleton
26
27   def initialize dir=BASE_DIR
28     @index_mutex = Monitor.new
29     @dir = dir
30
31     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
32     sa = Ferret::Analysis::StandardAnalyzer.new [], true
33     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
34     @analyzer[:body] = sa
35     @analyzer[:subject] = sa
36     @qparser ||= Ferret::QueryParser.new :default_field => :body, :analyzer => @analyzer, :or_default => false
37     @lock = Lockfile.new lockfile, :retries => 0, :max_age => nil
38
39     self.class.i_am_the_instance self
40   end
41
42   def lockfile; File.join @dir, "lock" end
43
44   def lock
45     Redwood::log "locking #{lockfile}..."
46     begin
47       @lock.lock
48     rescue Lockfile::MaxTriesLockError
49       raise LockError, @lock.lockinfo_on_disk
50     end
51   end
52
53   def start_lock_update_thread
54     @lock_update_thread = Redwood::reporting_thread("lock update") do
55       while true
56         sleep 30
57         @lock.touch_yourself
58       end
59     end
60   end
61
62   def stop_lock_update_thread
63     @lock_update_thread.kill if @lock_update_thread
64     @lock_update_thread = nil
65   end
66
67   def possibly_pluralize number_of, kind
68     "#{number_of} #{kind}" +
69         if number_of == 1 then "" else "s" end
70   end
71
72   def fancy_lock_error_message_for e
73     secs = (Time.now - e.mtime).to_i
74     mins = secs / 60
75     time =
76       if mins == 0
77         possibly_pluralize secs , "second"
78       else
79         possibly_pluralize mins, "minute"
80       end
81
82     <<EOS
83 Error: the sup index is locked by another process! User '#{e.user}' on
84 host '#{e.host}' is running #{e.pname} with pid #{e.pid}. The process was alive
85 as of #{time} ago.
86 EOS
87   end
88
89   def lock_or_die
90     begin
91       lock
92     rescue LockError => e
93       $stderr.puts fancy_lock_error_message_for(e)
94       $stderr.puts <<EOS
95
96 You can wait for the process to finish, or, if it crashed and left a
97 stale lock file behind, you can manually delete #{@lock.path}.
98 EOS
99       exit
100     end
101   end
102
103   def unlock
104     if @lock && @lock.locked?
105       Redwood::log "unlocking #{lockfile}..."
106       @lock.unlock
107     end
108   end
109
110   def load
111     SourceManager.load_sources
112     load_index
113   end
114
115   def save
116     Redwood::log "saving index and sources..."
117     FileUtils.mkdir_p @dir unless File.exists? @dir
118     SourceManager.save_sources
119     save_index
120   end
121
122   def load_index dir=File.join(@dir, "ferret")
123     if File.exists? dir
124       Redwood::log "loading index..."
125       @index_mutex.synchronize do
126         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
127         Redwood::log "loaded index of #{@index.size} messages"
128       end
129     else
130       Redwood::log "creating index..."
131       @index_mutex.synchronize do
132         field_infos = Ferret::Index::FieldInfos.new :store => :yes
133         field_infos.add_field :message_id, :index => :untokenized
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
138         field_infos.add_field :label
139         field_infos.add_field :attachments
140         field_infos.add_field :subject
141         field_infos.add_field :from
142         field_infos.add_field :to
143         field_infos.add_field :refs
144         field_infos.add_field :snippet, :index => :no, :term_vector => :no
145         field_infos.create_index dir
146         @index = Ferret::Index::Index.new(:path => dir, :analyzer => @analyzer, :id_field => 'message_id')
147       end
148     end
149   end
150
151   ## Syncs the message to the index, replacing any previous version.  adding
152   ## either way. Index state will be determined by the message's #labels
153   ## accessor.
154   def sync_message m, opts={}
155     entry = @index[m.id]
156
157     raise "no source info for message #{m.id}" unless m.source && m.source_info
158
159     source_id = if m.source.is_a? Integer
160       m.source
161     else
162       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
163     end
164
165     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
166       ""
167     else
168       m.snippet
169     end
170
171     ## write the new document to the index. if the entry already exists in the
172     ## index, reuse it (which avoids having to reload the entry from the source,
173     ## which can be quite expensive for e.g. large threads of IMAP actions.)
174     ##
175     ## exception: if the index entry belongs to an earlier version of the
176     ## message, use everything from the new message instead, but union the
177     ## flags. this allows messages sent to mailing lists to have their header
178     ## updated and to have flags set properly.
179     ##
180     ## minor hack: messages in sources with lower ids have priority over
181     ## messages in sources with higher ids. so messages in the inbox will
182     ## override everyone, and messages in the sent box will be overridden
183     ## by everyone else.
184     ##
185     ## written in this manner to support previous versions of the index which
186     ## did not keep around the entry body. upgrading is thus seamless.
187     entry ||= {}
188     labels = m.labels.uniq # override because this is the new state, unless...
189
190     ## if we are a later version of a message, ignore what's in the index,
191     ## but merge in the labels.
192     if entry[:source_id] && entry[:source_info] && entry[:label] &&
193       ((entry[:source_id].to_i > source_id) || (entry[:source_info].to_i < m.source_info))
194       labels = (entry[:label].symbolistize + m.labels).uniq
195       #Redwood::log "found updated version of message #{m.id}: #{m.subj}"
196       #Redwood::log "previous version was at #{entry[:source_id].inspect}:#{entry[:source_info].inspect}, this version at #{source_id.inspect}:#{m.source_info.inspect}"
197       #Redwood::log "merged labels are #{labels.inspect} (index #{entry[:label].inspect}, message #{m.labels.inspect})"
198       entry = {}
199     end
200
201     ## if force_overwite is true, ignore what's in the index. this is used
202     ## primarily by sup-sync to force index updates.
203     entry = {} if opts[:force_overwrite]
204
205     d = {
206       :message_id => m.id,
207       :source_id => source_id,
208       :source_info => m.source_info,
209       :date => (entry[:date] || m.date.to_indexable_s),
210       :body => (entry[:body] || m.indexable_content),
211       :snippet => snippet, # always override
212       :label => labels.uniq.join(" "),
213       :attachments => (entry[:attachments] || m.attachments.uniq.join(" ")),
214
215       ## always override :from and :to.
216       ## older versions of Sup would often store the wrong thing in the index
217       ## (because they were canonicalizing email addresses, resulting in the
218       ## wrong name associated with each.) the correct address is read from
219       ## the original header when these messages are opened in thread-view-mode,
220       ## so this allows people to forcibly update the address in the index by
221       ## marking those threads for saving.
222       :from => (m.from ? m.from.indexable_content : ""),
223       :to => (m.to + m.cc + m.bcc).map { |x| x.indexable_content }.join(" "),
224
225       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
226       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
227     }
228
229     @index_mutex.synchronize do
230       @index.delete m.id
231       @index.add_document d
232     end
233   end
234
235   def save_index fn=File.join(@dir, "ferret")
236     # don't have to do anything, apparently
237   end
238
239   def contains_id? id
240     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
241   end
242   def contains? m; contains_id? m.id end
243   def size; @index_mutex.synchronize { @index.size } end
244   def empty?; size == 0 end
245
246   ## you should probably not call this on a block that doesn't break
247   ## rather quickly because the results can be very large.
248   EACH_BY_DATE_NUM = 100
249   def each_id_by_date query={}
250     return if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
251     ferret_query = build_ferret_query query
252     offset = 0
253     while true
254       limit = (query[:limit])? [EACH_BY_DATE_NUM, query[:limit] - offset].min : EACH_BY_DATE_NUM
255       results = @index_mutex.synchronize { @index.search ferret_query, :sort => "date DESC", :limit => limit, :offset => offset }
256       Redwood::log "got #{results.total_hits} results for query (offset #{offset}) #{ferret_query.inspect}"
257       results.hits.each do |hit|
258         yield @index_mutex.synchronize { @index[hit.doc][:message_id] }, lambda { build_message hit.doc }
259       end
260       break if query[:limit] and offset >= query[:limit] - limit
261       break if offset >= results.total_hits - limit
262       offset += limit
263     end
264   end
265
266   def num_results_for query={}
267     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
268
269     ferret_query = build_ferret_query query
270     @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
271   end
272
273   ## yield all messages in the thread containing 'm' by repeatedly
274   ## querying the index. yields pairs of message ids and
275   ## message-building lambdas, so that building an unwanted message
276   ## can be skipped in the block if desired.
277   ##
278   ## only two options, :limit and :skip_killed. if :skip_killed is
279   ## true, stops loading any thread if a message with a :killed flag
280   ## is found.
281   SAME_SUBJECT_DATE_LIMIT = 7
282   MAX_CLAUSES = 1000
283   def each_message_in_thread_for m, query={}
284     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
285     messages = {}
286     searched = {}
287     num_queries = 0
288
289     pending = [m.id]
290     if $config[:thread_by_subject] # do subject queries
291       date_min = m.date - (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
292       date_max = m.date + (SAME_SUBJECT_DATE_LIMIT * 12 * 3600)
293
294       q = Ferret::Search::BooleanQuery.new true
295       sq = Ferret::Search::PhraseQuery.new(:subject)
296       wrap_subj(Message.normalize_subj(m.subj)).split.each do |t|
297         sq.add_term t
298       end
299       q.add_query sq, :must
300       q.add_query Ferret::Search::RangeQuery.new(:date, :>= => date_min.to_indexable_s, :<= => date_max.to_indexable_s), :must
301
302       q = build_ferret_query :qobj => q
303
304       p1 = @index_mutex.synchronize { @index.search(q).hits.map { |hit| @index[hit.doc][:message_id] } }
305       Redwood::log "found #{p1.size} results for subject query #{q}"
306
307       p2 = @index_mutex.synchronize { @index.search(q.to_s, :limit => :all).hits.map { |hit| @index[hit.doc][:message_id] } }
308       Redwood::log "found #{p2.size} results in string form"
309
310       pending = (pending + p1 + p2).uniq
311     end
312
313     until pending.empty? || (query[:limit] && messages.size >= query[:limit])
314       q = Ferret::Search::BooleanQuery.new true
315       # this disappeared in newer ferrets... wtf.
316       # q.max_clause_count = 2048
317
318       lim = [MAX_CLAUSES / 2, pending.length].min
319       pending[0 ... lim].each do |id|
320         searched[id] = true
321         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
322         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
323       end
324       pending = pending[lim .. -1]
325
326       q = build_ferret_query :qobj => q
327
328       num_queries += 1
329       killed = false
330       @index_mutex.synchronize do
331         @index.search_each(q, :limit => :all) do |docid, score|
332           break if query[:limit] && messages.size >= query[:limit]
333           if @index[docid][:label].split(/\s+/).include?("killed") && query[:skip_killed]
334             killed = true
335             break
336           end
337           mid = @index[docid][:message_id]
338           unless messages.member?(mid)
339             #Redwood::log "got #{mid} as a child of #{id}"
340             messages[mid] ||= lambda { build_message docid }
341             refs = @index[docid][:refs].split
342             pending += refs.select { |id| !searched[id] }
343           end
344         end
345       end
346     end
347
348     if killed
349       Redwood::log "thread for #{m.id} is killed, ignoring"
350       false
351     else
352       Redwood::log "ran #{num_queries} queries to build thread of #{messages.size} messages for #{m.id}: #{m.subj}" if num_queries > 0
353       messages.each { |mid, builder| yield mid, builder }
354       true
355     end
356   end
357
358   ## builds a message object from a ferret result
359   def build_message docid
360     @index_mutex.synchronize do
361       doc = @index[docid] or return
362
363       source = SourceManager[doc[:source_id].to_i]
364       raise "invalid source #{doc[:source_id]}" unless source
365
366       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
367
368       fake_header = {
369         "date" => Time.at(doc[:date].to_i),
370         "subject" => unwrap_subj(doc[:subject]),
371         "from" => doc[:from],
372         "to" => doc[:to].split.join(", "), # reformat
373         "message-id" => doc[:message_id],
374         "references" => doc[:refs].split.map { |x| "<#{x}>" }.join(" "),
375       }
376
377       m = Message.new :source => source, :source_info => doc[:source_info].to_i,
378                   :labels => doc[:label].symbolistize,
379                   :snippet => doc[:snippet]
380       m.parse_header fake_header
381       m
382     end
383   end
384
385   def fresh_thread_id; @next_thread_id += 1; end
386   def wrap_subj subj; "__START_SUBJECT__ #{subj} __END_SUBJECT__"; end
387   def unwrap_subj subj; subj =~ /__START_SUBJECT__ (.*?) __END_SUBJECT__/ && $1; end
388
389   def delete id; @index_mutex.synchronize { @index.delete id } end
390
391   def load_contacts emails, h={}
392     q = Ferret::Search::BooleanQuery.new true
393     emails.each do |e|
394       qq = Ferret::Search::BooleanQuery.new true
395       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
396       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
397       q.add_query qq
398     end
399     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
400     
401     Redwood::log "contact search: #{q}"
402     contacts = {}
403     num = h[:num] || 20
404     @index_mutex.synchronize do
405       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
406         break if contacts.size >= num
407         #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
408         f = @index[docid][:from]
409         t = @index[docid][:to]
410
411         if AccountManager.is_account_email? f
412           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
413         else
414           contacts[Person.from_address(f)] = true
415         end
416       end
417     end
418
419     contacts.keys.compact
420   end
421
422   def each_docid query={}
423     ferret_query = build_ferret_query query
424     results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
425     results.hits.map { |hit| yield hit.doc }
426   end
427
428   def each_message query={}
429     each_docid query do |docid|
430       yield build_message(docid)
431     end
432   end
433
434   def optimize
435     @index_mutex.synchronize { @index.optimize }
436   end
437
438   def source_for_id id
439     entry = @index[id]
440     return unless entry
441     entry[:source_id].to_i
442   end
443
444   class ParseError < StandardError; end
445
446   ## parse a query string from the user. returns a query object
447   ## that can be passed to any index method with a 'query'
448   ## argument, as well as build_ferret_query.
449   ##
450   ## raises a ParseError if something went wrong.
451   def parse_query s
452     query = {}
453
454     subs = s.gsub(/\b(to|from):(\S+)\b/) do
455       field, name = $1, $2
456       if(p = ContactManager.contact_for(name))
457         [field, p.email]
458       elsif name == "me"
459         [field, "(" + AccountManager.user_emails.join("||") + ")"]
460       else
461         [field, name]
462       end.join(":")
463     end
464
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?
472     ##
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     query[:load_spam] = true if subs =~ /\blabel:spam\b/
479     query[:load_deleted] = true if subs =~ /\blabel:deleted\b/
480
481     ## gmail style "is" operator
482     subs = subs.gsub(/\b(is|has):(\S+)\b/) do
483       field, label = $1, $2
484       case label
485       when "read"
486         "-label:unread"
487       when "spam"
488         query[:load_spam] = true
489         "label:spam"
490       when "deleted"
491         query[:load_deleted] = true
492         "label:deleted"
493       else
494         "label:#{$2}"
495       end
496     end
497
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)
501       case field
502       when "filename"
503         Redwood::log "filename - translated #{field}:#{name} to attachments:(#{name.downcase})"
504         "attachments:(#{name.downcase})"
505       when "filetype"
506         Redwood::log "filetype - translated #{field}:#{name} to attachments:(*.#{name.downcase})"
507         "attachments:(*.#{name.downcase})"
508       end
509     end
510
511     if $have_chronic
512       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
513         field, datestr = $1, ($3 || $4)
514         realdate = Chronic.parse datestr, :guess => false, :context => :past
515         if realdate
516           case field
517           when "after"
518             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
519             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
520           when "before"
521             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
522             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
523           else
524             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
525             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
526           end
527         else
528           raise ParseError, "can't understand date #{datestr.inspect}"
529         end
530       end
531     end
532
533     ## limit:42 restrict the search to 42 results
534     subs = subs.gsub(/\blimit:(\S+)\b/) do
535       lim = $1
536       if lim =~ /^\d+$/
537         query[:limit] = lim.to_i
538         ''
539       else
540         raise ParseError, "non-numeric limit #{lim.inspect}"
541       end
542     end
543     
544     begin
545       query[:qobj] = @qparser.parse(subs)
546       query[:text] = s
547       query
548     rescue Ferret::QueryParser::QueryParseException => e
549       raise ParseError, e.message
550     end
551   end
552
553 private
554
555   def build_ferret_query query
556     q = Ferret::Search::BooleanQuery.new
557     q.add_query query[:qobj], :must if query[:qobj]
558     labels = ([query[:label]] + (query[:labels] || [])).compact
559     labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
560     if query[:participants]
561       q2 = Ferret::Search::BooleanQuery.new
562       query[:participants].each do |p|
563         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
564         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
565       end
566       q.add_query q2, :must
567     end
568         
569     q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
570     q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
571     q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
572
573     q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
574     q
575   end
576 end
577
578 end