ekfa/apps/efka/src/efka_server_sup.erl
2025-04-19 17:09:52 +08:00

81 lines
2.7 KiB
Erlang

%%%-------------------------------------------------------------------
%%% @author anlicheng
%%% @copyright (C) 2025, <COMPANY>
%%% @doc
%%%
%%% @end
%%% Created : 18. 4月 2025 16:42
%%%-------------------------------------------------------------------
-module(efka_server_sup).
-author("anlicheng").
-behaviour(supervisor).
%% API
-export([start_link/0]).
-export([register_server/1, delete_server/1]).
%% Supervisor callbacks
-export([init/1]).
-define(SERVER, ?MODULE).
%%%===================================================================
%%% API functions
%%%===================================================================
%% @doc Starts the supervisor
-spec(start_link() -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}).
start_link() ->
supervisor:start_link({local, ?SERVER}, ?MODULE, []).
%%%===================================================================
%%% Supervisor callbacks
%%%===================================================================
%% @private
%% @doc Whenever a supervisor is started using supervisor:start_link/[2,3],
%% this function is called by the new process to find out about
%% restart strategy, maximum restart frequency and child
%% specifications.
-spec(init(Args :: term()) ->
{ok, {SupFlags :: {RestartStrategy :: supervisor:strategy(),
MaxR :: non_neg_integer(), MaxT :: non_neg_integer()},
[ChildSpec :: supervisor:child_spec()]}}
| ignore | {error, Reason :: term()}).
init([]) ->
SupFlags = #{strategy => one_for_one, intensity => 1000, period => 3600},
{ok, {SupFlags, []}}.
%%%===================================================================
%%% Internal functions
%%%===================================================================
-spec register_server(ServerId :: binary()) -> {ok, Pid :: pid()} | {error, Reason :: any()}.
register_server(ServerId) when is_binary(ServerId) ->
case supervisor:start_child(?MODULE, child_spec(ServerId)) of
{ok, Pid} when is_pid(Pid) ->
{ok, Pid};
{error, {'already_started', Pid}} when is_pid(Pid) ->
{ok, Pid};
{error, Error} ->
{error, Error}
end.
-spec delete_server(ServerId :: binary()) -> ok.
delete_server(ServerId) when is_binary(ServerId) ->
ChildId = efka_server:get_name(ServerId),
ok = supervisor:terminate_child(?MODULE, ChildId),
supervisor:delete_child(?MODULE, ChildId).
child_spec(ServerId) when is_binary(ServerId) ->
Name = efka_server:get_name(ServerId),
#{
id => Name,
start => {efka_server, start_link, [Name, ServerId]},
restart => permanent,
shutdown => 2000,
type => worker,
modules => ['efka_server']
}.