%%%------------------------------------------------------------------- %%% @author anlicheng %%% @copyright (C) 2025, %%% @doc %%% %%% @end %%% Created : 18. 4月 2025 16:42 %%%------------------------------------------------------------------- -module(efka_service_sup). -author("anlicheng"). -include("efka_tables.hrl"). -behaviour(supervisor). %% API -export([start_link/0]). -export([start_service/1, stop_service/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(list()) -> {ok, {supervisor:sup_flags(), [supervisor:child_spec()]}}. init([]) -> SupFlags = #{strategy => one_for_one, intensity => 1000, period => 3600}, {ok, {SupFlags, []}}. %%%=================================================================== %%% Internal functions %%%=================================================================== -spec start_service(ServiceId :: binary()) -> {ok, Pid :: pid()} | {error, Reason :: any()}. start_service(ServiceId) when is_binary(ServiceId) -> case supervisor:start_child(?MODULE, child_spec(ServiceId)) 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 stop_service(ServiceId :: binary()) -> ok. stop_service(ServiceId) when is_binary(ServiceId) -> ChildId = efka_service:get_name(ServiceId), supervisor:terminate_child(?MODULE, ChildId), supervisor:delete_child(?MODULE, ChildId). -spec child_spec(binary()) -> supervisor:child_spec(). child_spec(ServiceId) when is_binary(ServiceId) -> Name = efka_service:get_name(ServiceId), #{ id => Name, start => {efka_service, start_link, [Name, ServiceId]}, restart => permanent, shutdown => 5000, type => worker, modules => ['efka_service'] }.