]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/registry.rb
Improvements to the points plugin
[user/henk/code/ruby/rbot.git] / lib / rbot / registry.rb
1 #-- vim:sw=2:et
2 #++
3 #
4 # :title: Registry: Persistent storage interface and factory
5
6 # This class provides persistent storage for plugins via a hash interface.
7 # The default mode is an object store, so you can store ruby objects and
8 # reference them with hash keys. This is because the default store/restore
9 # methods of the plugins' RegistryAccessor are calls to Marshal.dump and
10 # Marshal.restore,
11 # for example:
12 #   blah = Hash.new
13 #   blah[:foo] = "fum"
14 #   @registry[:blah] = blah
15 # then, even after the bot is shut down and disconnected, on the next run you
16 # can access the blah object as it was, with:
17 #   blah = @registry[:blah]
18 # The registry can of course be used to store simple strings, fixnums, etc as
19 # well, and should be useful to store or cache plugin data or dynamic plugin
20 # configuration.
21 #
22 # WARNING:
23 # in object store mode, don't make the mistake of treating it like a live
24 # object, e.g. (using the example above)
25 #   @registry[:blah][:foo] = "flump"
26 # will NOT modify the object in the registry - remember that Registry#[]
27 # returns a Marshal.restore'd object, the object you just modified in place
28 # will disappear. You would need to:
29 #   blah = @registry[:blah]
30 #   blah[:foo] = "flump"
31 #   @registry[:blah] = blah
32 #
33 # If you don't need to store objects, and strictly want a persistant hash of
34 # strings, you can override the store/restore methods to suit your needs, for
35 # example (in your plugin):
36 #   def initialize
37 #     class << @registry
38 #       def store(val)
39 #         val
40 #       end
41 #       def restore(val)
42 #         val
43 #       end
44 #     end
45 #   end
46 # Your plugins section of the registry is private, it has its own namespace
47 # (derived from the plugin's class name, so change it and lose your data).
48 # Calls to registry.each etc, will only iterate over your namespace.
49
50 module Irc
51 class Bot
52
53 class Registry
54
55   # Dynamically loads the specified registry type library.
56   def initialize(format=nil)
57     @libpath = File.join(File.dirname(__FILE__), 'registry')
58     @format = format
59     load File.join(@libpath, @format+'.rb') if format
60   end
61
62   # Returns a list of supported registry database formats.
63   def discover
64     Dir.glob(File.join(@libpath, '*.rb')).map do |name|
65       File.basename(name, File.extname(name))
66     end
67   end
68
69   # Creates a new Accessor object for the specified database filename.
70   def create(path, filename)
71     # The get_impl method will return a list of all the classes that
72     # implement the accessor interface, since we only ever load one
73     # (the configured one) accessor implementation, we can just assume
74     # it to be the correct accessor to use.
75     cls = AbstractAccessor.get_impl.first
76     db = cls.new(File.join(path, 'registry_' + @format, filename.downcase))
77     db.optimize
78     db
79   end
80
81   # Helper method that will return a list of supported registry formats.
82   def self.formats
83     @@formats ||= Registry.new.discover
84   end
85
86   # Will detect tokyocabinet registry location: ~/.rbot/registry/*.tdb
87   #  and move it to its new location ~/.rbot/registry_tc/*.tdb
88   def migrate_registry_folder(path)
89     old_name = File.join(path, 'registry')
90     new_name = File.join(path, 'registry_tc')
91     if @format == 'tc' and File.exists?(old_name) and
92         not File.exists?(new_name) and
93         not Dir.glob(File.join(old_name, '*.tdb')).empty?
94       File.rename(old_name, new_name)
95     end
96   end
97
98   # Abstract database accessor (a hash-like interface).
99   class AbstractAccessor
100
101     attr_reader :filename
102
103     # lets the user define a recovery procedure in case the Marshal
104     # deserialization fails, it might be manually recover data.
105     # NOTE: weird legacy stuff, used by markov plugin (WTH?)
106     attr_accessor :recovery
107
108     def initialize(filename)
109       debug 'init registry accessor for: ' + filename
110       @filename = filename
111       @name = File.basename filename
112       @registry = nil
113       @default = nil
114       @recovery = nil
115       @sub_registries = {}
116     end
117
118     def sub_registry(prefix)
119       path = File.join(@filename.gsub(/\.[^\/\.]+$/,''), prefix.to_s)
120       @sub_registries[path] ||= self.class.new(path)
121     end
122
123     # creates the registry / subregistry folders
124     def create_folders
125       debug 'create folders for: ' + @filename
126       dirs = File.dirname(@filename).split("/")
127       dirs.length.times { |i|
128         dir = dirs[0,i+1].join("/")+"/"
129         unless File.exist?(dir)
130           Dir.mkdir(dir)
131         end
132       }
133     end
134
135     # Will return true if the database file exists.
136     def dbexists?
137       File.exists? @filename
138     end
139
140     # convert value to string form for storing in the registry
141     # defaults to Marshal.dump(val) but you can override this in your module's
142     # registry object to use any method you like.
143     # For example, if you always just handle strings use:
144     #   def store(val)
145     #     val
146     #   end
147     def store(val)
148       Marshal.dump(val)
149     end
150
151     # restores object from string form, restore(store(val)) must return val.
152     # If you override store, you should override restore to reverse the
153     # action.
154     # For example, if you always just handle strings use:
155     #   def restore(val)
156     #     val
157     #   end
158     def restore(val)
159       begin
160         Marshal.restore(val)
161       rescue Exception => e
162         error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
163         debug e
164         if defined? @recovery and @recovery
165           begin
166             return @recovery.call(val)
167           rescue Exception => ee
168             error _("marshal recovery failed, trying default")
169             debug ee
170           end
171         end
172         return default
173       end
174     end
175
176     # Returned instead of nil if key wasnt found.
177     def set_default (default)
178       @default = default
179     end
180
181     def default
182       @default && (@default.dup rescue @default)
183     end
184
185     # Opens the database (if not already open) for read/write access.
186     def registry
187       create_folders unless dbexists?
188     end
189
190     # Forces flush/sync the database on disk.
191     def flush
192       return unless @registry
193       # if not supported by the database, close/reopen:
194       close
195       registry
196     end
197
198     # Should optimize/vacuum the database. (if supported)
199     def optimize
200     end
201
202     # Closes the database.
203     def close
204       return unless @registry
205       @registry.close
206       @registry = nil
207     end
208
209     # lookup a key in the registry
210     def [](key)
211       if dbexists? and registry.has_key?(key.to_s)
212         return restore(registry[key.to_s])
213       else
214         return default
215       end
216     end
217
218     # set a key in the registry
219     def []=(key,value)
220       registry[key.to_s] = store(value)
221     end
222
223     # like Hash#each
224     def each(&block)
225       return nil unless dbexists?
226       registry.each do |key, value|
227         block.call(key, restore(value))
228       end
229     end
230
231     alias each_pair each
232
233     # like Hash#each_key
234     def each_key(&block)
235       self.each do |key|
236         block.call(key)
237       end
238     end
239
240     # like Hash#each_value
241     def each_value(&block)
242       self.each do |key, value|
243         block.call(value)
244       end
245     end
246
247     # just like Hash#has_key?
248     def has_key?(key)
249       return nil unless dbexists?
250       return registry.has_key?(key.to_s)
251     end
252
253     alias include? has_key?
254     alias member? has_key?
255     alias key? has_key?
256
257     # just like Hash#has_value?
258     def has_value?(value)
259       return nil unless dbexists?
260       return registry.has_value?(store(value))
261     end
262
263     # just like Hash#index?
264     def index(value)
265       self.each do |k,v|
266         return k if v == value
267       end
268       return nil
269     end
270
271     # delete a key from the registry
272     # returns the value in success, nil otherwise
273     def delete(key)
274       return default unless dbexists?
275       value = registry.delete(key.to_s)
276       if value
277         restore(value)
278       end
279     end
280
281     # returns a list of your keys
282     def keys
283       return [] unless dbexists?
284       return registry.keys
285     end
286
287     # Return an array of all associations [key, value] in your namespace
288     def to_a
289       return [] unless dbexists?
290       ret = Array.new
291       self.each {|key, value|
292         ret << [key, value]
293       }
294       return ret
295     end
296
297     # Return an hash of all associations {key => value} in your namespace
298     def to_hash
299       return {} unless dbexists?
300       ret = Hash.new
301       self.each {|key, value|
302         ret[key] = value
303       }
304       return ret
305     end
306
307     # empties the registry (restricted to your namespace)
308     def clear
309       return unless dbexists?
310       registry.clear
311     end
312     alias truncate clear
313
314     # returns an array of the values in your namespace of the registry
315     def values
316       return [] unless dbexists?
317       ret = Array.new
318       self.each {|k,v|
319         ret << v
320       }
321       return ret
322     end
323
324     # returns the number of keys in your registry namespace
325     def length
326       return 0 unless dbexists?
327       registry.length
328     end
329     alias size length
330
331     # Returns all classes from the namespace that implement this interface
332     def self.get_impl
333       ObjectSpace.each_object(Class).select { |klass| klass < self }
334     end
335   end
336
337 end # Registry
338
339 end # Bot
340 end # Irc
341