]> git.cworth.org Git - sup/blob - lib/sup/index.rb
index: remove unused method load_entry_for_id
[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
30     @dir = dir
31     @sources = {}
32     @sources_dirty = false
33     @source_mutex = Monitor.new
34
35     wsa = Ferret::Analysis::WhiteSpaceAnalyzer.new false
36     sa = Ferret::Analysis::StandardAnalyzer.new [], true
37     @analyzer = Ferret::Analysis::PerFieldAnalyzer.new wsa
38     @analyzer[:body] = sa
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
42
43     self.class.i_am_the_instance self
44   end
45
46   def lockfile; File.join @dir, "lock" end
47
48   def lock
49     Redwood::log "locking #{lockfile}..."
50     begin
51       @lock.lock
52     rescue Lockfile::MaxTriesLockError
53       raise LockError, @lock.lockinfo_on_disk
54     end
55   end
56
57   def start_lock_update_thread
58     @lock_update_thread = Redwood::reporting_thread("lock update") do
59       while true
60         sleep 30
61         @lock.touch_yourself
62       end
63     end
64   end
65
66   def stop_lock_update_thread
67     @lock_update_thread.kill if @lock_update_thread
68     @lock_update_thread = nil
69   end
70
71   def possibly_pluralize number_of, kind
72     "#{number_of} #{kind}" +
73         if number_of == 1 then "" else "s" end
74   end
75
76   def fancy_lock_error_message_for e
77     secs = (Time.now - e.mtime).to_i
78     mins = secs / 60
79     time =
80       if mins == 0
81         possibly_pluralize secs , "second"
82       else
83         possibly_pluralize mins, "minute"
84       end
85
86     <<EOS
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
89 as of #{time} ago.
90 EOS
91   end
92
93   def lock_or_die
94     begin
95       lock
96     rescue LockError => e
97       $stderr.puts fancy_lock_error_message_for(e)
98       $stderr.puts <<EOS
99
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}.
102 EOS
103       exit
104     end
105   end
106
107   def unlock
108     if @lock && @lock.locked?
109       Redwood::log "unlocking #{lockfile}..."
110       @lock.unlock
111     end
112   end
113
114   def load
115     load_sources
116     load_index
117   end
118
119   def save
120     Redwood::log "saving index and sources..."
121     FileUtils.mkdir_p @dir unless File.exists? @dir
122     save_sources
123     save_index
124   end
125
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
134     end
135   end
136
137   def sources
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
140   end
141
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
144
145   def load_index dir=File.join(@dir, "ferret")
146     if File.exists? dir
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"
151       end
152     else
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')
170       end
171     end
172   end
173
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
176   ## accessor.
177   def sync_message m, opts={}
178     entry = @index[m.id]
179
180     raise "no source info for message #{m.id}" unless m.source && m.source_info
181
182     source_id = if m.source.is_a? Integer
183       m.source
184     else
185       m.source.id or raise "unregistered source #{m.source} (id #{m.source.id.inspect})"
186     end
187
188     snippet = if m.snippet_contains_encrypted_content? && $config[:discard_snippets_from_encrypted_messages]
189       ""
190     else
191       m.snippet
192     end
193
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.)
197     ##
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.
202     ##
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
206     ## by everyone else.
207     ##
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.
210     entry ||= {}
211     labels = m.labels.uniq # override because this is the new state, unless...
212
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})"
221       entry = {}
222     end
223
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]
227
228     d = {
229       :message_id => m.id,
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(" ")),
237
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(" "),
247
248       :subject => (entry[:subject] || wrap_subj(Message.normalize_subj(m.subj))),
249       :refs => (entry[:refs] || (m.refs + m.replytos).uniq.join(" ")),
250     }
251
252     @index_mutex.synchronize do
253       @index.delete m.id
254       @index.add_document d
255     end
256   end
257
258   def save_index fn=File.join(@dir, "ferret")
259     # don't have to do anything, apparently
260   end
261
262   def contains_id? id
263     @index_mutex.synchronize { @index.search(Ferret::Search::TermQuery.new(:message_id, id)).total_hits > 0 }
264   end
265   def contains? m; contains_id? m.id end
266   def size; @index_mutex.synchronize { @index.size } end
267   def empty?; size == 0 end
268
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
275     offset = 0
276     while true
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 }
282       end
283       break if query[:limit] and offset >= query[:limit] - limit
284       break if offset >= results.total_hits - limit
285       offset += limit
286     end
287   end
288
289   def num_results_for query={}
290     return 0 if empty? # otherwise ferret barfs ###TODO: remove this once my ferret patch is accepted
291
292     ferret_query = build_ferret_query query
293     @index_mutex.synchronize { @index.search(ferret_query, :limit => 1).total_hits }
294   end
295
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.
300   ##
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
303   ## is found.
304   SAME_SUBJECT_DATE_LIMIT = 7
305   MAX_CLAUSES = 1000
306   def each_message_in_thread_for m, query={}
307     #Redwood::log "Building thread for #{m.id}: #{m.subj}"
308     messages = {}
309     searched = {}
310     num_queries = 0
311
312     pending = [m.id]
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)
316
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|
320         sq.add_term t
321       end
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
324
325       q = build_ferret_query :qobj => q
326
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}"
329
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"
332
333       pending = (pending + p1 + p2).uniq
334     end
335
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
340
341       lim = [MAX_CLAUSES / 2, pending.length].min
342       pending[0 ... lim].each do |id|
343         searched[id] = true
344         q.add_query Ferret::Search::TermQuery.new(:message_id, id), :should
345         q.add_query Ferret::Search::TermQuery.new(:refs, id), :should
346       end
347       pending = pending[lim .. -1]
348
349       q = build_ferret_query :qobj => q
350
351       num_queries += 1
352       killed = false
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]
357             killed = true
358             break
359           end
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] }
366           end
367         end
368       end
369     end
370
371     if killed
372       Redwood::log "thread for #{m.id} is killed, ignoring"
373       false
374     else
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 }
377       true
378     end
379   end
380
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
385
386       source = @source_mutex.synchronize { @sources[doc[:source_id].to_i] }
387       raise "invalid source #{doc[:source_id]}" unless source
388
389       #puts "building message #{doc[:message_id]} (#{source}##{doc[:source_info]})"
390
391       fake_header = {
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(" "),
398       }
399
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
404       m
405     end
406   end
407
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
411
412   def delete id; @index_mutex.synchronize { @index.delete id } end
413
414   def load_contacts emails, h={}
415     q = Ferret::Search::BooleanQuery.new true
416     emails.each do |e|
417       qq = Ferret::Search::BooleanQuery.new true
418       qq.add_query Ferret::Search::TermQuery.new(:from, e), :should
419       qq.add_query Ferret::Search::TermQuery.new(:to, e), :should
420       q.add_query qq
421     end
422     q.add_query Ferret::Search::TermQuery.new(:label, "spam"), :must_not
423     
424     Redwood::log "contact search: #{q}"
425     contacts = {}
426     num = h[:num] || 20
427     @index_mutex.synchronize do
428       @index.search_each q, :sort => "date DESC", :limit => :all do |docid, score|
429         break if contacts.size >= num
430         #Redwood::log "got message #{docid} to: #{@index[docid][:to].inspect} and from: #{@index[docid][:from].inspect}"
431         f = @index[docid][:from]
432         t = @index[docid][:to]
433
434         if AccountManager.is_account_email? f
435           t.split(" ").each { |e| contacts[Person.from_address(e)] = true }
436         else
437           contacts[Person.from_address(f)] = true
438         end
439       end
440     end
441
442     contacts.keys.compact
443   end
444
445   def load_sources fn=Redwood::SOURCE_FN
446     source_array = (Redwood::load_yaml_obj(fn) || []).map { |o| Recoverable.new o }
447     @source_mutex.synchronize do
448       @sources = Hash[*(source_array).map { |s| [s.id, s] }.flatten]
449       @sources_dirty = false
450     end
451   end
452
453   def has_any_from_source_with_label? source, label
454     q = Ferret::Search::BooleanQuery.new
455     q.add_query Ferret::Search::TermQuery.new("source_id", source.id.to_s), :must
456     q.add_query Ferret::Search::TermQuery.new("label", label.to_s), :must
457     @index_mutex.synchronize { @index.search(q, :limit => 1).total_hits > 0 }
458   end
459
460   def each_docid query={}
461     ferret_query = build_ferret_query query
462     results = @index_mutex.synchronize { @index.search ferret_query, :limit => (query[:limit] || :all) }
463     results.hits.map { |hit| yield hit.doc }
464   end
465
466   def each_message query={}
467     each_docid query do |docid|
468       yield build_message(docid)
469     end
470   end
471
472   def optimize
473     @index_mutex.synchronize { @index.optimize }
474   end
475
476   def source_for_id id
477     entry = @index[id]
478     return unless entry
479     entry[:source_id].to_i
480   end
481
482   class ParseError < StandardError; end
483
484   ## parse a query string from the user. returns a query object
485   ## that can be passed to any index method with a 'query'
486   ## argument, as well as build_ferret_query.
487   ##
488   ## raises a ParseError if something went wrong.
489   def parse_query s
490     query = {}
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     query[:load_spam] = true if subs =~ /\blabel:spam\b/
517     query[: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         query[:load_spam] = true
527         "label:spam"
528       when "deleted"
529         query[: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       subs = subs.gsub(/\b(before|on|in|during|after):(\((.+?)\)\B|(\S+)\b)/) do
551         field, datestr = $1, ($3 || $4)
552         realdate = Chronic.parse datestr, :guess => false, :context => :past
553         if realdate
554           case field
555           when "after"
556             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.end}"
557             "date:(>= #{sprintf "%012d", realdate.end.to_i})"
558           when "before"
559             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate.begin}"
560             "date:(<= #{sprintf "%012d", realdate.begin.to_i})"
561           else
562             Redwood::log "chronic: translated #{field}:#{datestr} to #{realdate}"
563             "date:(<= #{sprintf "%012d", realdate.end.to_i}) date:(>= #{sprintf "%012d", realdate.begin.to_i})"
564           end
565         else
566           raise ParseError, "can't understand date #{datestr.inspect}"
567         end
568       end
569     end
570
571     ## limit:42 restrict the search to 42 results
572     subs = subs.gsub(/\blimit:(\S+)\b/) do
573       lim = $1
574       if lim =~ /^\d+$/
575         query[:limit] = lim.to_i
576         ''
577       else
578         raise ParseError, "non-numeric limit #{lim.inspect}"
579       end
580     end
581     
582     begin
583       query[:qobj] = @qparser.parse(subs)
584       query[:text] = s
585       query
586     rescue Ferret::QueryParser::QueryParseException => e
587       raise ParseError, e.message
588     end
589   end
590
591 private
592
593   def build_ferret_query query
594     q = Ferret::Search::BooleanQuery.new
595     q.add_query query[:qobj], :must if query[:qobj]
596     labels = ([query[:label]] + (query[:labels] || [])).compact
597     labels.each { |t| q.add_query Ferret::Search::TermQuery.new("label", t.to_s), :must }
598     if query[:participants]
599       q2 = Ferret::Search::BooleanQuery.new
600       query[:participants].each do |p|
601         q2.add_query Ferret::Search::TermQuery.new("from", p.email), :should
602         q2.add_query Ferret::Search::TermQuery.new("to", p.email), :should
603       end
604       q.add_query q2, :must
605     end
606         
607     q.add_query Ferret::Search::TermQuery.new("label", "spam"), :must_not unless query[:load_spam] || labels.include?(:spam)
608     q.add_query Ferret::Search::TermQuery.new("label", "deleted"), :must_not unless query[:load_deleted] || labels.include?(:deleted)
609     q.add_query Ferret::Search::TermQuery.new("label", "killed"), :must_not if query[:skip_killed]
610
611     q.add_query Ferret::Search::TermQuery.new("source_id", query[:source_id]), :must if query[:source_id]
612     q
613   end
614
615   def save_sources fn=Redwood::SOURCE_FN
616     @source_mutex.synchronize do
617       if @sources_dirty || @sources.any? { |id, s| s.dirty? }
618         bakfn = fn + ".bak"
619         if File.exists? fn
620           File.chmod 0600, fn
621           FileUtils.mv fn, bakfn, :force => true unless File.exists?(bakfn) && File.size(fn) == 0
622         end
623         Redwood::save_yaml_obj sources.sort_by { |s| s.id.to_i }, fn, true
624         File.chmod 0600, fn
625       end
626       @sources_dirty = false
627     end
628   end
629 end
630
631 end