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