gen_statem
A gen_server treats every request the same way, whatever happened before. A protocol with phases is different: a door that is locked accepts one event and refuses another, a checkout has a basket, a payment and a delivery, and the same message means different things in each. gen_statem is the behaviour for that: the state is not a term inside the loop but a first class part of the callback pattern, and the runtime answers a call that no clause of the current state matches. The GenServer lesson covers the plain server; this one adds the state.
States and events
The state machine below is a door. callback_mode/0 chooses how the module writes its clauses; handle_event_function puts the state in the arguments of one function, which keeps the whole machine in one place. Every clause matches an event and a state, and answers the next state:
door.erl
-module(door). -behaviour(gen_statem). -export([start_link/0, push/0, state/0, main/0]). -export([callback_mode/0, init/1, handle_event/4]). start_link() -> gen_statem:start_link({local, ?MODULE}, ?MODULE, locked, []). push() -> gen_statem:call(?MODULE, push). state() -> gen_statem:call(?MODULE, state). main() -> {ok, _Pid} = start_link(), io:format("start: ~p~n", [state()]), io:format("first push: ~p~n", [push()]), io:format("second push: ~p~n", [push()]), ok = gen_statem:stop(?MODULE). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, push, locked, Data) -> {next_state, unlocked, Data, [{reply, From, unlocked}]}; handle_event({call, From}, push, unlocked, Data) -> {next_state, locked, Data, [{reply, From, locked}]}; handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.
erlc door.erl
erl -noshell -eval 'door:main(), halt().'
start: locked first push: unlocked second push: locked
A clause answers {next_state, NextState, Data, Actions}, and the actions run before the next event is handled. {reply, From, Value} answers the call; gen_statem:start_link/4, and the module never keeps the state in a variable of its own: the runtime does, and passes it back.
A timeout in a state
A state may also end by itself. A door that unlocked should lock again after a few seconds even when nobody pushes it, and that is a timeout attached to the state rather than to a call. The action {state_timeout, Ms, Event} starts the clock when the transition happens, and the runtime cancels it when the state changes for another reason:
lazy_door.erl
-module(lazy_door). -behaviour(gen_statem). -export([start_link/0, push/0, state/0, main/0]). -export([callback_mode/0, init/1, handle_event/4]). start_link() -> gen_statem:start_link({local, lazy_door}, ?MODULE, locked, []). push() -> gen_statem:call(lazy_door, push). state() -> gen_statem:call(lazy_door, state). main() -> {ok, _Pid} = start_link(), ok = push(), io:format("just after the push: ~p~n", [state()]), timer:sleep(300), io:format("after the timeout: ~p~n", [state()]), ok = gen_statem:stop(lazy_door). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, push, locked, Data) -> {next_state, unlocked, Data, [{reply, From, ok}, {state_timeout, 200, close}]}; handle_event(state_timeout, close, unlocked, Data) -> {next_state, locked, Data}; handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.
erlc lazy_door.erl
erl -noshell -eval 'lazy_door:main(), halt().'
just after the push: unlocked after the timeout: locked
The timeout event arrives as an ordinary event, with the atom state_timeout as its type and close as its content, so the clause that handles it looks like every other clause. A gen_server would need a timer reference in its state and a handle_info clause that checks it is still the current one; here the runtime owns the timer, and a transition to another state throws it away.
The event nobody handles
The mistake this behaviour punishes at once is the event the current state does not handle. There is no fallback clause: an event with no matching clause raises function_clause in the callback, the machine dies, and the caller gets an exit instead of an answer:
wrong_event.erl
-module(wrong_event). -behaviour(gen_statem). -export([main/0]). -export([callback_mode/0, init/1, handle_event/4]). main() -> logger:set_primary_config(level, none), {ok, _Pid} = gen_statem:start_link({local, ?MODULE}, ?MODULE, locked, []), Result = try gen_statem:call(?MODULE, kick) of Reply -> {ok, Reply} catch exit:{Reason, _Stack} -> {exit, element(1, Reason)} end, io:format("the call: ~p~n", [Result]), io:format("the machine: ~p~n", [whereis(?MODULE)]). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, push, locked, Data) -> {next_state, unlocked, Data, [{reply, From, unlocked}]}; handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.
erlc wrong_event.erl
erl -noshell -eval 'wrong_event:main(), halt().'
the call: {exit,function_clause} the machine: undefined
Two answers follow from that. A caller must expect the exit, as this program does, and the machine must decide what an unknown event means instead of dying: a clause with a guard or a catch-all handle_event(_Type, Event, State, Data) that answers {keep_state_and_data, [{reply, From, {error, {bad_event, Event}}}]} keeps the door alive. Silence is the third answer, and it is the worst one: a crash in a supervised tree restarts the machine in its initial state, and a door that was unlocked becomes locked without a word.
Callback modes
callback_mode/0 has four answers. state_functions writes one function per state, each matching the events of that state, and reads well for a machine with many states and few events. handle_event_function, the one used here, puts the state in the arguments and keeps every clause together, which reads better when states and events are both many. handle_events and handle_events_dirty form one list of clauses over both {EventType, Content, State} triples, and the dirty variant runs in a dirty scheduler for a callback that does heavy work. A machine can also ask for state_enter calls, which run whenever the machine enters a state; the gen_event lesson is the other behaviour built on the same idea of an event and a handler.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
gen_statemadd to agen_server?Answer
The state as part of the callback pattern
Each clause names the state it belongs to, so the same event can mean different things in different states.
-
What does
callback_mode/0choose?Answer
How the callbacks are organised
It selects
state_functionsorhandle_event_functionand whether the machine getsstate_entercalls. -
What does a clause answer to move to another state?
Answer
{next_state, NextState, Data, Actions}The tuple names the next state, the data the loop keeps, and the actions that run before the next event.
-
What happens to a call whose event no clause of the current state handles?
Answer
The callback raises
function_clauseand the machine diesThere is no fallback clause, so the callback raises and the caller gets an exit.
-
What does
{state_timeout, 200, close}do?Answer
Sends
closeas an event after 200 ms in that stateThe runtime starts the clock on the transition and delivers the event if the state has not changed.
-
Which action answers a call?
Answer
{reply, From, Value}The reply names the caller that is waiting and the value it receives.
-
What does this module print?
-module(q1). -behaviour(gen_statem). -export([main/0]). -export([callback_mode/0, init/1, handle_event/4]). main() -> {ok, _Pid} = gen_statem:start_link({local, ?MODULE}, ?MODULE, locked, []), io:format("~p~n", [gen_statem:call(?MODULE, state)]). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.Answer
lockedThe initial state is the third argument of
start_link, and the clause replies with the state it matched. -
What does this module print?
-module(q2). -behaviour(gen_statem). -export([main/0]). -export([callback_mode/0, init/1, handle_event/4]). main() -> {ok, _Pid} = gen_statem:start_link({local, ?MODULE}, ?MODULE, open, []), ok = gen_statem:call(?MODULE, close), io:format("~p~n", [gen_statem:call(?MODULE, state)]). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, close, open, Data) -> {next_state, shut, Data, [{reply, From, ok}]}; handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.Answer
shutThe
closecall moved the machine fromopentoshut, and the next call reports the new state. -
What does this module print?
-module(q3). -behaviour(gen_statem). -export([main/0]). -export([callback_mode/0, init/1, handle_event/4]). main() -> logger:set_primary_config(level, none), {ok, _Pid} = gen_statem:start_link({local, ?MODULE}, ?MODULE, a, []), Result = try gen_statem:call(?MODULE, b) of Reply -> Reply catch exit:{Reason, _Stack} -> element(1, Reason) end, io:format("~p~n", [Result]). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, a, a, Data) -> {keep_state, Data, [{reply, From, a}]}.Answer
function_clauseNo clause matches the event
b, so the callback raisesfunction_clauseand the caller exits with it. -
What does this module print?
-module(q4). -behaviour(gen_statem). -export([main/0]). -export([callback_mode/0, init/1, handle_event/4]). main() -> {ok, _Pid} = gen_statem:start_link({local, ?MODULE}, ?MODULE, locked, []), io:format("~p~n", [gen_statem:call(?MODULE, open)]), timer:sleep(150), io:format("~p~n", [gen_statem:call(?MODULE, state)]). callback_mode() -> handle_event_function. init(State) -> {ok, State, no_data}. handle_event({call, From}, open, locked, Data) -> {next_state, ajar, Data, [{reply, From, ajar}, {state_timeout, 50, shut}]}; handle_event(state_timeout, shut, ajar, Data) -> {next_state, shut, Data}; handle_event({call, From}, state, State, Data) -> {keep_state, Data, [{reply, From, State}]}.Answer
ajar/shutThe reply names the state the call moved to, and the state timeout moves the machine to
shutbefore the second call.
The examples on this page were compiled and run with Erlang/OTP 27 (erts-15.2.7.14) on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Автор статьи: Arthur Isaev