1gen_statem(3)              Erlang Module Definition              gen_statem(3)
2
3
4

NAME

6       gen_statem - Generic state machine behavior.
7

DESCRIPTION

9       gen_statem provides a generic state machine behaviour that for new code
10       replaces its predecessor gen_fsm since Erlang/OTP 20.0. The gen_fsm be‐
11       haviour remains in OTP "as is".
12
13   Note:
14       If you are new to gen_statem and want an overview of concepts and oper‐
15       ation the section gen_statem Behaviour  located  in  the  User's  Guide
16       OTP  Design  Principles   is  recommended to read before this reference
17       manual, possibly after the Description section you are reading here.
18
19
20       This reference manual contains type descriptions generated  from  types
21       in the gen_statem source code, so they are correct. However, the gener‐
22       ated descriptions also reflect  the  type  hierarchy,  which  sometimes
23       makes it hard to get a good overview. If so, see the section gen_statem
24       Behaviour  in the  OTP Design Principles  User's Guide.
25
26   Note:
27
28         * This behavior appeared in Erlang/OTP 19.0.
29
30         *
31            In OTP 19.1 a backwards incompatible change of  the  return  tuple
32           from  Module:init/1  was  made  and the mandatory callback function
33           Module:callback_mode/0 was introduced.
34
35         *
36            In OTP 20.0  generic time-outs  were added.
37
38         *
39            In OTP 22.1 time-out content update and explicit  time-out  cancel
40           were added.
41
42         *
43            In OTP 22.3 the possibility to change the callback module with ac‐
44           tions change_callback_module,  push_callback_module  and  pop_call‐
45           back_module, was added.
46
47       gen_statem has got the same features that gen_fsm had and adds some re‐
48       ally useful:
49
50         * Co-located state code
51
52         * Arbitrary term state
53
54         * Event postponing
55
56         * Self-generated events
57
58         * State time-out
59
60         * Multiple generic named time-outs
61
62         * Absolute time-out time
63
64         * Automatic state enter calls
65
66         *
67            Reply from other state than the request, sys traceable
68
69         * Multiple sys traceable replies
70
71         * Changing the callback module
72
73       Two callback modes are supported:
74
75         * One for finite-state machines (gen_fsm like),  which  requires  the
76           state  to be an atom and uses that state as the name of the current
77           callback function.
78
79         * One that allows the state to be any term and that uses one callback
80           function for all states.
81
82       The  callback model(s) for gen_statem differs from the one for gen_fsm,
83       but it is still fairly easy to  rewrite from  gen_fsm to gen_statem.
84
85       A generic state machine server process (gen_statem)  implemented  using
86       this  module  has  a  standard  set of interface functions and includes
87       functionality for tracing and error reporting. It also fits into an OTP
88       supervision tree. For more information, see OTP Design Principles.
89
90       A  gen_statem  assumes  all  specific parts to be located in a callback
91       module exporting a predefined set of functions.  The  relationship  be‐
92       tween the behavior functions and the callback functions is as follows:
93
94       gen_statem module            Callback module
95       -----------------            ---------------
96       gen_statem:start
97       gen_statem:start_monitor
98       gen_statem:start_link -----> Module:init/1
99
100       Server start or code change
101                             -----> Module:callback_mode/0
102
103       gen_statem:stop       -----> Module:terminate/3
104
105       gen_statem:call
106       gen_statem:cast
107       gen_statem:send_request
108       erlang:send
109       erlang:'!'            -----> Module:StateName/3
110                                    Module:handle_event/4
111
112       -                     -----> Module:terminate/3
113
114       -                     -----> Module:code_change/4
115
116       Events  are  of different types, so the callback functions can know the
117       origin of an event and how to respond.
118
119       If a callback function fails or returns a  bad  value,  the  gen_statem
120       terminates,  unless  otherwise  stated.  However, an exception of class
121       throw is not regarded as an error but as a valid return from all  call‐
122       back functions.
123
124       The state callback for a specific state in a gen_statem is the callback
125       function that is called for all events in this state.  It  is  selected
126       depending  on which callback mode that the callback module defines with
127       the callback function Module:callback_mode/0.
128
129       When the callback mode is state_functions, the state must  be  an  atom
130       and  is  used  as the state callback name; see Module:StateName/3. This
131       co-locates all code for  a  specific  state  in  one  function  as  the
132       gen_statem  engine branches depending on state name. Note the fact that
133       the callback function Module:terminate/3 makes the state name terminate
134       unusable in this mode.
135
136       When  the  callback mode is handle_event_function, the state can be any
137       term and the state callback name is Module:handle_event/4.  This  makes
138       it easy to branch depending on state or event as you desire. Be careful
139       about which events you handle in which states so that you do not  acci‐
140       dentally postpone an event forever creating an infinite busy loop.
141
142       When  gen_statem  receives  a  process  message it is converted into an
143       event and the state callback is called with the event as two arguments:
144       type  and  content.  When the state callback has processed the event it
145       returns to gen_statem which does a  state  transition.  If  this  state
146       transition is to a different state, that is: NextState =/= State, it is
147       a state change.
148
149       The state callback may return transition actions for gen_statem to exe‐
150       cute   during   the  state  transition,  for  example  to  reply  to  a
151       gen_statem:call/2,3.
152
153       One of the possible transition  actions  is  to  postpone  the  current
154       event.  Then it is not retried in the current state. The gen_statem en‐
155       gine keeps a queue of events divided into the postponed events and  the
156       events  still  to process. After a state change the queue restarts with
157       the postponed events.
158
159       The gen_statem event queue model is sufficient to  emulate  the  normal
160       process  message queue with selective receive. Postponing an event cor‐
161       responds to not matching it in a receive statement, and changing states
162       corresponds to entering a new receive statement.
163
164       The  state  callback  can  insert  events  using the transition actions
165       next_event and such an event is inserted in the event queue as the next
166       to call the state callback with. That is, as if it is the oldest incom‐
167       ing event. A dedicated event_type()  internal  can  be  used  for  such
168       events making them impossible to mistake for external events.
169
170       Inserting  an  event  replaces the trick of calling your own state han‐
171       dling functions that you often would have to resort to in, for example,
172       gen_fsm to force processing an inserted event before others.
173
174       The  gen_statem engine can automatically make a specialized call to the
175       state callback whenever a new state is entered; see state_enter(). This
176       is  for  writing code common to all state entries. Another way to do it
177       is to explicitly insert an event at the state transition, and/or to use
178       a  dedicated  state transition function, but that is something you will
179       have to remember at every state transition to the  state(s)  that  need
180       it.
181
182   Note:
183       If  you  in gen_statem, for example, postpone an event in one state and
184       then call another state callback of yours, you have not  done  a  state
185       change  and  hence the postponed event is not retried, which is logical
186       but can be confusing.
187
188
189       For the details of a state transition, see type transition_option().
190
191       A gen_statem handles system messages as described in sys. The sys  mod‐
192       ule can be used for debugging a gen_statem.
193
194       Notice that a gen_statem does not trap exit signals automatically, this
195       must be  explicitly  initiated  in  the  callback  module  (by  calling
196       process_flag(trap_exit, true).
197
198       Unless otherwise stated, all functions in this module fail if the spec‐
199       ified gen_statem does not exist or if bad arguments are specified.
200
201       The gen_statem process can go  into  hibernation;  see  proc_lib:hiber‐
202       nate/3. It is done when a state callback or Module:init/1 specifies hi‐
203       bernate in the returned Actions list. This feature can be useful to re‐
204       claim process heap memory while the server is expected to be idle for a
205       long time. However, use this feature with care, as hibernation  can  be
206       too costly to use after every event; see erlang:hibernate/3.
207
208       There  is  also  a  server  start option {hibernate_after, Timeout} for
209       start/3,4, start_monitor/3,4, start_link/3,4 or enter_loop/4,5,6,  that
210       may be used to automatically hibernate the server.
211
212       If the gen_statem process terminates, e.g. as a result of a function in
213       the callback module returning {stop,Reason}, an exit signal  with  this
214       Reason  is  sent  to  linked processes and ports. See  Processes in the
215       Reference Manual for details regarding error handling using  exit  sig‐
216       nals.
217
218   Note:
219       For  some  important  information  about  distributed  signals, see the
220       Blocking Signaling Over Distribution  section in the Processes  chapter
221       of  the  Erlang Reference Manual . Blocking signaling can, for example,
222       cause call timeouts in gen_statem to be significantly delayed.
223
224

EXAMPLE

226       The following example shows a simple pushbutton model  for  a  toggling
227       pushbutton implemented with callback mode state_functions. You can push
228       the button and it replies if it went on or off, and you can ask  for  a
229       count of how many times it has been pushed to switch on.
230
231       The following is the complete callback module file pushbutton.erl:
232
233       -module(pushbutton).
234       -behaviour(gen_statem).
235
236       -export([start/0,push/0,get_count/0,stop/0]).
237       -export([terminate/3,code_change/4,init/1,callback_mode/0]).
238       -export([on/3,off/3]).
239
240       name() -> pushbutton_statem. % The registered server name
241
242       %% API.  This example uses a registered name name()
243       %% and does not link to the caller.
244       start() ->
245           gen_statem:start({local,name()}, ?MODULE, [], []).
246       push() ->
247           gen_statem:call(name(), push).
248       get_count() ->
249           gen_statem:call(name(), get_count).
250       stop() ->
251           gen_statem:stop(name()).
252
253       %% Mandatory callback functions
254       terminate(_Reason, _State, _Data) ->
255           void.
256       code_change(_Vsn, State, Data, _Extra) ->
257           {ok,State,Data}.
258       init([]) ->
259           %% Set the initial state + data.  Data is used only as a counter.
260           State = off, Data = 0,
261           {ok,State,Data}.
262       callback_mode() -> state_functions.
263
264       %%% state callback(s)
265
266       off({call,From}, push, Data) ->
267           %% Go to 'on', increment count and reply
268           %% that the resulting status is 'on'
269           {next_state,on,Data+1,[{reply,From,on}]};
270       off(EventType, EventContent, Data) ->
271           handle_event(EventType, EventContent, Data).
272
273       on({call,From}, push, Data) ->
274           %% Go to 'off' and reply that the resulting status is 'off'
275           {next_state,off,Data,[{reply,From,off}]};
276       on(EventType, EventContent, Data) ->
277           handle_event(EventType, EventContent, Data).
278
279       %% Handle events common to all states
280       handle_event({call,From}, get_count, Data) ->
281           %% Reply with the current count
282           {keep_state,Data,[{reply,From,Data}]};
283       handle_event(_, _, Data) ->
284           %% Ignore all other events
285           {keep_state,Data}.
286
287
288       The following is a shell session when running it:
289
290       1> pushbutton:start().
291       {ok,<0.36.0>}
292       2> pushbutton:get_count().
293       0
294       3> pushbutton:push().
295       on
296       4> pushbutton:get_count().
297       1
298       5> pushbutton:push().
299       off
300       6> pushbutton:get_count().
301       1
302       7> pushbutton:stop().
303       ok
304       8> pushbutton:push().
305       ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
306            in function  gen:do_for_proc/2 (gen.erl, line 261)
307            in call from gen_statem:call/3 (gen_statem.erl, line 386)
308
309
310       To  compare  styles,  here follows the same example using callback mode
311       handle_event_function, or rather the code  to  replace  after  function
312       init/1 of the pushbutton.erl example file above:
313
314       callback_mode() -> handle_event_function.
315
316       %%% state callback(s)
317
318       handle_event({call,From}, push, off, Data) ->
319           %% Go to 'on', increment count and reply
320           %% that the resulting status is 'on'
321           {next_state,on,Data+1,[{reply,From,on}]};
322       handle_event({call,From}, push, on, Data) ->
323           %% Go to 'off' and reply that the resulting status is 'off'
324           {next_state,off,Data,[{reply,From,off}]};
325       %%
326       %% Event handling common to all states
327       handle_event({call,From}, get_count, State, Data) ->
328           %% Reply with the current count
329           {next_state,State,Data,[{reply,From,Data}]};
330       handle_event(_, _, State, Data) ->
331           %% Ignore all other events
332           {next_state,State,Data}.
333
334

DATA TYPES

336       server_name() =
337           {local, atom()} |
338           {global, GlobalName :: term()} |
339           {via, RegMod :: module(), Name :: term()}
340
341              Name specification to use when starting a gen_statem server. See
342              start_link/3 and server_ref() below.
343
344       server_ref() =
345           pid() |
346           (LocalName :: atom()) |
347           {Name :: atom(), Node :: atom()} |
348           {global, GlobalName :: term()} |
349           {via, RegMod :: module(), ViaName :: term()}
350
351              Server specification to use when addressing a gen_statem server.
352              See call/2 and server_name() above.
353
354              It can be:
355
356                pid() | LocalName:
357                  The gen_statem is locally registered.
358
359                {Name,Node}:
360                  The gen_statem is locally registered on another node.
361
362                {global,GlobalName}:
363                  The gen_statem is globally registered in global.
364
365                {via,RegMod,ViaName}:
366                  The  gen_statem is registered in an alternative process reg‐
367                  istry. The registry callback  module  RegMod  is  to  export
368                  functions         register_name/2,        unregister_name/1,
369                  whereis_name/1, and send/2, which are  to  behave  like  the
370                  corresponding functions in global. Thus, {via,global,Global‐
371                  Name} is the same as {global,GlobalName}.
372
373       start_opt() =
374           {timeout, Time :: timeout()} |
375           {spawn_opt, [proc_lib:spawn_option()]} |
376           enter_loop_opt()
377
378              Options that can be  used  when  starting  a  gen_statem  server
379              through, for example, start_link/3.
380
381       start_ret() = {ok, pid()} | ignore | {error, term()}
382
383              Return value from the start/3,4 and start_link/3,4 functions.
384
385       start_mon_ret() =
386           {ok, {pid(), reference()}} | ignore | {error, term()}
387
388              Return value from the start_monitor/3,4 functions.
389
390       enter_loop_opt() =
391           {hibernate_after, HibernateAfterTimeout :: timeout()} |
392           {debug, Dbgs :: [sys:debug_option()]}
393
394              Options  that  can  be  used  when  starting a gen_statem server
395              through, enter_loop/4-6.
396
397                hibernate_after:
398                  HibernateAfterTimeout specifies that the gen_statem  process
399                  awaits  any  message  for HibernateAfterTimeout milliseconds
400                  and if no message is received, the process goes into  hiber‐
401                  nation automatically (by calling proc_lib:hibernate/3).
402
403                debug:
404                  For  every  entry in Dbgs, the corresponding function in sys
405                  is called.
406
407       from() = {To :: pid(), Tag :: reply_tag()}
408
409              Destination to use when replying through, for example,  the  ac‐
410              tion()  {reply,From,Reply}  to  a  process  that  has called the
411              gen_statem server using call/2.
412
413       reply_tag()
414
415              A handle that associates a reply to the corresponding request.
416
417       state() = state_name() | term()
418
419              If the callback mode is handle_event_function, the state can  be
420              any  term. After a state change (NextState =/= State), all post‐
421              poned events are retried.
422
423       state_name() = atom()
424
425              If the callback mode is state_functions, the state  must  be  an
426              atom.  After a state change (NextState =/= State), all postponed
427              events are retried. Note that the state terminate is not  possi‐
428              ble  to  use  since  it would collide with the optional callback
429              function Module:terminate/3.
430
431       data() = term()
432
433              A term in which the state machine implementation is to store any
434              server  data  it  needs.  The  difference  between  this and the
435              state() itself is that a change in  this  data  does  not  cause
436              postponed  events to be retried. Hence, if a change in this data
437              would change the set of events that are handled, then that  data
438              item is to be made a part of the state.
439
440       event_type() =
441           external_event_type() | timeout_event_type() | internal
442
443              There  are 3 categories of events: external, timeout, and inter‐
444              nal.
445
446              internal events can only be generated by the state  machine  it‐
447              self through the transition action next_event.
448
449       external_event_type() = {call, From :: from()} | cast | info
450
451              External events are of 3 types: {call,From}, cast, or info. Type
452              call originates from  the  API  functions  call/2  and  send_re‐
453              quest/2.  For  calls,  the event contains whom to reply to. Type
454              cast originates from the API function cast/2. Type  info  origi‐
455              nates from regular process messages sent to the gen_statem.
456
457       timeout_event_type() =
458           timeout | {timeout, Name :: term()} | state_timeout
459
460              There  are 3 types of time-out events that the state machine can
461              generate for itself with the corresponding timeout_action()s.
462
463       event_content() = term()
464
465              Any event's content can be any term.
466
467              See event_type that describes the origins of the different event
468              types, which is also where the event content comes from.
469
470       callback_mode_result() =
471           callback_mode() | [callback_mode() | state_enter()]
472
473              This  is the return type from Module:callback_mode/0 and selects
474              callback mode and whether to do state enter calls, or not.
475
476       callback_mode() = state_functions | handle_event_function
477
478              The callback mode is selected with the return  value  from  Mod‐
479              ule:callback_mode/0:
480
481                state_functions:
482                  The  state  must  be  of  type state_name() and one callback
483                  function per state, that is, Module:StateName/3, is used.
484
485                handle_event_function:
486                  The state can be any term and  the  callback  function  Mod‐
487                  ule:handle_event/4 is used for all states.
488
489              The  function Module:callback_mode/0 is called when starting the
490              gen_statem, after code change and after  changing  the  callback
491              module   with   any   of   the  actions  change_callback_module,
492              push_callback_module  or  pop_callback_module.  The  result   is
493              cached for subsequent calls to state callbacks.
494
495       state_enter() = state_enter
496
497              Whether the state machine should use state enter calls or not is
498              selected when starting the gen_statem and after code change  us‐
499              ing the return value from Module:callback_mode/0.
500
501              If Module:callback_mode/0 returns a list containing state_enter,
502              the gen_statem engine will, at  every  state  change,  call  the
503              state callback with arguments (enter, OldState, Data) or (enter,
504              OldState, State, Data), depending on the callback mode. This may
505              look like an event but is really a call performed after the pre‐
506              vious state callback returned and before any event is  delivered
507              to  the  new  state  callback.  See  Module:StateName/3 and Mod‐
508              ule:handle_event/4. Such a call can be repeated by  returning  a
509              repeat_state or repeat_state_and_data tuple from the state call‐
510              back.
511
512              If Module:callback_mode/0 does not return such a list, no  state
513              enter calls are done.
514
515              If  Module:code_change/4  should  transform the state, it is re‐
516              garded as a state rename and not a state change, which will  not
517              cause a state enter call.
518
519              Note  that a state enter call will be done right before entering
520              the initial state even though  this  actually  is  not  a  state
521              change. In this case OldState =:= State, which cannot happen for
522              a subsequent state change, but will happen  when  repeating  the
523              state enter call.
524
525       transition_option() =
526           postpone() |
527           hibernate() |
528           event_timeout() |
529           generic_timeout() |
530           state_timeout()
531
532              Transition  options  can  be set by actions and modify the state
533              transition. The state transition  takes  place  when  the  state
534              callback  has  processed  an event and returns. Here are the se‐
535              quence of steps for a state transition:
536
537                * All returned actions are processed in order  of  appearance.
538                  In this step all replies generated by any reply_action() are
539                  sent. Other actions set transition_option()s that come  into
540                  play in subsequent steps.
541
542                * If  state enter calls are used, and either it is the initial
543                  state or one of the callback  results  repeat_state_and_data
544                  or repeat_state_and_data is used the gen_statem engine calls
545                  the current state callback  with  arguments  (enter,  State,
546                  Data)  or (enter, State, State, Data) (depending on callback
547                  mode) and when it returns starts again from the top of  this
548                  sequence.
549
550                  If  state  enter  calls  are used, and the state changes the
551                  gen_statem engine calls the new state  callback  with  argu‐
552                  ments  (enter,  OldState,  Data) or (enter, OldState, State,
553                  Data) (depending on  callback  mode)  and  when  it  returns
554                  starts again from the top of this sequence.
555
556                * If postpone() is true, the current event is postponed.
557
558                * If  this  is a state change, the queue of incoming events is
559                  reset to start with the oldest postponed.
560
561                * All events stored with action() next_event are  inserted  to
562                  be processed before previously queued events.
563
564                * Time-out   timers   event_timeout(),  generic_timeout()  and
565                  state_timeout() are handled. Time-outs with  zero  time  are
566                  guaranteed  to  be delivered to the state machine before any
567                  external not yet received event so if there is such a  time-
568                  out  requested, the corresponding time-out zero event is en‐
569                  queued as the newest received event; that is  after  already
570                  queued events such as inserted and postponed events.
571
572                  Any  event  cancels  an event_timeout() so a zero time event
573                  time-out is only generated if the event queue is empty.
574
575                  A state change cancels a state_timeout() and any new transi‐
576                  tion  option of this type belongs to the new state, that is;
577                  a state_timeout() applies to the state the state machine en‐
578                  ters.
579
580                * If there are enqueued events the state callback for the pos‐
581                  sibly new state is called with the  oldest  enqueued  event,
582                  and we start again from the top of this sequence.
583
584                * Otherwise  the  gen_statem  goes into receive or hibernation
585                  (if hibernate() is true) to wait for the  next  message.  In
586                  hibernation   the   next   non-system   event   awakens  the
587                  gen_statem, or rather the next incoming message awakens  the
588                  gen_statem,  but  if it is a system event it goes right back
589                  into hibernation. When a new message arrives the state call‐
590                  back  is  called  with the corresponding event, and we start
591                  again from the top of this sequence.
592
593       postpone() = boolean()
594
595              If true, postpones the current event  and  retries  it  after  a
596              state change (NextState =/= State).
597
598       hibernate() = boolean()
599
600              If  true,  hibernates  the gen_statem by calling proc_lib:hiber‐
601              nate/3 before going into receive to  wait  for  a  new  external
602              event.
603
604          Note:
605              If  there are enqueued events to process when hibernation is re‐
606              quested, this is optimized by not hibernating but instead  call‐
607              ing erlang:garbage_collect/0 to simulate that the gen_statem en‐
608              tered hibernation and immediately got awakened  by  an  enqueued
609              event.
610
611
612       event_timeout() = timeout() | integer()
613
614              Starts a timer set by enter_action() timeout. When the timer ex‐
615              pires an event of event_type() timeout will  be  generated.  See
616              erlang:start_timer/4  for  how Time and Options are interpreted.
617              Future erlang:start_timer/4 Options will not necessarily be sup‐
618              ported.
619
620              Any  event  that  arrives cancels this time-out. Note that a re‐
621              tried or inserted event counts as arrived. So does a state time-
622              out  zero event, if it was generated before this time-out is re‐
623              quested.
624
625              If Time is infinity, no timer is started, as it never would  ex‐
626              pire anyway.
627
628              If  Time is relative and 0 no timer is actually started, instead
629              the the time-out event is enqueued to ensure that it  gets  pro‐
630              cessed before any not yet received external event, but after al‐
631              ready queued events.
632
633              Note that it is not possible nor needed to cancel this time-out,
634              as it is cancelled automatically by any other event.
635
636       generic_timeout() = timeout() | integer()
637
638              Starts  a  timer  set by enter_action() {timeout,Name}. When the
639              timer expires an event of event_type()  {timeout,Name}  will  be
640              generated. See erlang:start_timer/4 for how Time and Options are
641              interpreted. Future erlang:start_timer/4 Options will not neces‐
642              sarily be supported.
643
644              If  Time is infinity, no timer is started, as it never would ex‐
645              pire anyway.
646
647              If Time is relative and 0 no timer is actually started,  instead
648              the  the  time-out event is enqueued to ensure that it gets pro‐
649              cessed before any not yet received external event.
650
651              Setting a timer with the same Name  while  it  is  running  will
652              restart it with the new time-out value. Therefore it is possible
653              to cancel a specific time-out by setting it to infinity.
654
655       state_timeout() = timeout() | integer()
656
657              Starts a timer set by  enter_action()  state_timeout.  When  the
658              timer  expires  an  event  of event_type() state_timeout will be
659              generated. See erlang:start_timer/4 for how Time and Options are
660              interpreted. Future erlang:start_timer/4 Options will not neces‐
661              sarily be supported.
662
663              If Time is infinity, no timer is started, as it never would  ex‐
664              pire anyway.
665
666              If  Time is relative and 0 no timer is actually started, instead
667              the the time-out event is enqueued to ensure that it  gets  pro‐
668              cessed before any not yet received external event.
669
670              Setting  this timer while it is running will restart it with the
671              new time-out value. Therefore it  is  possible  to  cancel  this
672              time-out by setting it to infinity.
673
674       timeout_option() = {abs, Abs :: boolean()}
675
676              If  Abs is true an absolute timer is started, and if it is false
677              a relative, which is the default. See  erlang:start_timer/4  for
678              details.
679
680       action() =
681           postpone |
682           {postpone, Postpone :: postpone()} |
683           {next_event,
684            EventType :: event_type(),
685            EventContent :: event_content()} |
686           {change_callback_module, NewModule :: module()} |
687           {push_callback_module, NewModule :: module()} |
688           pop_callback_module |
689           enter_action()
690
691              These  transition  actions can be invoked by returning them from
692              the state callback when it is called with an  event,  from  Mod‐
693              ule:init/1 or by giving them to enter_loop/5,6.
694
695              Actions are executed in the containing list order.
696
697              Actions  that  set  transition options  override any previous of
698              the same type, so the last in the containing list wins. For  ex‐
699              ample,  the last postpone() overrides any previous postpone() in
700              the list.
701
702                postpone:
703                  Sets the transition_option() postpone() for this state tran‐
704                  sition.  This  action  is  ignored  when  returned from Mod‐
705                  ule:init/1 or given to enter_loop/5,6, as there is no  event
706                  to postpone in those cases.
707
708                next_event:
709                  This action does not set any transition_option() but instead
710                  stores the specified EventType and EventContent  for  inser‐
711                  tion after all actions have been executed.
712
713                  The  stored  events are inserted in the queue as the next to
714                  process before any already queued events. The order of these
715                  stored  events  is preserved, so the first next_event in the
716                  containing list becomes the first to process.
717
718                  An event of type internal is to be used when you want to re‐
719                  liably  distinguish  an event inserted this way from any ex‐
720                  ternal event.
721
722                change_callback_module:
723                  Changes the callback module to NewModule which will be  used
724                  when calling all subsequent state callbacks.
725
726                  The  gen_statem  engine  will  find out the callback mode of
727                  NewModule by calling  NewModule:callback_mode/0  before  the
728                  next state callback.
729
730                  Changing the callback module does not affect the state tran‐
731                  sition in any way, it only changes which module that handles
732                  the events. Be aware that all relevant callback functions in
733                  NewModule   such   as   the    state    callback,    NewMod‐
734                  ule:code_change/4,   NewModule:format_status/1  and  NewMod‐
735                  ule:terminate/3 must be able to handle the  state  and  data
736                  from the old module.
737
738                push_callback_module:
739                  Pushes the current callback module to the top of an internal
740                  stack of callback modules and changes the callback module to
741                  NewModule.  Otherwise  like {change_callback_module, NewMod‐
742                  ule} above.
743
744                pop_callback_module:
745                   Pops the top module from the  internal  stack  of  callback
746                  modules  and  changes  the  callback module to be the popped
747                  module. If the stack is empty the  server  fails.  Otherwise
748                  like {change_callback_module, NewModule} above.
749
750       enter_action() =
751           hibernate |
752           {hibernate, Hibernate :: hibernate()} |
753           timeout_action() |
754           reply_action()
755
756              These  transition  actions can be invoked by returning them from
757              the state callback, from Module:init/1 or by giving them to  en‐
758              ter_loop/5,6.
759
760              Actions are executed in the containing list order.
761
762              Actions that set transition options override any previous of the
763              same type, so the last in the containing list wins. For example,
764              the  last event_timeout() overrides any previous event_timeout()
765              in the list.
766
767                hibernate:
768                  Sets the  transition_option()  hibernate()  for  this  state
769                  transition.
770
771       timeout_action() =
772           (Time :: event_timeout()) |
773           {timeout,
774            Time :: event_timeout(),
775            EventContent :: event_content()} |
776           {timeout,
777            Time :: event_timeout(),
778            EventContent :: event_content(),
779            Options :: timeout_option() | [timeout_option()]} |
780           {{timeout, Name :: term()},
781            Time :: generic_timeout(),
782            EventContent :: event_content()} |
783           {{timeout, Name :: term()},
784            Time :: generic_timeout(),
785            EventContent :: event_content(),
786            Options :: timeout_option() | [timeout_option()]} |
787           {state_timeout,
788            Time :: state_timeout(),
789            EventContent :: event_content()} |
790           {state_timeout,
791            Time :: state_timeout(),
792            EventContent :: event_content(),
793            Options :: timeout_option() | [timeout_option()]} |
794           timeout_cancel_action() |
795           timeout_update_action()
796
797              These  transition  actions can be invoked by returning them from
798              the state callback, from Module:init/1 or by giving them to  en‐
799              ter_loop/5,6.
800
801              These time-out actions sets time-out transition options.
802
803                Time:
804                  Short for {timeout,Time,Time}, that is, the time-out message
805                  is the time-out time. This form exists  to  make  the  state
806                  callback  return  value  {next_state,NextState,NewData,Time}
807                  allowed like for gen_fsm.
808
809                timeout:
810                  Sets the transition_option() event_timeout()  to  Time  with
811                  EventContent and time-out options Options.
812
813                {timeout,Name}:
814                  Sets  the  transition_option() generic_timeout() to Time for
815                  Name with EventContent and time-out options Options.
816
817                state_timeout:
818                  Sets the transition_option() state_timeout()  to  Time  with
819                  EventContent and time-out options Options.
820
821       timeout_cancel_action() =
822           {timeout, cancel} |
823           {{timeout, Name :: term()}, cancel} |
824           {state_timeout, cancel}
825
826              This  is  a  shorter and clearer form of  timeout_action()  with
827              Time = infinity which cancels a time-out.
828
829       timeout_update_action() =
830           {timeout, update, EventContent :: event_content()} |
831           {{timeout, Name :: term()},
832            update,
833            EventContent :: event_content()} |
834           {state_timeout, update, EventContent :: event_content()}
835
836              Updates a time-out with a  new  EventContent.  See   timeout_ac‐
837              tion()  for how to start a time-out.
838
839              If  no  time-out  of  the same type is active instead insert the
840              time-out event just like when starting a time-out with  relative
841              Time = 0.
842
843       reply_action() = {reply, From :: from(), Reply :: term()}
844
845              This  transition  action can be invoked by returning it from the
846              state callback, from  Module:init/1  or  by  giving  it  to  en‐
847              ter_loop/5,6.
848
849              It does not set any transition_option() but instead replies to a
850              caller waiting for a reply in call/2. From must be the term from
851              argument {call,From} in a call to a state callback.
852
853              Note that using this action from Module:init/1 or enter_loop/5,6
854              would be weird on the border of witchcraft since there has  been
855              no earlier call to a state callback in this server.
856
857       init_result(StateType) = init_result(StateType, term())
858
859       init_result(StateType, DataType) =
860           {ok, State :: StateType, Data :: DataType} |
861           {ok,
862            State :: StateType,
863            Data :: DataType,
864            Actions :: [action()] | action()} |
865           ignore |
866           {stop, Reason :: term()} |
867           {error, Reason :: term()}
868
869              For a succesful initialization, State is the initial state() and
870              Data the initial server data() of the gen_statem.
871
872              The Actions are executed when entering the first state  just  as
873              for  a state callback, except that the action postpone is forced
874              to false since there is no event to postpone.
875
876              For an unsuccesful initialization, {stop,Reason}, {error,Reason}
877              or ignore should be used; see start_link/3,4.
878
879              {error,Reason} was introduced in OTP 26.0.
880
881       state_enter_result(State) = state_enter_result(State, term())
882
883       state_enter_result(State, DataType) =
884           {next_state, State, NewData :: DataType} |
885           {next_state, State,
886            NewData :: DataType,
887            Actions :: [enter_action()] | enter_action()} |
888           state_callback_result(enter_action())
889
890              State  is  the  current state and it cannot be changed since the
891              state callback was called with a state enter call.
892
893                next_state:
894                  The gen_statem does a state transition to State,  which  has
895                  to  be the current state, sets NewData, and executes all Ac‐
896                  tions.
897
898       event_handler_result(StateType) =
899           event_handler_result(StateType, term())
900
901       event_handler_result(StateType, DataType) =
902           {next_state, NextState :: StateType, NewData :: DataType} |
903           {next_state,
904            NextState :: StateType,
905            NewData :: DataType,
906            Actions :: [action()] | action()} |
907           state_callback_result(action())
908
909              StateType is state_name() if callback mode  is  state_functions,
910              or state() if callback mode is handle_event_function.
911
912                next_state:
913                  The  gen_statem  does a state transition to NextState (which
914                  can be the same as the current state), sets NewData, and ex‐
915                  ecutes  all Actions. If NextState =/= CurrentState the state
916                  transition is a state change.
917
918       state_callback_result(ActionType) =
919           state_callback_result(ActionType, term())
920
921       state_callback_result(ActionType, DataType) =
922           {keep_state, NewData :: DataType} |
923           {keep_state,
924            NewData :: DataType,
925            Actions :: [ActionType] | ActionType} |
926           keep_state_and_data |
927           {keep_state_and_data, Actions :: [ActionType] | ActionType} |
928           {repeat_state, NewData :: DataType} |
929           {repeat_state,
930            NewData :: DataType,
931            Actions :: [ActionType] | ActionType} |
932           repeat_state_and_data |
933           {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
934           stop |
935           {stop, Reason :: term()} |
936           {stop, Reason :: term(), NewData :: DataType} |
937           {stop_and_reply,
938            Reason :: term(),
939            Replies :: [reply_action()] | reply_action()} |
940           {stop_and_reply,
941            Reason :: term(),
942            Replies :: [reply_action()] | reply_action(),
943            NewData :: DataType}
944
945              ActionType is enter_action() if the state  callback  was  called
946              with  a  state enter call and action() if the state callback was
947              called with an event.
948
949                keep_state:
950                  The same as {next_state,CurrentState,NewData,Actions}.
951
952                keep_state_and_data:
953                  The same as {keep_state,CurrentData,Actions}.
954
955                repeat_state:
956                  If the gen_statem runs with state enter calls, the state en‐
957                  ter  call  is  repeated, see type transition_option(), other
958                  than that repeat_state is the same as keep_state.
959
960                repeat_state_and_data:
961                  The same as {repeat_state,CurrentData,Actions}.
962
963                stop:
964                  Terminates the gen_statem by calling Module:terminate/3 with
965                  Reason  and  NewData, if specified. An exit signal with this
966                  reason is sent to linked processes and  ports.  The  default
967                  Reason is normal.
968
969                stop_and_reply:
970                  Sends all Replies, then terminates the gen_statem by calling
971                  Module:terminate/3 with Reason and NewData, if specified. An
972                  exit signal with this reason is sent to linked processes and
973                  ports.
974
975              All these terms are tuples or atoms and this property will  hold
976              in any future version of gen_statem.
977
978       request_id()
979
980              An opaque request identifier. See send_request/2 for details.
981
982       request_id_collection()
983
984              An opaque collection of request identifiers (request_id()) where
985              each request identifier can be associated with a label chosen by
986              the user. For more information see reqids_new/0.
987
988       response_timeout() = timeout() | {abs, integer()}
989
990              Used  to set a time limit on how long to wait for a response us‐
991              ing  either  receive_response/2,  receive_response/3,   wait_re‐
992              sponse/2, or wait_response/3. The time unit used is millisecond.
993              Currently valid values:
994
995                0..4294967295:
996                  Timeout relative to current time in milliseconds.
997
998                infinity:
999                  Infinite timeout. That is, the  operation  will  never  time
1000                  out.
1001
1002                {abs, Timeout}:
1003                  An  absolute  Erlang monotonic time timeout in milliseconds.
1004                  That is, the  operation  will  time  out  when  erlang:mono‐
1005                  tonic_time(millisecond) returns a value larger than or equal
1006                  to Timeout. Timeout is not allowed to identify a  time  fur‐
1007                  ther into the future than 4294967295 milliseconds. Identify‐
1008                  ing the timeout using an absolute  timeout  value  is  espe‐
1009                  cially  handy  when you have a deadline for responses corre‐
1010                  sponding  to  a  complete  collection   of   requests   (re‐
1011                  quest_id_collection())  ,  since you do not have to recalcu‐
1012                  late the relative time until  the  deadline  over  and  over
1013                  again.
1014
1015       format_status() =
1016           #{state => state(),
1017             data => data(),
1018             reason => term(),
1019             queue => [{event_type(), event_content()}],
1020             postponed => [{event_type(), event_content()}],
1021             timeouts => [{timeout_event_type(), event_content()}],
1022             log => [sys:system_event()]}
1023
1024              A map that describes the gen_statem status. The keys are:
1025
1026                state:
1027                  The current state of the gen_statem process.
1028
1029                data:
1030                  The state data of the the gen_statem process.
1031
1032                reason:
1033                  The reason that caused the state machine to terminate.
1034
1035                queue:
1036                  The event queue of the gen_statem process.
1037
1038                postponed:
1039                   The postponed events queue of the gen_statem process.
1040
1041                timeouts:
1042                   The active time-outs of the gen_statem process.
1043
1044                log:
1045                   The sys log of the server.
1046
1047              New  associations  may  be added to the status map without prior
1048              notice.
1049

EXPORTS

1051       call(ServerRef :: server_ref(), Request :: term()) ->
1052               Reply :: term()
1053
1054       call(ServerRef :: server_ref(),
1055            Request :: term(),
1056            Timeout ::
1057                timeout() |
1058                {clean_timeout, T :: timeout()} |
1059                {dirty_timeout, T :: timeout()}) ->
1060               Reply :: term()
1061
1062              Makes a synchronous call to the gen_statem ServerRef by  sending
1063              a  request  and  waiting until its reply arrives. The gen_statem
1064              calls the state callback with event_type() {call,From} and event
1065              content Request.
1066
1067              A  Reply  is  generated  when a state callback returns with {re‐
1068              ply,From,Reply} as one action(), and that Reply becomes the  re‐
1069              turn value of this function.
1070
1071              Timeout is an integer > 0, which specifies how many milliseconds
1072              to wait for a reply, or the atom infinity to wait  indefinitely,
1073              which  is the default. If no reply is received within the speci‐
1074              fied time, the function call fails.
1075
1076              Previous issue with late replies that could  occur  when  having
1077              network issues or using dirty_timeout is now prevented by use of
1078              process aliases .  {clean_timeout,  T}  and  {dirty_timeout,  T}
1079              therefore no longer serves any purpose and will work the same as
1080              Timeout while all of them also being equally efficient.
1081
1082              The call can also fail, for example, if the gen_statem dies  be‐
1083              fore or during this function call.
1084
1085              When this call fails it exits the calling process. The exit term
1086              is  on  the   form   {Reason,   Location}   where   Location   =
1087              {gen_statem,call,ArgList}.  See gen_server:call/3 that has a de‐
1088              scription of relevant values for the Reason in the exit term.
1089
1090       cast(ServerRef :: server_ref(), Msg :: term()) -> ok
1091
1092              Sends an asynchronous event to the gen_statem ServerRef and  re‐
1093              turns  ok  immediately,  ignoring  if  the  destination  node or
1094              gen_statem does not exist. The gen_statem calls the state  call‐
1095              back with event_type() cast and event content Msg.
1096
1097       check_response(Msg, ReqId) -> Result
1098
1099              Types:
1100
1101                 Msg = term()
1102                 ReqId = request_id()
1103                 Response =
1104                     {reply, Reply :: term()} |
1105                     {error, {Reason :: term(), server_ref()}}
1106                 Result = Response | no_reply
1107
1108              Check  if Msg is a response corresponding to the request identi‐
1109              fier ReqId. The request must have been made  by  send_request/2.
1110              If  Msg is a reply to the handle ReqId the result of the request
1111              is returned in Reply. Otherwise returns no_reply and no  cleanup
1112              is done, and thus the function shall be invoked repeatedly until
1113              a reply is returned.
1114
1115              The return value Reply is generated when a  state  callback  re‐
1116              turns  with  {reply,From,Reply}  as one action(), and that Reply
1117              becomes the return value of this function.
1118
1119              The function returns an error if the gen_statem dies  before  or
1120              during this request.
1121
1122       check_response(Msg, ReqIdCollection, Delete) -> Result
1123
1124              Types:
1125
1126                 Msg = term()
1127                 ReqIdCollection = request_id_collection()
1128                 Delete = boolean()
1129                 Response =
1130                     {reply, Reply :: term()} |
1131                     {error, {Reason :: term(), server_ref()}}
1132                 Result =
1133                     {Response,
1134                      Label :: term(),
1135                      NewReqIdCollection :: request_id_collection()} |
1136                     no_request | no_reply
1137
1138              Check if Msg is a response corresponding to a request identifier
1139              saved in ReqIdCollection. All request identifiers  of  ReqIdCol‐
1140              lection  must  correspond  to requests that have been made using
1141              send_request/2 or send_request/4, and  all  requests  must  have
1142              been made by the process calling this function.
1143
1144              The  Label  in the response equals the Label associated with the
1145              request identifier that the response corresponds to.  The  Label
1146              of a request identifier is associated when saving the request id
1147              in a request identifier collection, or when sending the  request
1148              using send_request/4.
1149
1150              Compared  to  check_response/2,  the  returned result associated
1151              with a specific request identifier or  an  exception  associated
1152              with a specific request identifier will be wrapped in a 3-tuple.
1153              The first element of this tuple equals the value that would have
1154              been produced by check_response/2, the second element equals the
1155              Label associated with the specific request identifier,  and  the
1156              third  element NewReqIdCollection is a possibly modified request
1157              identifier collection.
1158
1159              If ReqIdCollection is empty, the atom  no_request  will  be  re‐
1160              turned. If Msg does not correspond to any of the request identi‐
1161              fiers in ReqIdCollection, the atom no_reply is returned.
1162
1163              If Delete equals true, the association with Label will have been
1164              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1165              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1166              qIdCollection. Note that deleting an association is not for free
1167              and that a collection containing already  handled  requests  can
1168              still  be  used  by  subsequent  calls  to check_response/3, re‐
1169              ceive_response/3, and wait_response/3. However, without deleting
1170              handled associations, the above calls will not be able to detect
1171              when there are no more outstanding requests to  handle,  so  you
1172              will have to keep track of this some other way than relying on a
1173              no_request return. Note that if you pass a collection only  con‐
1174              taining associations of already handled or abandoned requests to
1175              check_response/3, it will always return no_reply.
1176
1177       enter_loop(Module :: module(),
1178                  Opts :: [enter_loop_opt()],
1179                  State :: state(),
1180                  Data :: data()) ->
1181                     no_return()
1182
1183              The same as enter_loop/6  with  Actions  =  []  except  that  no
1184              server_name()  must have been registered. This creates an anony‐
1185              mous server.
1186
1187       enter_loop(Module :: module(),
1188                  Opts :: [enter_loop_opt()],
1189                  State :: state(),
1190                  Data :: data(),
1191                  Server_or_Actions :: server_name() | pid() | [action()]) ->
1192                     no_return()
1193
1194              If Server_or_Actions is a list(), the same as  enter_loop/6  ex‐
1195              cept that no server_name() must have been registered and Actions
1196              = Server_or_Actions. This creates an anonymous server.
1197
1198              Otherwise the same as enter_loop/6 with Server  =  Server_or_Ac‐
1199              tions and Actions = [].
1200
1201       enter_loop(Module :: module(),
1202                  Opts :: [enter_loop_opt()],
1203                  State :: state(),
1204                  Data :: data(),
1205                  Server :: server_name() | pid(),
1206                  Actions :: [action()] | action()) ->
1207                     no_return()
1208
1209              Makes  the calling process become a gen_statem. Does not return,
1210              instead the calling process enters the gen_statem  receive  loop
1211              and  becomes  a  gen_statem  server.  The process must have been
1212              started using one of the start functions in proc_lib.  The  user
1213              is  responsible for any initialization of the process, including
1214              registering a name for it.
1215
1216              This function is useful when a more complex initialization  pro‐
1217              cedure is needed than the gen_statem behavior provides.
1218
1219              Module,   Opts   have   the   same   meaning   as  when  calling
1220              start[_link|_monitor]/3,4.
1221
1222              If Server is self() an anonymous server is created just as  when
1223              using  start[_link|_monitor]/3.  If  Server is a server_name() a
1224              named server is created just as  when  using  start[_link|_moni‐
1225              tor]/4.  However,  the  server_name() name must have been regis‐
1226              tered accordingly before this function is called.
1227
1228              State, Data, and Actions have the same meanings as in the return
1229              value  of Module:init/1. Also, the callback module does not need
1230              to export a Module:init/1 function.
1231
1232              The function fails if the calling process was not started  by  a
1233              proc_lib start function, or if it is not registered according to
1234              server_name().
1235
1236       receive_response(ReqId) -> Result
1237
1238              Types:
1239
1240                 ReqId = request_id()
1241                 Response =
1242                     {reply, Reply :: term()} |
1243                     {error, {Reason :: term(), server_ref()}}
1244                 Result = Response | timeout
1245
1246              The same as  calling  gen_statem:receive_response(ReqId,  infin‐
1247              ity).
1248
1249       receive_response(ReqId, Timeout) -> Result
1250
1251              Types:
1252
1253                 ReqId = request_id()
1254                 Timeout = response_timeout()
1255                 Response =
1256                     {reply, Reply :: term()} |
1257                     {error, {Reason :: term(), server_ref()}}
1258                 Result = Response | timeout
1259
1260              Receive  a  response corresponding to the request identifier Re‐
1261              qId- The request must have been made by  send_request/2  to  the
1262              gen_statem  process.  This function must be called from the same
1263              process from which send_request/2 was made.
1264
1265              Timeout specifies how long to wait for a  response.  If  no  re‐
1266              sponse  is  received within the specified time, the function re‐
1267              turns timeout. Assuming that the server executes on a node  sup‐
1268              porting  aliases (introduced in OTP 24) the request will also be
1269              abandoned. That is, no response will be received after  a  time‐
1270              out.  Otherwise,  a  stray response might be received at a later
1271              time.
1272
1273              The return value Reply is generated when a  state  callback  re‐
1274              turns  with  {reply,From,Reply}  as one action(), and that Reply
1275              becomes the return value of this function.
1276
1277              The function returns an error if the gen_statem dies  before  or
1278              during this function call.
1279
1280              The difference between wait_response/2 and receive_response/2 is
1281              that receive_response/2 abandons the request at timeout so  that
1282              a  potential  future  response is ignored, while wait_response/2
1283              does not.
1284
1285       receive_response(ReqIdCollection, Timeout, Delete) -> Result
1286
1287              Types:
1288
1289                 ReqIdCollection = request_id_collection()
1290                 Timeout = response_timeout()
1291                 Delete = boolean()
1292                 Response =
1293                     {reply, Reply :: term()} |
1294                     {error, {Reason :: term(), server_ref()}}
1295                 Result =
1296                     {Response,
1297                      Label :: term(),
1298                      NewReqIdCollection :: request_id_collection()} |
1299                     no_request | timeout
1300
1301              Receive a response corresponding to a request  identifier  saved
1302              in  ReqIdCollection.  All request identifiers of ReqIdCollection
1303              must correspond to requests that have been made  using  send_re‐
1304              quest/2  or send_request/4, and all requests must have been made
1305              by the process calling this function.
1306
1307              The Label in the response equals the Label associated  with  the
1308              request  identifier  that the response corresponds to. The Label
1309              of a request identifier is associated when adding the request id
1310              in  a request identifier collection, or when sending the request
1311              using send_request/4.
1312
1313              Compared to receive_response/2, the returned  result  associated
1314              with a specific request identifier will be wrapped in a 3-tuple.
1315              The first element of this tuple equals the value that would have
1316              been  produced  by receive_response/2, the second element equals
1317              the Label associated with the specific request  identifier,  and
1318              the  third element NewReqIdCollection is a possibly modified re‐
1319              quest identifier collection.
1320
1321              If ReqIdCollection is empty, the atom  no_request  will  be  re‐
1322              turned.
1323
1324              Timeout  specifies  how  long  to wait for a response. If no re‐
1325              sponse is received within the specified time, the  function  re‐
1326              turns  timeout. Assuming that the server executes on a node sup‐
1327              porting aliases (introduced in OTP 24) all  requests  identified
1328              by ReqIdCollection will also be abandoned. That is, no responses
1329              will be received after a  timeout.  Otherwise,  stray  responses
1330              might be received at a later time.
1331
1332              The difference between receive_response/3 and wait_response/3 is
1333              that receive_response/3 abandons the requests at timeout so that
1334              potential  future  responses  are ignored, while wait_response/3
1335              does not.
1336
1337              If Delete equals true, the association with Label will have been
1338              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1339              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1340              qIdCollection. Note that deleting an association is not for free
1341              and that a collection containing already  handled  requests  can
1342              still   be  used  by  subsequent  calls  to  receive_response/3,
1343              check_response/3, and wait_response/3. However, without deleting
1344              handled associations, the above calls will not be able to detect
1345              when there are no more outstanding requests to  handle,  so  you
1346              will have to keep track of this some other way than relying on a
1347              no_request return. Note that if you pass a collection only  con‐
1348              taining associations of already handled or abandoned requests to
1349              receive_response/3, it will always block until a timeout  deter‐
1350              mined by Timeout is triggered.
1351
1352       reply(Replies :: [reply_action()] | reply_action()) -> ok
1353
1354       reply(From :: from(), Reply :: term()) -> ok
1355
1356              This  function  can be used by a gen_statem to explicitly send a
1357              reply to a process that waits in call/2 when the reply cannot be
1358              defined in the return value of a state callback.
1359
1360              From  must  be  the  term from argument {call,From} to the state
1361              callback. A reply or multiple replies canalso be sent using  one
1362              or several reply_action()s from a state callback.
1363
1364          Note:
1365              A reply sent with this function is not visible in sys debug out‐
1366              put.
1367
1368
1369       reqids_add(ReqId :: request_id(),
1370                  Label :: term(),
1371                  ReqIdCollection :: request_id_collection()) ->
1372                     NewReqIdCollection :: request_id_collection()
1373
1374              Saves ReqId and associates a Label with the  request  identifier
1375              by  adding this information to ReqIdCollection and returning the
1376              resulting request identifier collection.
1377
1378       reqids_new() -> NewReqIdCollection :: request_id_collection()
1379
1380              Returns a new empty request  identifier  collection.  A  request
1381              identifier collection can be utilized in order the handle multi‐
1382              ple outstanding requests.
1383
1384              Request identifiers of requests made by  send_request/2  can  be
1385              saved  in  a  request  identifier collection using reqids_add/3.
1386              Such a collection of request identifiers can later  be  used  in
1387              order to get one response corresponding to a request in the col‐
1388              lection by passing the collection  as  argument  to  receive_re‐
1389              sponse/3, wait_response/3, or, check_response/3.
1390
1391              reqids_size/1  can  be  used  to determine the amount of request
1392              identifiers in a request identifier collection.
1393
1394       reqids_size(ReqIdCollection :: request_id_collection()) ->
1395                      integer() >= 0
1396
1397              Returns the amount of request identifiers saved in  ReqIdCollec‐
1398              tion.
1399
1400       reqids_to_list(ReqIdCollection :: request_id_collection()) ->
1401                         [{ReqId :: request_id(), Label :: term()}]
1402
1403              Returns a list of {ReqId, Label} tuples which corresponds to all
1404              request identifiers with their associated labels present in  the
1405              ReqIdCollection collection.
1406
1407       send_request(ServerRef :: server_ref(), Request :: term()) ->
1408                       ReqId :: request_id()
1409
1410              Sends  an  asynchronous  call  request Request to the gen_statem
1411              process identified by ServerRef and returns a request identifier
1412              ReqId.  The  return  value  ReqId  shall  later be used with re‐
1413              ceive_response/2, wait_response/2, or check_response/2 to  fetch
1414              the  actual  result  of the request. Besides passing the request
1415              identifier directly to these functions, it can also be saved  in
1416              a  request identifier collection using reqids_add/3. Such a col‐
1417              lection of request identifiers can later be used in order to get
1418              one  response  corresponding  to  a request in the collection by
1419              passing  the  collection  as  argument  to   receive_response/3,
1420              wait_response/3,  or  check_response/3. If you are about to save
1421              the request identifier in a request identifier  collection,  you
1422              may want to consider using send_request/4 instead.
1423
1424              The       call      gen_statem:wait_response(gen_statem:send_re‐
1425              quest(ServerRef,Request), Timeout) can be seen as equivalent  to
1426              gen_statem:call(Server,Request,Timeout), ignoring the error han‐
1427              dling.
1428
1429              The  gen_statem  calls  the  state  callback  with  event_type()
1430              {call,From} and event content Request.
1431
1432              A  Reply  is  generated  when a state callback returns with {re‐
1433              ply,From,Reply} as one action(), and that Reply becomes the  re‐
1434              turn   value   of  receive_response/1,2,  wait_response/1,2,  or
1435              check_response/2 function.
1436
1437       send_request(ServerRef :: server_ref(),
1438                    Request :: term(),
1439                    Label :: term(),
1440                    ReqIdCollection :: request_id_collection()) ->
1441                       NewReqIdCollection :: request_id_collection()
1442
1443              Sends an asynchronous call request  Request  to  the  gen_statem
1444              process  identified  by  ServerRef. The Label will be associated
1445              with the request identifier of the operation and  added  to  the
1446              returned  request  identifier collection NewReqIdCollection. The
1447              collection can later be used in order to get one response corre‐
1448              sponding  to  a request in the collection by passing the collec‐
1449              tion as argument  to  receive_response/3,  wait_response/3,  or,
1450              check_response/3.
1451
1452              The   same   as   calling  gen_statem:reqids_add(statem:send_re‐
1453              quest(ServerRef, Request), Label, ReqIdCollection), but  calling
1454              send_request/4 is slightly more efficient.
1455
1456       start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1457                start_ret()
1458
1459       start(ServerName :: server_name(),
1460             Module :: module(),
1461             Args :: term(),
1462             Opts :: [start_opt()]) ->
1463                start_ret()
1464
1465              Creates  a standalone gen_statem process according to OTP design
1466              principles (using proc_lib  primitives).  As  it  does  not  get
1467              linked  to  the  calling  process, this start function cannot be
1468              used by a supervisor to start a child.
1469
1470              For  a  description  of  arguments  and   return   values,   see
1471              start_link/3,4.
1472
1473       start_link(Module :: module(),
1474                  Args :: term(),
1475                  Opts :: [start_opt()]) ->
1476                     start_ret()
1477
1478       start_link(ServerName :: server_name(),
1479                  Module :: module(),
1480                  Args :: term(),
1481                  Opts :: [start_opt()]) ->
1482                     start_ret()
1483
1484              Creates  a gen_statem process according to OTP design principles
1485              (using proc_lib primitives) that is spawned  as  linked  to  the
1486              calling  process.  This is essential when the gen_statem must be
1487              part of a supervision tree so it gets linked to its supervisor.
1488
1489              The gen_statem process calls  Module:init/1  to  initialize  the
1490              server.    To   ensure   a   synchronized   startup   procedure,
1491              start_link/3,4 does not return until Module:init/1 has  returned
1492              or failed.
1493
1494              ServerName  specifies  the  server_name()  to  register  for the
1495              gen_statem process. If the gen_statem process  is  started  with
1496              start_link/3,  no  ServerName  is  provided  and  the gen_statem
1497              process is not registered.
1498
1499              Module is the name of the callback module.
1500
1501              Args is an arbitrary term that is passed as the argument to Mod‐
1502              ule:init/1.
1503
1504                * If  option {timeout,Time} is present in Opts, the gen_statem
1505                  process is allowed to spend Time  milliseconds  initializing
1506                  or  it  is  terminated  and  the start function returns {er‐
1507                  ror,timeout}.
1508
1509                * If   option    {hibernate_after,HibernateAfterTimeout}    is
1510                  present,  the  gen_statem process awaits any message for Hi‐
1511                  bernateAfterTimeout milliseconds and if no  message  is  re‐
1512                  ceived,  the process goes into hibernation automatically (by
1513                  calling proc_lib:hibernate/3).
1514
1515                * If option {debug,Dbgs} is present in Opts, debugging through
1516                  sys is activated.
1517
1518                * If   option   {spawn_opt,SpawnOpts}   is  present  in  Opts,
1519                  SpawnOpts is passed as option  list  to  erlang:spawn_opt/2,
1520                  which is used to spawn the gen_statem process.
1521
1522          Note:
1523              Using  spawn option monitor is not allowed, it causes this func‐
1524              tion to fail with reason badarg.
1525
1526
1527              If the gen_statem process is successfully created  and  initial‐
1528              ized,  this function returns {ok,Pid}, where Pid is the pid() of
1529              the gen_statem process. If a process with the specified  Server‐
1530              Name   exists   already,   this   function  returns  {error,{al‐
1531              ready_started,OtherPid}}, where OtherPid is the  pid()  of  that
1532              process, and the gen_statem process exits with reason normal be‐
1533              fore calling Module:init/1.
1534
1535              If Module:init/1 does not return within the start  timeout,  the
1536              gen_statem  process is killed with exit(_, kill), and this func‐
1537              tion returns {error,timeout}.
1538
1539              This function returns {error,Reason}  if  Module:init/1  returns
1540              {stop,Reason}  or  {error,Reason},  or fails with reason Reason.
1541              This function returns ignore if Module:init/1 returns ignore. In
1542              these cases the gen_statem process exits with reason Reason, ex‐
1543              cept when Module:init/1 returns ignore or  {error,_};  then  the
1544              gen_statem process exits with reason normal.
1545
1546              If  start_link/3,4  returns  ignore  or  {error,_},  the started
1547              gen_statem process has terminated. If an 'EXIT' message was  de‐
1548              livered  to  the calling process (due to the process link), that
1549              message has been consumed.
1550
1551          Warning:
1552              Before OTP 26.0, if the started gen_statem process returned e.g.
1553              {stop,Reason}  from  Module:init/1,  this  function could return
1554              {error,Reason} before the started gen_statem process had  termi‐
1555              nated  so starting again might fail because VM resources such as
1556              the registered name was not yet unregistered, and an 'EXIT' mes‐
1557              sage could arrive later to the process calling this function.
1558
1559              But if the started gen_statem process instead failed during Mod‐
1560              ule:init/1, a process link  {'EXIT',Pid,Reason}  message  caused
1561              this function to return {error,Reason} so the 'EXIT' message had
1562              been consumed and the started gen_statem process had terminated.
1563
1564              Since it was impossible to tell the difference between these two
1565              cases from start_link/3,4's return value, this inconsistency was
1566              cleaned up in OTP 26.0.
1567
1568
1569              The difference between returning  {stop,_}  and  {error,_}  from
1570              Module:init/1,   is   that   {error,_}  results  in  a  graceful
1571              ("silent") termination since the gen_statem process  exits  with
1572              reason normal.
1573
1574       start_monitor(Module :: module(),
1575                     Args :: term(),
1576                     Opts :: [start_opt()]) ->
1577                        start_mon_ret()
1578
1579       start_monitor(ServerName :: server_name(),
1580                     Module :: module(),
1581                     Args :: term(),
1582                     Opts :: [start_opt()]) ->
1583                        start_mon_ret()
1584
1585              Creates  a standalone gen_statem process according to OTP design
1586              principles (using proc_lib primitives) and atomically sets up  a
1587              monitor  to the newly created process. As it does not get linked
1588              to the calling process, this start function cannot be used by  a
1589              supervisor to start a child.
1590
1591              For   a   description   of  arguments  and  return  values,  see
1592              start_link/3,4. Note that the return value on  successful  start
1593              differs   from  start_link/3,4.  start_monitor/3,4  will  return
1594              {ok,{Pid,Mon}} where  Pid  is  the  process  identifier  of  the
1595              process, and Mon is a reference to the monitor set up to monitor
1596              the process. If the start is not successful, the caller will  be
1597              blocked  until  the  DOWN  message has been received and removed
1598              from the message queue.
1599
1600       stop(ServerRef :: server_ref()) -> ok
1601
1602              The same as stop(ServerRef, normal, infinity).
1603
1604       stop(ServerRef :: server_ref(),
1605            Reason :: term(),
1606            Timeout :: timeout()) ->
1607               ok
1608
1609              Orders the gen_statem ServerRef to exit with the specified  Rea‐
1610              son  and  waits  for  it to terminate. The gen_statem calls Mod‐
1611              ule:terminate/3 before exiting.
1612
1613              This function returns ok if the server terminates with  the  ex‐
1614              pected reason. Any other reason than normal, shutdown, or {shut‐
1615              down,Term} causes an error report  to  be  issued  through  log‐
1616              ger(3).  An  exit  signal with the same reason is sent to linked
1617              processes and ports. The default Reason is normal.
1618
1619              Timeout is an integer > 0, which specifies how many milliseconds
1620              to  wait  for  the  server to terminate, or the atom infinity to
1621              wait indefinitely. Defaults to infinity. If the server does  not
1622              terminate  within the specified time, the call exits the calling
1623              process with reason timeout.
1624
1625              If the process does  not  exist,  the  call  exits  the  calling
1626              process  with  reason noproc, and with reason {nodedown,Node} if
1627              the connection fails to the remote Node where the server runs.
1628
1629       wait_response(ReqId) -> Result
1630
1631              Types:
1632
1633                 ReqId = request_id()
1634                 Response =
1635                     {reply, Reply :: term()} |
1636                     {error, {Reason :: term(), server_ref()}}
1637                 Result = Response | timeout
1638
1639              The same as  calling  gen_statem:receive_response(ReqId,  infin‐
1640              ity).
1641
1642       wait_response(ReqId, WaitTime) -> Result
1643
1644              Types:
1645
1646                 ReqId = request_id()
1647                 WaitTime = response_timeout()
1648                 Response =
1649                     {reply, Reply :: term()} |
1650                     {error, {Reason :: term(), server_ref()}}
1651                 Result = Response | timeout
1652
1653              Wait  for a response corresponding to the request identifier Re‐
1654              qId. The request must have been made by  send_request/2  to  the
1655              gen_statem  process.  This function must be called from the same
1656              process from which send_request/2 was made.
1657
1658              WaitTime specifies how long to wait for a reply. If no reply  is
1659              received within the specified time, the function returns timeout
1660              and no cleanup is done, and thus the function can be invoked re‐
1661              peatedly until a reply is returned.
1662
1663              The  return  value  Reply is generated when a state callback re‐
1664              turns with {reply,From,Reply} as one action(),  and  that  Reply
1665              becomes the return value of this function.
1666
1667              The  function  returns an error if the gen_statem dies before or
1668              during this function call.
1669
1670              The difference between receive_response/2 and wait_response/2 is
1671              that  receive_response/2 abandons the request at timeout so that
1672              a potential future response is  ignored,  while  wait_response/2
1673              does not.
1674
1675       wait_response(ReqIdCollection, WaitTime, Delete) -> Result
1676
1677              Types:
1678
1679                 ReqIdCollection = request_id_collection()
1680                 WaitTime = response_timeout()
1681                 Delete = boolean()
1682                 Response =
1683                     {reply, Reply :: term()} |
1684                     {error, {Reason :: term(), server_ref()}}
1685                 Result =
1686                     {Response,
1687                      Label :: term(),
1688                      NewReqIdCollection :: request_id_collection()} |
1689                     no_request | timeout
1690
1691              Wait  for a response corresponding to a request identifier saved
1692              in ReqIdCollection. All request identifiers  of  ReqIdCollection
1693              must  correspond  to requests that have been made using send_re‐
1694              quest/2 or send_request/4, and all requests must have been  made
1695              by the process calling this function.
1696
1697              The  Label  in the response equals the Label associated with the
1698              request identifier that the response corresponds to.  The  Label
1699              of a request identifier is associated when saving the request id
1700              in a request identifier collection, or when sending the  request
1701              using send_request/4.
1702
1703              Compared to wait_response/2, the returned result associated with
1704              a specific request identifier or an exception associated with  a
1705              specific  request  identifier  will be wrapped in a 3-tuple. The
1706              first element of this tuple equals the  value  that  would  have
1707              been  produced by wait_response/2, the second element equals the
1708              Label associated with the specific request identifier,  and  the
1709              third  element NewReqIdCollection is a possibly modified request
1710              identifier collection.
1711
1712              If ReqIdCollection is empty, no_request will be returned. If  no
1713              response  is received before the WaitTime timeout has triggered,
1714              the atom timeout is returned. It is valid  to  continue  waiting
1715              for  a  response as many times as needed up until a response has
1716              been received and  completed  by  check_response(),  receive_re‐
1717              sponse(), or wait_response().
1718
1719              The difference between receive_response/3 and wait_response/3 is
1720              that receive_response/3 abandons requests at timeout so that po‐
1721              tential future responses are ignored, while wait_response/3 does
1722              not.
1723
1724              If Delete equals true, the association with Label will have been
1725              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1726              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1727              qIdCollection. Note that deleting an association is not for free
1728              and that a collection containing already  handled  requests  can
1729              still  be used by subsequent calls to wait_response/3, check_re‐
1730              sponse/3, and receive_response/3. However, without deleting han‐
1731              dled  associations,  the  above calls will not be able to detect
1732              when there are no more outstanding requests to  handle,  so  you
1733              will have to keep track of this some other way than relying on a
1734              no_request return. Note that if you pass a collection only  con‐
1735              taining associations of already handled or abandoned requests to
1736              wait_response/3, it will always block until a timeout determined
1737              by WaitTime is triggered and then return no_reply.
1738

CALLBACK FUNCTIONS

1740       The  following  functions are to be exported from a gen_statem callback
1741       module.
1742

EXPORTS

1744       Module:callback_mode() -> CallbackMode
1745
1746              Types:
1747
1748                  CallbackMode  =  callback_mode()  |  [   callback_mode()   |
1749                 state_enter() ]
1750
1751              This  function  is  called by a gen_statem when it needs to find
1752              out the callback mode of  the  callback  module.  The  value  is
1753              cached by gen_statem for efficiency reasons, so this function is
1754              only called once after server start, after code change, and  af‐
1755              ter  changing  the  callback  module, but before the first state
1756              callback in  the  current  callback  module's  code  version  is
1757              called.  More  occasions  may  be  added  in  future versions of
1758              gen_statem.
1759
1760              Server start happens either when Module:init/1 returns  or  when
1761              enter_loop/4-6   is   called.  Code  change  happens  when  Mod‐
1762              ule:code_change/4 returns. A change of the callback module  hap‐
1763              pens   when   a  state  callback  returns  any  of  the  actions
1764              change_callback_module,   push_callback_module   or    pop_call‐
1765              back_module.
1766
1767              The  CallbackMode  is either just callback_mode() or a list con‐
1768              taining callback_mode() and possibly the atom state_enter.
1769
1770          Note:
1771              If this function's body does not return an inline constant value
1772              the callback module is doing something strange.
1773
1774
1775       Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1776
1777              Types:
1778
1779                 OldVsn = Vsn | {down,Vsn}
1780                  Vsn = term()
1781                 OldState = NewState = term()
1782                 Extra = term()
1783                 Result = {ok,NewState,NewData} | Reason
1784                  OldState = NewState = state()
1785                  OldData = NewData = data()
1786                 Reason = term()
1787
1788          Note:
1789              This  callback  is optional, so callback modules need not export
1790              it. If a release upgrade/downgrade with Change  =  {advanced,Ex‐
1791              tra}  specified in the .appup file is made when code_change/4 is
1792              not implemented the process will crash with exit reason undef.
1793
1794
1795              This function is called by a gen_statem when it is to update its
1796              internal state during a release upgrade/downgrade, that is, when
1797              the instruction {update,Module,Change,...}, where Change =  {ad‐
1798              vanced,Extra}, is specified in the appup file. For more informa‐
1799              tion, see OTP Design Principles.
1800
1801              For an upgrade, OldVsn is Vsn, and for a  downgrade,  OldVsn  is
1802              {down,Vsn}.  Vsn  is  defined by the vsn attribute(s) of the old
1803              version of the callback module Module. If no such  attribute  is
1804              defined, the version is the checksum of the Beam file.
1805
1806              OldState and OldData is the internal state of the gen_statem.
1807
1808              Extra  is  passed  "as is" from the {advanced,Extra} part of the
1809              update instruction.
1810
1811              If successful, the function must  return  the  updated  internal
1812              state in an {ok,NewState,NewData} tuple.
1813
1814              If  the  function  returns a failure Reason, the ongoing upgrade
1815              fails and rolls back to the old release. Note that Reason cannot
1816              be  an  {ok,_,_} tuple since that will be regarded as a {ok,New‐
1817              State,NewData} tuple, and that a tuple  matching  {ok,_}  is  an
1818              also invalid failure Reason. It is recommended to use an atom as
1819              Reason since it will be wrapped in an {error,Reason} tuple.
1820
1821              Also note when upgrading a gen_statem, this function  and  hence
1822              the Change = {advanced,Extra} parameter in the appup file is not
1823              only needed to update the internal state or to act on the  Extra
1824              argument.  It  is  also needed if an upgrade or downgrade should
1825              change callback mode, or else the callback mode after  the  code
1826              change  will  not  be  honoured,  most probably causing a server
1827              crash.
1828
1829              If the server changes callback module using any of  the  actions
1830              change_callback_module,    push_callback_module   or   pop_call‐
1831              back_module, be aware that it is  always  the  current  callback
1832              module  that will get this callback call. That the current call‐
1833              back module handles the current state and data update should  be
1834              no  surprise,  but  it  must be able to handle even parts of the
1835              state and data that it is not familiar with, somehow.
1836
1837              In the supervisor child specification there is a list of modules
1838              which  is recommended to contain only the callback module. For a
1839              gen_statem with multiple callback modules there is no real  need
1840              to  list all of them, it may not even be possible since the list
1841              could change after code upgrade. If this list would contain only
1842              the  start callback module, as recommended, what is important is
1843              to upgrade that module whenever a synchronized code  replacement
1844              is done. Then the release handler concludes that an upgrade that
1845              upgrades that module needs to suspend, code change,  and  resume
1846              any  server  whose child specification declares that it is using
1847              that module. And again; the current callback module will get the
1848              Module:code_change/4 call.
1849
1850       Module:init(Args) -> Result(StateType)
1851
1852              Types:
1853
1854                 Args = term()
1855                  Result(StateType) = init_result(StateType)
1856
1857              Whenever   a   gen_statem   is   started  using  start_link/3,4,
1858              start_monitor/3,4, or start/3,4, this function is called by  the
1859              new  process  to  initialize the implementation state and server
1860              data.
1861
1862              Args is the Args argument provided to that start function.
1863
1864          Note:
1865              Note that if the gen_statem is started through proc_lib and  en‐
1866              ter_loop/4-6,  this  callback  will  never be called. Since this
1867              callback is not optional it can in that case be implemented as:
1868
1869              -spec init(_) -> no_return().
1870              init(Args) -> erlang:error(not_implemented, [Args]).
1871
1872
1873       Module:format_status(Status) -> NewStatus
1874
1875              Types:
1876
1877                 Status = format_status()
1878                 NewStatus = format_status()
1879
1880          Note:
1881              This callback is optional, so a callback module does not need to
1882              export  it. The gen_statem module provides a default implementa‐
1883              tion of this function that returns {State,Data}.
1884
1885              If this callback is exported but fails, to hide possibly  sensi‐
1886              tive   data,   the   default   function   will   instead  return
1887              {State,Info}, where Info says nothing but  the  fact  that  for‐
1888              mat_status/2 has crashed.
1889
1890
1891              This  function is called by a gen_statem process when any of the
1892              following apply:
1893
1894                * sys:get_status/1,2 is invoked to get the gen_statem status.
1895
1896                * The gen_statem process terminates abnormally and logs an er‐
1897                  ror.
1898
1899              This  function is useful for changing the form and appearance of
1900              the gen_statem status for these cases. A callback module wishing
1901              to change the sys:get_status/1,2 return value and how its status
1902              appears in termination error logs exports an  instance  of  for‐
1903              mat_status/1,  which  will  get  a map Status that describes the
1904              current states of the gen_statem, and shall return a map NewSta‐
1905              tus containing the same keys as the input map, but it may trans‐
1906              form some values.
1907
1908              One use case for this function is to return compact  alternative
1909              state  representations to avoid having large state terms printed
1910              in log files. Another is to hide sensitive data from being writ‐
1911              ten to the error log.
1912
1913              Example:
1914
1915              format_status(Status) ->
1916                maps:map(
1917                  fun(state,State) ->
1918                          maps:remove(private_key, State);
1919                     (message,{password, _Pass}) ->
1920                          {password, removed};
1921                     (_,Value) ->
1922                          Value
1923                  end, Status).
1924
1925
1926       Module:format_status(Opt, [PDict,State,Data]) -> Status
1927
1928              Types:
1929
1930                 Opt = normal | terminate
1931                 PDict = [{Key, Value}]
1932                  State = state()
1933                  Data = data()
1934                 Key = term()
1935                 Value = term()
1936                 Status = term()
1937
1938          Warning:
1939              This  callback  is deprecated, in new code use  format_status/1.
1940              If a format_status/1 callback exists, then  this  function  will
1941              never be called.
1942
1943
1944          Note:
1945              This callback is optional, so a callback module does not need to
1946              export it. The gen_statem module provides a default  implementa‐
1947              tion of this function that returns {State,Data}.
1948
1949              If  this callback is exported but fails, to hide possibly sensi‐
1950              tive  data,   the   default   function   will   instead   return
1951              {State,Info},  where  Info  says  nothing but the fact that for‐
1952              mat_status/2 has crashed.
1953
1954
1955              This function is called by a gen_statem process when any of  the
1956              following apply:
1957
1958                *
1959                   One  of sys:get_status/1,2 is invoked to get the gen_statem
1960                  status. Opt is set to the atom normal for this case.
1961
1962                *
1963                   The gen_statem terminates abnormally and logs an error. Opt
1964                  is set to the atom terminate for this case.
1965
1966              This  function is useful for changing the form and appearance of
1967              the gen_statem status for these cases. A callback module wishing
1968              to change the sys:get_status/1,2 return value and how its status
1969              appears in termination error logs exports an  instance  of  for‐
1970              mat_status/2, which returns a term describing the current status
1971              of the gen_statem.
1972
1973              PDict is the current value of  the  process  dictionary  of  the
1974              gen_statem.
1975
1976              State is the internal state of the gen_statem.
1977
1978              Data is the internal server data of the gen_statem.
1979
1980              The  function  is to return Status, a term that contains the ap‐
1981              propriate details  of  the  current  state  and  status  of  the
1982              gen_statem.  There  are  no  restrictions on the form Status can
1983              take, but for the sys:get_status/1,2 case (when Opt is  normal),
1984              the  recommended form for the Status value is [{data, [{"State",
1985              Term}]}], where Term provides relevant details of the gen_statem
1986              state.  Following  this  recommendation  is not required, but it
1987              makes the callback module status consistent with the rest of the
1988              sys:get_status/1,2 return value.
1989
1990              One use for this function is to return compact alternative state
1991              representations to avoid having large state terms printed in log
1992              files.  Another use is to hide sensitive data from being written
1993              to the error log.
1994
1995       Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1996       Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1997       Module:handle_event(enter,  OldState,  State,  Data)  ->  StateEnterRe‐
1998       sult(State)
1999       Module:handle_event(EventType,   EventContent,  State,  Data)  ->  Han‐
2000       dleEventResult
2001
2002              Types:
2003
2004                  EventType = event_type()
2005                 EventContent = term()
2006                  State = state()
2007                  Data = NewData = data()
2008                  StateEnterResult(StateName) = state_enter_result(StateName)
2009                  StateFunctionResult = event_handler_result(state_name())
2010                  StateEnterResult(State) = state_enter_result(State)
2011                  HandleEventResult = event_handler_result(state())
2012
2013              Whenever a gen_statem receives an event from call/2, cast/2,  or
2014              as  a  normal process message, one of these functions is called.
2015              If  callback  mode  is  state_functions,  Module:StateName/3  is
2016              called,   and   if   it  is  handle_event_function,  Module:han‐
2017              dle_event/4 is called.
2018
2019              If EventType is {call,From}, the caller waits for a  reply.  The
2020              reply  can be sent from this or from any other state callback by
2021              returning with {reply,From,Reply} in Actions, in Replies, or  by
2022              calling reply(From, Reply).
2023
2024              If  this  function returns with a next state that does not match
2025              equal (=/=) to the current state, all postponed events  are  re‐
2026              tried in the next state.
2027
2028              The  only difference between StateFunctionResult and HandleEven‐
2029              tResult is that for StateFunctionResult the next state  must  be
2030              an  atom,  but  for HandleEventResult there is no restriction on
2031              the next state.
2032
2033              For options that can be set and actions  that  can  be  done  by
2034              gen_statem after returning from this function, see action().
2035
2036              When the gen_statem runs with state enter calls, these functions
2037              are also called with arguments (enter, OldState, ...) during ev‐
2038              ery  state  change.  In this case there are some restrictions on
2039              the actions that may be  returned:  postpone()  is  not  allowed
2040              since a state enter call is not an event so there is no event to
2041              postpone, and {next_event,_,_} is not allowed since using  state
2042              enter  calls  should not affect how events are consumed and pro‐
2043              duced. You may also not change states from this call. Should you
2044              return  {next_state,NextState, ...} with NextState =/= State the
2045              gen_statem crashes. Note that it is actually allowed to use {re‐
2046              peat_state,  NewData,  ...} although it makes little sense since
2047              you immediately will be called again with a new state enter call
2048              making  this  just  a weird way of looping, and there are better
2049              ways to loop in Erlang. If you do not update  NewData  and  have
2050              some   loop   termination   condition,   or   if  you  use  {re‐
2051              peat_state_and_data, _} or repeat_state_and_data you have an in‐
2052              finite   loop!   You   are   advised  to  use  {keep_state,...},
2053              {keep_state_and_data,_} or  keep_state_and_data  since  changing
2054              states from a state enter call is not possible anyway.
2055
2056              Note the fact that you can use throw to return the result, which
2057              can   be   useful.   For    example    to    bail    out    with
2058              throw(keep_state_and_data)  from  deep  within complex code that
2059              cannot return {next_state,State,Data} because State or  Data  is
2060              no longer in scope.
2061
2062       Module:terminate(Reason, State, Data) -> Ignored
2063
2064              Types:
2065
2066                 Reason = normal | shutdown | {shutdown,term()} | term()
2067                 State = state()
2068                 Data = data()
2069                 Ignored = term()
2070
2071          Note:
2072              This  callback  is optional, so callback modules need not export
2073              it. The gen_statem  module  provides  a  default  implementation
2074              without cleanup.
2075
2076
2077              This function is called by a gen_statem when it is about to ter‐
2078              minate. It is to be the opposite of  Module:init/1  and  do  any
2079              necessary  cleaning  up.  When it returns, the gen_statem termi‐
2080              nates with Reason. The return value is ignored.
2081
2082              Reason is a term denoting the stop reason and State is  the  in‐
2083              ternal state of the gen_statem.
2084
2085              Reason  depends  on  why the gen_statem is terminating. If it is
2086              because another callback function has  returned,  a  stop  tuple
2087              {stop,Reason} in Actions, Reason has the value specified in that
2088              tuple. If it is because of a failure, Reason is the  error  rea‐
2089              son.
2090
2091              If  the  gen_statem is part of a supervision tree and is ordered
2092              by its supervisor to terminate, this  function  is  called  with
2093              Reason = shutdown if both the following conditions apply:
2094
2095                * The gen_statem has been set to trap exit signals.
2096
2097                * The  shutdown  strategy as defined in the supervisor's child
2098                  specification is an integer time-out value, not brutal_kill.
2099
2100              Even if the gen_statem is not part of a supervision  tree,  this
2101              function  is  called  if  it receives an 'EXIT' message from its
2102              parent. Reason is the same as in the 'EXIT' message.
2103
2104              Otherwise, the gen_statem is immediately terminated.
2105
2106              Notice that for any  other  reason  than  normal,  shutdown,  or
2107              {shutdown,Term},  the gen_statem is assumed to terminate because
2108              of an error and an error report is issued using logger(3).
2109
2110              When the gen_statem process exits, an exit signal with the  same
2111              reason is sent to linked processes and ports.
2112

SEE ALSO

2114       gen_event(3),  gen_fsm(3),  gen_server(3),  proc_lib(3), supervisor(3),
2115       sys(3).
2116
2117
2118
2119Ericsson AB                      stdlib 5.1.1                    gen_statem(3)
Impressum