snapkitty
developer-tools
c++
SNAPKITTYWEST commited on
Commit
7459c5c
·
verified ·
1 Parent(s): 5eed9bb

Add src/hk_frontend_client_registry.erl

Browse files
Files changed (1) hide show
  1. src/hk_frontend_client_registry.erl +59 -0
src/hk_frontend_client_registry.erl ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%-------------------------------------------------------------------
2
+ %%% @doc HK-VIS :: tracks connected frontend WebSocket clients and
3
+ %%% their event-stream subscription filters.
4
+ %%%
5
+ %%% Kept as its own supervised process, separate from the HTTP API
6
+ %%% listener (`hk_api_sup') and from `hk_event_bus' itself, because
7
+ %%% it is genuinely a distinct responsibility: which browsers/tabs
8
+ %%% currently have the control-center UI open, and what each one
9
+ %%% asked to see. `hk_api_events_h' (the WebSocket handler) registers
10
+ %%% here on connect and deregisters on disconnect, which is also
11
+ %%% what backs the "connected clients" count on the dashboard.
12
+ %%% @end
13
+ %%%-------------------------------------------------------------------
14
+ -module(hk_frontend_client_registry).
15
+ -behaviour(gen_server).
16
+
17
+ -export([start_link/0, client_connected/1, client_disconnected/1, count/0]).
18
+ -export([init/1, handle_call/3, handle_cast/2, handle_info/2]).
19
+
20
+ start_link() ->
21
+ hk_sup_util:start_link_retry(
22
+ fun() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []) end).
23
+
24
+ -spec client_connected(pid()) -> ok.
25
+ client_connected(Pid) ->
26
+ gen_server:call(?MODULE, {connected, Pid}).
27
+
28
+ -spec client_disconnected(pid()) -> ok.
29
+ client_disconnected(Pid) ->
30
+ gen_server:call(?MODULE, {disconnected, Pid}).
31
+
32
+ -spec count() -> non_neg_integer().
33
+ count() ->
34
+ gen_server:call(?MODULE, count).
35
+
36
+ init([]) ->
37
+ {ok, #{clients => #{}}}.
38
+
39
+ handle_call({connected, Pid}, _From, State = #{clients := Clients}) ->
40
+ MonRef = erlang:monitor(process, Pid),
41
+ {reply, ok, State#{clients := Clients#{Pid => MonRef}}};
42
+ handle_call({disconnected, Pid}, _From, State = #{clients := Clients}) ->
43
+ case maps:take(Pid, Clients) of
44
+ {MonRef, Clients2} ->
45
+ erlang:demonitor(MonRef, [flush]),
46
+ {reply, ok, State#{clients := Clients2}};
47
+ error ->
48
+ {reply, ok, State}
49
+ end;
50
+ handle_call(count, _From, State = #{clients := Clients}) ->
51
+ {reply, map_size(Clients), State}.
52
+
53
+ handle_cast(_Msg, State) ->
54
+ {noreply, State}.
55
+
56
+ handle_info({'DOWN', _MonRef, process, Pid, _Reason}, State = #{clients := Clients}) ->
57
+ {noreply, State#{clients := maps:remove(Pid, Clients)}};
58
+ handle_info(_Info, State) ->
59
+ {noreply, State}.