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