gen_statem(3)

๐Ÿ“ฆ
version 29.0.6 ยท 3 versions
, in ubuntu stonking

โœจ gen_statem โœจ

so bestie, this is the manual page for gen_statem, from the Erlang module definitions ๐Ÿ’– buckle up, it's a big one.


๐Ÿ’ซ NAME ๐Ÿ’ซ

gen_statem โ€” Generic state machine behavior. that's it, that's the whole name section ๐ŸŽ€


๐ŸŒธ DESCRIPTION ๐ŸŒธ

okay so gen_statem gives you a generic state machine behaviour. since Erlang/OTP 20.0 it replaced its predecessor gen_fsm, and honestly? it's the one you should be using for any new code. the old gen_fsm behaviour is still sitting there in OTP "as is" so that old code using it doesn't break โ€” it's giving legacy, not a glow-up.

A generic state machine server process (that's your gen_statem) implemented with this module comes with a standard set of interface functions, plus functionality for tracing and error reporting. it also slots perfectly into an OTP supervision tree ๐ŸŒณ for more info, go look at the gen_statem section in OTP Design Principles.

NOTE: if you're new to gen_statem and you want a chill overview of concepts and how it operates, please read the section gen_statem Behaviour in the User's Guide, OTP Design Principles. it's the vibe. โœจ this reference manual, on the other hand, is obsessed with being correct and complete, which ngl might make it hard to see the forest for all the trees ๐ŸŒฒ๐Ÿ˜ญ

๐Ÿฆ‹ Features ๐Ÿฆ‹

gen_statem has got all the features gen_fsm had, and it adds some genuinely iconic ones:

  • Co-located state code
  • Arbitrary term state
  • Event postponing
  • Self-generated events
  • State time-out
  • Multiple generic named time-outs
  • Absolute time-out time
  • Automatic state enter calls
  • Reply from other state than the request, traceable with sys
  • Multiple replies, traceable with sys
  • Changing the callback module

Two callback modes are supported, and you have to pick one:

  • state_functions โ€” for finite-state machines (gen_fsm like ๐Ÿซถ). this one requires the state to be an atom and uses that state as the name of the current callback function, arity 3.
  • handle_event_function โ€” this one lets the state be any term ๐Ÿ”ฅ and it uses handle_event/4 as the callback function for all states.

the callback modes for gen_statem are different from the ones for gen_fsm, but it's still fairly easy to rewrite from gen_fsm to gen_statem. see the rewrite guide at the start of the gen_fsm documentation ๐Ÿ“š

๐Ÿ’… Callback module ๐Ÿ’…

a gen_statem assumes all the specific parts live in a callback module that exports a predefined set of functions. the relationship between the behavior functions and the callback functions is, like, exactly this:

gen_statem module            Callback module
-----------------            ---------------
gen_statem:start
gen_statem:start_monitor
gen_statem:start_link -----> Module:init/1

Server start or code change
                          -----> Module:callback_mode/0
                          selects callback mode

gen_statem:stop
Supervisor exit
Callback failure      -----> Module:terminate/3

gen_statem:call
gen_statem:cast
gen_statem:send_request
erlang:send
erlang:'!'            -----> Module:StateName/3
                       or -----> Module:handle_event/4
                       depending on callback mode

Release upgrade/downgrade
(code change)
                          -----> Module:code_change/4

๐ŸŒˆ State callback ๐ŸŒˆ

the state callback for a specific state in a gen_statem is the callback function that gets called for all events in that state. which one it is depends on the callback mode that the callback module defines with the callback function Module:callback_mode/0. ๐Ÿ‘‘

when the callback mode is state_functions, the state must be an atom and is used as the state callback name; see Module:StateName/3. this co-locates all the code for a specific state in one function, because the gen_statem engine branches depending on the state name. ๐ŸŒŸ careful though: the fact that the callback function Module:terminate/3 exists makes the state name terminate unusable in this mode ๐Ÿ˜ญ not me making that mistake.

when the callback mode is handle_event_function, the state can be any term and the state callback name is Module:handle_event/4. this makes it easy to branch depending on state or event however you want. but bestie, be careful about which events you handle in which states so that you don't accidentally postpone an event forever and create an infinite busy loop ๐Ÿ’€

โœจ Event types โœจ

events come in different types, so the callback functions can know where an event came from when they handle it. External events are call, cast, and info. Internal events are timeout and internal. periodt.

๐ŸŽ€ Event handling ๐ŸŽ€

when gen_statem receives a process message, it gets transformed into an event, and the state callback is called with the event as two arguments: type and content. when the state callback has processed the event, it returns to gen_statem, which does a state transition. if this state transition is to a different state โ€” that is, NextState =/= State โ€” it's a state change. ๐Ÿ’…

๐Ÿซถ Transition actions ๐Ÿซถ

the state callback may return transition actions for gen_statem to execute during the state transition, for example to set a time-out or reply to a call. yes, you get to boss the engine around ๐Ÿ˜Œ

๐Ÿ’œ Reply to a call ๐Ÿ’œ

see gen_statem:call/2,3 about how to reply to a call. a reply can be sent from any state callback, not just the one that got the request event. that's the freedom we love โœจ

๐Ÿ“ Event postponing ๐Ÿ“

one of the possible transition actions is to postpone the current event. then it will not be handled in the current state. the gen_statem engine keeps a queue of events divided into postponed events and events still to process (not presented yet). after a state change, the queue restarts with the postponed events. ๐Ÿ”

the gen_statem event queue model is sufficient to emulate the normal process message queue with selective receive. postponing an event corresponds to not matching it in a receive statement, and changing states corresponds to entering a new receive statement. iykyk ๐Ÿงš

๐Ÿฆ‹ Event insertion ๐Ÿฆ‹

the state callback can insert events using the transition action next_event, and such an event is inserted in the event queue as the next event to call the state callback with. that is, as if it's the oldest incoming event. a dedicated event_type/0 internal can be used for such events, making it possible to safely distinguish them from external events. ๐Ÿ’–

inserting an event replaces the trick of calling your own state handling functions, which you often would have had to resort to in, for example, gen_fsm to force processing an inserted event before others. no more hacky self-calls, we're thriving now ๐ŸŒธ

NOTE: if you postpone an event and (against good practice ๐Ÿ˜ฌ) directly call a different state callback, the postponed event is not retried, since there was no state change. instead of directly calling a state callback, do a state change. this makes the gen_statem engine retry postponed events. inserting an event in a state change also triggers the new state callback to be called with that event before receiving any external events. so good โญ

๐Ÿ‘‘ State enter calls ๐Ÿ‘‘

the gen_statem engine can automatically make a special call to the state callback whenever a new state is entered; see state_enter/0. this is for writing code common to all state entries. another way to do it is to explicitly insert an event at the state transition, and/or to use a dedicated state transition function โ€” but that is something you will have to remember at every state transition to the state(s) that need it ๐Ÿ˜ฎโ€๐Ÿ’จ

for the details of a state transition, see type transition_option/0.

๐Ÿ˜ด Hibernation ๐Ÿ˜ด

the gen_statem process can go into hibernation; see proc_lib:hibernate/3. it's done when a state callback or Module:init/1 specifies hibernate in the returned Actions list. this feature can be useful to reclaim process heap memory while the server is expected to be idle for a long time. but use it with care, bestie โ€” hibernation can be too costly to use after every event; see erlang:hibernate/3. ๐Ÿ’€

there is also a server start option {hibernate_after, Timeout} for start/3,4, start_link/3,4, start_monitor/3,4, or enter_loop/4,5,6, that may be used to automatically hibernate the server. naptime on autopilot โœจ

๐Ÿ˜ญ Callback failure ๐Ÿ˜ญ

if a callback function fails or returns a bad value, the gen_statem terminates. however, an exception of class throw is not regarded as an error but as a valid return, from all callback functions. so throwing is a whole vibe, just don't abuse it ๐ŸŽ€

๐ŸŒˆ System messages and the sys module ๐ŸŒˆ

a gen_statem handles system messages as described in sys. the sys module can be used for debugging a gen_statem. replies sent through transition actions get logged, but not replies sent through reply/1,2. ๐Ÿ“

๐Ÿงš Trapping exit ๐Ÿงš

a gen_statem process, like all gen_* behaviours, does not trap exit signals automatically; this must be explicitly initiated in the callback module (by calling process_flag(trap_exit, true), preferably from init/1). you have to opt in, okay?

๐ŸŒธ Server termination ๐ŸŒธ

if the gen_statem process terminates, e.g. as a result of a callback function returning {stop, Reason}, an exit signal with this Reason is sent to linked processes and ports. see Processes in the Reference Manual for details regarding error handling using exit signals. ๐Ÿ’…

NOTE: for some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. blocking signaling can, for example, cause call time-outs in gen_statem to be significantly delayed. ๐Ÿ˜ฑ don't say i didn't warn you.

๐ŸŽ€ Bad argument ๐ŸŽ€

unless otherwise stated, all functions in this module fail if the specified gen_statem does not exist or if bad arguments are specified. no cap.


โญ Example โญ

the following example shows a simple pushbutton model for a toggling pushbutton implemented with callback mode state_functions. you can push the button and it replies if it went on or off, and you can ask for a count of how many times it has been pushed to switch on. adorable, right? ๐Ÿซถ

Pushbutton State Diagram

---
title: Pushbutton State Diagram
---
stateDiagram-v2
    [*]  --> off
    off  --> on  : push\n* Increment count\n* Reply 'on'
    on   --> off : push\n* Reply 'off'

not shown in the state diagram:

  • the API function push() generates an event push of type call.
  • the API function get_count() generates an event get_count of type call that is handled in all states by replying with the current count value.
  • unknown events are ignored and discarded.
  • there is boilerplate code for start, stop, terminate, code change, init, to set the callback mode to state_functions, etc...

Pushbutton Code

the following is the complete callback module file pushbutton.erl:

-module(pushbutton).
-behaviour(gen_statem).

-export([start/0,push/0,get_count/0,stop/0]).
-export([terminate/3,code_change/4,init/1,callback_mode/0]).
-export([on/3,off/3]).

name() -> pushbutton_statem. % The registered server name

and bestie, that's literally only the beginning โ€” there's so much more of this file coming ๐ŸŒˆ don't go anywhere โœจ

so the module keeps going โ€” here's the rest of it, the API bits and the mandatory callbacks that you literally cannot skip: ๐Ÿ’–

%% API.  This example uses a registered name name()
%% and does not link to the caller.
start() ->
    gen_statem:start({local,name()}, ?MODULE, [], []).
push() ->
    gen_statem:call(name(), push).
get_count() ->
    gen_statem:call(name(), get_count).
stop() ->
    gen_statem:stop(name()).

%% Mandatory callback functions
terminate(_Reason, _State, _Data) ->
    void.
code_change(_Vsn, State, Data, _Extra) ->
    {ok,State,Data}.
init([]) ->
    %% Set the initial state + data.  Data is used only as a counter.
    State = off, Data = 0,
    {ok,State,Data}.
callback_mode() -> state_functions.

%%% state callback(s)

off({call,From}, push, Data) ->
    %% Go to 'on', increment count and reply
    %% that the resulting status is 'on'
    {next_state,on,Data+1,[{reply,From,on}]};
off(EventType, EventContent, Data) ->
    handle_event(EventType, EventContent, Data).

on({call,From}, push, Data) ->
    %% Go to 'off' and reply that the resulting status is 'off'
    {next_state,off,Data,[{reply,From,off}]};
on(EventType, EventContent, Data) ->
    handle_event(EventType, EventContent, Data).

%% Handle events common to all states
handle_event({call,From}, get_count, Data) ->
    %% Reply with the current count
    {keep_state,Data,[{reply,From,Data}]};
handle_event(_, _, Data) ->
    %% Ignore all other events
    {keep_state,Data}.

and here's what it looks like when you actually run it, a whole little shell session, iconic behavior fr: ๐ŸŽ€

1> pushbutton:start().
{ok,<0.36.0>}
2> pushbutton:get_count().
0
3> pushbutton:push().
on
4> pushbutton:get_count().
1
5> pushbutton:push().
off
6> pushbutton:get_count().
1
7> pushbutton:stop().
ok
8> pushbutton:push().
** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
     in function  gen:do_for_proc/2 (gen.erl, line 261)
     in call from gen_statem:call/3 (gen_statem.erl, line 386)

to compare styles โ€” like a little side-by-side slay-off โ€” here comes that exact same example but with callback mode handle_event_function. or rather, this is the code you swap in after function init/1 of the pushbutton.erl example file up there: ๐Ÿ”ฅ

callback_mode() -> handle_event_function.

%%% state callback(s)

handle_event({call,From}, push, off, Data) ->
    %% Go to 'on', increment count and reply
    %% that the resulting status is 'on'
    {next_state,on,Data+1,[{reply,From,on}]};
handle_event({call,From}, push, on, Data) ->
    %% Go to 'off' and reply that the resulting status is 'off'
    {next_state,off,Data,[{reply,From,off}]};
%%
%% Event handling common to all states
handle_event({call,From}, get_count, State, Data) ->
    %% Reply with the current count
    {next_state,State,Data,[{reply,From,Data}]};
handle_event(_, _, State, Data) ->
    %% Ignore all other events
    {next_state,State,Data}.

๐Ÿ“ Note

๐Ÿ’… API changes

  • This behavior appeared in Erlang/OTP 19.0 as experimental. yes bestie, it was babygirl once ๐Ÿ™ˆ
  • In OTP 19.1 a backwards incompatible change of the return tuple from Module:init/1 was made, the mandatory callback function Module:callback_mode/0 was introduced, and enter_loop/4 was added.
  • In OTP 19.2 state enter calls were added.
  • In OTP 19.3 state time-outs were added.
  • In OTP 20.0 generic time-outs were added and gen_statem was stated to be no longer experimental and preferred over gen_fsm.
  • In OTP 22.1 time-out content update and explicit time-out cancel were added.
  • In OTP 22.3 the possibility to change the callback module with actions change_callback_module, push_callback_module and pop_callback_module, was added.
  • In OTP 23.0 start_monitor/3,4 were added, as well as functions for asynchronous calls: send_request/2, wait_response/1,2, and check_response/2.
  • In OTP 24.0 receive_response/1,2 were added.
  • In OTP 25.0 Module:format_status/1 was added to replace Module:format_status/2, as well as functions for collections of asynchronous calls: send_request/4, wait_response/3, receive_response/3, check_response/3, reqids_new/0, reqids_size/1, reqids_add/3, reqids_to_list/1.
  • In OTP 26.0 the possibility to return {error, Reason} from Module:init/1 was added.
  • In OTP 27.0 Module:format_status/2 was deprecated.

๐ŸŒˆ See Also

gen_event, gen_fsm, gen_server, proc_lib, supervisor, sys.


๐Ÿฆ‹ DATA TYPES ๐Ÿฆ‹

action()

action() ::
          postpone |
          {postpone, Postpone :: postpone()} |
          {next_event,
           EventType :: event_type(),
           EventContent :: event_content()} |
          {change_callback_module, NewModule :: module()} |
          {push_callback_module, NewModule :: module()} |
          pop_callback_module |
          enter_action().

These are your actions for a state transition โ€” or for when you're starting the server up. ๐Ÿซถ

You can invoke these transition actions by returning them from the state callback when it gets called with an event, from Module:init/1, or by passing them to enter_loop/4,5,6. They are not allowed from state enter calls, so don't even try it. ๐Ÿ˜ญ

Actions are executed in the containing list order. (First one in the list goes first, no cutting the line. ๐Ÿ’…)

Actions that set transition options override any previous one of the same type, so the last one in the containing list wins. For example, the last postpone/0 overrides any previous postpone/0 in the list.

{postpone, Value}

Sets the transition_option() postpone/0 for this state transition. Heads up though: this action is ignored when returned from Module:init/1 or passed to enter_loop/4,5,6, since there's literally no event to postpone in those cases. ๐Ÿซ 

postpone is equivalent to {postpone, true}.

{next_event, EventType, EventContent}

This action doesn't set any transition_option(). Instead it stores the specified EventType and EventContent for insertion after all actions have been executed. โœจ

The stored events get inserted into the queue as the next to process, coming before any already queued events. The order of these stored events is preserved, so the first next_event in the containing list becomes the first to process.

An event of type internal should be used when you want to reliably distinguish an event inserted this way from any external event. iykyk. ๐Ÿงš

{change_callback_module, NewModule}

Changes the callback module to NewModule, which will be used when calling all subsequent state callbacks. Since OTP 22.3.

The gen_statem engine will find out the callback mode of NewModule by calling NewModule:callback_mode/0 before the next state callback.

Changing the callback module does not affect the state transition in any way, it only changes which module handles the events. Be aware that all relevant callback functions in NewModule such as the state callback, NewModule:code_change/4, NewModule:format_status/1 and NewModule:terminate/3 must be able to handle the state and data from the old module.

{push_callback_module, NewModule}

Pushes the current callback module to the top of an internal stack of callback modules, and changes the callback module to NewModule. Otherwise like {change_callback_module, NewModule} above. Since OTP 22.3.

pop_callback_module

Pops the top module from the internal stack of callback modules and changes the callback module to be the popped module. If the stack is empty the server fails. ๐Ÿ˜ญ Otherwise like {change_callback_module, NewModule} above. Since OTP 22.3.


callback_mode()

callback_mode() :: state_functions | handle_event_function.

One function per state, or one common event handler. pick your fighter ๐Ÿ’–

The callback mode is selected with the return value from Module:callback_mode/0:

  • state_functions โ€” The state must be of type state_name/0 and one callback function per state, that is, Module:StateName/3, is used.
  • handle_event_function โ€” The state can be any term and the callback function Module:handle_event/4 is used for all states.

The function Module:callback_mode/0 is called when starting the gen_statem, after code change and after changing the callback module with any of the actions change_callback_module, push_callback_module, or pop_callback_module. The result is cached for subsequent calls to state callbacks.


callback_mode_result()

callback_mode_result() ::
          callback_mode() | [callback_mode() | state_enter()].

Return value from Module:callback_mode/0.

This is the return type from Module:callback_mode/0 which selects callback mode and whether to do state enter calls, or not. that's it, that's the vibe check ๐ŸŒธ


data()

data() :: term().

Generic state data for the server.

A term in which the state machine implementation is to store any server data it needs. The difference between this and the state/0 itself is that a change in this data does not cause postponed events to be retried. Hence, if a change in this data would change the set of events that are handled, then that data item should be part of the state/0 instead. lowkey important, don't mix them up ๐Ÿ’…


enter_action()

enter_action() ::
          hibernate |
          {hibernate, Hibernate :: hibernate()} |
          timeout_action() |
          reply_action().

Actions for any callback: hibernate, time-outs or replies.

These transition actions are allowed when a action/0 is allowed, and also from a state enter call, and can be invoked by returning them from the state callback, from Module:init/1 or by passing them to enter_loop/4,5,6.

Actions are executed in the containing list order.

Actions that set transition options override any previous one of the same type, so the last one in the containing list wins. For example, the last event_timeout/0 overrides any previous event_timeout/0 in the list. ๐ŸŽ€

  • {hibernate, Value} โ€” Sets the transition_option/0 hibernate/0 for this state transition. hibernate is literally equivalent to {hibernate, true}. ๐Ÿ’ค

enter_loop_opt()

enter_loop_opt() ::
          {hibernate_after, HibernateAfterTimeout :: timeout()} |
          {debug, Dbgs :: [sys:debug_option()]}.

These are the server start options for enter_loop/4,5,6, start/3,4, start_link/3,4, and start_monitor/3,4. Peep start_link/4 for the deets. ๐Ÿ‘€


event_content()

event_content() :: term().

The event payload from wherever the event came from, delivered to the state callback. Check event_type โ€” it explains where each event type originates, and that's also where the event's content comes from. ๐Ÿ“ฆ


event_handler_result(StateType) & event_handler_result(StateType, DataType)

event_handler_result(StateType) ::
          event_handler_result(StateType, term()).

event_handler_result(StateType, DataType) ::
          {next_state, NextState :: StateType, NewData :: DataType} |
          {next_state,
           NextState :: StateType,
           NewData :: DataType,
           Actions :: [action()] | action()} |
          state_callback_result(action(), DataType).

This is what a state callback returns after it handles an event. StateType is state_name/0 if callback mode is state_functions, or state/0 if callback mode is handle_event_function. The {next_state, NextState, NewData [, Actions]} tuple makes gen_statem do a state transition to NextState (which can be the same as the current state), sets NewData as the current server data/0, and runs all Actions. If NextState =/= CurrentState, that transition is a state change. ๐Ÿ’ƒ


event_timeout()

event_timeout() :: Time :: timeout() | integer().

How long to wait for an event. Starts a timer set by the timeout_action/0 Time, or {timeout, Time, EventContent [, Options]}. When the timer expires, an event of event_type/0 timeout gets generated. Look at erlang:start_timer/4 for how Time and Options are interpreted. Heads up: future erlang:start_timer/4 Options might not necessarily be supported. ๐Ÿ˜ฌ

Any event that arrives cancels this time-out. Note that a retried or inserted event counts as arrived. So does a state time-out zero event, if it was generated before this time-out is requested.

If Time is infinity, no timer is started, because it would never expire anyway.

If Time is relative and 0, no timer is actually started; instead the time-out event is enqueued to make sure it gets processed before any not-yet-received external event, but after already queued events.

Note that it's not possible nor needed to cancel this time-out, because it's cancelled automatically by any other event. That means whenever a callback is invoked that may want to cancel this time-out, the timer is already cancelled or expired.

The timer EventContent can be updated with the {timeout, update, NewEventContent} action without affecting the time of expiry. โณ


event_type()

event_type() ::
          external_event_type() | timeout_event_type() | internal.

All the event types: external, time-out, or internal. internal events can only be generated by the state machine itself through the transition action next_event. ๐ŸŽญ


external_event_type()

external_event_type() :: {call, From :: from()} | cast | info.

An event from a call, cast, or regular process message; "info". Type {call, From} comes from the API functions call/2,3 or send_request/2. The event contains From, which is who to reply to via a reply_action/0 or reply/2,3 call. Type cast comes from the API function cast/2. Type info comes from regular process messages sent to the gen_statem process. ๐Ÿ“จ


format_status()

format_status() ::
          #{state => state(),
            data => data(),
            reason => term(),
            queue => [{event_type(), event_content()}],
            postponed => [{event_type(), event_content()}],
            timeouts => [{timeout_event_type(), event_content()}],
            log => [sys:system_event()]}.

A map that describes the server's status. The keys are:

  • state โ€” the current state.
  • data โ€” the state data.
  • reason โ€” the reason that caused the process to terminate.
  • queue โ€” the event queue.
  • postponed โ€” the queue of postponed events.
  • timeouts โ€” the active time-outs.
  • log โ€” the sys log of the server.

New associations may be added to the status map without prior notice. ๐Ÿ—บ๏ธ


from()

from() :: {To :: pid(), Tag :: reply_tag()}.

The reply destination for a call event. This is the destination to use when replying through, for example, the action {reply, From, Reply} to a process that called the gen_statem server using call/2,3. ๐Ÿ“ฌ


generic_timeout()

generic_timeout() :: Time :: timeout() | integer().

How long to wait for a named time-out event. Starts a timer set by timeout_action/0 {{timeout, Name}, Time, EventContent [, Options]}. When the timer expires, an event of event_type/0 {timeout, Name} gets generated. Look at erlang:start_timer/4 for how Time and Options are interpreted. Heads up: future erlang:start_timer/4 Options might not necessarily be supported.

If Time is infinity, no timer is started, because it would never expire anyway.

If Time is relative and 0, no timer is actually started; instead the time-out event is enqueued to make sure it gets processed before any not-yet-received external event.

Setting a timer with the same Name while it is running will restart it with the new time-out value. So you can cancel a specific time-out by setting it to infinity. It can also be cancelled more explicitly with the {{timeout, Name}, cancel} action.

The timer EventContent can be updated with the {{timeout, Name}, update, NewEventContent} action without affecting the time of expiry. โฒ๏ธ


hibernate()

hibernate() :: boolean().

Hibernate the server process. If true, hibernates the gen_statem by calling proc_lib:hibernate/3 before going into receive to wait for a new external event.

There's also a server start option {hibernate_after, Timeout} for automatic hibernation.

NOTE: If there are enqueued events to process when hibernation is requested, this is optimized by not hibernating but instead calling erlang:garbage_collect/0 to simulate, in a more efficient way, that the gen_statem entered hibernation and immediately got awakened by an enqueued event. ๐Ÿป๐Ÿ’ค


init_result(StateType) & init_result(StateType, DataType)

init_result(StateType) :: init_result(StateType, term()).

init_result(StateType, DataType) ::
          {ok, State :: StateType, Data :: DataType} |
          {ok,
           State :: StateType,
           Data :: DataType,
           Actions :: [action()] | action()} |
          ignore |
          {stop, Reason :: term()} |
          {error, Reason :: term()}.

The return value from Module:init/1. For a successful initialization, State is the initial state/0, and Data the initial server data/0 of the gen_statem.

The Actions are executed when entering the first state just like for a state callback, except that the action postpone is forced to false since there is no event to postpone.

For an unsuccessful initialization, {stop, Reason}, {error, Reason}, or ignore should be used; see start_link/3,4.

{error, Reason} has been allowed since OTP 26.0.

The {ok, ...} tuples have existed since OTP 19.1; before that they were not ok tagged. That was before gen_statem replaced gen_fsm in OTP 20.0. ๐Ÿ“œ


postpone()

postpone() :: boolean().

Postpone an event to handle it later. If true, postpones the current event. After a state change (NextState =/= State), it is retried. โณ


reply_action()

reply_action() :: {reply, From :: from(), Reply :: term()}.

Reply to a call/2,3. This transition action can be invoked by returning it from the state callback, from Module:init/1 or by passing it to enter_loop/4,5,6.

It does not set any transition_option() but instead replies to a caller waiting for a reply in call/3. From must be the term from argument {call, From} in a call to a state callback.

Note that using this action from Module:init/1 or enter_loop/4,5,6 would be weird on the border of witchcraft since there has been no earlier call to a state callback in this server. ๐Ÿง™โ€โ™€๏ธ


-opaque reply_tag()

A handle that associates a reply to the corresponding request. ๐Ÿ”–


-opaque request_id()

An opaque request identifier. See send_request/2 for details. ๐Ÿ†”


-opaque request_id_collection()

An opaque collection of request identifiers (request_id/0). Each request identifier can be associated with a label chosen by the user. For more info see reqids_new/0. ๐Ÿ—‚๏ธ


response_timeout()

response_timeout() :: timeout() | {abs, integer()}.

Response time-out for an asynchronous call. Used to set a time limit on how long to wait for a response using either receive_response/2, receive_response/3, wait_response/2, or wait_response/3. The time unit used is millisecond.

Currently valid values:

  • 0..4294967295 โ€” time-out relative to current time in milliseconds.
  • infinity โ€” infinite time-out. That is, the operation will never time out.
  • {abs, Timeout} โ€” an absolute Erlang monotonic time time-out in milliseconds. That is, the operation will time out when erlang:monotonic_time(millisecond) returns a value larger than or equal to Timeout. Timeout is not allowed to identify a time further into the future than 4294967295 milliseconds. Specifying the time-out using an absolute value is especially handy when you have a deadline for responses corresponding to a complete collection of requests (request_id_collection/0), since you do not have to recalculate the relative time until the deadline over and over again. โฐ

server_name()

server_name() ::
          {local, atom()} |
          {global, GlobalName :: term()} |
          {via, RegMod :: module(), Name :: term()}.

Server name specification: local, global, or via registered. {local, atom()} or {global, GlobalName :: term()} or {via, RegMod :: module(), Name :: term()}. ๐Ÿท๏ธ

๐ŸŽ€ server_name()

The name spec you hand over when you're starting a gen_statem server. Peep start_link/3 and server_ref/0 down below for the deets.

๐Ÿซถ server_ref()

server_ref() ::
          pid() |
          (LocalName :: atom()) |
          {Name :: atom(), Node :: atom()} |
          {global, GlobalName :: term()} |
          {via, RegMod :: module(), ViaName :: term()}.

Server spec, bestie: either a pid/0 or a registered server_name/0. You use this in call/2,3 to say which server you're talking to. It can be:

  • pid() | LocalName โ€” the gen_statem is registered locally. cute and simple.
  • {Name, Node} โ€” the gen_statem is registered locally over on another node. long-distance relationship fr.
  • {global, GlobalName} โ€” the gen_statem is globally registered in global. iconic.
  • {via, RegMod, ViaName} โ€” the gen_statem is registered in some alternative process registry. The registry callback module RegMod has to export register_name/2, unregister_name/1, whereis_name/1, and send/2, and those all gotta behave like their twins in global. So {via, global, GlobalName} is literally the exact same thing as {global, GlobalName}. no cap.

๐Ÿ’ซ start_mon_ret()

start_mon_ret() ::
          {ok, {pid(), reference()}} | ignore | {error, term()}.

What the start_monitor/3,4 functions hand back to you. It's like start_link/4, except a successful return wraps up the process ID and the monitor reference together in a {ok, {pid(), reference()}} tuple. two for one, slay.

โœจ start_opt()

start_opt() ::
          {timeout, Time :: timeout()} |
          {spawn_opt, [proc_lib:start_spawn_option()]} |
          enter_loop_opt().

Server start options for the start/3,4, start_link/3,4, and start_monitor/3,4 functions. Go look at start_link/4 for the full tea.

๐ŸŒˆ start_ret()

start_ret() :: {ok, pid()} | ignore | {error, term()}.

Return value from the start/3,4 and start_link/3,4 functions. Again: start_link/4 has the details, go read it.

๐Ÿฆ‹ state()

state() :: state_name() | term().

A state name or a state term, depending. If the callback mode is handle_event_function, the state can be literally any term. And the second you change state (NextState =/= State), every single postponed event gets retried. every. single. one.

Comparing two states for strict equality is assumed to be a fast operation, because for every state transition the gen_statem engine has to figure out if it's a state change or not.

NOTE: the smaller the state term, the faster the comparison (in general). Now, if the same state term gets returned for a state transition โ€” or you use a return action with no NextState field โ€” the equality check is always fast, because the engine can see that straight from the term handle. But if a newly constructed state term gets returned, then both the old and the new state terms have to be traversed until it finds an inequality, or until both terms have been fully walked through. So technically you can use big state terms that happen to be fast to compare โ€” but it's soooo easy to accidentally mess that up. Small state terms are the safe choice, periodt. ๐Ÿ‘‘

๐Ÿ’… state_callback_result(ActionType, DataType)

state_callback_result(ActionType, DataType) ::
          {keep_state, NewData :: DataType} |
          {keep_state,
           NewData :: DataType,
           Actions :: [ActionType] | ActionType} |
          keep_state_and_data |
          {keep_state_and_data, Actions :: [ActionType] | ActionType} |
          {repeat_state, NewData :: DataType} |
          {repeat_state,
           NewData :: DataType,
           Actions :: [ActionType] | ActionType} |
          repeat_state_and_data |
          {repeat_state_and_data, Actions :: [ActionType] | ActionType}
|
          stop |
          {stop, Reason :: term()} |
          {stop, Reason :: term(), NewData :: DataType} |
          {stop_and_reply,
           Reason :: term(),
           Replies :: [reply_action()] | reply_action()} |
          {stop_and_reply,
           Reason :: term(),
           Replies :: [reply_action()] | reply_action(),
           NewData :: DataType}.

The return value from any state callback, no matter what. ActionType is enter_action/0 if the state callback was called with a state enter call, and action/0 if it was called with an event.

  • {keep_state, NewData [, Actions]} โ€” same thing as {next_state, CurrentState, NewData [, Actions]}.
  • keep_state_and_data | {keep_state_and_data, Actions} โ€” same thing as {keep_state, CurrentData [, Actions]}.
  • {repeat_state, NewData [, Actions]} โ€” if the gen_statem runs with state enter calls, the state enter call gets repeated, see type transition_option/0. Other than that, {repeat_state, NewData [, Actions]} is the same as {keep_state, NewData [, Actions]}.
  • repeat_state_and_data | {repeat_state_and_data, Actions} โ€” same as {repeat_state, CurrentData [, Actions]}.
  • {stop, Reason [, NewData]} โ€” terminates the gen_statem by calling Module:terminate/3 with Reason and NewData, if NewData is specified. An exit signal with this reason gets sent to linked processes and ports. ๐Ÿ’€
  • stop โ€” same as {stop, normal}.
  • {stop_and_reply, Reason, Replies [, NewData]} โ€” sends all the Replies first, then terminates the gen_statem just like {stop, Reason [, NewData]} does.
  • All of these terms are tuples or atoms, and they will stay tuples or atoms in all future versions of gen_statem. promise. ๐Ÿคž

๐Ÿงš state_enter()

state_enter() :: state_enter.

Callback mode modifier for state enter calls โ€” it's just the atom state_enter. Both callback modes can use state enter calls, and you turn them on by adding this state_enter flag to the callback mode return value from Module:callback_mode/0.

If Module:callback_mode/0 returns a list containing state_enter, then the gen_statem engine will โ€” on every state change, meaning NextState =/= CurrentState โ€” call the state callback with arguments (enter, OldState, Data) or (enter, OldState, State, Data), depending on which callback mode you're in.

This looks like an event but it's actually a call that happens after the previous state callback returned, and before any event gets delivered to the new state callback. See Module:StateName/3 and Module:handle_event/4. A state enter call can also be repeated without any state change at all โ€” just return a repeat_state or repeat_state_and_data action from the state callback and boom, it re-runs.

If Module:callback_mode/0 does not return a list containing state_enter, then no state enter calls ever happen. simple as that.

If Module:code_change/4 should transform the state, that counts as a state rename, not a state change โ€” so it will not trigger a state enter call. don't get got by that one. ๐Ÿ™ˆ

Note that a state enter call will be done right before entering the initial state, which can be seen as a state change from no state to the initial state. In that case OldState =:= State, which cannot happen for a later state change โ€” but it does happen when repeating the state enter call.

๐ŸŒธ state_enter_result(State)

state_enter_result(State) :: state_enter_result(State, term()).

๐ŸŒธ state_enter_result(State, DataType)

state_enter_result(State, DataType) ::
          {next_state, State, NewData :: DataType} |
          {next_state, State,
           NewData :: DataType,
           Actions :: [enter_action()] | enter_action()} |
          state_callback_result(enter_action(), DataType).

The return value from a state callback after a state enter call. Here State is the current state, and it cannot be changed since the state callback was called with a state enter call.

  • {next_state, State, NewData [, Actions]} โ€” the gen_statem does a state transition to State, which has to be equal to the current state, sets NewData, and executes all the Actions.

๐Ÿ‘‘ state_name()

state_name() :: atom().

A state name, in callback mode state_functions. If the callback mode is state_functions, the state must be an atom. After a state change (NextState =/= State), all postponed events get retried. Also heads up: you can't use terminate as a state, because it would collide with the optional callback function Module:terminate/3. name clash city. ๐Ÿ˜ญ

โฐ state_timeout()

state_timeout() :: Time :: timeout() | integer().

How long to wait while you're sitting in the current state. Starts a timer that's set by timeout_action/0, or by {state_timeout, Time, EventContent [, Options]}.

When the timer expires, an event of event_type/0 state_timeout gets generated. See erlang:start_timer/4 for how Time and Options are interpreted. Just so you know โ€” future erlang:start_timer/4 Options will not necessarily be supported. ๐Ÿ™ƒ

A state change cancels this timer, if it's running. Like, if the timeout_action/0 that starts this timer is part of a list of action/0s for a state change, NextState =/= CurrentState, then the timer runs in NextState.

If the state machine stays in that new state โ€” which is now the current state โ€” the timer just runs until it expires, which creates the time-out event. But if the state machine changes states away from the now-current state, the timer gets cancelled. And during that state change from the now-current state, a brand new state time-out may be started for the next NextState.

If the timeout_action/0 that starts this timer is part of a list of action/0s for a state transition that is not a state change, then the timer runs in the current state.

If Time is infinity, no timer gets started at all โ€” it would never expire anyway, so like... why. ๐Ÿ’…

If Time is relative and 0, no timer is actually started. Instead the time-out event gets enqueued, which makes sure it gets processed before any not-yet-received external event. sneaky but intentional.

Setting this timer while it's already running restarts it with the new time-out value. Which means you can cancel the time-out by just setting it to infinity โ€” clever. It can also be cancelled more explicitly with {state_timeout, cancel}.

And the timer EventContent can be updated with the {state_timeout, update, NewEventContent} action without messing with the time of expiry at all.


timeout_action()

timeout_action() ::
          (Time :: event_timeout()) |
          {timeout,
           Time :: event_timeout(),
           EventContent :: event_content()} |
          {timeout,
           Time :: event_timeout(),
           EventContent :: event_content(),
           Options :: timeout_option() | [timeout_option()]} |
          {{timeout, Name :: term()},
           Time :: generic_timeout(),
           EventContent :: event_content()} |
          {{timeout, Name :: term()},
           Time :: generic_timeout(),
           EventContent :: event_content(),
           Options :: timeout_option() | [timeout_option()]} |
          {state_timeout,
           Time :: state_timeout(),
           EventContent :: event_content()} |
          {state_timeout,
           Time :: state_timeout(),
           EventContent :: event_content(),
           Options :: timeout_option() | [timeout_option()]} |
          timeout_cancel_action() |
          timeout_update_action().

okay bestie, this is event time-out, generic time-outs or state time-out ๐Ÿ’… all in one gorgeous little union.

These transition actions can be invoked by returning them from the state callback, from Module:init/1 or by passing them to enter_loop/4,5,6. โœจ

These time-out actions sets time-out transition options. ๐ŸŽ€

  • Time โ€” short for {timeout, Time, Time}, that is, the time-out message is the time-out time. This form exists to allow the state callback return value {next_state, NextState, NewData, Time} like in gen_fsm. ๐Ÿซถ
  • {timeout, Time, EventContent [, Options]} โ€” sets the transition_option/0 event_timeout/0 to Time with EventContent, and time-out options Options. โญ
  • {{timeout,Name}, Time, EventContent [, Options]} โ€” sets the transition_option/0 generic_timeout/0 to Time for time-out Name with EventContent, and time-out options Options. Since OTP 20.0. ๐Ÿ”ฅ
  • {state_timeout, Time, EventContent [, Options]} โ€” sets the transition_option/0 state_timeout/0 to Time with EventContent, and time-out options Options. Since OTP 19.3. ๐Ÿฆ‹

timeout_cancel_action()

timeout_cancel_action() ::
          {timeout, cancel} |
          {{timeout, Name :: term()}, cancel} |
          {state_timeout, cancel}.

the clearer way to cancel a time-out than the original setting it to 'infinity' ๐Ÿ˜Œ no cap.

it has always been possible to cancel a time-out using timeout_action/0 with Time = infinity, since setting a new time-out time overrides a running timer, and since setting the time to infinity is optimized to not setting a timer (that never will expire). Using this action shows the intention more clearly. periodt ๐Ÿ’…


timeout_event_type()

timeout_event_type() ::
          timeout | {timeout, Name :: term()} | state_timeout.

event time-out, generic time-out, or state time-out. it's giving three flavours of timer โœจ

the time-out event types that the state machine can generate for itself with the corresponding timeout_action/0s:

  • Event time-out โ€” action {timeout, Time, ...} โ€” event type timeout โฐ
  • Generic time-out โ€” action {{timeout, Name}, Time, ...} โ€” event type {timeout, Name} ๐Ÿท๏ธ
  • State time-out โ€” action {state_timeout, Time, ...} โ€” event type state_timeout ๐ŸŒธ

in short; the action to set a time-out with EventType is {EventType, Time, ...}. that's the whole vibe ๐Ÿซถ


timeout_option()

timeout_option() :: {abs, Abs :: boolean()}.

time-out timer start option, to select absolute time of expiry ๐ŸŽฏ

if Abs is true an absolute timer is started, and if it is false a relative, which is the default. See erlang:start_timer/4 for details. iykyk โญ


timeout_update_action()

timeout_update_action() ::
          {timeout, update, EventContent :: event_content()} |
          {{timeout, Name :: term()},
           update,
           EventContent :: event_content()} |
          {state_timeout, update, EventContent :: event_content()}.

update the EventContent without affecting the time of expiry ๐Ÿ‘‘ glow-up for the content only, the clock stays exactly where it is.

sets a new EventContent for a running time-out timer. See timeout_action() for how to start a time-out. ๐Ÿ’–

heads up bestie โ€” if no time-out of this type is active, instead inserts the time-out event just like when starting a time-out with relative Time = 0. This is a time-out autostart with immediate expiry, so there will be noise for example if a generic time-out name was misspelled. ๐Ÿ’€ so watch your spelling fr fr.

transition_option()

transition_option() ::
          postpone() |
          hibernate() |
          event_timeout() |
          generic_timeout() |
          state_timeout().

state transition options set by actions โœจ these determine what happens during the state transition. the state transition takes place when the state callback has processed an event and returns. here are the sequence of steps for a state transition ๐Ÿ‘‡

  1. All returned actions are processed in order of appearance. In this step all replies generated by any reply_action/0 are sent. Other actions set transition_option/0s that come into play in subsequent steps. ๐Ÿ“ฌ
  2. If state enter calls are used, it is either the initial state or one of the callback results repeat_state or repeat_state_and_data is used the gen_statem engine calls the current state callback with arguments (enter, State, Data) or (enter, State, State, Data) (depending on callback mode) and when it returns starts again from the top of this sequence.

If state enter calls are used, and the state changes, the gen_statem engine calls the new state callback with arguments (enter, OldState, Data) or (enter, OldState, State, Data) (depending on callback mode) and when it returns starts again from the top of this sequence. ๐Ÿšชโœจ

  1. If postpone/0 is true, the current event is postponed. ๐Ÿ™ˆ
  2. If this is a state change, the queue of incoming events is reset to start with the oldest postponed. ๐Ÿ”„
  3. All events stored with action/0 next_event are inserted to be processed before previously queued events. ๐Ÿ“ฅ
  4. Time-out timers event_timeout/0, generic_timeout/0 and state_timeout/0 are handled. Time-outs with zero time are guaranteed to be delivered to the state machine before any external not yet received event so if there is such a time-out requested, the corresponding time-out zero event is enqueued as the newest received event; that is after already queued events such as inserted and postponed events. โฑ๏ธ

Any event cancels an event_timeout/0 so a zero time event time-out is only generated if the event queue is empty.

A state change cancels a state_timeout/0 and any new transition option of this type belongs to the new state, that is; a state_timeout/0 applies to the state the state machine enters. ๐Ÿ‘‘

  1. If there are enqueued events the state callback for the possibly new state is called with the oldest enqueued event, and we start again from the top of this sequence. ๐Ÿ”
  2. Otherwise the gen_statem goes into receive or hibernation (if hibernate/0 is true) to wait for the next message. In hibernation the next non-system event awakens the gen_statem, or rather the next incoming message awakens the gen_statem, but if it is a system event it goes right back into hibernation. When a new message arrives the state callback is called with the corresponding event, and we start again from the top of this sequence. ๐Ÿ˜ด๐Ÿ’ค
NOTE: The behaviour of a time-out zero (a time-out with time 0) differs subtly from Erlang's receive ... after 0 ... end. The latter receives one message if there is one, while using the timeout_action/0 {timeout, 0} does not receive any external event. gen_server's time-out works like Erlang's receive ... after 0 ... end, in contrast to gen_statem. ๐Ÿซ  so like, not the same thing at all, do not conflate them.

๐ŸŒˆ FUNCTIONS ๐ŸŒˆ

call(ServerRef, Request, Timeout)

call(ServerRef :: server_ref(),
            Request :: term(),
            Timeout ::
                timeout() |
                {clean_timeout, T :: timeout()} |
                {dirty_timeout, T :: timeout()}) ->
               Reply :: term().

call a server: send request and wait for response ๐Ÿ“žโœจ

makes a synchronous call to the gen_statem ServerRef by sending a request and waiting until the response arrives. the classic "hey bestie answer me" move ๐Ÿ’…

the gen_statem calls the state callback with event_type/0 {call, From} and event content Request. ๐Ÿซถ

the server's reply is sent from a state callback, by returning a transition action {reply, From, Reply}, calling reply(Replies) with such a reply action in the Replies list, or calling reply(From, Reply). ๐Ÿ’Œ

Timeout is an integer > 0, which specifies how many milliseconds to wait for a reply, or the atom infinity to wait indefinitely, which is the default. If no reply is received within the specified time, the function call fails. โฐ๐Ÿ˜ญ

previous issue with late replies that could occur when having network issues or using dirty_timeout is now prevented by use of process aliases. {clean_timeout, T} and {dirty_timeout, T} therefore no longer serves any purpose and will work the same as Timeout while all of them also being equally efficient. ๐ŸŽ€ iconic behaviour fix tbh.

Oh and bestie, be warnedโ€” this call can also just flat-out fail, like if the gen_statem dies before or during this function call. ๐Ÿ’€

When this call fails it exits the calling process. The exit term is on the form {Reason, Location} where Location = {gen_statem, call, ArgList}. See gen_server:call/3 that has a description of relevant values for the Reason in the exit term.


โœจ cast(ServerRef :: server_ref(), Msg :: term()) -> ok. โœจ

cast(ServerRef :: server_ref(), Msg :: term()) -> ok.

Okay so this one's the chill one, no cap. It casts an event to a server. ๐ŸŽ€

Sends an asynchronous cast event to the gen_statem ServerRef and returns ok immediately, ignoring if the destination node or gen_statem does not exist. Like, it literally does not care. ๐Ÿ’…

The gen_statem calls the state callback with event type cast and event content Msg.


โœจ check_response/2 โœจ

check_response(Msg, ReqId) -> Result
                        when
                            Msg :: term(),
                            ReqId :: request_id(),
                            Response ::
                                {reply, Reply :: term()} |
                                {error,
                                 {Reason :: term(), server_ref()}},
                            Result :: Response | no_reply.

Check if a received message is a request response. ๐Ÿฆ‹

Checks if Msg is a response corresponding to the request identifier ReqId. The request must have been made by send_request/2 and by the same process calling this function. (Yes bestie, the same process, we don't do impostors here. ๐Ÿ™ˆ)

If Msg is a reply to the handle ReqId the result of the request is returned in Reply. Otherwise this function returns no_reply and no cleanup is done, and thus the function shall be invoked repeatedly until the response is returned.

See call/3 about how the request is handled and the Reply is sent by the gen_statem server.

If the gen_statem server process has died when this function is called, that is; Msg reports the server's death, this function returns an error return with the exit Reason. ๐Ÿ˜ญ


โœจ check_response/3 โœจ

check_response(Msg, ReqIdCollection, Delete) -> Result
                        when
                            Msg :: term(),
                            ReqIdCollection :: request_id_collection(),
                            Delete :: boolean(),
                            Response ::
                                {reply, Reply :: term()} |
                                {error,
                                 {Reason :: term(), server_ref()}},
                            Result ::
                                {Response,
                                 Label :: term(),
                                 NewReqIdCollection ::
                                     request_id_collection()} |
                                no_request | no_reply.

Check if a received message is a request response, but make it a collection. โœจ

Check if Msg is a response corresponding to a request identifier stored in ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/2 or send_request/4, by the process calling this function.

The Label in the response equals the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when storing the request id in a collection, or when sending the request using send_request/4. ๐Ÿท๏ธ

Compared to check_response/2, the returned result or exception associated with a specific request identifier will be wrapped in a 3-tuple {Response, Label, NewReqIdCollection}. Response is the value that would have been produced by check_response/2, Label is the value associated with the specific request identifier and NewReqIdCollection is a possibly modified request identifier collection.

If ReqIdCollection is empty, no_request is returned.

If Msg does not correspond to any of the request identifiers in ReqIdCollection, no_reply is returned.

If Delete equals true, the association with Label has been deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, NewReqIdCollection will equal ReqIdCollection. Note that deleting an association is not for free and that a collection containing already handled requests can still be used by subsequent calls to wait_response/3, check_response/3, and receive_response/3.

โš ๏ธ However, without deleting handled associations, the above calls will not be able to detect when there are no more outstanding requests to handle, so you will have to keep track of this some other way than relying on a no_request return. Note that if you pass a collection only containing associations of already handled or abandoned requests to this function, it will always return no_reply. ๐Ÿ’€

โœจ enter_loop/5 โœจ

enter_loop(Module :: term(),
           Opts :: term(),
           State :: term(),
           Data :: term(),
           Actions) ->
               no_return()
               when Actions :: list();
           (Module :: term(),
            Opts :: term(),
            State :: term(),
            Data :: term(),
            Server) ->
               no_return()
               when Server :: server_name() | pid().

Make the calling process become a gen_statem server. ๐Ÿ‘‘

With argument Actions, equivalent to enter_loop(Module, Opts, State, Data, self(), Actions).

Otherwise equivalent to enter_loop(Module, Opts, State, Data, Server, []).


โœจ enter_loop/6 โœจ

enter_loop(Module :: module(),
           Opts :: [enter_loop_opt()],
           State :: state(),
           Data :: data(),
           Server :: server_name() | pid(),
           Actions :: [action()] | action()) ->
               no_return().

Make the calling process become a gen_statem server. Same slay, more arguments. ๐Ÿ‘‘โœจ

Does not return, instead the calling process enters the gen_statem receive loop and becomes a gen_statem server. The process must have been started using one of the start functions in proc_lib. The user is responsible for any initialization of the process, including registering a name for it.

This function is useful when a more complex initialization procedure is needed than the gen_statem Module:init/1 callback offers.

Module and Opts have the same meanings as when calling start[link | monitor]/3,4.

If Server is self/0 an anonymous server is created just as when using start[link |_monitor]/3](start_link/3). If Server is a server_name/0 a named server is created just as when using [start[link |_monitor]/4. However, the server_name/0 name must have been registered accordingly before this function is called. ๐ŸŽ€

State, Data, and Actions have the same meanings as in the return value of Module:init/1. Also, the callback module does not need to export a Module:init/1 function.

The function fails if the calling process was not started by a proc_lib start function, or if it is not registered according to server_name/0. ๐Ÿšจ

โœจ receive_response/2 โœจ

receive_response(ReqId, Timeout) -> Result
                        when
                            ReqId :: request_id(),
                            Timeout :: response_timeout(),
                            Response ::
                                {reply, Reply :: term()} |
                                {error,
                                 {Reason :: term(), server_ref()}},
                            Result :: Response | timeout.

Receive a request response. ๐Ÿซถ

Receive a response corresponding to the request identifier ReqId. The request must have been made by send_request/2 to the gen_statem process. This function must be called from the same process from which send_request/2 was made.

Timeout specifies how long to wait for a response. If no response is received within the specified time, this function returns timeout. Assuming that the server executes on a node supporting aliases (introduced in OTP 24) the request will also be abandoned. That is, no response will be received after a time-out. Otherwise, a stray response might be received at a later time. ๐Ÿ™ˆ

See call/3 about how the request is handled and the Reply is sent by the gen_statem server.

If the gen_statem server process is dead or dies while this function waits for the reply, it returns an error return with the exit Reason. ๐Ÿ’€

The difference between wait_response/2 and receive_response/2 is that receive_response/2 abandons the request at time-out so that a potential future response is ignored, while wait_response/2 does not. ๐ŸŽ€


โœจ receive_response/3 โœจ

receive_response(ReqIdCollection, Timeout, Delete) -> Result
                        when
                            ReqIdCollection :: request_id_collection(),
                            Timeout :: response_timeout(),
                            Delete :: boolean(),
                            Response ::
                                {reply, Reply :: term()} |
                                {error,
                                 {Reason :: term(), server_ref()}},
                            Result ::
                                {Response,
                                 Label :: term(),
                                 NewReqIdCollection ::
                                     request_id_collection()} |
                                no_request | timeout.

Receive a request response in a collection. ๐Ÿ’…

Receive a response in ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/2 or send_request/4, and all requests must have been made by the process calling this function.

The Label in the response is the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when adding the request id to a collection, or when sending the request using send_request/4. ๐Ÿฆ‹

Compared to receive_response/2, bestie, the result or exception you get back is wrapped up differently โ€” you get a 3-tuple {Response, Label, NewReqIdCollection} โœจ. Here's the tea on each bit:

  1. Response โ€” literally the exact same value receive_response/2 would've handed you.
  2. Label โ€” the label that's associated with that specific request identifier.
  3. NewReqIdCollection โ€” a possibly modified request identifier collection, no cap.

If ReqIdCollection is empty, you get no_request back. Simple as that. ๐Ÿซถ

Timeout says how long you're willing to wait for a response. If nothing shows up in that window, the function returns timeout. Now โ€” assuming the server is running on a node that supports aliases (those came in with OTP 24 ๐Ÿ’…), every request identified by ReqIdCollection also gets abandoned. Meaning: after a time-out, no responses will arrive. If the node doesn't support aliases? Then stray responses might come knocking at a later time. ๐Ÿ™ˆ

The whole difference between receive_response/3 and wait_response/3 is exactly this: receive_response/3 abandons requests at time-out so potential future responses get ignored, while wait_response/3 does not. Iconic behaviour difference, honestly.

If Delete is true, the association with Label gets deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, NewReqIdCollection will equal ReqIdCollection. Heads up though โ€” deleting an association is not free, and a collection that still holds already-handled requests can totally still be used by later calls to wait_response/3, check_response/3, and receive_response/3. โœจ

But here's the catch, bestie ๐Ÿ˜ญ: if you never delete handled associations, those calls above won't be able to detect when there are no more outstanding requests to handle. So you'll have to keep track of that some other way instead of relying on a no_request return. And note โ€” if you pass a collection that only contains associations of already handled or abandoned requests to this function, it will always block until Timeout expires and then return timeout. Every single time. ๐Ÿ’€


๐Ÿ’– FUNCTIONS (continuing) ๐Ÿ’–

  • reply(Replies :: [reply_action()] | reply_action()) -> ok. โ€” send one or multiple call replies.

This function can be used by a gen_statem callback to explicitly send one reply, or a bunch of replies, to the processes waiting on call requests' replies โ€” perfect for when it's impractical or straight-up impossible to return reply_action/0s from a state callback. ๐ŸŒธ

NOTE: a reply sent with this function is not visible in sys debug output. ๐Ÿ‘€
  • reply(From :: from(), Reply :: term()) -> ok. โ€” send a call Reply to From.

This function can be used by a gen_statem callback to explicitly send a reply to a process waiting for a call request's reply, for those times when it's impractical or impossible to return a reply_action/0 from a state callback. She's the escape hatch fr fr.

NOTE: a reply sent with this function is not visible in sys debug output either. ๐Ÿ‘€
  • reqids_add(ReqId :: request_id(), Label :: term(), ReqIdCollection :: request_id_collection()) -> NewReqIdCollection :: request_id_collection(). โ€” store a request identifier in a collection. ๐ŸŽ€

Stores ReqId and associates a Label with that request identifier by adding this info into ReqIdCollection, then hands you back the resulting request identifier collection.

  • reqids_new() -> NewReqIdCollection :: request_id_collection(). โ€” create an empty request identifier collection. โœจ

Returns a brand new empty request identifier collection. A request identifier collection is your bestie for handling multiple outstanding requests at once.

Request identifiers from requests made by send_request/2 can be stashed in a collection using reqids_add/3. Later, that collection can be used to grab one response corresponding to a request in the collection โ€” just pass the collection as the argument to receive_response/3, wait_response/3, or check_response/3. ๐Ÿ‘‘

And reqids_size/1 is right there whenever you need to know how many request identifiers are chilling in a collection.

  • reqids_size(ReqIdCollection :: request_id_collection()) -> non_neg_integer(). โ€” return the number of request identifiers in ReqIdCollection. That's it, that's the whole job. ๐Ÿ’…
  • reqids_to_list(ReqIdCollection :: request_id_collection()) -> [{ReqId :: request_id(), Label :: term()}]. โ€” convert a request identifier collection to a list.

Returns a list of {ReqId, Label} tuples, and it corresponds to all request identifiers with their associated labels in ReqIdCollection. Every single one. ๐ŸŒˆ

  • send_request(ServerRef :: server_ref(), Request :: term()) -> ReqId :: request_id(). โ€” send an asynchronous call request. ๐Ÿฆ‹

Sends Request to the gen_statem process identified by ServerRef and returns a request identifier ReqId.

That ReqId you get back shall later be used with receive_response/2, wait_response/2, or check_response/2 to fetch the actual result of the request. And besides passing the request identifier directly to those functions, you can also store it in a request identifier collection using reqids_add/3. Such a collection of request identifiers can later be used to get one response corresponding to a request in the collection by passing the collection as the argument to receive_response/3, wait_response/3, or check_response/3. ๐Ÿ‘›

Oh and heads up โ€” if you're about to store the request identifier in a collection anyway, you may want to consider using send_request/4 instead. Slightly better vibes.

This call:

gen_statem:wait_response(gen_statem:send_request(ServerRef, Request), Timeout)

can be seen as equivalent to gen_statem:call(Server, Request, Timeout) โ€” ignoring the error handling, obviously. ๐Ÿ˜Œ

See call/3 for the lore on how the request is handled and how the Reply gets sent by the gen_statem server.

The server's Reply is returned by one of the receive_response/1,2, wait_response/1,2, or check_response/2 functions.

  • send_request(ServerRef :: server_ref(), Request :: term(), Label :: term(), ReqIdCollection :: request_id_collection()) -> NewReqIdCollection :: request_id_collection(). โ€” send an asynchronous call request and add it to a request identifier collection. Two birds, one stone. ๐ŸŽฏ

Sends Request to the gen_statem process identified by ServerRef. The Label will be associated with the request identifier of the operation and added to the returned request identifier collection NewReqIdCollection. That collection can later be used to get one response corresponding to a request in the collection by passing the collection as the argument to receive_response/3, wait_response/3, or check_response/3.

It's the same as calling reqids_add(send_request(ServerRef, Request), Label, ReqIdCollection), but slightly more efficient. Efficiency queen ๐Ÿ‘‘

  • start(Module :: module(), Args :: term(), Opts :: [start_opt()]) -> start_ret(). โ€” start a server, neither linked nor registered.

Equivalent to start/4 except the gen_statem process is not registered with any name service. Free agent energy โœจ

  • start(ServerName :: server_name(), Module :: module(), Args :: term(), Opts :: [start_opt()]) -> start_ret(). โ€” start a server, registered but not linked.

Creates a standalone gen_statem process according to OTP design principles (using proc_lib primitives). And because it does not get linked to the calling process, this start function cannot be used by a supervisor to start a child. Nope. Not happening bestie ๐Ÿ˜ญ

For a description of arguments and return values, go see start_link/4.

  • start_link(Module :: module(), Args :: term(), Opts :: [start_opt()]) -> start_ret(). โ€” start a server, linked but not registered.

Equivalent to start_link/4 except the gen_statem process is not registered with any name service. ๐Ÿ’ซ

  • start_link(ServerName :: server_name(), Module :: module(), Args :: term(), Opts :: [start_opt()]) -> start_ret(). โ€” start a server, linked and registered.

Creates a gen_statem process according to OTP design principles (using proc_lib primitives) that is spawned linked to the calling process. This is essential when the gen_statem must be part of a supervision tree, so it gets linked to its supervisor. ๐Ÿ 

The spawned gen_statem process calls Module:init/1 to initialize the server. And to ensure a synchronized startup procedure, start_link/3,4 does not return until Module:init/1 has returned or failed. No half-baked starts around here.

ServerName specifies the server_name/0 to register for the gen_statem process. If the gen_statem process is started with start_link/3, no ServerName is provided and the gen_statem process is not registered.

Module is the name of the callback module.

Args is an arbitrary term that is passed as the argument to Module:init/1. Whatever you want, she'll hold it. ๐Ÿ‘œ

โœจ Start options in Opts โœจ

  • {timeout, Time} โ€” the gen_statem process is allowed to spend Time milliseconds before returning from Module:init/1, or it is terminated and this start function returns {error, timeout}. Clock is ticking โฐ
  • {spawn_opt, SpawnOpts} โ€” SpawnOpts is passed as an option list to erlang:spawn_opt/2, which is what's used to spawn the gen_statem process. See proc_lib:start_spawn_option/0.
NOTE: using spawn option monitor is not allowed โ€” it causes a badarg failure. Do not try it. ๐Ÿ’€
  • {hibernate_after, HibernateAfterTimeout} โ€” when the gen_statem process is waiting for a message, if no message is received within HibernateAfterTimeout milliseconds, the process goes into hibernation automatically (by calling proc_lib:hibernate/3). This option is also allowed for the enter_loop functions. ๐Ÿ˜ด

Note that there's also a transition_option/0 to explicitly hibernate the server from a state callback, if you like being in control like that.

  • {debug, Dbgs} โ€” activates debugging through sys. For every entry in Dbgs, the corresponding function in sys is called. This option is also allowed for the enter_loop functions. ๐Ÿ”

โญ Return values โญ

  • {ok, Pid} โ€” the gen_statem server process got created and initialized, we love to see it ๐Ÿ’–. Pid is the pid/0 of the process.
  • ignore โ€” Module:init/1 returned ignore. The gen_statem process has exited with reason normal.
  • {error, {already_started, OtherPid}} โ€” a process with the specified ServerName already exists ๐Ÿ™ˆ. OtherPid is the pid/0 of that process. The gen_statem process exited with reason normal before calling Module:init/1.
  • {error, timeout} โ€” Module:init/1 did not return within the start time-out. The gen_statem process has been killed with exit_signal(_, kill) ๐Ÿ’€.
  • {error, Reason}
    • Either Module:init/1 returned {stop, Reason} or failed with reason Reason, The gen_statem process exited with reason Reason.
    • Or Module:init/1 returned {error, Reason}. The gen_statem process did a graceful exit with reason normal.

If the return value is ignore or {error, _}, the started gen_statem process has terminated. If an 'EXIT' message was delivered to the calling process (due to the process link), that message has been consumed.

WARNING: Before OTP 26.0, if the started gen_statem process returned e.g. {stop, Reason} from Module:init/1, this function could return {error, Reason} before the started gen_statem process had terminated, so starting again might fail because VM resources such as the registered name was not yet unregistered, and an 'EXIT' message could arrive later to the process calling this function. But if the started gen_statem process instead failed during Module:init/1, a process link {'EXIT', Pid, Reason} message caused this function to return {error, Reason}, so the 'EXIT' message had been consumed and the started gen_statem process had terminated. Since it was impossible to tell the difference between these two cases from start_link/3,4's return value, this inconsistency was cleaned up in OTP 26.0.

โœจ start_monitor/3 โœจ

start_monitor(Module :: module(),
              Args :: term(),
              Opts :: [start_opt()]) ->
                 start_mon_ret().

Start a server, monitored but neither linked nor registered.

Equivalent to start_monitor/4 except that the gen_statem process is not registered with any name service.

๐Ÿ’ซ start_monitor/4 ๐Ÿ’ซ

start_monitor(ServerName :: server_name(),
              Module :: module(),
              Args :: term(),
              Opts :: [start_opt()]) ->
                 start_mon_ret().

Start a server, monitored and registered, but not linked.

Creates a standalone gen_statem process according to OTP design principles (using proc_lib primitives), and atomically sets up a monitor to the newly created process. Bestie, atomically is doing so much work here, no cap.

As the started process does not get linked to the calling process, this start function cannot be used by a supervisor to start a child.

For a description of arguments and return values, see start_link/4, but note that for a succesful start the return value differs since this function returns {ok, {Pid, Mon}}, where Pid is the process identifier of the process, and Mon is the monitor reference for the process. If the start is not successful, the caller will be blocked until the DOWN message has been received and removed from the caller's message queue.

๐Ÿ›‘ stop/3 ๐Ÿ›‘

stop(ServerRef :: server_ref(),
     Reason :: term(),
     Timeout :: timeout()) ->
        ok.

Stop a server. It's giving goodbye, but make it official ๐Ÿซถ.

Orders the gen_statem ServerRef to exit with the specified Reason and waits for it to terminate. The gen_statem calls Module:terminate/3 before exiting.

This function returns ok if the server terminates with the expected reason. Any other reason than normal, shutdown, or {shutdown, Term} causes an error report to be issued through logger. An exit signal with the same reason is sent to linked processes and ports. The default Reason is normal.

Timeout is an integer > 0, which specifies how many milliseconds to wait for the server to terminate, or the atom infinity to wait indefinitely. Defaults to infinity. If the server does not terminate within the specified time, the call exits the calling process with reason timeout ๐Ÿ˜ญ.

If the process does not exist, the call exits the calling process with reason noproc, or with reason {nodedown, Node} if the connection fails to the remote Node where the server runs.

โณ wait_response/2 โณ

wait_response(ReqId, WaitTime) -> Result
    when
        ReqId :: request_id(),
        WaitTime :: response_timeout(),
        Response ::
            {reply, Reply :: term()} |
            {error, {Reason :: term(),
server_ref()}},
        Result :: Response | timeout.

Wait for a request response. Chilling, but for a specific reply ๐Ÿ’….

Waits for the response to the request identifier ReqId. The request must have been made by send_request/2 to the gen_statem process. This function must be called from the same process from which send_request/2 was called.

WaitTime specifies how long to wait for a reply. If no reply is received within the specified time, the function returns timeout and no cleanup is done, Thus the function can be invoked repeatedly until a reply is returned.

See call/3 about how the request is handled and the Reply is sent by the gen_statem server.

If the gen_statem server process is dead or dies while this function waits for the reply, it returns an error return with the exit Reason.

The difference between receive_response/2 and wait_response/2 is that receive_response/2 abandons the request at time-out so that a potential future response is ignored, while wait_response/2 does not.

๐ŸŒธ wait_response/3 ๐ŸŒธ

wait_response(ReqIdCollection, WaitTime, Delete) -> Result
    when
        ReqIdCollection :: request_id_collection(),
        WaitTime :: response_timeout(),
        Delete :: boolean(),
        Response ::
            {reply, Reply :: term()} |
            {error, {Reason :: term(),
server_ref()}},
        Result ::
            {Response,
             Label :: term(),
             NewReqIdCollection ::
                 request_id_collection()} |
            no_request | timeout.

Wait for any request response in a collection. Multi-tasking queen energy ๐Ÿ‘‘.

Waits for a response in ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/2 or send_request/4, and all requests must have been made by the process calling this function.

The Label in the response is the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when adding the request id to a collection, or when sending the request using send_request/4.

Compared to wait_response/2, the returned result or exception associated with a specific request identifier will be wrapped in a 3-tuple {Response, Label, NewReqIdCollection}. Response is the value that would have been produced by wait_response/2, Label is the value associated with the specific request identifier and NewReqIdCollection is a possibly modified request identifier collection.

If ReqIdCollection is empty, no_request is returned.

If no response is received before WaitTime has expired, timeout is returned. It is valid to continue waiting for a response as many times as needed up until a response has been received and completed by check_response(), receive_response(), or wait_response().

The difference between receive_response/3 and wait_response/3 is that receive_response/3 abandons requests at time-out so that potential future responses are ignored, while wait_response/3 does not.

If Delete is true, the association with Label has been deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, NewReqIdCollection will equal ReqIdCollection. Note that deleting an association is not for free and that a collection containing already handled requests can still be used by subsequent calls to wait_response/3, check_response/3, and receive_response/3.

However, without deleting handled associations, the above calls will not be able to detect when there are no more outstanding requests to handle, so you will have to keep track of this some other way than relying on a no_request return. Note that if you pass a collection only containing associations of already handled or abandoned requests to this function, it will always block until WaitTime expires and then return timeout. (it's committed to the bit, honestly ๐Ÿ’€)


๐ŸŽ€ CALLBACKS ๐ŸŽ€

'StateName'/3

State callback in callback mode state_functions.

State callback that handles all events in state StateName, where StateName :: state_name() has to be an atom/0.

StateName cannot be terminate since that would collide with the callback function Module:terminate/3.

Besides that when doing a state change the next state always has to be an atom/0, this function is equivalent to Module:handle_event(EventType, EventContent, ?FUNCTION_NAME, Data), which is the state callback in callback mode handle_event_function.

callback_mode()

Select the callback mode and possibly state enter calls. Iconic little decision-maker tbh โœจ.

This function is called by a gen_statem when it needs to find out the callback mode of the callback module.

The value is cached by gen_statem for efficiency reasons, so this function is only called once after server start, after code change, and after changing the callback module, but before the first state callback in the current callback module's code is called. More occasions may be added in future versions of gen_statem.

Server start happens either when Module:init/1 returns, or when enter_loop/4,5,6 gets called. Code change happens when Module:code_change/4 returns. And a change of the callback module happens when a state callback returns any of the actions change_callback_module, push_callback_module or pop_callback_module. ๐Ÿ’ซ

The CallbackMode is either just callback_mode/0, or a list containing callback_mode/0 and possibly the atom state_enter.

NOTE: if this function's body does not return an inline constant value, the callback module is doing something strange. ๐Ÿ‘€ Not shady. Just strange. Leave it alone bestie.

๐ŸŒธ code_change(OldVsn, OldState, OldData, Extra)

Update the state and data after code change. Glow-up era for your running process โœจ

This function is called by a gen_statem when it is to update its internal state during a release upgrade/downgrade โ€” that is, when the instruction {update, Module, Change, ...}, where Change = {advanced, Extra}, is specified in the appup file. For more info, see Release Handling Instructions in OTP Design Principles.

For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is {down, Vsn}. Vsn is defined by the vsn attribute(s) of the old version of the callback module Module. If no such attribute is defined, the version is the checksum of the Beam file.

OldState and OldData is the internal state of the gen_statem.

Extra is passed "as is" from the {advanced, Extra} part of the update instruction.

If successful, the function must return the updated internal state in an {ok, NewState, NewData} tuple.

If the function returns a failure Reason, the ongoing upgrade fails and rolls back to the old release. Note that Reason cannot be an {ok, _, _} tuple since that will be regarded as a {ok, NewState, NewData} tuple, and a tuple matching {ok, _} is an also invalid failure Reason. It is recommended to use an atom as Reason since it will be wrapped in an {error, Reason} tuple. ๐Ÿซ  (yes, really โ€” read that twice, it matters)

Also note: when upgrading a gen_statem, this function โ€” and hence the Change = {advanced, Extra} parameter in the appup file โ€” is not only needed to update the internal state or to act on the Extra argument. It is also needed if an upgrade or downgrade should change callback mode, or else the callback mode after the code change will not be honoured, most probably causing a server crash. ๐Ÿ’€ Big deal, do not skip it.

If the server changes callback module using any of the actions change_callback_module, push_callback_module, or pop_callback_module, be aware that it is always the current callback module that will get this callback call. That the current callback module handles the current state and data update should be no surprise, but it must be able to handle even parts of the state and data that it is not familiar with, somehow. ๐Ÿ™ˆ

In the supervisor child specification there is a list of modules which is recommended to contain only the callback module. For a gen_statem with multiple callback modules there is no real need to list all of them โ€” it may not even be possible, since the list could change after code upgrade. If this list would contain only the start callback module, as recommended, what is important is to upgrade that module whenever a synchronized code replacement is done. Then the release handler concludes that an upgrade that upgrades that module needs to suspend, code change, and resume any server whose child specification declares that it is using that module. And again: the current callback module will get the Module:code_change/4 call. Periodt. ๐Ÿ‘‘

NOTE: if a release upgrade/downgrade with Change = {advanced, Extra} specified in the .appup file is made when Module:code_change/4 is not implemented, the process will crash with exit reason undef. ๐Ÿ˜ญ Not a vibe.

๐ŸŽ€ format_status(Status)

Format/limit the status value.

This function is called by a gen_statem process in order to format/limit the server status for debugging and logging purposes.

It is called in the following situations:

  • sys:get_status/1,2 is invoked to get the gen_statem status.
  • The gen_statem process terminates abnormally and logs an error.

This function is useful for changing the form and appearance of the gen_statem status for these cases. A callback module wishing to change the sys:get_status/1,2 return value and how its status appears in termination error logs, exports an instance of Module:format_status/1, which will get a map Status that describes the current state of the gen_statem, and shall return a map NewStatus containing the same keys as the input map, but it may transform some values.

One use case for this function is to return compact alternative state representations to avoid having large state terms printed in log files. Another is to hide sensitive data from being written to the error log. ๐Ÿ”’โœจ (protect the private keys, bestie)

Example:

format_status(Status) ->
  maps:map(
    fun(state,State) ->
            maps:remove(private_key, State);
       (message,{password, _Pass}) ->
            {password, removed};
       (_,Value) ->
            Value
    end, Status).
NOTE: this callback is optional, so a callback module does not need to export it. The gen_statem module provides a default implementation of this function that returns {State, Data}. If this callback is exported but fails, to hide possibly sensitive data, the default function will instead return {State, Info}, where Info says nothing but the fact that Module:format_status/2 has crashed. ๐Ÿ’€

๐Ÿ’œ format_status/2

Deprecated: the callback gen_statem:format_status(_,_) is deprecated; use format_status/1 instead ๐Ÿšซ

Format/limit the status value.

This function is called by a gen_statem process in in order to format/limit the server state for debugging and logging purposes.

It is called in the following situations:

  • One of sys:get_status/1,2 is invoked to get the gen_statem status. Opt is set to the atom normal for this case.
  • The gen_statem terminates abnormally and logs an error. Opt is set to the atom terminate for this case.

This function is useful for changing the form and appearance of the gen_statem status for these cases. A callback module wishing to change the sys:get_status/1,2 return value and how its status appears in termination error logs, should export an instance of Module:format_status/2, that returns a term describing the current status of the gen_statem.

PDict is the current value of the process dictionary of the gen_statem.

State is the internal state of the gen_statem.

Data is the internal server data of the gen_statem.

The function is to return Status, a term that contains the appropriate details of the current state and status of the gen_statem. There are no restrictions of the form Status can take, but for the sys:get_status/1,2 case (when Opt is normal), the recommended form for the Status value is [{data, [{"State", Term}]}], where Term provides relevant details of the gen_statem state. Following this recommendation is not required, but it makes the callback module status consistent with the rest of the sys:get_status/1,2 return value.

One use for this function is to return compact alternative state representations to avoid having large state terms printed in log files. Another use is to hide sensitive data from being written to the error log.

NOTE: this callback is optional, so a callback module does not need to export it. The gen_statem module provides a default implementation of this function that returns {State, Data}. If this callback is exported but fails, to hide possibly sensitive data, the default function will instead return {State, Info}, where Info says nothing but the fact that Module:format_status/2 has crashed. ๐Ÿ™ˆ

๐ŸŒˆ handle_event/4

State callback in callback mode handle_event_function.

Whenever a gen_statem receives an event from call/2,3, cast/2, or as a normal process message, this function is called.

If EventType is {call, From}, the caller waits for a reply. The reply can be sent from this or from any other state callback by returning with {reply, From, Reply} in Actions, in Replies, or by calling reply(From, Reply).

If this function returns with a next state that does not match equal (=/=) to the current state, all postponed events are retried in the next state.

For options that can be set and actions that can be done by gen_statem after returning from this function, see action/0.

When the gen_statem runs with state enter calls, this function is also called with arguments (enter, OldState, ...) during every state change. In this case there are some restrictions on the actions that may be returned:

  • postpone/0 is not allowed, since a state enter call is not an event so there is no event to postpone.
  • {next_event, _, _} is not allowed, since using state enter calls should not affect how events are consumed and produced.
  • It is not allowed to change states from this call. Should you return {next_state, NextState, ...} with NextState =/= State the gen_statem crashes. ๐Ÿ’ฅ
    • Note that it is actually allowed to use {repeat_state, NewData, ...} although it makes little sense, since you immediately will be called again with a new state enter call making this just a weird way of looping, and there are better ways to loop in Erlang.
    • If you do not update NewData and have some loop termination condition, or if you use {repeat_state_and_data, _} or repeat_state_and_data you have an infinite loop! ๐Ÿ˜ตโ€๐Ÿ’ซ
    • You are advised to use {keep_state, ...}, {keep_state_and_data, _} or keep_state_and_data since changing states from a state enter call is not possible anyway.

Also, bestie, you can literally use throw to return the result, which is lowkey iconic when you need it. Like, if you're deep in some complex code and you cannot return {next_state, State, Data} because State or Data is no longer in scope, you can just bail out with throw(keep_state_and_data). No cap, it's useful. ๐Ÿ’…

โœจ init(Args) โœจ

Initialize the state machine, bestie. Every single time a gen_statem is started using start_link/3,4, start_monitor/3,4, or start/3,4, this function is called by the new process to initialize the implementation state and server data.

Args is literally the Args argument you handed to that start function.

โš ๏ธ NOTE: If the gen_statem is started through proc_lib and enter_loop/4,5,6, this callback will never be called. And since this callback is not optional, you can in that case just implement it as:
-spec init(_) -> no_return().
init(Args) -> erlang:error(not_implemented, [Args]).

๐ŸŽ€ terminate/3 ๐ŸŽ€

Handle state machine termination, queen. This function is called by a gen_statem when it is about to terminate. It is supposed to be the opposite of Module:init/1 and do any necessary cleaning up. When it returns, the gen_statem terminates with Reason. The return value is ignored.

Reason is a term denoting the stop reason and State is the internal state of the gen_statem.

Reason depends on why the gen_statem is terminating. If it is because another callback function has returned a stop tuple {stop, Reason} in Actions, then Reason has the value specified in that tuple. If it is because of a failure, Reason is the error reason.

If the gen_statem is part of a supervision tree and is ordered by its supervisor to terminate, this function is called with Reason = shutdown if both the following conditions apply:

  • The gen_statem process has been set to trap exit signals.
  • The shutdown strategy as defined in the supervisor's child specification is an integer time-out value, not brutal_kill.

Even if the gen_statem is not part of a supervision tree, this function is called if it receives an 'EXIT' message from its parent. Reason is the same as in the 'EXIT' message.

If the gen_statem process is not set up to trap exit signals it is immediately terminated, just like any process, and this function is not called.

Notice that for any other reason than normal, shutdown, or {shutdown, Term}, the gen_statem is assumed to terminate because of an error and an error report is issued using logger.

When the gen_statem process exits, an exit signal with the same reason is sent to linked processes and ports, just as for any process.


And that's the whole page, bestie! Massive shoutout to Ericsson AB, stdlib 8.0.4, and gen_statem(3) for bringing us this absolute classic. Stay slaying those state machines! ๐Ÿ’–โœจ๐ŸŽ€๐Ÿฆ‹

๐Ÿ“ฆ where this page comes from