1 |
|
-module(mod_keystore_mnesia). |
2 |
|
-behaviour(mod_keystore_backend). |
3 |
|
|
4 |
|
-export([init/2, |
5 |
|
stop/1, |
6 |
|
init_ram_key/1, |
7 |
|
get_key/1]). |
8 |
|
|
9 |
|
-ignore_xref([get_key/1, init/2, init_ram_key/1]). |
10 |
|
|
11 |
|
-include("mod_keystore.hrl"). |
12 |
|
|
13 |
|
-spec init(mongooseim:host_type(), gen_mod:module_opts()) -> ok. |
14 |
|
init(_HostType, _Opts) -> |
15 |
:-( |
mongoose_mnesia:create_table(key, |
16 |
|
[{ram_copies, [node()]}, {type, set}, |
17 |
|
{attributes, record_info(fields, key)}]), |
18 |
:-( |
ok. |
19 |
|
|
20 |
|
-spec stop(mongooseim:host_type()) -> ok. |
21 |
|
stop(_HostType) -> |
22 |
:-( |
ok. |
23 |
|
|
24 |
|
-spec init_ram_key(ProposedKey) -> Result when |
25 |
|
ProposedKey :: mod_keystore:key(), |
26 |
|
Result :: {ok, ActualKey} | {error, any()}, |
27 |
|
ActualKey :: mod_keystore:key(). |
28 |
|
init_ram_key(ProposedKey) -> |
29 |
:-( |
case mnesia:transaction(fun init_ram_key_transaction/1, [ProposedKey]) of |
30 |
:-( |
{aborted, Reason} -> {error, Reason}; |
31 |
:-( |
{atomic, Key} -> {ok, Key} |
32 |
|
end. |
33 |
|
|
34 |
|
init_ram_key_transaction(#key{id = KeyID} = ProposedKey) -> |
35 |
:-( |
case mnesia:wread({key, KeyID}) of |
36 |
|
[#key{} = ActualKey] -> |
37 |
:-( |
ActualKey; |
38 |
|
[] -> |
39 |
:-( |
mnesia:write(ProposedKey), |
40 |
:-( |
ProposedKey |
41 |
|
end. |
42 |
|
|
43 |
|
-spec get_key(ID :: mod_keystore:key_id()) -> mod_keystore:key_list(). |
44 |
|
get_key(ID) -> |
45 |
:-( |
case mnesia:transaction(fun mnesia:read/1, [{key, ID}]) of |
46 |
:-( |
{aborted, Reason} -> error(Reason, [ID]); |
47 |
:-( |
{atomic, []} -> []; |
48 |
:-( |
{atomic, [#key{id = ID, key = Key}]} -> [{ID, Key}] |
49 |
|
end. |