ranch_server_proxy.erl 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. %% Copyright (c) 2019-2021, Jan Uhlig <juhlig@hnc-agency.org>
  2. %%
  3. %% Permission to use, copy, modify, and/or distribute this software for any
  4. %% purpose with or without fee is hereby granted, provided that the above
  5. %% copyright notice and this permission notice appear in all copies.
  6. %%
  7. %% THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  8. %% WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  9. %% MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  10. %% ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  11. %% WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  12. %% ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  13. %% OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. -module(ranch_server_proxy).
  15. -behavior(gen_server).
  16. -export([start_link/0]).
  17. -export([init/1]).
  18. -export([handle_call/3]).
  19. -export([handle_cast/2]).
  20. -export([handle_info/2]).
  21. -export([code_change/3]).
  22. -spec start_link() -> {ok, pid()} | {error, term()}.
  23. start_link() ->
  24. gen_server:start_link(?MODULE, [], []).
  25. -spec init([]) -> {ok, pid()} | {stop, term()}.
  26. init([]) ->
  27. case wait_ranch_server(50) of
  28. {ok, Monitor} ->
  29. {ok, Monitor, hibernate};
  30. {error, Reason} ->
  31. {stop, Reason}
  32. end.
  33. -spec handle_call(_, _, reference()) -> {noreply, reference(), hibernate}.
  34. handle_call(_, _, Monitor) ->
  35. {noreply, Monitor, hibernate}.
  36. -spec handle_cast(_, reference()) -> {noreply, reference(), hibernate}.
  37. handle_cast(_, Monitor) ->
  38. {noreply, Monitor, hibernate}.
  39. -spec handle_info(term(), reference()) -> {noreply, reference(), hibernate} | {stop, term(), reference()}.
  40. handle_info({'DOWN', Monitor, process, _, Reason}, Monitor) ->
  41. {stop, Reason, Monitor};
  42. handle_info(_, Monitor) ->
  43. {noreply, Monitor, hibernate}.
  44. -spec code_change(term() | {down, term()}, reference(), term()) -> {ok, reference()}.
  45. code_change(_, Monitor, _) ->
  46. {ok, Monitor}.
  47. wait_ranch_server(N) ->
  48. case whereis(ranch_server) of
  49. undefined when N > 0 ->
  50. receive after 100 -> ok end,
  51. wait_ranch_server(N - 1);
  52. undefined ->
  53. {error, noproc};
  54. Pid ->
  55. Monitor = monitor(process, Pid),
  56. {ok, Monitor}
  57. end.