Comparison

core/storagemanager.lua @ 3401:2387f35db5c8

storagemanager: Initial commit.
author Waqas Hussain <waqas20@gmail.com>
date Fri, 23 Jul 2010 23:09:58 +0500
child 3403:b89680015b7b
comparison
equal deleted inserted replaced
3400:502a634f0578 3401:2387f35db5c8
1
2 local error = error;
3 local setmetatable = setmetatable;
4
5 local config = require "core.configmanager";
6 local datamanager = require "util.datamanager";
7 local multitable = require "util.multitable";
8 local modulemanager = require "core.modulemanager";
9 local hosts = hosts;
10 local log = require "util.logger".init("storagemanager");
11
12 local olddm = {}; -- maintain old datamanager, for backwards compatibility
13 for k,v in pairs(datamanager) do olddm[k] = v; end
14
15 local driver_cache = multitable.new();
16 local store_cache = multitable.new();
17
18 module("storagemanager")
19
20 local default_driver_mt = {};
21 default_driver_mt.__index = default_driver_mt;
22 function default_driver_mt:open(store)
23 return setmetatable({ host = self.host, store = self.store }, default_driver_mt);
24 end
25 function default_driver_mt:get(user) return olddm.load(user, self.host, self.store); end
26 function default_driver_mt:set(user, data) return olddm.store(user, self.host, self.store, data); end
27
28 local function load_driver_for_host(host)
29 if driver_cache:get(host) then return driver_cache:get(host); end
30
31 local host_session = hosts[host];
32 if not host_session then error("No such host"); end
33
34 local driver_plugin = config.get(host, "core", "datastore");
35 if not driver_plugin then return setmetatable({ host = host }, default_driver_mt); end
36
37 local provider;
38 local function handler(event) provider = event.item; end
39 host_session.events.add_handler("item-added/data-driver", handler);
40 local success, err = modulemanager.load(host, driver_plugin);
41 host_session.events.remove_handler("item-added/data-driver", handler);
42 if not success then error(err); end
43 if not provider then error("Module didn't add a provider"); end
44
45 driver_cache:set(host, provider);
46 log("debug", "Data driver '%s' loaded for host '%s'", driver_plugin, host);
47 return provider;
48 end
49
50 function open(host, store, typ)
51 local ret = store_cache:get(host, store);
52 if not ret then
53 local driver = load_driver_for_host(host);
54 ret = driver:open(store, typ);
55 if not ret then ret = setmetatable({ host = host, store = store }, default_driver_mt); end -- default to default driver
56 store_cache:set(host, store, ret);
57 end
58 return ret;
59 end
60
61 function datamanager.load(username, host, datastore)
62 return open(host, datastore):get(username);
63 end
64 function datamanager.store(username, host, datastore, data)
65 return open(host, datastore):set(username, data);
66 end
67
68 return _M;