Compare commits

...

2 commits

Author SHA1 Message Date
918de5941b draft 2024-11-27 21:33:35 +00:00
9da6231702 ping and monitoring bus actor not service 2024-11-27 18:11:24 +00:00

View file

@ -12,6 +12,7 @@ init(R, _) ->
websocket_init(S) ->
Ref = st:lookup(wsbus),
erlang:send_after(?TTL_PING, self(), ping),
{ok, S#{wsbus => nil, ref_wsbus => Ref}}.
websocket_handle({text, <<Data/binary>>}, S) ->
@ -22,9 +23,9 @@ websocket_handle({text, <<Data/binary>>}, S) ->
{ok, S}
end;
websocket_handle({json, #{<<"ref">> := Ref}}, #{wsbus := nil} = S) ->
{[{text, jsx:encode(#{<<"ref">> => Ref, <<"wsio-code">> => 0})}], S};
{[{text, jsx:encode(#{<<"ref">> => Ref, <<"wsio-code">> => <<"0">>})}], S};
websocket_handle({json, Data}, #{wsbus := BUS} = S) ->
gen_server:cast(BUS, {call, Data, self()}),
gen_server:cast(BUS, {call, Data}),
{ok, S};
websocket_handle(_, State) ->
{ok, State}.
@ -42,10 +43,20 @@ websocket_info({send, List}, S) when is_list(List) ->
{List, S};
websocket_info({'DOWN', _, process, PID, _}, #{wsbus := PID} = S) ->
{ok, S#{wsbus => nil, ref_wsbus => st:lookup(wsbus)}};
websocket_info({_, {send, _} = Msg}, S) ->
websocket_info(Msg, S);
websocket_info({_, {Ref, {error, notfound}}}, #{ref_wsbus := Ref} = S) ->
{ok, S#{ref_wsbus => st:lookup(wsbus)}};
websocket_info({_, {Ref, {ok, PID}}}, #{ref_wsbus := Ref} = S) ->
erlang:monitor(process, PID),
{ok, maps:remove(ref_wsbus, S#{wsbus => PID})};
websocket_info({_, {Ref, {ok, Service}}}, #{wsbus := nil, ref_wsbus := Ref} = S) ->
try gen_server:call(Service, {new, self()}) of
{ok, PID} ->
erlang:monitor(process, PID),
{ok, maps:remove(ref_wsbus, S#{wsbus => PID})};
{error, ignored} ->
{ok, S#{ref_wsbus => st:lookup(wsbus)}}
catch
_:_ ->
{ok, S#{ref_wsbus => st:lookup(wsbus)}}
end;
websocket_info(_, S) ->
{ok, S}.