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