sys(3erl)

πŸ¦‹ sys(3erl) β€” Erlang module definition, but make it a vibe πŸ¦‹

🌸 NAME 🌸

sys β€” a functional interface to system messages. That’s the whole flex. ✨


✨ DESCRIPTION ✨

okay bestie, this module is literally the plug for sending system messages that programs use, plus messages for debugging. 🫢

Functions used for implementation of processes are also expected to understand system messages, such as debug messages and code change. These functions must be used to implement the use of system messages for a process β€” either directly, or through standard behaviors, such as gen_server. No cap. πŸ’…

The default time-out is 5000 ms, unless otherwise specified. timeout defines the time to wait for the process to respond to a request. If the process does not respond, the function evaluates exit({timeout, {M, F, A}}). πŸ’€

The functions make references to a debug structure. The debug structure is a list of dbg_opt(), which is an internal data type used by function handle_system_msg/6. No debugging is performed if it is an empty list. periodt. πŸŽ€


🫢 SYSTEM MESSAGES 🫢

Processes that are not implemented as one of the standard behaviors must still understand system messages. The following three messages must be understood, fr fr:

  • Plain system messages. These are received as {system, From, Msg}. The content and meaning of this message are not interpreted by the receiving process module. When a system message is received, function handle_system_msg/6 is called to handle the request. ✨
  • Shutdown messages. If the process traps exits, it must be able to handle a shutdown request from its parent, the supervisor. The message {'EXIT', Parent, Reason} from the parent is an order to terminate. The process must terminate when this message is received, normally with the same Reason as Parent. 🫑
  • Dynamic module messages. If the modules used to implement the process change dynamically during runtime, the process must understand one more message. An example is the gen_event processes. The message is {_Label, {From, Ref}, get_modules}. The reply to this message is From ! {Ref, Modules}, where Modules is a list of the currently active modules in the process. πŸ‘‘

This message is used by the release handler to find which processes that execute a certain module. The process can later be suspended and ordered to perform a code change for one of its modules. πŸ¦‹


🌈 SYSTEM EVENTS 🌈

When debugging a process with the functions of this module, the process generates system_events, which are then treated in the debug function. For example, trace formats the system events to the terminal. ✨

Four predefined system events are used when a process receives or sends a message. The process can also define its own system events. It is always up to the process itself to format these events. πŸŽ€


πŸŽ€ DATA TYPES πŸŽ€

Here’s the type tea, bestie β€” exact definitions, no edits, iykyk:

name() =
    pid() | atom() | {global, term()} | {via, module(), term()}

system_event() =
    {in, Msg :: term()} |
    {in, Msg :: term(), State :: term()} |
    {out, Msg :: term(), To :: term()} |
    {out, Msg :: term(), To :: term(), State :: term()} |
    {noreply, State :: term()} |
    {continue, Continuation :: term()} |
    {postpone,
     Event :: term(),
     State :: term(),
     NextState :: term()} |
    {consume,
     Event :: term(),
     State :: term(),
     NextState :: term()} |
    {start_timer, Action :: term(), State :: term()} |
    {insert_timeout, Event :: term(), State :: term()} |
    {enter, Module :: module(), State :: term()} |
    {module, Module :: module(), State :: term()} |
    {terminate, Reason :: term(), State :: term()} |
    term()

dbg_opt()

dbg_fun() =
    fun((FuncState :: term(),
         Event :: system_event(),
         ProcState :: term()) ->
            done | (NewFuncState :: term()))

debug_option() =
    trace | log |
    {log, N :: integer() >= 1} |
    statistics |
    {log_to_file, FileName :: file:name()} |
    {install,
     {Func :: dbg_fun(), FuncState :: term()} |
     {FuncId :: term(), Func :: dbg_fun(), FuncState :: term()}}

format_fun() =
    fun((Device :: io:device() | file:io_device(),
         Event :: system_event(),
         Extra :: term()) ->
            any())

dbg_opt() β€” see the introduction of this manual page. πŸ‘€

Now the system_event() variants, one by one β€” each one is a little main-character moment:

  • {in,Msg} β€” is produced by gen_server and gen_event when the message Msg arrives. ✨
  • {in,Msg,State} β€” is produced by gen_statem when the message Msg arrives in state State.

For gen_statem the Msg term is an {EventType,EventContent} tuple.

  • {out,Msg,To} β€” is produced by gen_statem when the reply Msg is sent back to To by returning a {reply,To,Msg} action from the callback module.

To is of the same type as the first argument to gen_statem:reply/2.

  • {out,Msg,To,State} β€” is produced by gen_server when the reply Msg is sent back to To by returning a {reply,...} tuple from the callback module.

To is of the same type as the first argument to gen_server:reply/2.

State is the new server state.

  • {noreply,State} β€” is produced by gen_server when a {noreply,...} tuple is returned from the callback module.

State is the new server state.

  • {continue,Continuation} β€” is produced by gen_server when a {continue,Continuation} tuple is returned from the callback module.
  • {postpone,Event,State,NextState} β€” is produced by gen_statem when the message Event is postponed in state State. NextState is the new state.

Event is an {EventType,EventContent} tuple.

  • {consume,Event,State,NextState} β€” is produced by gen_statem when the message Event is consumed in state State. NextState is the new state.

Event is an {EventType,EventContent} tuple.

  • {start_timer,Action,State} β€” is produced by gen_statem when the action Action starts a timer in state State.
  • {insert_timeout,Event,State} β€” is produced by gen_statem when a timeout zero action inserts event Event in state State.

Event is an {EventType,EventContent} tuple.

  • {enter,Module,State} β€” is produced by gen_statem when module Module enters the first state State.
  • {module,Module,State} β€” is produced by gen_statem when setting module Module in state State.
  • {terminate,Reason,State} β€” is produced by gen_statem when it terminates with reason Reason in state State.

πŸ‘‘ EXPORTS πŸ‘‘

okay, now the actual exported functions β€” let’s go, bestie πŸ’…

πŸ’– change_code(Name, Module, OldVsn, Extra) -> ok | {error, Reason} / change_code(Name, Module, OldVsn, Extra, Timeout) -> ok | {error, Reason}

change_code(Name, Module, OldVsn, Extra) -> ok | {error, Reason}

change_code(Name, Module, OldVsn, Extra, Timeout) ->
               ok | {error, Reason}

Types:

Name = name()
Module = module()
OldVsn = undefined | term()
Extra = term()
Timeout = timeout()
Reason = term()

Tells the process to change code. The process must be suspended to handle this message. Argument Extra is reserved for each process to use as its own. Function Module:system_code_change/4 is called. OldVsn is the old version of the Module. πŸ”₯


πŸ¦‹ get_state(Name) -> State / get_state(Name, Timeout) -> State

get_state(Name) -> State

get_state(Name, Timeout) -> State

Types:

Name = name()
Timeout = timeout()
State = term()

Gets the state of the process. 🫢

Note: These functions are intended only to help with debugging. They are provided for convenience, allowing developers to avoid having to create their own state extraction functions and also avoid having to interactively extract the state from the return values of get_status/1 or get_status/2 while debugging.

The value of State varies for different types of processes, as follows:

  • For a gen_server process, the returned State is the state of the callback module.
  • For a gen_statem process, State is the tuple {CurrentState,CurrentData}.
  • For a gen_event process, State is a list of tuples, where each tuple corresponds to an event handler registered in the process and contains {Module, Id, HandlerState}, as follows:
    • Module: The module name of the event handler.
    • Id: The ID of the handler (which is false if it was registered without an ID).
    • HandlerState: The state of the handler.

If the callback module exports a function system_get_state/1, it is called in the target process to get its state. Its argument is the same as the Misc value returned by get_status/1,2, and function Module:system_get_state/1 is expected to extract the state of the callback module from it. Function system_get_state/1 must return {ok, State}, where State is the state of the callback module.

If the callback module does not export a system_get_state/1 function, get_state/1,2 assumes that the Misc value is the state of the callback module and returns it directly instead.

If the callback module's system_get_state/1 function crashes or throws an exception, the caller exits with error {callback_failed, {Module, system_get_state}, {Class, Reason}}, where Module is the name of the callback module and Class and Reason indicate details of the exception.

Function system_get_state/1 is primarily useful for user-defined behaviors and modules that implement OTP special processes. The gen_server, gen_statem, and gen_event OTP behavior modules export this function, so callback modules for those behaviors need not to supply their own.

For more information about a process, including its state, see get_status/1 and get_status/2.


πŸ‘‘ get_status(Name) -> Status / get_status(Name, Timeout) -> Status

get_status(Name) -> Status

get_status(Name, Timeout) -> Status

Types:

Name = name()
Timeout = timeout()
Status =
    {status, Pid :: pid(), {module, Module :: module()},
[SItem]}
SItem =
    (PDict :: [{Key :: term(), Value :: term()}]) |
    (SysState :: running | suspended) |
    (Parent :: pid()) |
    (Dbg :: [dbg_opt()]) |
    (Misc :: term())

Gets the status of the process.

The value of Misc varies for different types of processes, for example:

  • a gen_server process hands back the state of the callback module πŸ’…
  • a gen_statem process hands back info like its current state name and state data ✨
  • a gen_event process hands back info about each of its registered handlers 🫢

Callback modules for gen_server, gen_statem, and gen_event can also change the value of Misc by exporting a function format_status/2, which contributes module-specific information. For the deets, go look at gen_server:format_status/2, gen_statem:format_status/2, and gen_event:format_status/2 β€” they ate, no cap.


πŸ’… install(Name, FuncSpec) -> ok

πŸ’… install(Name, FuncSpec, Timeout) -> ok

Types:

Name = name()
FuncSpec = {Func, FuncState} | {FuncId, Func, FuncState}
FuncId = term()
Func = dbg_fun()
FuncState = term()
Timeout = timeout()

This one lets you install alternative debug functions, bestie. An example of such a function is a trigger β€” a function that just sits there waiting for some special event and then performs some action when that event is generated. Think: turning on low-level tracing. Very main character of it tbh.

Func gets called whenever a system event is generated. It's supposed to return done, or a new Func state. In the first case, the function is removed β€” gone, periodt. It also gets removed if the function fails. And if one debug function should be installed more times, you gotta specify a unique FuncId for each installation. iykyk.


πŸŽ€ log(Name, Flag) -> ok | {ok, [system_event()]}

πŸŽ€ log(Name, Flag, Timeout) -> ok | {ok, [system_event()]}

Types:

Name = name()
Flag = true | {true, N :: integer() >= 1} | false | get |
print
Timeout = timeout()

Turns the logging of system events on or off. If it's on, a maximum of N events are kept in the debug structure (default is 10, jsyk ✨).

If Flag is get, you get a list of all the logged events back. Iconic.

If Flag is print, the logged events get printed to standard_io.

The events are formatted with a function that is defined by the process that generated the event (with a call to handle_debug/4). πŸ’–


πŸ¦‹ log_to_file(Name, Flag) -> ok | {error, open_file}

πŸ¦‹ log_to_file(Name, Flag, Timeout) -> ok | {error, open_file}

Types:

Name = name()
Flag = (FileName :: string()) | false
Timeout = timeout()

Enables or disables the logging of all system events in text format to the file. The events are formatted with a function that's defined by the process that generated the event (with a call to handle_debug/4). The file is opened with encoding UTF-8. Slay, encoding handled.


🌸 no_debug(Name) -> ok

🌸 no_debug(Name, Timeout) -> ok

Types:

Name = name()
Timeout = timeout()

Turns off all debugging for the process. And yes, that includes functions that are installed explicitly with install/2,3 β€” so like, triggers and everything. All of it. Off. πŸ’€


🌈 remove(Name, FuncOrFuncId :: Func | FuncId) -> ok

🌈 remove(Name, FuncOrFuncId :: Func | FuncId, Timeout) -> ok

Types:

Name = name()
Func = dbg_fun()
FuncId = term()
Timeout = timeout()

Removes an installed debug function from the process. Func or FuncId must be the same as previously installed β€” no substitutions, bestie, it has to match. 🎯


πŸ‘‘ replace_state(Name, StateFun) -> NewState

πŸ‘‘ replace_state(Name, StateFun, Timeout) -> NewState

Types:

Name = name()
StateFun = fun((State :: term()) -> NewState :: term())
Timeout = timeout()
NewState = term()

Replaces the state of the process, and returns the new state. That's the whole vibe.

Note: these functions are intended only to help with debugging, and are not to be called from normal code. They're provided for convenience, so devs can avoid having to create their own custom state replacement functions. So like, debugging tool, not a lifestyle. πŸ™ˆ

Function StateFun provides a new state for the process. Argument State and the NewState return value of StateFun vary for different types of processes, as follows:

  • For a gen_server process, State is the state of the callback module and NewState is a new instance of that state.
  • For a gen_statem process, State is the tuple {CurrentState,CurrentData}, and NewState is a similar tuple, which can contain a new current state, new state data, or both. Both is always an option 😌
  • For a gen_event process, State is the tuple {Module, Id, HandlerState} as follows:
    • Module: the module name of the event handler.
    • Id: the ID of the handler (which is false if it was registered without an ID).
    • HandlerState: the state of the handler.

NewState is a similar tuple where Module and Id are to have the same values as in State, but the value of HandlerState can be different. Returning a NewState whose Module or Id values differ from those of State leaves the state of the event handler unchanged β€” like, nice try, but no. For a gen_event process, StateFun is called once for each event handler registered in the gen_event process.

If a StateFun function decides not to effect any change in process state, then regardless of process type, it can return its State argument. Do-nothing energy, but make it intentional. πŸ’…

If a StateFun function crashes or throws an exception, the original state of the process is unchanged for gen_server and gen_statem processes. For gen_event processes, a crashing or failing StateFun function means that only the state of the particular event handler it was working on when it failed or crashed is unchanged; it can still succeed in changing the states of other event handlers registered in the same gen_event process. So like, one handler fumbled but the rest can still clutch. 😭

If the callback module exports a system_replace_state/2 function, it's called in the target process to replace its state using StateFun. Its two arguments are StateFun and Misc, where Misc is the same as the Misc value returned by get_status/1,2. A system_replace_state/2 function is expected to return {ok, NewState, NewMisc}, where NewState is the new state of the callback module, obtained by calling StateFun, and NewMisc is a possibly new value used to replace the original Misc (required because Misc often contains the state of the callback module within it β€” sneaky like that).

If the callback module does not export a system_replace_state/2 function, replace_state/2,3 assumes that Misc is the state of the callback module, passes it to StateFun and uses the return value as both the new state and as the new value of Misc. Assumptions! We love a confident guess.

If the callback module's function system_replace_state/2 crashes or throws an exception, the caller exits with error {callback_failed, {Module, system_replace_state}, {Class, Reason}}, where Module is the name of the callback module and Class and Reason indicate details of the exception. If the callback module does not provide a system_replace_state/2 function and StateFun crashes or throws an exception, the caller exits with error {callback_failed, StateFun, {Class, Reason}}. Not the cute kind of exit, jsyk πŸ’€

Function system_replace_state/2 is primarily useful for user-defined behaviors and modules that implement OTP special processes. The OTP behavior modules gen_server, gen_statem, and gen_event export this function, so callback modules for those behaviors need not to supply their own. Free real estate 🎁


⭐ resume(Name) -> ok

⭐ resume(Name, Timeout) -> ok

Types:

Name = name()
Timeout = timeout()

Resumes a suspended process. Welcome back bestie, we missed you 🫢


πŸ“ statistics(Name, Flag) -> ok | {ok, Statistics}

πŸ“ statistics(Name, Flag, Timeout) -> ok | {ok, Statistics}

Types:

Name = name()
Flag = true | false | get
Statistics = [StatisticsTuple] | no_statistics
StatisticsTuple =
    {start_time, DateTime1} |
    {current_time, DateTime2} |
    {reductions, integer() >= 0} |
    {messages_in, integer() >= 0} |
    {messages_out, integer() >= 0}
DateTime1 = DateTime2 = file:date_time()
Timeout = timeout()

Enables or disables the collection of statistics. If Flag is get, the statistical collection is returned. Numbers! Data! The math is mathing. πŸ”₯


🧚 suspend(Name) -> ok

🧚 suspend(Name, Timeout) -> ok

Types:

Name = name()
Timeout = timeout()

Suspends the process. When the process is suspended, it only responds to other system messages, but not other messages. Like, it's on do-not-disturb, but system messages are still in the favorites list. 😴


πŸ’œ terminate(Name, Reason) -> ok

πŸ’œ terminate(Name, Reason, Timeout) -> ok

Types:

Name = name()
Reason = term()
Timeout = timeout()

Orders the process to terminate with the specified Reason. Heads up though: the termination is done asynchronously, so it is not guaranteed that the process is terminated when the function returns. It's giving "I sent the text" not "they read the text", ngl. πŸ’€


πŸ’– trace(Name, Flag) -> ok

πŸ’– trace(Name, Flag, Timeout) -> ok

Types:

Name = name()
Flag = boolean()
Timeout = timeout()

Prints all system events on standard_io. The events are formatted with a function that is defined by the process that generated the event (with a call to handle_debug/4). Spammy? Yes. Iconic? Also yes. ✨


πŸ› οΈ PROCESS IMPLEMENTATION FUNCTIONS

The following functions are used when implementing a special process. This is an ordinary process, which does not use a standard behavior, but a process that understands the standard system messages. That's the whole assignment β€” ordinary process, extraordinary system-message literacy. πŸ‘‘

debug_options/1 β€” option-list glow-up ✨

debug_options(Options :: [Opt :: debug_option()]) -> [dbg_opt()]

Okay so this one is for a process that initiates a debug structure from a list of options. The values of argument Opt are the same as for the corresponding functions. Slay πŸ’…


get_debug/3 β€” deprecated but still here, bestie πŸ’€

get_debug(Item, Debug, Default) -> term()

Types:

  • Item = log | statistics
  • Debug = [dbg_opt()]
  • Default = term()
Warning: get_debug/3 is deprecated since it returns data of an internal type only useful for debugging.

It gets the data associated with a debug option. Default is returned if Item is not found. Can be used by the process to retrieve debug data for printing before it terminates. Lowkey useful, highkey deprecated, iykyk 🫢


handle_debug/4 β€” event-formatting central πŸŽ€

handle_debug(Debug, FormFunc, Extra, Event) -> [dbg_opt()]

Types:

  • Debug = [dbg_opt()]
  • FormFunc = format_fun()
  • Extra = term()
  • Event = system_event()

This function is called by a process when it generates a system event. FormFunc is a formatting function, called as FormFunc(Device, Event, Extra) to print the events, which is necessary if tracing is activated. Extra is any extra information that the process needs in the format function, for example, the process name. Obsessed with a clean format function, ngl 🌸


handle_system_msg/6 β€” the system-message handler that never comes back 😭

handle_system_msg(Msg, From, Parent, Module, Debug, Misc) ->
                     no_return()

Types:

  • Msg = term()
  • From = {pid(), Tag :: term()}
  • Parent = pid()
  • Module = module()
  • Debug = [dbg_opt()]
  • Misc = term()

This function is used by a process module to take care of system messages. The process receives a {system, From, Msg} message and passes Msg and From to this function.

This function never returns. It calls either of the following functions:

  • Module:system_continue(Parent, NDebug, Misc), where the process continues the execution.
  • Module:system_terminate(Reason, Parent, Debug, Misc), if the process is to terminate.

Module must export the following:

  • system_continue/3
  • system_terminate/4
  • system_code_change/4
  • system_get_state/1
  • system_replace_state/2

Argument Misc can be used to save internal data in a process, for example, its state. It is sent to Module:system_continue/3 or Module:system_terminate/4. Main character energy for real πŸ‘‘


print_log(Debug) -> ok

Types:

  • Debug = [dbg_opt()]

Prints the logged system events in the debug structure, using FormFunc as defined when the event was generated by a call to handle_debug/4. Cute little event printer moment πŸŽ€


get_log/1 β€” hand over the logged events 🫢

get_log(Debug) -> [system_event()]

Types:

  • Debug = [dbg_opt()]

Returns the logged system events in the debug structure, that is the last argument to handle_debug/4. It's giving "give me the receipts" energy, fr fr 🧾✨


Module:system_code_change/4 β€” code-change converter πŸ¦‹

Module:system_code_change(Misc, Module, OldVsn, Extra) -> {ok, NMisc}

Types:

  • Misc = term()
  • OldVsn = undefined | term()
  • Module = atom()
  • Extra = term()
  • NMisc = term()

Called from handle_system_msg/6 when the process is to perform a code change. The code change is used when the internal data structure has changed. This function converts argument Misc to the new data structure. OldVsn is attribute vsn of the old version of the Module. If no such attribute is defined, the atom undefined is sent. Glow-up via code change, no cap πŸ’œ


Module:system_continue/3 β€” keep going, bestie ✨

Module:system_continue(Parent, Debug, Misc) -> none()

Types:

  • Parent = pid()
  • Debug = [dbg_opt()]
  • Misc = term()

Called from handle_system_msg/6 when the process is to continue its execution (for example, after it has been suspended). This function never returns. Resume era, periodt 🌈


Module:system_get_state/1 β€” state check-in 🌸

Module:system_get_state(Misc) -> {ok, State}

Types:

  • Misc = term()
  • State = term()

Called from handle_system_msg/6 when the process is to return a term that reflects its current state. State is the value returned by get_state/2. Yes bestie, get_state/2 is literally what the page says β€” not me inventing a typo πŸ™ˆ


Module:system_replace_state/2 β€” state swap glow-up πŸ”₯

Module:system_replace_state(StateFun, Misc) -> {ok, NState, NMisc}

Types:

  • StateFun = fun((State :: term()) -> NState)
  • Misc = term()
  • NState = term()
  • NMisc = term()

Called from handle_system_msg/6 when the process is to replace its current state. NState is the value returned by replace_state/3. New state, new me, iconic behavior πŸ’…β­


Module:system_terminate/4 β€” cleanup era πŸ’–

Module:system_terminate(Reason, Parent, Debug, Misc) -> none()

Types:

  • Reason = term()
  • Parent = pid()
  • Debug = [dbg_opt()]
  • Misc = term()

Called from handle_system_msg/6 when the process is to terminate. For example, this function is called when the process is suspended and its parent orders shutdown. It gives the process a chance to do a cleanup. This function never returns. Cleanup before exit is self-care, bestie πŸ«ΆπŸŽ€


mwah πŸ’‹ β€” that's the exports situation, bestie. Footer fairy says: Ericsson AB Β· stdlib 4.3.1.3 Β· sys(3erl). Date? This footer didn't bring one, so I'm not inventing it β€” no cap πŸ™ˆπŸ’œ

πŸ“¦ where this page comes from