snapkitty
developer-tools
c++
SNAPKITTYWEST commited on
Commit
a6b5e84
·
verified ·
1 Parent(s): c762712

Add src/hk_api_listener.erl

Browse files
Files changed (1) hide show
  1. src/hk_api_listener.erl +49 -0
src/hk_api_listener.erl ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ %%%-------------------------------------------------------------------
2
+ %%% @doc Owns the Cowboy HTTP/WebSocket listener's lifecycle as a
3
+ %%% proper supervised process: starts it in `init/1', stops it in
4
+ %%% `terminate/2'. Ranch/Cowboy manage their own internal acceptor
5
+ %%% supervision once running; this wrapper is what makes "the API
6
+ %%% layer has an explicit process boundary and lifecycle" true
7
+ %%% rather than the listener being global, ambient state started
8
+ %%% once from `hyperkitty_app' and owned by nothing.
9
+ %%% @end
10
+ %%%-------------------------------------------------------------------
11
+ -module(hk_api_listener).
12
+ -behaviour(gen_server).
13
+
14
+ -export([start_link/0]).
15
+ -export([init/1, handle_call/3, handle_cast/2, terminate/2]).
16
+
17
+ -define(LISTENER, hk_http_listener).
18
+
19
+ start_link() ->
20
+ hk_sup_util:start_link_retry(
21
+ fun() -> gen_server:start_link({local, ?MODULE}, ?MODULE, [], []) end).
22
+
23
+ init([]) ->
24
+ %% A gen_server's `terminate/2' only runs on a supervised shutdown
25
+ %% (the ordinary `exit(Pid, shutdown)' every restart and
26
+ %% application stop uses) if the process traps exits -- otherwise
27
+ %% that exit signal kills it directly, skipping Erlang-level code
28
+ %% entirely. Without this, `terminate/2' below (which releases the
29
+ %% Ranch listener registered under `?LISTENER') would never run
30
+ %% during a restart, leaking the listener and making the next
31
+ %% `cowboy:start_clear/3' fail with `{already_started, _}'.
32
+ process_flag(trap_exit, true),
33
+ Port = application:get_env(hyperkitty, api_port, 8420),
34
+ Dispatch = hk_api_router:dispatch(),
35
+ {ok, _} = cowboy:start_clear(?LISTENER,
36
+ [{port, Port}],
37
+ #{env => #{dispatch => Dispatch}}
38
+ ),
39
+ {ok, #{port => Port}}.
40
+
41
+ handle_call(_Msg, _From, State) ->
42
+ {reply, ok, State}.
43
+
44
+ handle_cast(_Msg, State) ->
45
+ {noreply, State}.
46
+
47
+ terminate(_Reason, _State) ->
48
+ catch cowboy:stop_listener(?LISTENER),
49
+ ok.