1 |
|
-module(mod_keystore_cets). |
2 |
|
-behaviour(mod_keystore_backend). |
3 |
|
|
4 |
|
-export([init/2, |
5 |
|
stop/1, |
6 |
|
init_ram_key/1, |
7 |
|
get_key/1]). |
8 |
|
|
9 |
|
%% CETS callbacks |
10 |
|
-export([handle_conflict/2]). |
11 |
|
|
12 |
|
-ignore_xref([get_key/1, init/2, init_ram_key/1]). |
13 |
|
|
14 |
|
-include("mod_keystore.hrl"). |
15 |
|
-include("mongoose_logger.hrl"). |
16 |
|
|
17 |
|
table_name(HostType) -> |
18 |
59 |
binary_to_atom(<<"cets_keystore_", HostType/binary>>). |
19 |
|
|
20 |
|
-spec init(mongooseim:host_type(), gen_mod:module_opts()) -> ok. |
21 |
|
init(HostType, _Opts) -> |
22 |
|
%% There is no logic to remove keys. |
23 |
|
%% Separate table per HostType (so we could remove the table once the module is unloaded). |
24 |
2 |
Tab = table_name(HostType), |
25 |
2 |
cets:start(Tab, #{handle_conflict => fun ?MODULE:handle_conflict/2}), |
26 |
2 |
cets_discovery:add_table(mongoose_cets_discovery, Tab), |
27 |
2 |
ok. |
28 |
|
|
29 |
|
-spec stop(mongooseim:host_type()) -> ok. |
30 |
|
stop(HostType) -> |
31 |
2 |
Tab = table_name(HostType), |
32 |
2 |
cets_discovery:delete_table(mongoose_cets_discovery, Tab), |
33 |
2 |
cets:stop(Tab), |
34 |
2 |
ok. |
35 |
|
|
36 |
|
%% We need to choose one key consistently. |
37 |
|
handle_conflict(Rec1, Rec2) -> |
38 |
:-( |
max(Rec1, Rec2). |
39 |
|
|
40 |
|
-spec init_ram_key(ProposedKey) -> Result when |
41 |
|
ProposedKey :: mod_keystore:key(), |
42 |
|
Result :: {ok, ActualKey} | {error, init_ram_key_failed}, |
43 |
|
ActualKey :: mod_keystore:key(). |
44 |
|
init_ram_key(#key{id = Id = {_, HostType}, key = PropKey}) -> |
45 |
4 |
Tab = table_name(HostType), |
46 |
4 |
{_, [{Id, Key}]} = cets:insert_new_or_lookup(Tab, {Id, PropKey}), |
47 |
4 |
{ok, #key{id = Id, key = Key}}. |
48 |
|
|
49 |
|
-spec get_key(Id :: mod_keystore:key_id()) -> mod_keystore:key_list(). |
50 |
|
get_key(Id = {_, HostType}) -> |
51 |
51 |
Tab = table_name(HostType), |
52 |
51 |
ets:lookup(Tab, Id). |