Skip to content

Commit

Permalink
Simplify mod_keystore_cets:init_ram_key/1
Browse files Browse the repository at this point in the history
Use cets:insert_new_or_lookup/2
  • Loading branch information
arcusfelis committed Oct 6, 2023
1 parent 37d7c46 commit 77ef883
Show file tree
Hide file tree
Showing 3 changed files with 5 additions and 29 deletions.
2 changes: 1 addition & 1 deletion rebar.config
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@
{cache_tab, "1.0.30"},
{segmented_cache, "0.3.0"},
{worker_pool, "6.0.1"},
{cets, {git, "https://github.com/esl/cets.git", {branch, "main"}}},
{cets, {git, "https://github.com/esl/cets.git", {branch, "insert-new-or-lookup"}}},

%%% HTTP tools
{graphql, {git, "https://github.com/esl/graphql-erlang.git", {branch, "master"}}},
Expand Down
2 changes: 1 addition & 1 deletion rebar.lock
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
{<<"certifi">>,{pkg,<<"certifi">>,<<"2.9.0">>},1},
{<<"cets">>,
{git,"https://github.com/esl/cets.git",
{ref,"def7da28917fe7e21ad2b50d1b9939b1da5046cf"}},
{ref,"72b01d2dd97c193e60365f0e7e53d30d0876ba1b"}},
0},
{<<"cowboy">>,{pkg,<<"cowboy">>,<<"2.9.0">>},0},
{<<"cowboy_swagger">>,{pkg,<<"cowboy_swagger">>,<<"2.5.1">>},0},
Expand Down
30 changes: 3 additions & 27 deletions src/mod_keystore_cets.erl
Original file line number Diff line number Diff line change
Expand Up @@ -41,34 +41,10 @@ handle_conflict(Rec1, Rec2) ->
ProposedKey :: mod_keystore:key(),
Result :: {ok, ActualKey} | {error, init_ram_key_failed},
ActualKey :: mod_keystore:key().
init_ram_key(ProposedKey) ->
init_ram_key(ProposedKey, 1, 3).

%% Inserts new key or returns already inserted.
-spec init_ram_key(Key, TriedTimes, Retries) -> Result when
Result :: {ok, Key} | {error, init_ram_key_failed},
Key :: mod_keystore:key(),
TriedTimes :: non_neg_integer(),
Retries :: non_neg_integer().
init_ram_key(#key{id = Id, key = Key}, _, 0) ->
?LOG_ERROR(#{what => init_ram_key_failed, id => Id, key => Key}),
{error, init_ram_key_failed};
init_ram_key(ProposedKey = #key{id = Id = {_, HostType}, key = PropKey}, N, Retries) ->
init_ram_key(#key{id = Id = {_, HostType}, key = PropKey}) ->
Tab = table_name(HostType),
case cets:insert_new(Tab, {Id, PropKey}) of
true ->
{ok, ProposedKey};
false ->
case ets:lookup(Tab, Id) of
[{Id, Key}] ->
%% Return already inserted key
{ok, #key{id = Id, key = Key}};
[] ->
?LOG_WARNING(#{what => init_ram_key_retry,
id => Id, key => PropKey, tried_times => N}),
init_ram_key(ProposedKey, N + 1, Retries - 1)
end
end.
{_, [{Id, Key}]} = cets:insert_new_or_lookup(Tab, {Id, PropKey}),
{ok, #key{id = Id, key = Key}}.

-spec get_key(Id :: mod_keystore:key_id()) -> mod_keystore:key_list().
get_key(Id = {_, HostType}) ->
Expand Down

0 comments on commit 77ef883

Please sign in to comment.