%%%------------------------------------------------------------------- %%% @author anlicheng %%% @copyright (C) 2025, %%% @doc %%% %%% @end %%% Created : 30. 4月 2025 09:22 %%%------------------------------------------------------------------- -module(efka_tcp_channel). -author("anlicheng"). -behaviour(gen_server). %% API -export([start_link/1]). -export([push_config/4, invoke/4]). %% gen_server callbacks -export([init/1, handle_call/3, handle_cast/2, handle_info/2, terminate/2, code_change/3]). -define(SERVER, ?MODULE). %% 消息类型 %% 服务注册 -define(PACKET_REGISTER, 16#00). %% 消息响应 -define(PACKET_RESPONSE, 16#01). %% 上传数据 -define(PACKET_METRIC_DATA, 16#02). %% 微服务事件上报 -define(PACKET_EVENT, 16#03). %% 微服务从efka获取自身的采集项 -define(PACKET_REQUEST_CONFIG, 16#04). %% efka下发给微服务配置 -define(PACKET_PUSH_CONFIG, 16#10). -define(PACKET_INVOKE, 16#11). -record(state, { packet_id = 1, socket :: gen_tcp:socket(), service_id :: undefined | binary(), service_pid :: undefined | pid(), is_registered = false :: boolean(), %% 请求响应的对应关系, #{packet_id => {ReceiverPid, Ref}} inflight = #{} }). %%%=================================================================== %%% API %%%=================================================================== -spec push_config(ChannelPid :: pid(), Ref :: reference(), ReceiverPid :: pid(), ConfigJson :: binary()) -> no_return(). push_config(ChannelPid, Ref, ReceiverPid, ConfigJson) when is_pid(ChannelPid), is_pid(ReceiverPid), is_binary(ConfigJson), is_reference(Ref) -> gen_server:cast(ChannelPid, {push_config, Ref, ReceiverPid, ConfigJson}). -spec invoke(ChannelPid :: pid(), Ref :: reference(), ReceiverPid :: pid(), Payload :: binary()) -> no_return(). invoke(ChannelPid, Ref, ReceiverPid, Payload) when is_pid(ChannelPid), is_pid(ReceiverPid), is_binary(Payload), is_reference(Ref) -> gen_server:cast(ChannelPid, {invoke, Ref, ReceiverPid, Payload}). %% @doc Spawns the server and registers the local name (unique) -spec(start_link(Socket :: gen_tcp:socket()) -> {ok, Pid :: pid()} | ignore | {error, Reason :: term()}). start_link(Socket) -> gen_server:start_link(?MODULE, [Socket], []). %%%=================================================================== %%% gen_server callbacks %%%=================================================================== %% @private %% @doc Initializes the server -spec(init(Args :: term()) -> {ok, State :: #state{}} | {ok, State :: #state{}, timeout() | hibernate} | {stop, Reason :: term()} | ignore). init([Socket]) -> ok = inet:setopts(Socket, [{active, true}]), lager:debug("[tcp_channel] get new socket: ~p", [Socket]), {ok, #state{socket = Socket}}. %% @private %% @doc Handling call messages -spec(handle_call(Request :: term(), From :: {pid(), Tag :: term()}, State :: #state{}) -> {reply, Reply :: term(), NewState :: #state{}} | {reply, Reply :: term(), NewState :: #state{}, timeout() | hibernate} | {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), Reply :: term(), NewState :: #state{}} | {stop, Reason :: term(), NewState :: #state{}}). handle_call(_Request, _From, State = #state{}) -> {reply, ok, State}. %% @private %% @doc Handling cast messages -spec(handle_cast(Request :: term(), State :: #state{}) -> {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), NewState :: #state{}}). %% 推送配置项目 handle_cast({push_config, Ref, ReceiverPid, ConfigJson}, State = #state{socket = Socket, packet_id = PacketId, inflight = Inflight}) -> ok = gen_tcp:send(Socket, <>), {noreply, State#state{packet_id = next_packet_id(PacketId), inflight = maps:put(PacketId, {ReceiverPid, Ref}, Inflight)}}; handle_cast({invoke, Ref, ReceiverPid, Payload}, State = #state{socket = Socket, packet_id = PacketId, inflight = Inflight}) -> ok = gen_tcp:send(Socket, <>), {noreply, State#state{packet_id = next_packet_id(PacketId), inflight = maps:put(PacketId, {ReceiverPid, Ref}, Inflight)}}; handle_cast(_Request, State = #state{}) -> {noreply, State}. %% @private %% @doc Handling all non call/cast messages -spec(handle_info(Info :: timeout() | term(), State :: #state{}) -> {noreply, NewState :: #state{}} | {noreply, NewState :: #state{}, timeout() | hibernate} | {stop, Reason :: term(), NewState :: #state{}}). %% 注册 handle_info({tcp, Socket, <>}, State = #state{socket = Socket}) -> case efka_service:get_pid(ServiceId) of undefined -> lager:warning("[efka_tcp_channel] service_id: ~p, not running", [ServiceId]), ok = gen_tcp:send(Socket, <>), {stop, normal, State}; Pid when is_pid(Pid) -> case efka_service:attach_channel(Pid, self()) of ok -> ok = gen_tcp:send(Socket, <>), {noreply, State#state{service_id = ServiceId, service_pid = Pid, is_registered = true}}; {error, Error} -> lager:warning("[efka_tcp_channel] service_id: ~p, attach_channel get error: ~p", [ServiceId, Error]), ok = gen_tcp:send(Socket, <>), {stop, normal, State} end end; %% 请求参数 handle_info({tcp, Socket, <>}, State = #state{socket = Socket, service_pid = ServicePid, is_registered = true}) -> {ok, ConfigJson} = efka_service:request_config(ServicePid), ok = gen_tcp:send(Socket, <>), {noreply, State}; %% 数据项 handle_info({tcp, Socket, <>}, State = #state{socket = Socket, service_pid = ServicePid, is_registered = true}) -> efka_service:metric_data(ServicePid, DeviceUUID, Data), {noreply, State}; %% Event事件 handle_info({tcp, Socket, <>}, State = #state{socket = Socket, service_pid = ServicePid, is_registered = true}) -> efka_service:send_event(ServicePid, EventType, Params), {noreply, State}; %% 收到端上的响应 handle_info({tcp, Socket, <>}, State = #state{socket = Socket, inflight = Inflight}) -> case maps:take(PacketId, Inflight) of error -> lager:warning("[tcp_channel] get unknown publish response message: ~p, packet_id: ~p", [Response, PacketId]), {noreply, State}; {{ReceiverPid, Ref}, NInflight} -> case is_pid(ReceiverPid) andalso is_process_alive(ReceiverPid) of true -> case Response of <<1:8, Result/binary>> -> ReceiverPid ! {channel_reply, Ref, {ok, Result}}; <<0:8, Error/binary>> -> ReceiverPid ! {channel_reply, Ref, {error, Error}} end; false -> lager:warning("[tcp_channel] get publish response message: ~p, packet_id: ~p, but receiver_pid is deaded", [Response, PacketId]) end, {noreply, State#state{inflight = NInflight}} end; handle_info(Info, State = #state{}) -> lager:debug("[tcp_channel] get info: ~p", [Info]), {noreply, State}. %% @private %% @doc This function is called by a gen_server when it is about to %% terminate. It should be the opposite of Module:init/1 and do any %% necessary cleaning up. When it returns, the gen_server terminates %% with Reason. The return value is ignored. -spec(terminate(Reason :: (normal | shutdown | {shutdown, term()} | term()), State :: #state{}) -> term()). terminate(_Reason, _State = #state{}) -> ok. %% @private %% @doc Convert process state when code is changed -spec(code_change(OldVsn :: term() | {down, term()}, State :: #state{}, Extra :: term()) -> {ok, NewState :: #state{}} | {error, Reason :: term()}). code_change(_OldVsn, State = #state{}, _Extra) -> {ok, State}. %%%=================================================================== %%% Internal functions %%%=================================================================== %% 采用32位编码 -spec next_packet_id(PacketId :: integer()) -> NextPacketId :: integer(). next_packet_id(PacketId) when PacketId >= 4294967295 -> 1; next_packet_id(PacketId) -> PacketId + 1.