fewd/src/fd_tetris.erl
Peter Harpending 4e48d6b40b [wip] websockets should have their own supervision tree
I also hate this bullshit of

- fd_client having such a stupid name
- websocket lib needs some love

basically I think this should be the approach:

renames:

- fd_clients    -> fd_http
- fd_client_man -> fd_http_client_man
- fd_client_sup -> fd_http_client_sup
- fd_client     -> fd_http_client
- fd_cache      -> fd_wfc_cache

new trees:

- tetris        -> new tree
- websockets    -> probably should fall into http supervision tree

Notes:
- fd_client_man is necessary because someone needs to own the listen socket
- rewrite fd_client as gen_server
2025-10-27 10:35:05 -07:00

89 lines
2.2 KiB
Erlang

% @doc tetris
%
% manages state for a single game of tetris
%
% sends parent process messages `{tetris, String}` where String is an encoded
% JSON blob meant to be sent to the page script in /priv/static/js/ts/tetris.ts
%
% Refs:
% 1. https://www.erlang.org/docs/24/man/gen_server
-module(fd_tetris).
-behavior(gen_server).
-export([
%% caller context
start_link/0,
%% process context
%% gen_server callbacks
init/1, handle_call/3, handle_cast/2, handle_info/2,
code_change/3, terminate/2
]).
-include("$zx_include/zx_logger.hrl").
-record(s, {parent :: pid()}).
-type state() :: #s{}.
%%-----------------------------------------------------------------------------
%% caller context below this line
%%-----------------------------------------------------------------------------
-spec ws_msg(Tetris, Message) -> ok
when Tetris :: pid(),
Message :: fd_ws:ws_msg().
ws_msg(Tetris, Msg) ->
gen_server:cast(Tetris, {ws_msg, Msg}).
-spec start_link() -> {ok, pid()} | {error, term()}.
start_link() ->
gen_server:start_link(?MODULE, [self()], []).
%%-----------------------------------------------------------------------------
%% process context below this line
%%-----------------------------------------------------------------------------
%% gen_server callbacks
-spec init(Args) -> {ok, State}
when Args :: [Parent],
Parent :: pid(),
State :: state().
init([Parent]) ->
tell("~tp:~tp starting fd_tetris with parent ~p", [?MODULE, self(), Parent]),
self() ! {poop, 0},
InitState = #s{parent = Parent},
{ok, InitState}.
handle_call(Unexpected, From, State) ->
tell("~tp:~tp unexpected call from ~tp: ~tp", [?MODULE, self(), From, Unexpected]),
{noreply, State}.
handle_cast(Unexpected, State) ->
tell("~tp:~tp unexpected cast: ~tp", [?MODULE, self(), Unexpected]),
{noreply, State}.
handle_info({poop, N}, State = #s{parent = Parent}) ->
Parent ! {tetris, io_lib:format("poop~p", [N])},
erlang:send_after(1_000, self(), {poop, N+1}),
{noreply, State};
handle_info(Unexpected, State) ->
tell("~tp:~tp unexpected info: ~tp", [?MODULE, self(), Unexpected]),
{noreply, State}.
code_change(_, State, _) ->
{ok, State}.
terminate(_, _) ->
ok.