chore: add some docs and specs; treat some possible errors

This commit is contained in:
Thales Macedo Garitezi 2022-10-27 13:19:07 -03:00
parent 7f4ffee7b5
commit 4a06c25178
2 changed files with 23 additions and 5 deletions

View File

@ -25,6 +25,8 @@
-export([init/1]). -export([init/1]).
-type worker_id() :: term().
start_link() -> start_link() ->
supervisor:start_link({local, ?MODULE}, ?MODULE, []). supervisor:start_link({local, ?MODULE}, ?MODULE, []).
@ -37,14 +39,30 @@ init([]) ->
ChildSpecs = [], ChildSpecs = [],
{ok, {SupFlags, ChildSpecs}}. {ok, {SupFlags, ChildSpecs}}.
%% @doc Starts a new JWT worker. The worker will send the caller a
%% message when it creates and stores its first JWT, or if it fails to
%% do so, using a generated reference.
-spec start_worker(worker_id(), map()) ->
{ok, {reference(), supervisor:child()}}
| {error, already_present}
| {error, {already_started, supervisor:child()}}.
start_worker(Id, Config) -> start_worker(Id, Config) ->
Ref = erlang:alias([reply]), Ref = erlang:alias([reply]),
ChildSpec = jwt_worker_child_spec(Id, Config, Ref), ChildSpec = jwt_worker_child_spec(Id, Config, Ref),
{ok, Pid} = supervisor:start_child(?MODULE, ChildSpec), case supervisor:start_child(?MODULE, ChildSpec) of
{Ref, Pid}. {ok, Pid} ->
{ok, {Ref, Pid}};
Error ->
Error
end.
%% @doc Stops a given JWT worker by its id.
-spec stop_worker(worker_id()) -> ok.
stop_worker(Id) -> stop_worker(Id) ->
supervisor:terminate_child(?MODULE, Id). case supervisor:terminate_child(?MODULE, Id) of
ok -> ok;
{error, not_found} -> ok
end.
jwt_worker_child_spec(Id, Config, Ref) -> jwt_worker_child_spec(Id, Config, Ref) ->
#{ id => Id #{ id => Id

View File

@ -225,12 +225,12 @@ t_lookup_badarg(_Config) ->
t_start_supervised_worker(_Config) -> t_start_supervised_worker(_Config) ->
{ok, _} = emqx_rule_engine_jwt_sup:start_link(), {ok, _} = emqx_rule_engine_jwt_sup:start_link(),
Config = #{resource_id := ResourceId} = generate_config(), Config = #{resource_id := ResourceId} = generate_config(),
{Ref, Pid} = emqx_rule_engine_jwt_sup:start_worker(ResourceId, Config), {ok, {Ref, Pid}} = emqx_rule_engine_jwt_sup:start_worker(ResourceId, Config),
receive receive
{Ref, token_created} -> {Ref, token_created} ->
ok ok
after after
1_000 -> 5_000 ->
ct:fail("timeout") ct:fail("timeout")
end, end,
MRef = monitor(process, Pid), MRef = monitor(process, Pid),