]> git.netwichtig.de Git - user/henk/code/ruby/rbot.git/blob - lib/rbot/registry.rb
[registry] small refactoring and added flush test
[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     end
116
117     def sub_registry(prefix)
118       path = File.join(@filename.gsub(/\.[^\/\.]+$/,''), prefix.to_s)
119       return self.class.new(path)
120     end
121
122     # creates the registry / subregistry folders
123     def create_folders
124       debug 'create folders for: ' + @filename
125       dirs = File.dirname(@filename).split("/")
126       dirs.length.times { |i|
127         dir = dirs[0,i+1].join("/")+"/"
128         unless File.exist?(dir)
129           Dir.mkdir(dir)
130         end
131       }
132     end
133
134     # Will return true if the database file exists.
135     def dbexists?
136       File.exists? @filename
137     end
138
139     # convert value to string form for storing in the registry
140     # defaults to Marshal.dump(val) but you can override this in your module's
141     # registry object to use any method you like.
142     # For example, if you always just handle strings use:
143     #   def store(val)
144     #     val
145     #   end
146     def store(val)
147       Marshal.dump(val)
148     end
149
150     # restores object from string form, restore(store(val)) must return val.
151     # If you override store, you should override restore to reverse the
152     # action.
153     # For example, if you always just handle strings use:
154     #   def restore(val)
155     #     val
156     #   end
157     def restore(val)
158       begin
159         Marshal.restore(val)
160       rescue Exception => e
161         error _("failed to restore marshal data for #{val.inspect}, attempting recovery or fallback to default")
162         debug e
163         if defined? @recovery and @recovery
164           begin
165             return @recovery.call(val)
166           rescue Exception => ee
167             error _("marshal recovery failed, trying default")
168             debug ee
169           end
170         end
171         return default
172       end
173     end
174
175     # Returned instead of nil if key wasnt found.
176     def set_default (default)
177       @default = default
178     end
179
180     def default
181       @default && (@default.dup rescue @default)
182     end
183
184     # Opens the database (if not already open) for read/write access.
185     def registry
186       create_folders unless dbexists?
187     end
188
189     # Forces flush/sync the database on disk.
190     def flush
191       return unless @registry
192       # if not supported by the database, close/reopen:
193       close
194       registry
195     end
196
197     # Should optimize/vacuum the database. (if supported)
198     def optimize
199     end
200
201     # Closes the database.
202     def close
203       return unless @registry
204       @registry.close
205       @registry = nil
206     end
207
208     # lookup a key in the registry
209     def [](key)
210       if dbexists? and registry.has_key?(key.to_s)
211         return restore(registry[key.to_s])
212       else
213         return default
214       end
215     end
216
217     # set a key in the registry
218     def []=(key,value)
219       registry[key.to_s] = store(value)
220     end
221
222     # like Hash#each
223     def each(&block)
224       return nil unless dbexists?
225       registry.each_key do |key|
226         block.call(key, self[key])
227       end
228     end
229
230     alias each_pair each
231
232     # like Hash#each_key
233     def each_key(&block)
234       self.each do |key|
235         block.call(key)
236       end
237     end
238
239     # like Hash#each_value
240     def each_value(&block)
241       self.each do |key, value|
242         block.call(value)
243       end
244     end
245
246     # just like Hash#has_key?
247     def has_key?(key)
248       return nil unless dbexists?
249       return registry.has_key?(key.to_s)
250     end
251
252     alias include? has_key?
253     alias member? has_key?
254     alias key? has_key?
255
256     # just like Hash#has_value?
257     def has_value?(value)
258       return nil unless dbexists?
259       return registry.has_value?(store(value))
260     end
261
262     # just like Hash#index?
263     def index(value)
264       self.each do |k,v|
265         return k if v == value
266       end
267       return nil
268     end
269
270     # delete a key from the registry
271     def delete(key)
272       return default unless dbexists?
273       value = registry.delete(key.to_s)
274       if value
275         restore(value)
276       end
277     end
278
279     # returns a list of your keys
280     def keys
281       return [] unless dbexists?
282       return registry.keys
283     end
284
285     # Return an array of all associations [key, value] in your namespace
286     def to_a
287       return [] unless dbexists?
288       ret = Array.new
289       self.each {|key, value|
290         ret << [key, value]
291       }
292       return ret
293     end
294
295     # Return an hash of all associations {key => value} in your namespace
296     def to_hash
297       return {} unless dbexists?
298       ret = Hash.new
299       self.each {|key, value|
300         ret[key] = value
301       }
302       return ret
303     end
304
305     # empties the registry (restricted to your namespace)
306     def clear
307       return unless dbexists?
308       registry.clear
309     end
310     alias truncate clear
311
312     # returns an array of the values in your namespace of the registry
313     def values
314       return [] unless dbexists?
315       ret = Array.new
316       self.each {|k,v|
317         ret << v
318       }
319       return ret
320     end
321
322     # returns the number of keys in your registry namespace
323     def length
324       return 0 unless dbexists?
325       registry.length
326     end
327     alias size length
328
329     # Returns all classes from the namespace that implement this interface
330     def self.get_impl
331       ObjectSpace.each_object(Class).select { |klass| klass < self }
332     end
333   end
334
335 end # Registry
336
337 end # Bot
338 end # Irc
339