Authentication with cowboy & stormpath

I’ve been meaning to try out an “authentication as a service” offering for a little while now. The first one I had come across was Auth0, which looks very slick, particularly if you use their “Lock” frontend.

Unfortunately, their documentation didn’t seem to have much information on what to do if you’re using a language they don’t provide an SDK for. I’m sure I could have deconstructed the node version, but I decided to try out Stormpath instead.

My weapon of choice at the moment is Cowboy, which is quite barebones; more of an http toolkit than a web framework (whether this is good or bad has been discussed, at length, elsewhere). To make things more interesting, I also wanted to support a mixture of secure and insecure content.

I chose to use an existing solution for session management, rather than re-inventing all the wheels at once; and to use Hackney (from an ever expanding roster of clients) for http requests.

Users need to be able to login:

handle_req(<<"POST">>, Req) ->
    {ok, Body, Req2} = cowboy_req:body_qs(Req),
    Email = proplists:get_value(<<"email">>, Body),
    Password = proplists:get_value(<<"password">>, Body),
    case stormpath:login(Email, Password) of
        {ok, UserInfo} ->
            {ok, Req3} = cowboy_session:set(<<"user">>, UserInfo, Req2),
            redirect_to(<<"/user/info">>, Req3);
        {error, Error} ->
            render_login_page([{error, Error}, {email, Email}], Req2)
    end;

which calls the Stormpath API:

login(Email, Password) ->
    Uri = get_stormpath_uri(<<"/loginAttempts">>),
    ReqBody = #{type => <<"basic">>, value => base64:encode(<<Email/binary, ":", Password/binary>>)},
    ReqJson = jiffy:encode(ReqBody),
    {ok, StatusCode, _, ClientRef} = stormpath_request(post, Uri, ReqJson),
    {ok, RespBody} = hackney:body(ClientRef),
    RespJson = jiffy:decode(RespBody, [return_maps]),
    case StatusCode of
        200 ->
            get_user_info(RespJson);
        400 ->
            get_error_message(RespJson);
        _ ->
            generic_error()
    end.

It’s then possible to check if a user is logged in:

execute(Req, Env) ->
    {Path, _} = cowboy_req:path(Req),
    check_path(Path, Req, Env).

check_path(<<"/user/", _/binary>>, Req, Env) ->
    case logged_in(Req) of
        false ->
            redirect_to(<<"/login">>, Req);
        true ->
            {ok, Req, Env}
    end;

check_path(_, Req, Env) ->
    {ok, Req, Env}.

logged_in(Req) ->
    {User, _} = cowboy_session:get(<<"user">>, Req),
    case User of
        undefined -> false;
        _ -> true
    end.

redirect_to(Location, Req) ->
    {ok, Req2} = cowboy_req:reply(302, [{<<"Location">>, Location}], Req),
    {halt, Req2}.

before processing a request; and bouncing them to the login page if they aren’t, when they should be.

You can find the source here. I think using one of these services could definitely save you some time at the start of a new project, as well as removing the risk of making common security blunders. On the other hand you take on their uptime as well as your own, and you are locked in to using their service should the pricing become unattractive (although Stormpath, at least, allows you to export your data). YMMV.

Automatic bidding

Moving on from the excitement of tic-tac-toe, I wanted to try my hand at something a little more complex. I decided to have a look at implementing ebay style “automatic bidding“, which turned out to be a lot more interesting than I expected.

It’s a good exercise because it’s realistic, the behaviour is well documented, and there are plenty of examples. I chose to implement it as a gen_server, but it would work in any language.

I started out by just implementing basic bidding with a starting price, if the bid is higher than the current bid then it is accepted:

-record(state, {starting_price, bids=[]}).
-record(bid, {bidder, amount, time}).

-type money() :: {integer(), integer()}.
-spec start_link([money()]) -> {ok, pid()}.
start_link(StartingPrice) ->
    gen_server:start_link(?MODULE, [StartingPrice], []).

init([StartingPrice]) ->
    {ok, #state{starting_price = StartingPrice}}.

handle_call({bid, _UserId, Bid}, _From, State) when Bid < State#state.starting_price ->
    {reply, bid_too_low, State};

handle_call({bid, UserId, BidAmount}, _From, State) when State#state.bids =:= [] ->
    Bid = #bid{bidder = UserId, amount = BidAmount, time = calendar:universal_time()},
    NewState = State#state{bids = [Bid | State#state.bids]},
    {reply, bid_accepted, NewState};

handle_call({bid, UserId, BidAmount}, _From, State) ->
    CurrentHighBid = hd(State#state.bids),
    case BidAmount > CurrentHighBid#bid.amount of
        true ->
            Bid = #bid{bidder = UserId, amount = BidAmount, time = calendar:universal_time()},
            NewState = State#state{bids = [Bid | State#state.bids]},
            {reply, bid_accepted, NewState};
        false ->
            {reply, bid_too_low, State}
    end;

handle_call(list_bids, _From, State) ->
    {reply, State#state.bids, State};

I decided to handle currency as a tuple of pounds & pennies, due to the way Erlang term comparisons work they are ordered correctly.

With this in place, I started moving towards automatic bidding (the commit history is available, but I’ll skip ahead). The algorithm is fairly simple, but as always the devil is in the details!

-type user_id() :: integer().
-record(bid, {bidder :: user_id(), amount :: eb_money:money(), time :: calendar:datetime(), automatic = false :: boolean()}).
-record(state, {starting_price :: eb_money:money(), bids = [] :: [#bid{}], high_bid :: #bid{}}).

-spec start_link(eb_money:money(), calendar:datetime()) -> {ok, pid()}.
start_link(StartingPrice, EndTime) ->
    gen_server:start_link(?MODULE, [StartingPrice, EndTime], []).

init([StartingPrice, EndTime]) ->
    lager:info("Bidding begins. Starting price: ~p", [StartingPrice]),
    TimeRemaining = calculate_time_remaining(EndTime),
    lager:info("Time remaining: ~p", [TimeRemaining]),
    _TimerRef = erlang:send_after(TimeRemaining, self(), bidding_ends),
    {ok, #state{starting_price = StartingPrice}}.

handle_call({bid, _UserId, MaxBid}, _From, State) when MaxBid < State#state.starting_price ->
    {reply, bid_too_low, State};

handle_call({bid, UserId, MaxBid}, _From, State) when State#state.bids =:= [] ->
    BidTime = calendar:universal_time(),
    Bid = #bid{bidder = UserId, amount = State#state.starting_price, time = BidTime},
    NewState = State#state{bids = [Bid | State#state.bids], high_bid = #bid{bidder = UserId, amount = MaxBid, time = BidTime}},
    {reply, bid_accepted, NewState};

handle_call({bid, UserId, MaxBid}, _From, State) ->
    HighBid = State#state.high_bid,
    case HighBid#bid.bidder =:= UserId of
        true ->
            update_bid_for_high_bidder(State, UserId, MaxBid);
        false ->
            handle_new_bid(State, MaxBid, UserId)
    end;

handle_call(list_bids, _From, State) ->
    {reply, lists:reverse(State#state.bids), State};

handle_info(bidding_ends, State) when State#state.bids =:= [] ->
    lager:info("Bidding ends", []),
    lager:info("No winner", []),
    {stop, normal, State};

handle_info(bidding_ends, State) ->
    lager:info("Bidding ends", []),
    WinningBid = hd(State#state.bids),
    lager:info("Winner: ~p, Bid: ~p", [WinningBid#bid.bidder, WinningBid#bid.amount]),
    {stop, normal, State};

update_bid_for_high_bidder(State, UserId, MaxBid) ->
    HighBid = State#state.high_bid,
    case MaxBid > HighBid#bid.amount of
        true ->
            NewState = State#state{high_bid = #bid{bidder = UserId, amount = MaxBid, time = calendar:universal_time()}},
            {reply, bid_accepted, NewState};
        false ->
            {reply, bid_too_low, State}
    end.

handle_new_bid(State, MaxBid, UserId) ->
    CurrentBid = hd(State#state.bids),
    case MaxBid =< CurrentBid#bid.amount of
        true ->
            {reply, bid_too_low, State};
        false ->
            handle_valid_new_bid(State, MaxBid, UserId)
    end.

handle_valid_new_bid(State, MaxBid, UserId) ->
    HighBid = State#state.high_bid,
    BidTime = calendar:universal_time(),
    case MaxBid =< HighBid#bid.amount of
        true ->
            bid_lower_than_or_equal_to_high_bid(State, MaxBid, UserId, BidTime, HighBid);
        false ->
            bid_higher_than_current_high_bid(State, MaxBid, UserId, BidTime, HighBid)
    end.

bid_lower_than_or_equal_to_high_bid(State, MaxBid, UserId, BidTime, HighBid) ->
    LosingBid = #bid{bidder=UserId, amount=MaxBid, time=BidTime},
    update_bid_list(State, LosingBid, HighBid).

bid_higher_than_current_high_bid(State, MaxBid, UserId, BidTime, HighBid) ->
    WinningBid = #bid{bidder=UserId, amount=MaxBid, time=BidTime},
    update_bid_list(State, HighBid, WinningBid).

update_bid_list(State, LosingBid, WinningBid) ->
    NewAmount = eb_money:add(LosingBid#bid.amount, eb_bid_increments:get(LosingBid#bid.amount)),
    NewHighBid = case NewAmount < WinningBid#bid.amount of
        true ->
            #bid{bidder = WinningBid#bid.bidder, amount = NewAmount, time = WinningBid#bid.time, automatic = true};
        false ->
            #bid{bidder = WinningBid#bid.bidder, amount = WinningBid#bid.amount, time = WinningBid#bid.time, automatic = false}
    end,
    NewState = State#state{bids = [NewHighBid | [LosingBid | State#state.bids]]},
    {reply, bid_accepted, NewState}.

calculate_time_remaining(EndTime) ->
    Now = calendar:universal_time(),
    (calendar:datetime_to_gregorian_seconds(EndTime) - calendar:datetime_to_gregorian_seconds(Now)) * 1000. %% milliseconds!

Once you get used to the convenience of features like tuples and pattern matching, it can be quite painful to go back to a language without them. The next step was reserve price auctions, and some day I might get round to implementing the lowering of them.

If you want to play along, the tests can be found here.

Handling a POST with Cowboy

It’s not immediately obvious how to handle different HTTP methods using Cowboy.
This SO answer, and one of the examples show the way:

handle(Req, State) ->
	{Method, Req2} = cowboy_req:method(Req),
	{ok, Req3} = process_req(Method, Req2),
	{ok, Req3, State}.

process_req(<<"POST">>, Req) ->
	{ok, Body, Req2} = cowboy_req:body_qs(Req),
	_Foo = proplists:get_value(<<"foo">>, Body),
	cowboy_req:reply(200, [
		{<<"content-type">>, <<"text/plain; charset=utf-8">>}
	], <<"ohai">>, Req);

process_req(_, _, Req) ->
	%% Method not allowed.
	cowboy_req:reply(405, Req).

Basic auth with Hackney

Hackney is an Erlang http client library. The homepage states that it supports basic authentication, but documentation of this feature is a little light.

The only evidence of it’s existence seems to be this test, but usage is pretty simple:

Url = <<"http://localhost:8000/basic-auth/username/password">>,
Options = [{basic_auth, {<<"username">>, <<"password">>}}],
{ok, StatusCode, _, _} = hackney:request(get, URL, [], <<>>, Options)

Using erlydtl with Cowboy

Erlydtl seems to be the most popular Erlang templating library, and using it with Cowboy is fairly simple; but doesn’t seem to be terribly well documented.

As always, I’m assuming you’re using erlang.mk and know how to set up a Cowboy project. First, you need to add erlydtl as a dependency in your Makefile:

PROJECT = cowboy_stormpath
DEPS = cowboy erlydtl
include erlang.mk

and as a dependency in your .app.src:

{application, cowboy_erlydtl, [
    {description, ""},
    {vsn, "0.1.0"},
    {id, "git"},
    {modules, []},
    {registered, []},
    {applications, [
        kernel,
        stdlib,
        cowboy,
        erlydtl
    ]},
    {mod, {cowboy_erlydtl_app, []}},
    {env, []}
]}.

Next, create a folder called “templates” in your project root, any .dtl files in here will be compiled when you run “make app”:

<html><body>Your favourite Smurf is {{ smurf_name }}.</body></html>

If you look in ebin/ you should see a file named smurfin_dtl.beam (or whatever), this is the compiled version of your template. Finally, you need a handler to render the template:

-module(smurf_handler).
-behaviour(cowboy_http_handler).

-export([init/3]).
-export([handle/2]).
-export([terminate/3]).

-record(state, {}).

init(_, Req, _Opts) ->
    {ok, Req, #state{}}.

handle(Req, State=#state{}) ->
    {ok, Body} = smurfin_dtl:render([{smurf_name, "Smurfette"}]),
    {ok, Req2} = cowboy_req:reply(200, [{<<"content-type">>, <<"text/html">>}], Body, Req),
    {ok, Req2, State}.

terminate(_Reason, _Req, _State) ->
    ok.

and add a route:

    Dispatch = cowboy_router:compile([
        {'_', [
            {"/smurfin", smurf_handler, []}
        ]}
    ]),

et voila, you’ve rendered your first template!

Using bunyan with express

I’ve pontificated previously about the benefits of combining bunyan with logstash, but if your app is using express it can be a little more complicated.

I wanted to add the user id & IP address of a request to all log output involved in that request. Bunyan makes it simple to create a child logger, and add the necessary properties; but due to the way express is architected (and how node works) the only way to access it is to pass it to the handler, and all it’s dependencies:

app.post("/foo", function(req, res) {
    var childLogger = logger.child({
            userId: req.userId, // taken from a header by middleware
            ip: req.ip
        }),
        barService = new BarService(childLogger),
        handler = new Handler(barService, childLogger);
    handler.handle(req, res);
});

Which makes it possible to search the logs for all information relating to a specific user, or IP address.

Using promises with node-pg

While it is possible to use node-pg with just raw callbacks, as soon as you want to use transactions the chances of getting it right dwindle rapidly.

Using a promise library helps remove some of the pain. I ended up with something like this (using Q):

var Q = require('q'),
    pg = require('pg'),
    Connection = require('./Connection');

module.exports = function(connString) {
    this.connect = function() {
        var deferred = Q.defer();

        pg.connect(connString, function(err, client, done) {
            if (err) {
                return deferred.reject(new Error(err));
            }

            deferred.resolve(new Connection(client, done));
        });

        return deferred.promise;
    };
};
var Q = require('q'),
    pg = require('pg');

module.exports = function(client, done) {
    this.begin = function() {
        return this.query('BEGIN;', []);
    };

    this.query = function(sql, args) {
        var deferred = Q.defer();

        client.query(sql, args, function(err, result) {
            if (err) {
                err.message = err.message + ' (Query: ' + sql + ', Args: ' + args + ')';
                return deferred.reject(err);
            }

            deferred.resolve(result.rows);
        });

        return deferred.promise;
    };

    this.rollback = function() {
        var deferred = Q.defer();

        client.query('ROLLBACK', function(err) {
            deferred.resolve();
            return done(err);
        });

        return deferred.promise;
    };

    this.commit = function() {
        var deferred = Q.defer();

        client.query('COMMIT', function(err) {
            if (err) {
                deferred.reject(err);
            } else {
                deferred.resolve();
            }
            return done(err);
        });

        return deferred.promise;
    };

    this.close = function() {
        done();
    };
}

Which you can use like this:

var db = new Db(connString);

return db.connect().then(function(conn) {
    return db.begin().then(function() {
        return conn.query('SELECT something FROM foo WHERE id = $1;', [id]).then(function(rows) {
            return conn.query('INSERT INTO ...', [...]);
        }).then(function() {
            return conn.commit();
        });
    }).fin(conn.close);
});

And remove at least some of the risk of failing to return the connection to the pool, or otherwise bungling your error handling.

Testing a gen_server with eunit

Of all the strange corners of Erlang, eunit can be one of the hardest to get your head around. Particularly if you’re used to one of the XUnit frameworks.

It is very powerful, especially once you get into generating tests; but it can also be very confusing, and sometimes the error messages are not that helpful.

I wanted to write some tests for a gen_server, using a new instance for each test, and it took me a couple of attempts to get what I wanted working. It’s very important to make sure your test can actually fail, either in advance or by mutating it, or to add some output (?debugMsg) that proves it ran.

-module(foo_server_tests).

-include_lib("eunit/include/eunit.hrl").

foo_server_test_() ->
    {foreach, fun setup/0, fun cleanup/1, [
        fun(Pid) -> fun() -> server_is_alive(Pid) end end,
        fun(Pid) -> fun() -> something_else(Pid) end end
    ]}.

setup() ->
    ?debugMsg("setup"),
    process_flag(trap_exit, true),
    {ok, Pid} = foo_server:start_link(),
    Pid.

server_is_alive(Pid) ->
    ?assertEqual(true, is_process_alive(Pid)).

something_else(Pid) ->
    ?assertEqual(bar, gen_server:call(Pid, foo)).

cleanup(Pid) ->
    ?debugMsg("cleanup"),
    exit(Pid, kill), %% brutal kill!
    ?assertEqual(false, is_process_alive(Pid)).

We need to trap exits in the setup fun, as the process is linked to the gen_server when it starts. The tricky bit is the nested funs in the generator, if you try to call the “test” directly:

foo_server_test_() ->
    {foreach, fun setup/0, fun cleanup/1, [
        fun(Pid) -> server_is_alive(Pid) end
    ]}.

you’ll get an error like this:

*** result from instantiator foo_server_tests:'-foo_server_test_/0-fun-2-'/1 is not a test ***

because eunit is trying to use the output of the called fun as a test. And if you return multiple tests from one block:

foo_server_test_() ->
    {foreach, fun setup/0, fun cleanup/1, [
        fun(Pid) -> [
             fun() -> server_is_alive(Pid) end,
             fun() -> something_else(Pid) end
        ] end
    ]}.

then the setup & teardown will only be called once for those tests (which may, or may not, be what you want).

UPDATE: actually this is a better approach:

-module(foo_server_tests).

-include_lib("eunit/include/eunit.hrl").

foo_server_test_() ->
    {foreach, fun setup/0, fun cleanup/1, [
        fun server_is_alive/1,
        fun something_else/1
    ]}.

server_is_alive(Pid) ->
    fun() ->
        ?assertEqual(true, is_process_alive(Pid))
    end.

something_else(Pid) ->
    fun() ->
        ?assertEqual(bar, gen_server:call(Pid, foo))
    end.

as the test names are included in the output:

$ SKIP_DEPS=true make eunit
 APP    foo.app.src
 GEN    test-dir
 GEN    eunit
======================== EUnit ========================
directory "ebin"
  module 'foo_server'
    module 'foo_server_tests'
      foo_server_tests: server_is_alive...ok
      foo_server_tests: something_else...[0.001 s] ok
      [done in 0.012 s]
    [done in 0.012 s]
  [done in 0.028 s]
=======================================================
  All 2 tests passed.

UPDATE 2: in case it wasn’t clear, this is effectively an “integration” test or black box test. The server is started, and messages are passed to it. It is also possible to “unit” test individual methods, if you don’t mind being more tightly coupled to the internal state of the server (white box). Both kinds of testing can provide value, pick whichever works for you for that scenario.

Building a Tic Tac Toe game with Cowboy & websockets (Part 4)

Saving game state

As discussed in Part 3, if the FSM crashes it will be re-started, but the game state will be lost. Which isn’t ideal.

The easiest way to solve this is to store the state record in an Ets or Dets table (the main difference being whether it is stored on disk or just in memory). I decided to use a Dets table, although if the VM were to crash (or be stopped deliberately) the game supervisor would not restart the child FSMs when it came back up (yet, there are some other problems to solve (e.g. restoring sessions) before that would be possible).

The first step was to add the game id, and current FSM state to the state record:

-record(state, {game_id, current_state=p1_turn, p1, p2, board=#{
    <<"1,1">> => '_', <<"1,2">> => '_', <<"1,3">> => '_',
    <<"2,1">> => '_', <<"2,2">> => '_', <<"2,3">> => '_',
    <<"3,1">> => '_', <<"3,2">> => '_', <<"3,3">> => '_'
}}).

And update the init function to open the table, and check if any state already exists for that game id:

init(Args) ->
    [{P1, P2, GameId}] = Args,
    process_flag(trap_exit, true),
    true = gproc:reg({n, l, GameId}),
    {ok, t3_game_state} = dets:open_file(t3_game_state, []),
    State = get_game_state(GameId, P1, P2),
    notify_players(State),
    {ok, State#state.current_state, State}.

get_game_state(GameId, P1, P2) ->
    case dets:lookup(t3_game_state, GameId) of
        [] ->
            save_game_state(#state{game_id = GameId, p1 = P1, p2 = P2});
        [{GameId, State}] ->
            State
    end.

We also trap exits; so the terminate function of the FSM is called, and we can close the table:

terminate(_Reason, _StateName, _State) ->
    dets:close(t3_game_state).

Finally, we save the game state after any successful FSM transition:

p1_turn({play, P1, Cell}, State = #state{p1 = P1}) ->
    NewState = play(Cell, State, 'O', p2_turn),
    Res = case t3_game:has_won(NewState#state.board, 'O') of
        true ->
            game_won(NewState#state.p1, NewState#state.p2, NewState#state.board),
            {stop, normal, NewState};
        false ->
            case t3_game:is_draw(NewState#state.board) of
                true ->
                    game_drawn(NewState#state.p1, NewState#state.p2, NewState#state.board),
                    {stop, normal, NewState};
                false ->
                    notify_players(NewState),
                    {next_state, p2_turn, NewState}
            end
    end,
    save_game_state(NewState),
    Res.

save_game_state(State = #state{game_id = GameId}) ->
    ok = dets:insert(t3_game_state, {GameId, State}),
    State.

Now, if the process crashes, it will be resurrected with the state rolled back to before the offending message. Of course in this system, it’s likely that any crash will be repeated if the same message arrives at the same state; but if your application is likely to suffer from transient errors (e.g. network errors calling another system) then you can just “let it crash”.

There are, of course, some trade-offs to this solution. A Dets table is only available to one Erlang node, if you wanted to scale out it would make more sense to use replicated Mnesia or an external data store such as Postgres, or Riak. And the shared Dets table could become a bottleneck when there were many games running.

A more pressing problem would be handling versioning of the game state, this naive code would crash if the record was changed and an old version was retrieved from the data store.

Building a Tic Tac Toe game with Cowboy & websockets (Part 3)

Game FSM

Following on from Part 1, and Part 2, we’re now going to take a look at the game itself.

My first attempt at modeling the game state was using an array of arrays:

-record(state, {p1, p2, board=[
    ['_', '_', '_'],
    ['_', '_', '_'],
    ['_', '_', '_']
]).

but the lack of mutation makes that awkward to work with. My second draft used a map, keyed by {row, column} tuples:

-record(state, {p1, p2, board=#{
    {1,1} => '_', {1,2} => '_', {1,3} => '_',
    {2,1} => '_', {2,2} => '_', {2,3} => '_',
    {3,1} => '_', {3,2} => '_', {3,3} => '_'
}}).

but that blew up when being serialized to send to the client, due to the tuple keys. I could have re-formatted it before sending, but it seemed like less hassle to use the one model. So the final version just used bitstring keys:

-record(state, {p1, p2, board=#{
    <<"1,1">> => '_', <<"1,2">> => '_', <<"1,3">> => '_',
    <<"2,1">> => '_', <<"2,2">> => '_', <<"2,3">> => '_',
    <<"3,1">> => '_', <<"3,2">> => '_', <<"3,3">> => '_'
}}).

When the game is started:

init(Args) ->
    io:format("New game started: ~p~n", [Args]),
    [{P1, P2, GameId}] = Args,
    true = gproc:reg({n, l, GameId}),
    State = #state{p1 = P1, p2 = P2},
    P1 ! {your_turn, State#state.board},
    P2 ! {wait, State#state.board},
    {ok, p1_turn, State}.

It registers itself with gproc using the game id, and notifies the players of whose turn it is. There are only two states p1_turn and p2_turn:

p1_turn({play, P1, Cell}, State = #state{p1 = P1}) ->
    NewState = play(Cell, State, 'O'),
    case t3_game:has_won(NewState#state.board, 'O') of
        true ->
            game_won(NewState#state.p1, NewState#state.p2, NewState#state.board),
            {stop, normal, NewState};
        false ->
            case t3_game:is_draw(NewState#state.board) of
                true ->
                    game_drawn(NewState#state.p1, NewState#state.p2, NewState#state.board),
                    {stop, normal, NewState};
                false ->
                    notify_players(NewState#state.p2, NewState#state.p1, NewState#state.board),
                    {next_state, p2_turn, NewState}
            end
    end.

play(Cell, State, Symbol) ->
    '_' = maps:get(Cell, State#state.board),
    State#state{board = maps:update(Cell, Symbol, State#state.board)}.

notify_players(Play, Wait, Board) ->
    Play ! {your_turn, Board},
    Wait ! {wait, Board}.

game_won(Win, Lose, Board) ->
    Win ! {you_win, Board},
    Lose ! {you_lose, Board}.

game_drawn(P1, P2, Board) ->
    P1 ! {draw, Board},
    P2 ! {draw, Board}.

First we check if it was a winning move, or a draw; in either case, the game is over and the process stops normally. As it was registered as a “transient” process, it will not be restarted. Otherwise it becomes the other player’s turn. In all cases, the updated board is sent to the client.

While this is a working implementation of multi-player game of tic-tac-toe, there are still a lot of rough edges. For example, if the FSM crashes it will be restarted but the game state will be lost. An improvement would be to store it (in an ETS table, or Mnesia, or even something like Riak) after successfully processing a message. It also relies on pids in a few places, that could change if a process is restarted; it would be better to look them up in gproc using a more stable identifier. It’s also possible that the websocket connection would be interrupted, and the client would need to resync with the server.