1gen_statem(3) Erlang Module Definition gen_statem(3)
2
3
4
6 gen_statem - Generic state machine behavior.
7
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
219 The following example shows a simple pushbutton model for a toggling
220 pushbutton implemented with callback mode state_functions. You can push
221 the button and it replies if it went on or off, and you can ask for a
222 count of how many times it has been pushed to switch on.
223
224 The following is the complete callback module file pushbutton.erl:
225
226 -module(pushbutton).
227 -behaviour(gen_statem).
228
229 -export([start/0,push/0,get_count/0,stop/0]).
230 -export([terminate/3,code_change/4,init/1,callback_mode/0]).
231 -export([on/3,off/3]).
232
233 name() -> pushbutton_statem. % The registered server name
234
235 %% API. This example uses a registered name name()
236 %% and does not link to the caller.
237 start() ->
238 gen_statem:start({local,name()}, ?MODULE, [], []).
239 push() ->
240 gen_statem:call(name(), push).
241 get_count() ->
242 gen_statem:call(name(), get_count).
243 stop() ->
244 gen_statem:stop(name()).
245
246 %% Mandatory callback functions
247 terminate(_Reason, _State, _Data) ->
248 void.
249 code_change(_Vsn, State, Data, _Extra) ->
250 {ok,State,Data}.
251 init([]) ->
252 %% Set the initial state + data. Data is used only as a counter.
253 State = off, Data = 0,
254 {ok,State,Data}.
255 callback_mode() -> state_functions.
256
257 %%% state callback(s)
258
259 off({call,From}, push, Data) ->
260 %% Go to 'on', increment count and reply
261 %% that the resulting status is 'on'
262 {next_state,on,Data+1,[{reply,From,on}]};
263 off(EventType, EventContent, Data) ->
264 handle_event(EventType, EventContent, Data).
265
266 on({call,From}, push, Data) ->
267 %% Go to 'off' and reply that the resulting status is 'off'
268 {next_state,off,Data,[{reply,From,off}]};
269 on(EventType, EventContent, Data) ->
270 handle_event(EventType, EventContent, Data).
271
272 %% Handle events common to all states
273 handle_event({call,From}, get_count, Data) ->
274 %% Reply with the current count
275 {keep_state,Data,[{reply,From,Data}]};
276 handle_event(_, _, Data) ->
277 %% Ignore all other events
278 {keep_state,Data}.
279
280
281 The following is a shell session when running it:
282
283 1> pushbutton:start().
284 {ok,<0.36.0>}
285 2> pushbutton:get_count().
286 0
287 3> pushbutton:push().
288 on
289 4> pushbutton:get_count().
290 1
291 5> pushbutton:push().
292 off
293 6> pushbutton:get_count().
294 1
295 7> pushbutton:stop().
296 ok
297 8> pushbutton:push().
298 ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
299 in function gen:do_for_proc/2 (gen.erl, line 261)
300 in call from gen_statem:call/3 (gen_statem.erl, line 386)
301
302
303 To compare styles, here follows the same example using callback mode
304 handle_event_function, or rather the code to replace after function
305 init/1 of the pushbutton.erl example file above:
306
307 callback_mode() -> handle_event_function.
308
309 %%% state callback(s)
310
311 handle_event({call,From}, push, off, Data) ->
312 %% Go to 'on', increment count and reply
313 %% that the resulting status is 'on'
314 {next_state,on,Data+1,[{reply,From,on}]};
315 handle_event({call,From}, push, on, Data) ->
316 %% Go to 'off' and reply that the resulting status is 'off'
317 {next_state,off,Data,[{reply,From,off}]};
318 %%
319 %% Event handling common to all states
320 handle_event({call,From}, get_count, State, Data) ->
321 %% Reply with the current count
322 {next_state,State,Data,[{reply,From,Data}]};
323 handle_event(_, _, State, Data) ->
324 %% Ignore all other events
325 {next_state,State,Data}.
326
327
329 server_name() =
330 {global, GlobalName :: term()} |
331 {via, RegMod :: module(), Name :: term()} |
332 {local, atom()}
333
334 Name specification to use when starting a gen_statem server. See
335 start_link/3 and server_ref() below.
336
337 server_ref() =
338 pid() |
339 (LocalName :: atom()) |
340 {Name :: atom(), Node :: atom()} |
341 {global, GlobalName :: term()} |
342 {via, RegMod :: module(), ViaName :: term()}
343
344 Server specification to use when addressing a gen_statem server.
345 See call/2 and server_name() above.
346
347 It can be:
348
349 pid() | LocalName:
350 The gen_statem is locally registered.
351
352 {Name,Node}:
353 The gen_statem is locally registered on another node.
354
355 {global,GlobalName}:
356 The gen_statem is globally registered in global.
357
358 {via,RegMod,ViaName}:
359 The gen_statem is registered in an alternative process reg‐
360 istry. The registry callback module RegMod is to export
361 functions register_name/2, unregister_name/1,
362 whereis_name/1, and send/2, which are to behave like the
363 corresponding functions in global. Thus, {via,global,Global‐
364 Name} is the same as {global,GlobalName}.
365
366 start_opt() =
367 {timeout, Time :: timeout()} |
368 {spawn_opt, [proc_lib:start_spawn_option()]} |
369 enter_loop_opt()
370
371 Options that can be used when starting a gen_statem server
372 through, for example, start_link/3.
373
374 start_ret() = {ok, pid()} | ignore | {error, term()}
375
376 Return value from the start() and start_link() functions, for
377 example, start_link/3.
378
379 start_mon_ret() =
380 {ok, {pid(), reference()}} | ignore | {error, term()}
381
382 Return value from the start_monitor() functions.
383
384 enter_loop_opt() =
385 {hibernate_after, HibernateAfterTimeout :: timeout()} |
386 {debug, Dbgs :: [sys:debug_option()]}
387
388 Options that can be used when starting a gen_statem server
389 through, enter_loop/4-6.
390
391 hibernate_after:
392 HibernateAfterTimeout specifies that the gen_statem process
393 awaits any message for HibernateAfterTimeout milliseconds
394 and if no message is received, the process goes into hiber‐
395 nation automatically (by calling proc_lib:hibernate/3).
396
397 debug:
398 For every entry in Dbgs, the corresponding function in sys
399 is called.
400
401 from() = {To :: pid(), Tag :: term()}
402
403 Destination to use when replying through, for example, the ac‐
404 tion() {reply,From,Reply} to a process that has called the
405 gen_statem server using call/2.
406
407 state() = state_name() | term()
408
409 If the callback mode is handle_event_function, the state can be
410 any term. After a state change (NextState =/= State), all post‐
411 poned events are retried.
412
413 state_name() = atom()
414
415 If the callback mode is state_functions, the state must be an
416 atom. After a state change (NextState =/= State), all postponed
417 events are retried. Note that the state terminate is not possi‐
418 ble to use since it would collide with the optional callback
419 function Module:terminate/3.
420
421 data() = term()
422
423 A term in which the state machine implementation is to store any
424 server data it needs. The difference between this and the
425 state() itself is that a change in this data does not cause
426 postponed events to be retried. Hence, if a change in this data
427 would change the set of events that are handled, then that data
428 item is to be made a part of the state.
429
430 event_type() =
431 external_event_type() | timeout_event_type() | internal
432
433 There are 3 categories of events: external, timeout, and inter‐
434 nal.
435
436 internal events can only be generated by the state machine it‐
437 self through the transition action next_event.
438
439 external_event_type() = {call, From :: from()} | cast | info
440
441 External events are of 3 types: {call,From}, cast, or info. Type
442 call originates from the API functions call/2 and send_re‐
443 quest/2. For calls, the event contains whom to reply to. Type
444 cast originates from the API function cast/2. Type info origi‐
445 nates from regular process messages sent to the gen_statem.
446
447 timeout_event_type() =
448 timeout | {timeout, Name :: term()} | state_timeout
449
450 There are 3 types of time-out events that the state machine can
451 generate for itself with the corresponding timeout_action()s.
452
453 callback_mode_result() =
454 callback_mode() | [callback_mode() | state_enter()]
455
456 This is the return type from Module:callback_mode/0 and selects
457 callback mode and whether to do state enter calls, or not.
458
459 callback_mode() = state_functions | handle_event_function
460
461 The callback mode is selected with the return value from Mod‐
462 ule:callback_mode/0:
463
464 state_functions:
465 The state must be of type state_name() and one callback
466 function per state, that is, Module:StateName/3, is used.
467
468 handle_event_function:
469 The state can be any term and the callback function Mod‐
470 ule:handle_event/4 is used for all states.
471
472 The function Module:callback_mode/0 is called when starting the
473 gen_statem, after code change and after changing the callback
474 module with any of the actions change_callback_module,
475 push_callback_module or pop_callback_module. The result is
476 cached for subsequent calls to state callbacks.
477
478 state_enter() = state_enter
479
480 Whether the state machine should use state enter calls or not is
481 selected when starting the gen_statem and after code change us‐
482 ing the return value from Module:callback_mode/0.
483
484 If Module:callback_mode/0 returns a list containing state_enter,
485 the gen_statem engine will, at every state change, call the
486 state callback with arguments (enter, OldState, Data) or (enter,
487 OldState, State, Data), depending on the callback mode. This may
488 look like an event but is really a call performed after the pre‐
489 vious state callback returned and before any event is delivered
490 to the new state callback. See Module:StateName/3 and Mod‐
491 ule:handle_event/4. Such a call can be repeated by returning a
492 repeat_state or repeat_state_and_data tuple from the state call‐
493 back.
494
495 If Module:callback_mode/0 does not return such a list, no state
496 enter calls are done.
497
498 If Module:code_change/4 should transform the state, it is re‐
499 garded as a state rename and not a state change, which will not
500 cause a state enter call.
501
502 Note that a state enter call will be done right before entering
503 the initial state even though this actually is not a state
504 change. In this case OldState =:= State, which cannot happen for
505 a subsequent state change, but will happen when repeating the
506 state enter call.
507
508 transition_option() =
509 postpone() |
510 hibernate() |
511 event_timeout() |
512 generic_timeout() |
513 state_timeout()
514
515 Transition options can be set by actions and modify the state
516 transition. The state transition takes place when the state
517 callback has processed an event and returns. Here are the se‐
518 quence of steps for a state transition:
519
520 * All returned actions are processed in order of appearance.
521 In this step all replies generated by any reply_action() are
522 sent. Other actions set transition_option()s that come into
523 play in subsequent steps.
524
525 * If state enter calls are used, and either it is the initial
526 state or one of the callback results repeat_state_and_data
527 or repeat_state_and_data is used the gen_statem engine calls
528 the current state callback with arguments (enter, State,
529 Data) or (enter, State, State, Data) (depending on callback
530 mode) and when it returns starts again from the top of this
531 sequence.
532
533 If state enter calls are used, and the state changes the
534 gen_statem engine calls the new state callback with argu‐
535 ments (enter, OldState, Data) or (enter, OldState, State,
536 Data) (depending on callback mode) and when it returns
537 starts again from the top of this sequence.
538
539 * If postpone() is true, the current event is postponed.
540
541 * If this is a state change, the queue of incoming events is
542 reset to start with the oldest postponed.
543
544 * All events stored with action() next_event are inserted to
545 be processed before previously queued events.
546
547 * Time-out timers event_timeout(), generic_timeout() and
548 state_timeout() are handled. Time-outs with zero time are
549 guaranteed to be delivered to the state machine before any
550 external not yet received event so if there is such a time-
551 out requested, the corresponding time-out zero event is en‐
552 queued as the newest received event; that is after already
553 queued events such as inserted and postponed events.
554
555 Any event cancels an event_timeout() so a zero time event
556 time-out is only generated if the event queue is empty.
557
558 A state change cancels a state_timeout() and any new transi‐
559 tion option of this type belongs to the new state, that is;
560 a state_timeout() applies to the state the state machine en‐
561 ters.
562
563 * If there are enqueued events the state callback for the pos‐
564 sibly new state is called with the oldest enqueued event,
565 and we start again from the top of this sequence.
566
567 * Otherwise the gen_statem goes into receive or hibernation
568 (if hibernate() is true) to wait for the next message. In
569 hibernation the next non-system event awakens the
570 gen_statem, or rather the next incoming message awakens the
571 gen_statem, but if it is a system event it goes right back
572 into hibernation. When a new message arrives the state call‐
573 back is called with the corresponding event, and we start
574 again from the top of this sequence.
575
576 postpone() = boolean()
577
578 If true, postpones the current event and retries it after a
579 state change (NextState =/= State).
580
581 hibernate() = boolean()
582
583 If true, hibernates the gen_statem by calling proc_lib:hiber‐
584 nate/3 before going into receive to wait for a new external
585 event.
586
587 Note:
588 If there are enqueued events to process when hibrnation is re‐
589 quested, this is optimized by not hibernating but instead call‐
590 ing erlang:garbage_collect/0 to simulate that the gen_statem en‐
591 tered hibernation and immediately got awakened by an enqueued
592 event.
593
594
595 event_timeout() = timeout() | integer()
596
597 Starts a timer set by enter_action() timeout. When the timer ex‐
598 pires an event of event_type() timeout will be generated. See
599 erlang:start_timer/4 for how Time and Options are interpreted.
600 Future erlang:start_timer/4 Options will not necessarily be sup‐
601 ported.
602
603 Any event that arrives cancels this time-out. Note that a re‐
604 tried or inserted event counts as arrived. So does a state time-
605 out zero event, if it was generated before this time-out is re‐
606 quested.
607
608 If Time is infinity, no timer is started, as it never would ex‐
609 pire anyway.
610
611 If Time is relative and 0 no timer is actually started, instead
612 the the time-out event is enqueued to ensure that it gets pro‐
613 cessed before any not yet received external event, but after al‐
614 ready queued events.
615
616 Note that it is not possible nor needed to cancel this time-out,
617 as it is cancelled automatically by any other event.
618
619 generic_timeout() = timeout() | integer()
620
621 Starts a timer set by enter_action() {timeout,Name}. When the
622 timer expires an event of event_type() {timeout,Name} will be
623 generated. See erlang:start_timer/4 for how Time and Options are
624 interpreted. Future erlang:start_timer/4 Options will not neces‐
625 sarily be supported.
626
627 If Time is infinity, no timer is started, as it never would ex‐
628 pire anyway.
629
630 If Time is relative and 0 no timer is actually started, instead
631 the the time-out event is enqueued to ensure that it gets pro‐
632 cessed before any not yet received external event.
633
634 Setting a timer with the same Name while it is running will
635 restart it with the new time-out value. Therefore it is possible
636 to cancel a specific time-out by setting it to infinity.
637
638 state_timeout() = timeout() | integer()
639
640 Starts a timer set by enter_action() state_timeout. When the
641 timer expires an event of event_type() state_timeout will be
642 generated. See erlang:start_timer/4 for how Time and Options are
643 interpreted. Future erlang:start_timer/4 Options will not neces‐
644 sarily be supported.
645
646 If Time is infinity, no timer is started, as it never would ex‐
647 pire anyway.
648
649 If Time is relative and 0 no timer is actually started, instead
650 the the time-out event is enqueued to ensure that it gets pro‐
651 cessed before any not yet received external event.
652
653 Setting this timer while it is running will restart it with the
654 new time-out value. Therefore it is possible to cancel this
655 time-out by setting it to infinity.
656
657 timeout_option() = {abs, Abs :: boolean()}
658
659 If Abs is true an absolute timer is started, and if it is false
660 a relative, which is the default. See erlang:start_timer/4 for
661 details.
662
663 action() =
664 postpone |
665 {postpone, Postpone :: postpone()} |
666 {next_event,
667 EventType :: event_type(),
668 EventContent :: term()} |
669 {change_callback_module, NewModule :: module()} |
670 {push_callback_module, NewModule :: module()} |
671 pop_callback_module |
672 enter_action()
673
674 These transition actions can be invoked by returning them from
675 the state callback when it is called with an event, from Mod‐
676 ule:init/1 or by giving them to enter_loop/5,6.
677
678 Actions are executed in the containing list order.
679
680 Actions that set transition options override any previous of
681 the same type, so the last in the containing list wins. For ex‐
682 ample, the last postpone() overrides any previous postpone() in
683 the list.
684
685 postpone:
686 Sets the transition_option() postpone() for this state tran‐
687 sition. This action is ignored when returned from Mod‐
688 ule:init/1 or given to enter_loop/5,6, as there is no event
689 to postpone in those cases.
690
691 next_event:
692 This action does not set any transition_option() but instead
693 stores the specified EventType and EventContent for inser‐
694 tion after all actions have been executed.
695
696 The stored events are inserted in the queue as the next to
697 process before any already queued events. The order of these
698 stored events is preserved, so the first next_event in the
699 containing list becomes the first to process.
700
701 An event of type internal is to be used when you want to re‐
702 liably distinguish an event inserted this way from any ex‐
703 ternal event.
704
705 change_callback_module:
706 Changes the callback module to NewModule which will be used
707 when calling all subsequent state callbacks.
708
709 The gen_statem engine will find out the callback mode of
710 NewModule by calling NewModule:callback_mode/0 before the
711 next state callback.
712
713 Changing the callback module does not affect the state tran‐
714 sition in any way, it only changes which module that handles
715 the events. Be aware that all relevant callback functions in
716 NewModule such as the state callback, NewMod‐
717 ule:code_change/4, NewModule:format_status/2 and NewMod‐
718 ule:terminate/3 must be able to handle the state and data
719 from the old module.
720
721 push_callback_module:
722 Pushes the current callback module to the top of an internal
723 stack of callback modules and changes the callback module to
724 NewModule. Otherwise like {change_callback_module, NewMod‐
725 ule} above.
726
727 pop_callback_module:
728 Pops the top module from the internal stack of callback
729 modules and changes the callback module to be the popped
730 module. If the stack is empty the server fails. Otherwise
731 like {change_callback_module, NewModule} above.
732
733 enter_action() =
734 hibernate |
735 {hibernate, Hibernate :: hibernate()} |
736 timeout_action() |
737 reply_action()
738
739 These transition actions can be invoked by returning them from
740 the state callback, from Module:init/1 or by giving them to en‐
741 ter_loop/5,6.
742
743 Actions are executed in the containing list order.
744
745 Actions that set transition options override any previous of the
746 same type, so the last in the containing list wins. For example,
747 the last event_timeout() overrides any previous event_timeout()
748 in the list.
749
750 hibernate:
751 Sets the transition_option() hibernate() for this state
752 transition.
753
754 timeout_action() =
755 (Time :: event_timeout()) |
756 {timeout, Time :: event_timeout(), EventContent :: term()} |
757 {timeout,
758 Time :: event_timeout(),
759 EventContent :: term(),
760 Options :: timeout_option() | [timeout_option()]} |
761 {{timeout, Name :: term()},
762 Time :: generic_timeout(),
763 EventContent :: term()} |
764 {{timeout, Name :: term()},
765 Time :: generic_timeout(),
766 EventContent :: term(),
767 Options :: timeout_option() | [timeout_option()]} |
768 {state_timeout,
769 Time :: state_timeout(),
770 EventContent :: term()} |
771 {state_timeout,
772 Time :: state_timeout(),
773 EventContent :: term(),
774 Options :: timeout_option() | [timeout_option()]} |
775 timeout_cancel_action() |
776 timeout_update_action()
777
778 These transition actions can be invoked by returning them from
779 the state callback, from Module:init/1 or by giving them to en‐
780 ter_loop/5,6.
781
782 These time-out actions sets time-out transition options.
783
784 Time:
785 Short for {timeout,Time,Time}, that is, the time-out message
786 is the time-out time. This form exists to make the state
787 callback return value {next_state,NextState,NewData,Time}
788 allowed like for gen_fsm.
789
790 timeout:
791 Sets the transition_option() event_timeout() to Time with
792 EventContent and time-out options Options.
793
794 {timeout,Name}:
795 Sets the transition_option() generic_timeout() to Time for
796 Name with EventContent and time-out options Options.
797
798 state_timeout:
799 Sets the transition_option() state_timeout() to Time with
800 EventContent and time-out options Options.
801
802 timeout_cancel_action() =
803 {timeout, cancel} |
804 {{timeout, Name :: term()}, cancel} |
805 {state_timeout, cancel}
806
807 This is a shorter and clearer form of timeout_action() with
808 Time = infinity which cancels a time-out.
809
810 timeout_update_action() =
811 {timeout, update, EventContent :: term()} |
812 {{timeout, Name :: term()}, update, EventContent :: term()} |
813 {state_timeout, update, EventContent :: term()}
814
815 Updates a time-out with a new EventContent. See timeout_ac‐
816 tion() for how to start a time-out.
817
818 If no time-out of the same type is active instead insert the
819 time-out event just like when starting a time-out with relative
820 Time = 0.
821
822 reply_action() = {reply, From :: from(), Reply :: term()}
823
824 This transition action can be invoked by returning it from the
825 state callback, from Module:init/1 or by giving it to en‐
826 ter_loop/5,6.
827
828 It does not set any transition_option() but instead replies to a
829 caller waiting for a reply in call/2. From must be the term from
830 argument {call,From} in a call to a state callback.
831
832 Note that using this action from Module:init/1 or enter_loop/5,6
833 would be weird on the border of witchcraft since there has been
834 no earlier call to a state callback in this server.
835
836 init_result(StateType) = init_result(StateType, term())
837
838 init_result(StateType, DataType) =
839 {ok, State :: StateType, Data :: DataType} |
840 {ok,
841 State :: StateType,
842 Data :: DataType,
843 Actions :: [action()] | action()} |
844 ignore |
845 {stop, Reason :: term()}
846
847 For a succesful initialization, State is the initial state() and
848 Data the initial server data() of the gen_statem.
849
850 The Actions are executed when entering the first state just as
851 for a state callback, except that the action postpone is forced
852 to false since there is no event to postpone.
853
854 For an unsuccesful initialization, {stop,Reason} or ignore
855 should be used; see start_link/3,4.
856
857 state_enter_result(State) = state_enter_result(State, term())
858
859 state_enter_result(State, DataType) =
860 {next_state, State, NewData :: DataType} |
861 {next_state, State,
862 NewData :: DataType,
863 Actions :: [enter_action()] | enter_action()} |
864 state_callback_result(enter_action())
865
866 State is the current state and it cannot be changed since the
867 state callback was called with a state enter call.
868
869 next_state:
870 The gen_statem does a state transition to State, which has
871 to be the current state, sets NewData, and executes all Ac‐
872 tions.
873
874 event_handler_result(StateType) =
875 event_handler_result(StateType, term())
876
877 event_handler_result(StateType, DataType) =
878 {next_state, NextState :: StateType, NewData :: DataType} |
879 {next_state,
880 NextState :: StateType,
881 NewData :: DataType,
882 Actions :: [action()] | action()} |
883 state_callback_result(action())
884
885 StateType is state_name() if callback mode is state_functions,
886 or state() if callback mode is handle_event_function.
887
888 next_state:
889 The gen_statem does a state transition to NextState (which
890 can be the same as the current state), sets NewData, and ex‐
891 ecutes all Actions. If NextState =/= CurrentState the state
892 transition is a state change.
893
894 state_callback_result(ActionType) =
895 state_callback_result(ActionType, term())
896
897 state_callback_result(ActionType, DataType) =
898 {keep_state, NewData :: DataType} |
899 {keep_state,
900 NewData :: DataType,
901 Actions :: [ActionType] | ActionType} |
902 keep_state_and_data |
903 {keep_state_and_data, Actions :: [ActionType] | ActionType} |
904 {repeat_state, NewData :: DataType} |
905 {repeat_state,
906 NewData :: DataType,
907 Actions :: [ActionType] | ActionType} |
908 repeat_state_and_data |
909 {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
910 stop |
911 {stop, Reason :: term()} |
912 {stop, Reason :: term(), NewData :: DataType} |
913 {stop_and_reply,
914 Reason :: term(),
915 Replies :: [reply_action()] | reply_action()} |
916 {stop_and_reply,
917 Reason :: term(),
918 Replies :: [reply_action()] | reply_action(),
919 NewData :: DataType}
920
921 ActionType is enter_action() if the state callback was called
922 with a state enter call and action() if the state callback was
923 called with an event.
924
925 keep_state:
926 The same as {next_state,CurrentState,NewData,Actions}.
927
928 keep_state_and_data:
929 The same as {keep_state,CurrentData,Actions}.
930
931 repeat_state:
932 If the gen_statem runs with state enter calls, the state en‐
933 ter call is repeated, see type transition_option(), other
934 than that repeat_state is the same as keep_state.
935
936 repeat_state_and_data:
937 The same as {repeat_state,CurrentData,Actions}.
938
939 stop:
940 Terminates the gen_statem by calling Module:terminate/3 with
941 Reason and NewData, if specified. An exit signal with this
942 reason is sent to linked processes and ports. The default
943 Reason is normal.
944
945 stop_and_reply:
946 Sends all Replies, then terminates the gen_statem by calling
947 Module:terminate/3 with Reason and NewData, if specified. An
948 exit signal with this reason is sent to linked processes and
949 ports.
950
951 All these terms are tuples or atoms and this property will hold
952 in any future version of gen_statem.
953
954 request_id() = term()
955
956 A request handle, see send_request/2 for details.
957
959 call(ServerRef :: server_ref(), Request :: term()) ->
960 Reply :: term()
961
962 call(ServerRef :: server_ref(),
963 Request :: term(),
964 Timeout ::
965 timeout() |
966 {clean_timeout, T :: timeout()} |
967 {dirty_timeout, T :: timeout()}) ->
968 Reply :: term()
969
970 Makes a synchronous call to the gen_statem ServerRef by sending
971 a request and waiting until its reply arrives. The gen_statem
972 calls the state callback with event_type() {call,From} and event
973 content Request.
974
975 A Reply is generated when a state callback returns with {re‐
976 ply,From,Reply} as one action(), and that Reply becomes the re‐
977 turn value of this function.
978
979 Timeout is an integer > 0, which specifies how many milliseconds
980 to wait for a reply, or the atom infinity to wait indefinitely,
981 which is the default. If no reply is received within the speci‐
982 fied time, the function call fails.
983
984 Note:
985 For Timeout < infinity, to avoid getting a late reply in the
986 caller's inbox if the caller should catch exceptions, this func‐
987 tion spawns a proxy process that does the call. A late reply
988 gets delivered to the dead proxy process, hence gets discarded.
989 This is less efficient than using Timeout == infinity.
990
991
992 Timeout can also be a tuple {clean_timeout,T} or {dirty_time‐
993 out,T}, where T is the time-out time. {clean_timeout,T} works
994 like just T described in the note above and uses a proxy process
995 while {dirty_timeout,T} bypasses the proxy process which is more
996 lightweight.
997
998 Note:
999 If you combine catching exceptions from this function with
1000 {dirty_timeout,T} to avoid that the calling process dies when
1001 the call times out, you will have to be prepared to handle a
1002 late reply. Note that there is an odd chance to get a late reply
1003 even with {dirty_timeout,infinity} or infinity for example in
1004 the event of network problems. So why not just let the calling
1005 process die by not catching the exception?
1006
1007
1008 The call can also fail, for example, if the gen_statem dies be‐
1009 fore or during this function call.
1010
1011 cast(ServerRef :: server_ref(), Msg :: term()) -> ok
1012
1013 Sends an asynchronous event to the gen_statem ServerRef and re‐
1014 turns ok immediately, ignoring if the destination node or
1015 gen_statem does not exist. The gen_statem calls the state call‐
1016 back with event_type() cast and event content Msg.
1017
1018 check_response(Msg :: term(), RequestId :: request_id()) ->
1019 {reply, Reply :: term()} |
1020 no_reply |
1021 {error, {term(), server_ref()}}
1022
1023 This function is used to check if a previously received message,
1024 for example by receive or handle_info/2, is a result of a re‐
1025 quest made with send_request/2. If Msg is a reply to the handle
1026 RequestId the result of the request is returned in Reply. Other‐
1027 wise returns no_reply and no cleanup is done, and thus the func‐
1028 tion shall be invoked repeatedly until a reply is returned.
1029
1030 The return value Reply is generated when a state callback re‐
1031 turns with {reply,From,Reply} as one action(), and that Reply
1032 becomes the return value of this function.
1033
1034 The function returns an error if the gen_statem dies before or
1035 during this request.
1036
1037 enter_loop(Module :: module(),
1038 Opts :: [enter_loop_opt()],
1039 State :: state(),
1040 Data :: data()) ->
1041 no_return()
1042
1043 The same as enter_loop/6 with Actions = [] except that no
1044 server_name() must have been registered. This creates an anony‐
1045 mous server.
1046
1047 enter_loop(Module :: module(),
1048 Opts :: [enter_loop_opt()],
1049 State :: state(),
1050 Data :: data(),
1051 Server_or_Actions :: server_name() | pid() | [action()]) ->
1052 no_return()
1053
1054 If Server_or_Actions is a list(), the same as enter_loop/6 ex‐
1055 cept that no server_name() must have been registered and Actions
1056 = Server_or_Actions. This creates an anonymous server.
1057
1058 Otherwise the same as enter_loop/6 with Server = Server_or_Ac‐
1059 tions and Actions = [].
1060
1061 enter_loop(Module :: module(),
1062 Opts :: [enter_loop_opt()],
1063 State :: state(),
1064 Data :: data(),
1065 Server :: server_name() | pid(),
1066 Actions :: [action()] | action()) ->
1067 no_return()
1068
1069 Makes the calling process become a gen_statem. Does not return,
1070 instead the calling process enters the gen_statem receive loop
1071 and becomes a gen_statem server. The process must have been
1072 started using one of the start functions in proc_lib. The user
1073 is responsible for any initialization of the process, including
1074 registering a name for it.
1075
1076 This function is useful when a more complex initialization pro‐
1077 cedure is needed than the gen_statem behavior provides.
1078
1079 Module, Opts have the same meaning as when calling
1080 start[_link|_monitor]/3,4.
1081
1082 If Server is self() an anonymous server is created just as when
1083 using start[_link|_monitor]/3. If Server is a server_name() a
1084 named server is created just as when using start[_link|_moni‐
1085 tor]/4. However, the server_name() name must have been regis‐
1086 tered accordingly before this function is called.
1087
1088 State, Data, and Actions have the same meanings as in the return
1089 value of Module:init/1. Also, the callback module does not need
1090 to export a Module:init/1 function.
1091
1092 The function fails if the calling process was not started by a
1093 proc_lib start function, or if it is not registered according to
1094 server_name().
1095
1096 receive_response(RequestId :: request_id()) ->
1097 {reply, Reply :: term()} |
1098 {error, {term(), server_ref()}}
1099
1100 receive_response(RequestId :: request_id(), Timeout :: timeout()) ->
1101 {reply, Reply :: term()} |
1102 timeout |
1103 {error, {term(), server_ref()}}
1104
1105 This function is used to receive for a reply of a request made
1106 with send_request/2 to the gen_statem process. This function
1107 must be called from the same process from which send_request/2
1108 was made.
1109
1110 Timeout is an integer greater then or equal to zero that speci‐
1111 fies how many milliseconds to wait for an reply, or the atom in‐
1112 finity to wait indefinitely. Defaults to infinity. If no reply
1113 is received within the specified time, the function returns
1114 timeout. Assuming that the server executes on a node supporting
1115 aliases (introduced in OTP 24) no response will be received af‐
1116 ter a timeout. Otherwise, a garbage response might be received
1117 at a later time.
1118
1119 The return value Reply is generated when a state callback re‐
1120 turns with {reply,From,Reply} as one action(), and that Reply
1121 becomes the return value of this function.
1122
1123 The function returns an error if the gen_statem dies before or
1124 during this function call.
1125
1126 The difference between wait_response() and receive_response() is
1127 that receive_response() abandons the request at timeout so that
1128 a potential future response is ignored, while wait_response()
1129 does not.
1130
1131 reply(Replies :: [reply_action()] | reply_action()) -> ok
1132
1133 reply(From :: from(), Reply :: term()) -> ok
1134
1135 This function can be used by a gen_statem to explicitly send a
1136 reply to a process that waits in call/2 when the reply cannot be
1137 defined in the return value of a state callback.
1138
1139 From must be the term from argument {call,From} to the state
1140 callback. A reply or multiple replies canalso be sent using one
1141 or several reply_action()s from a state callback.
1142
1143 Note:
1144 A reply sent with this function is not visible in sys debug out‐
1145 put.
1146
1147
1148 send_request(ServerRef :: server_ref(), Request :: term()) ->
1149 RequestId :: request_id()
1150
1151 Sends a request to the gen_statem ServerRef and returns a handle
1152 RequestId.
1153
1154 The return value RequestId shall later be used with receive_re‐
1155 sponse/1,2, wait_response/1,2, or check_response/2 to fetch the
1156 actual result of the request.
1157
1158 The call gen_statem:wait_response(gen_statem:send_re‐
1159 quest(ServerRef,Request), Timeout) can be seen as equivalent to
1160 gen_statem:call(Server,Request,Timeout), ignoring the error han‐
1161 dling.
1162
1163 The gen_statem calls the state callback with event_type()
1164 {call,From} and event content Request.
1165
1166 A Reply is generated when a state callback returns with {re‐
1167 ply,From,Reply} as one action(), and that Reply becomes the re‐
1168 turn value of receive_response/1,2, wait_response/1,2, or
1169 check_response/2 function.
1170
1171 start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1172 start_ret()
1173
1174 start(ServerName :: server_name(),
1175 Module :: module(),
1176 Args :: term(),
1177 Opts :: [start_opt()]) ->
1178 start_ret()
1179
1180 Creates a standalone gen_statem process according to OTP design
1181 principles (using proc_lib primitives). As it does not get
1182 linked to the calling process, this start function cannot be
1183 used by a supervisor to start a child.
1184
1185 For a description of arguments and return values, see
1186 start_link/3,4.
1187
1188 start_link(Module :: module(),
1189 Args :: term(),
1190 Opts :: [start_opt()]) ->
1191 start_ret()
1192
1193 start_link(ServerName :: server_name(),
1194 Module :: module(),
1195 Args :: term(),
1196 Opts :: [start_opt()]) ->
1197 start_ret()
1198
1199 Creates a gen_statem process according to OTP design principles
1200 (using proc_lib primitives) that is linked to the calling
1201 process. This is essential when the gen_statem must be part of a
1202 supervision tree so it gets linked to its supervisor.
1203
1204 The gen_statem process calls Module:init/1 to initialize the
1205 server. To ensure a synchronized startup procedure,
1206 start_link/3,4 does not return until Module:init/1 has returned.
1207
1208 ServerName specifies the server_name() to register for the
1209 gen_statem. If the gen_statem is started with start_link/3, no
1210 ServerName is provided and the gen_statem is not registered.
1211
1212 Module is the name of the callback module.
1213
1214 Args is an arbitrary term that is passed as the argument to Mod‐
1215 ule:init/1.
1216
1217 * If option {timeout,Time} is present in Opts, the gen_statem
1218 is allowed to spend Time milliseconds initializing or it
1219 terminates and the start function returns {error,timeout}.
1220
1221 * If option {hibernate_after,HibernateAfterTimeout} is
1222 present, the gen_statem process awaits any message for Hi‐
1223 bernateAfterTimeout milliseconds and if no message is re‐
1224 ceived, the process goes into hibernation automatically (by
1225 calling proc_lib:hibernate/3).
1226
1227 * If option {debug,Dbgs} is present in Opts, debugging through
1228 sys is activated.
1229
1230 * If option {spawn_opt,SpawnOpts} is present in Opts,
1231 SpawnOpts is passed as option list to erlang:spawn_opt/2,
1232 which is used to spawn the gen_statem process.
1233
1234 Note:
1235 Using spawn option monitor is not allowed, it causes this func‐
1236 tion to fail with reason badarg.
1237
1238
1239 If the gen_statem is successfully created and initialized, this
1240 function returns {ok,Pid}, where Pid is the pid() of the
1241 gen_statem. If a process with the specified ServerName exists
1242 already, this function returns {error,{already_started,Pid}},
1243 where Pid is the pid() of that process.
1244
1245 If Module:init/1 fails with Reason, this function returns {er‐
1246 ror,Reason}. If Module:init/1 returns {stop,Reason} or ignore,
1247 the process is terminated and this function returns {error,Rea‐
1248 son} or ignore, respectively. An exit signal with the same Rea‐
1249 son (or normal if Module:init/1 returns ignore) is set to linked
1250 processes and ports, including the process calling
1251 start_link/3,4.
1252
1253 start_monitor(Module :: module(),
1254 Args :: term(),
1255 Opts :: [start_opt()]) ->
1256 start_mon_ret()
1257
1258 start_monitor(ServerName :: server_name(),
1259 Module :: module(),
1260 Args :: term(),
1261 Opts :: [start_opt()]) ->
1262 start_mon_ret()
1263
1264 Creates a standalone gen_statem process according to OTP design
1265 principles (using proc_lib primitives) and atomically sets up a
1266 monitor to the newly created process. As it does not get linked
1267 to the calling process, this start function cannot be used by a
1268 supervisor to start a child.
1269
1270 For a description of arguments and return values, see
1271 start_link/3,4. Note that the return value on successful start
1272 differs from start_link/3,4. start_monitor/3,4 will return
1273 {ok,{Pid,Mon}} where Pid is the process identifier of the
1274 process, and Mon is a reference to the monitor set up to monitor
1275 the process. If the start is not successful, the caller will be
1276 blocked until the DOWN message has been received and removed
1277 from the message queue.
1278
1279 stop(ServerRef :: server_ref()) -> ok
1280
1281 The same as stop(ServerRef, normal, infinity).
1282
1283 stop(ServerRef :: server_ref(),
1284 Reason :: term(),
1285 Timeout :: timeout()) ->
1286 ok
1287
1288 Orders the gen_statem ServerRef to exit with the specified Rea‐
1289 son and waits for it to terminate. The gen_statem calls Mod‐
1290 ule:terminate/3 before exiting.
1291
1292 This function returns ok if the server terminates with the ex‐
1293 pected reason. Any other reason than normal, shutdown, or {shut‐
1294 down,Term} causes an error report to be issued through log‐
1295 ger(3). An exit signal with the same reason is sent to linked
1296 processes and ports. The default Reason is normal.
1297
1298 Timeout is an integer > 0, which specifies how many milliseconds
1299 to wait for the server to terminate, or the atom infinity to
1300 wait indefinitely. Defaults to infinity. If the server does not
1301 terminate within the specified time, a timeout exception is
1302 raised.
1303
1304 If the process does not exist, a noproc exception is raised.
1305
1306 wait_response(RequestId :: request_id()) ->
1307 {reply, Reply :: term()} |
1308 {error, {term(), server_ref()}}
1309
1310 wait_response(RequestId :: request_id(), Timeout :: timeout()) ->
1311 {reply, Reply :: term()} |
1312 timeout |
1313 {error, {term(), server_ref()}}
1314
1315 This function is used to wait for a reply of a request made with
1316 send_request/2 to the gen_statem process. This function must be
1317 called from the same process from which send_request/2 was made.
1318
1319 Timeout is an integer greater then or equal to zero that speci‐
1320 fies how many milliseconds to wait for an reply, or the atom in‐
1321 finity to wait indefinitely. Defaults to infinity. If no reply
1322 is received within the specified time, the function returns
1323 timeout and no cleanup is done, and thus the function can be in‐
1324 voked repeatedly until a reply is returned.
1325
1326 The return value Reply is generated when a state callback re‐
1327 turns with {reply,From,Reply} as one action(), and that Reply
1328 becomes the return value of this function.
1329
1330 The function returns an error if the gen_statem dies before or
1331 during this function call.
1332
1333 The difference between receive_response() and wait_response() is
1334 that receive_response() abandons the request at timeout so that
1335 a potential future response is ignored, while wait_response()
1336 does not.
1337
1339 The following functions are to be exported from a gen_statem callback
1340 module.
1341
1343 Module:callback_mode() -> CallbackMode
1344
1345 Types:
1346
1347 CallbackMode = callback_mode() | [ callback_mode() |
1348 state_enter() ]
1349
1350 This function is called by a gen_statem when it needs to find
1351 out the callback mode of the callback module. The value is
1352 cached by gen_statem for efficiency reasons, so this function is
1353 only called once after server start, after code change, and af‐
1354 ter changing the callback module, but before the first state
1355 callback in the current callback module's code version is
1356 called. More occasions may be added in future versions of
1357 gen_statem.
1358
1359 Server start happens either when Module:init/1 returns or when
1360 enter_loop/4-6 is called. Code change happens when Mod‐
1361 ule:code_change/4 returns. A change of the callback module hap‐
1362 pens when a state callback returns any of the actions
1363 change_callback_module, push_callback_module or pop_call‐
1364 back_module.
1365
1366 The CallbackMode is either just callback_mode() or a list con‐
1367 taining callback_mode() and possibly the atom state_enter.
1368
1369 Note:
1370 If this function's body does not return an inline constant value
1371 the callback module is doing something strange.
1372
1373
1374 Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1375
1376 Types:
1377
1378 OldVsn = Vsn | {down,Vsn}
1379 Vsn = term()
1380 OldState = NewState = term()
1381 Extra = term()
1382 Result = {ok,NewState,NewData} | Reason
1383 OldState = NewState = state()
1384 OldData = NewData = data()
1385 Reason = term()
1386
1387 Note:
1388 This callback is optional, so callback modules need not export
1389 it. If a release upgrade/downgrade with Change = {advanced,Ex‐
1390 tra} specified in the .appup file is made when code_change/4 is
1391 not implemented the process will crash with exit reason undef.
1392
1393
1394 This function is called by a gen_statem when it is to update its
1395 internal state during a release upgrade/downgrade, that is, when
1396 the instruction {update,Module,Change,...}, where Change = {ad‐
1397 vanced,Extra}, is specified in the appup file. For more informa‐
1398 tion, see OTP Design Principles.
1399
1400 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
1401 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
1402 version of the callback module Module. If no such attribute is
1403 defined, the version is the checksum of the Beam file.
1404
1405 OldState and OldData is the internal state of the gen_statem.
1406
1407 Extra is passed "as is" from the {advanced,Extra} part of the
1408 update instruction.
1409
1410 If successful, the function must return the updated internal
1411 state in an {ok,NewState,NewData} tuple.
1412
1413 If the function returns a failure Reason, the ongoing upgrade
1414 fails and rolls back to the old release. Note that Reason cannot
1415 be an {ok,_,_} tuple since that will be regarded as a {ok,New‐
1416 State,NewData} tuple, and that a tuple matching {ok,_} is an
1417 also invalid failure Reason. It is recommended to use an atom as
1418 Reason since it will be wrapped in an {error,Reason} tuple.
1419
1420 Also note when upgrading a gen_statem, this function and hence
1421 the Change = {advanced,Extra} parameter in the appup file is not
1422 only needed to update the internal state or to act on the Extra
1423 argument. It is also needed if an upgrade or downgrade should
1424 change callback mode, or else the callback mode after the code
1425 change will not be honoured, most probably causing a server
1426 crash.
1427
1428 If the server changes callback module using any of the actions
1429 change_callback_module, push_callback_module or pop_call‐
1430 back_module, be aware that it is always the current callback
1431 module that will get this callback call. That the current call‐
1432 back module handles the current state and data update should be
1433 no surprise, but it must be able to handle even parts of the
1434 state and data that it is not familiar with, somehow.
1435
1436 In the supervisor child specification there is a list of modules
1437 which is recommended to contain only the callback module. For a
1438 gen_statem with multiple callback modules there is no real need
1439 to list all of them, it may not even be possible since the list
1440 could change after code upgrade. If this list would contain only
1441 the start callback module, as recommended, what is important is
1442 to upgrade that module whenever a synchronized code replacement
1443 is done. Then the release handler concludes that an upgrade that
1444 upgrades that module needs to suspend, code change, and resume
1445 any server whose child specification declares that it is using
1446 that module. And again; the current callback module will get the
1447 Module:code_change/4 call.
1448
1449 Module:init(Args) -> Result(StateType)
1450
1451 Types:
1452
1453 Args = term()
1454 Result(StateType) = init_result(StateType)
1455
1456 Whenever a gen_statem is started using start_link/3,4,
1457 start_monitor/3,4, or start/3,4, this function is called by the
1458 new process to initialize the implementation state and server
1459 data.
1460
1461 Args is the Args argument provided to that start function.
1462
1463 Note:
1464 Note that if the gen_statem is started through proc_lib and en‐
1465 ter_loop/4-6, this callback will never be called. Since this
1466 callback is not optional it can in that case be implemented as:
1467
1468 -spec init(_) -> no_return().
1469 init(Args) -> erlang:error(not_implemented, [Args]).
1470
1471
1472 Module:format_status(Opt, [PDict,State,Data]) -> Status
1473
1474 Types:
1475
1476 Opt = normal | terminate
1477 PDict = [{Key, Value}]
1478 State = state()
1479 Data = data()
1480 Key = term()
1481 Value = term()
1482 Status = term()
1483
1484 Note:
1485 This callback is optional, so a callback module does not need to
1486 export it. The gen_statem module provides a default implementa‐
1487 tion of this function that returns {State,Data}.
1488
1489 If this callback is exported but fails, to hide possibly sensi‐
1490 tive data, the default function will instead return
1491 {State,Info}, where Info says nothing but the fact that for‐
1492 mat_status/2 has crashed.
1493
1494
1495 This function is called by a gen_statem process when any of the
1496 following apply:
1497
1498 *
1499 One of sys:get_status/1,2 is invoked to get the gen_statem
1500 status. Opt is set to the atom normal for this case.
1501
1502 *
1503 The gen_statem terminates abnormally and logs an error. Opt
1504 is set to the atom terminate for this case.
1505
1506 This function is useful for changing the form and appearance of
1507 the gen_statem status for these cases. A callback module wishing
1508 to change the sys:get_status/1,2 return value and how its status
1509 appears in termination error logs exports an instance of for‐
1510 mat_status/2, which returns a term describing the current status
1511 of the gen_statem.
1512
1513 PDict is the current value of the process dictionary of the
1514 gen_statem.
1515
1516 State is the internal state of the gen_statem.
1517
1518 Data is the internal server data of the gen_statem.
1519
1520 The function is to return Status, a term that contains the ap‐
1521 propriate details of the current state and status of the
1522 gen_statem. There are no restrictions on the form Status can
1523 take, but for the sys:get_status/1,2 case (when Opt is normal),
1524 the recommended form for the Status value is [{data, [{"State",
1525 Term}]}], where Term provides relevant details of the gen_statem
1526 state. Following this recommendation is not required, but it
1527 makes the callback module status consistent with the rest of the
1528 sys:get_status/1,2 return value.
1529
1530 One use for this function is to return compact alternative state
1531 representations to avoid having large state terms printed in log
1532 files. Another use is to hide sensitive data from being written
1533 to the error log.
1534
1535 Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1536 Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1537 Module:handle_event(enter, OldState, State, Data) -> StateEnterRe‐
1538 sult(State)
1539 Module:handle_event(EventType, EventContent, State, Data) -> Han‐
1540 dleEventResult
1541
1542 Types:
1543
1544 EventType = event_type()
1545 EventContent = term()
1546 State = state()
1547 Data = NewData = data()
1548 StateEnterResult(StateName) = state_enter_result(StateName)
1549 StateFunctionResult = event_handler_result(state_name())
1550 StateEnterResult(State) = state_enter_result(State)
1551 HandleEventResult = event_handler_result(state())
1552
1553 Whenever a gen_statem receives an event from call/2, cast/2, or
1554 as a normal process message, one of these functions is called.
1555 If callback mode is state_functions, Module:StateName/3 is
1556 called, and if it is handle_event_function, Module:han‐
1557 dle_event/4 is called.
1558
1559 If EventType is {call,From}, the caller waits for a reply. The
1560 reply can be sent from this or from any other state callback by
1561 returning with {reply,From,Reply} in Actions, in Replies, or by
1562 calling reply(From, Reply).
1563
1564 If this function returns with a next state that does not match
1565 equal (=/=) to the current state, all postponed events are re‐
1566 tried in the next state.
1567
1568 The only difference between StateFunctionResult and HandleEven‐
1569 tResult is that for StateFunctionResult the next state must be
1570 an atom, but for HandleEventResult there is no restriction on
1571 the next state.
1572
1573 For options that can be set and actions that can be done by
1574 gen_statem after returning from this function, see action().
1575
1576 When the gen_statem runs with state enter calls, these functions
1577 are also called with arguments (enter, OldState, ...) during ev‐
1578 ery state change. In this case there are some restrictions on
1579 the actions that may be returned: postpone() is not allowed
1580 since a state enter call is not an event so there is no event to
1581 postpone, and {next_event,_,_} is not allowed since using state
1582 enter calls should not affect how events are consumed and pro‐
1583 duced. You may also not change states from this call. Should you
1584 return {next_state,NextState, ...} with NextState =/= State the
1585 gen_statem crashes. Note that it is actually allowed to use {re‐
1586 peat_state, NewData, ...} although it makes little sense since
1587 you immediately will be called again with a new state enter call
1588 making this just a weird way of looping, and there are better
1589 ways to loop in Erlang. If you do not update NewData and have
1590 some loop termination condition, or if you use {re‐
1591 peat_state_and_data, _} or repeat_state_and_data you have an in‐
1592 finite loop! You are advised to use {keep_state,...},
1593 {keep_state_and_data,_} or keep_state_and_data since changing
1594 states from a state enter call is not possible anyway.
1595
1596 Note the fact that you can use throw to return the result, which
1597 can be useful. For example to bail out with
1598 throw(keep_state_and_data) from deep within complex code that
1599 cannot return {next_state,State,Data} because State or Data is
1600 no longer in scope.
1601
1602 Module:terminate(Reason, State, Data) -> Ignored
1603
1604 Types:
1605
1606 Reason = normal | shutdown | {shutdown,term()} | term()
1607 State = state()
1608 Data = data()
1609 Ignored = term()
1610
1611 Note:
1612 This callback is optional, so callback modules need not export
1613 it. The gen_statem module provides a default implementation
1614 without cleanup.
1615
1616
1617 This function is called by a gen_statem when it is about to ter‐
1618 minate. It is to be the opposite of Module:init/1 and do any
1619 necessary cleaning up. When it returns, the gen_statem termi‐
1620 nates with Reason. The return value is ignored.
1621
1622 Reason is a term denoting the stop reason and State is the in‐
1623 ternal state of the gen_statem.
1624
1625 Reason depends on why the gen_statem is terminating. If it is
1626 because another callback function has returned, a stop tuple
1627 {stop,Reason} in Actions, Reason has the value specified in that
1628 tuple. If it is because of a failure, Reason is the error rea‐
1629 son.
1630
1631 If the gen_statem is part of a supervision tree and is ordered
1632 by its supervisor to terminate, this function is called with
1633 Reason = shutdown if both the following conditions apply:
1634
1635 * The gen_statem has been set to trap exit signals.
1636
1637 * The shutdown strategy as defined in the supervisor's child
1638 specification is an integer time-out value, not brutal_kill.
1639
1640 Even if the gen_statem is not part of a supervision tree, this
1641 function is called if it receives an 'EXIT' message from its
1642 parent. Reason is the same as in the 'EXIT' message.
1643
1644 Otherwise, the gen_statem is immediately terminated.
1645
1646 Notice that for any other reason than normal, shutdown, or
1647 {shutdown,Term}, the gen_statem is assumed to terminate because
1648 of an error and an error report is issued using logger(3).
1649
1650 When the gen_statem process exits, an exit signal with the same
1651 reason is sent to linked processes and ports.
1652
1654 gen_event(3), gen_fsm(3), gen_server(3), proc_lib(3), supervisor(3),
1655 sys(3).
1656
1657
1658
1659Ericsson AB stdlib 3.17.2 gen_statem(3)