gen_event(3)
๐ gen_event โ Erlang Module Definition ๐
ok bestie, sit DOWN, because we're doing gen_event(3) from the Erlang manual and it's genuinely iconic. it's the Generic event handling behavior, and yeah it's a whole manual page but we're getting through it together, one section at a time. slay. ๐
โจ NAME โจ
gen_event โ Generic event handling behavior. that's it, that's the whole name, short and powerful. ๐
๐ธ DESCRIPTION ๐ธ
okay so picture this: this behavior module gives you event handling functionality. it's a generic event manager process, and attached to it is any number of event handlers that get added and deleted dynamically. like a group chat where people keep joining and leaving and the chat itself does not care, it just keeps doing its thing. ๐โ๏ธ
an event manager built with this module gets a standard set of interface functions, plus functionality for tracing and error reporting. it also fits all cute and cozy inside an OTP supervision tree. for more info, see the gen_event section in OTP Design Principles.
each event handler is implemented as a callback module that exports a predefined set of functions. the relationship between the behavior functions and the callback functions is giving this:
gen_event module Callback module
---------------- ---------------
gen_event:start
gen_event:start_monitor
gen_event:start_link -----> -
gen_event:add_handler
gen_event:add_sup_handler -----> Module:init/1
gen_event:notify
gen_event:sync_notify -----> Module:handle_event/2
gen_event:send_request
gen_event:call -----> Module:handle_call/2
- -----> Module:handle_info/2
gen_event:delete_handler -----> Module:terminate/2
gen_event:swap_handler
gen_event:swap_sup_handler -----> Module1:terminate/2
Module2:init/1
gen_event:which_handlers -----> -
gen_event:stop -----> Module:terminate/2
- -----> Module:code_change/3
since each event handler is one callback module, an event manager has many callback modules that get added and deleted dynamically. and that's exactly why gen_event is more tolerant of callback module errors than the other behaviors. literally the chillest of the behaviors. ๐
here's the tea: if a callback function for an installed event handler fails with Reason, or returns a bad value Term, the event manager does not fail. instead it deletes the event handler by calling callback function Module:terminate/2, passing as argument {error, {'EXIT', Reason}} or {error, Term}, respectively. and no other event handler is affected. one handler melting down does not take the whole vibe down with it. ๐ซถ
a gen_event process handles system messages as described in sys. the sys module can be used for debugging an event manager.
โ ๏ธ notice that an event manager does trap exit signals automatically. no cap.
the gen_event process can go into hibernation (see erlang:hibernate/3) if a callback function in a handler module specifies hibernate in its return value. this can be useful if the server is expected to be idle for a long time. however โ use this feature with care, bestie, because hibernation implies at least two garbage collections (one when hibernating, and one shortly after waking up) and is not something you want to do between each event handled by a busy event manager. like, do not. ๐
โจ notice that when multiple event handlers are invoked, it is sufficient that one single event handler returns a hibernate request for the whole event manager to go into hibernation.
unless otherwise stated, all functions in this module fail if the specified event manager does not exist or if bad arguments are specified. periodt.
๐ NOTE: for some important information about distributed signals, see the Blocking Signaling Over Distribution section in the Processes chapter of the Erlang Reference Manual. blocking signaling can, for example, cause call timeouts in gen_event to be significantly delayed. ๐
See Also โ supervisor, sys. the besties of this module. ๐
๐ฆ DATA TYPES ๐ฆ
add_handler_ret() :: ok | term() | {'EXIT', term()}.debug_flag() :: trace | log | statistics | debug | {logfile, string()}.del_handler_ret() :: ok | term() | {'EXIT', term()}.emgr_name() :: {local, atom()} | {global, term()} | {via, atom(), term()}.
event manager name specification: local, global, or via registered. three flavors, all valid, pick your fighter. ๐
{local, Name}โ the event manager is registered locally asNameusingregister/2.{global, GlobalName}โ the event manager is registered globally asGlobalNameusingglobal:register_name/2. if no name is provided, the event manager is not registered.{via, Module, ViaName}โ the event manager registers with the registry represented byModule. theModulecallback is to export the functionsregister_name/2,unregister_name/1,whereis_name/1, andsend/2, which are to behave as the corresponding functions inglobal. thus,{via, global, GlobalName}is a valid reference.
emgr_ref() :: atom() | {atom(), node()} | {global, term()} | {via, atom(), term()} | pid().
a reference used to locate an event manager. the reference can be any of the following:
- the
pidof the event manager Name, if the event manager is locally registered{Name, Node}, if the event manager is locally registered at another node{global, GlobalName}, if the event manager is globally registered{via, Module, ViaName}, if the event manager is registered through an alternative process registry
format_status() :: #{state => term(), message => term(), reason => term(), log => [sys:system_event()]}.
a map that describes the gen_event process status. the keys are:
stateโ the internal state of the event handler.messageโ the message that caused the event handler to terminate.reasonโ the reason that caused the event handler to terminate.logโ thesyslog of the server.
๐ new associations may be added into the status map without prior notice. so don't get too attached to the exact shape, bestie.
handler() :: atom() | {atom(), term()}.handler_args() :: term().options() :: [{timeout, timeout()} | {debug, [debug_flag()]} | {spawn_opt, [proc_lib:start_spawn_option()]} | {hibernate_after, timeout()}].
options that can be used to configure an event handler when it is started. โจ
-opaque request_id()โ an opaque request identifier. seesend_request/3for details. ๐-opaque request_id_collection()โ an opaque collection of request identifiers (request_id/0). each request identifier can be associated with a label chosen by the user. for more information seereqids_new/0.response_timeout() :: timeout() | {abs, integer()}.
response time-out for an asynchronous call. used to set a time limit on how long to wait for a response using either receive_response/2, receive_response/3, wait_response/2, or wait_response/3. the time unit used is millisecond. currently valid values:
0..4294967295โ timeout relative to current time in milliseconds.infinityโ infinite timeout. that is, the operation will never time out. (main character energy tbh.){abs, Timeout}โ an absolute Erlang monotonic time timeout in milliseconds. that is, the operation will time out whenerlang:monotonic_time(millisecond)returns a value larger than or equal toTimeout.Timeoutis not allowed to identify a time further into the future than4294967295milliseconds. identifying the timeout using an absolute timeout value is especially handy when you have a deadline for responses corresponding to a complete collection of requests (request_id_collection/0), since you do not have to recalculate the relative time until the deadline over and over again. ๐ฎ๐จ thank u for that.
start_mon_ret() :: {ok, {pid(), reference()}} | {error, term()}.start_ret() :: {ok, pid()} | {error, term()}.
๐ฅ FUNCTIONS ๐ฅ
๐
add_handler(EventMgrRef :: emgr_ref(), Handler :: handler(), Args :: term()) -> term().
add a new event handler to an event manager. bestie, you're expanding the roster. ๐ซถ
the new event handler is added to event manager EventMgrRef. the event manager calls Module:init/1 to initiate the event handler and its internal state.
Handler is the name of the callback module Module or a tuple {Module, Id}, where Id is any term. the {Module, Id} representation makes it possible to identify a specific event handler, when many event handlers use the same callback module. iykyk. โจ
Args is any term that is passed as the argument to Module:init/1.
if Module:init/1 returns a correct value indicating successful completion, the event manager adds the event handler and this function returns ok. if Module:init/1 fails with Reason or returns {error,Reason}, the event handler is ignored and this function returns {'EXIT',Reason} or {error,Reason}, respectively. simple as that. ๐โ๏ธ
๐
add_sup_handler(EventMgrRef :: emgr_ref(), Handler :: handler(), Args :: term()) -> term().
add a new event handler to an event manager, supervised. it's the same as above but with a bodyguard. ๐
the new event handler is added as for add_handler/3, but the event manager also supervises the connection by linking the event handler and the calling process.
- if the calling process later terminates with
Reason, the event manager deletes any supervised event handlers by callingModule:terminate/2, then callsModule:handle_info/2for each remaining handler. - if the event handler is deleted later, the event manager sends a message
{gen_event_EXIT,Handler,Reason}to the calling process.Reasonis one of the following:normal, if the event handler has been removed because of a call todelete_handler/3, orremove_handlerhas been returned by a callback function (see below).shutdown, if the event handler has been removed because the event manager is terminating.{swapped, NewHandler, Pid}, if the processPidhas replaced the event handler with another event handlerNewHandler, through a call toswap_handler/3orswap_sup_handler/3.- other
term/0, if the event handler is removed because of an error. which term depends on the error. ๐
for a description of the arguments and return values, see add_handler/3.
and that's part 1 wrapped, but we are NOT done, bestie, there's more coming โ do not close the tab. ๐ธโจ
call/4 ๐ซถ
call(EventMgrRef :: emgr_ref(),
Handler :: handler(),
Request :: term(),
Timeout :: timeout()) ->
term().
Okay so this one is a synchronous call to an event handler โ like you're sliding into its DMs and waiting for a reply. ๐
The call gets sent to Handler, which is installed in the event manager EventMgrRef. You send a request and then you wait until a reply shows up or the time-out hits. The event manager is the one that calls Module:handle_call/2 to handle the request. โจ
Request is literally any term, and it gets passed as one of the arguments to Module:handle_call/2. No cap.
Timeout is an integer greater than zero that says how many milliseconds to wait for a reply, or the atom infinity to wait indefinitely. It defaults to 5000. If no reply arrives within the time you specified, the function call fails. ๐ญ
The return value Reply is defined in the return value of Module:handle_call/2. If the specified event handler is not installed, the function returns {error, bad_module}. If the callback function fails with Reason, or returns an unexpected value Term, this function returns {error, {'EXIT', Reason}} or {error, Term}, respectively.
When this call fails it exits the calling process. The exit term is of the form {Reason, Location} where Location = {gen_event, call, ArgList}. See gen_server:call/3 that has a description of relevant values for Reason in the exit term.
check_response/2 ๐ธ
check_response(Msg, ReqId) -> Result
when
Msg :: term(),
ReqId :: request_id(),
Response ::
{reply, Reply :: term()} |
{error, {Reason :: term(), emgr_ref()}},
Result :: Response | no_reply.
Check if a received message is a request response. ๐
So you're checking if Msg is a response that corresponds to the request identifier ReqId. The request must have been made by send_request/3, and by the same process that's calling this function. iykyk.
If Msg is a response corresponding to ReqId, the response is returned in Reply. Otherwise this function returns no_reply and no cleanup is done. So you literally have to invoke this function repeatedly until a response is returned. ๐
If the specified event handler is not installed, the function returns {error, bad_module}. If the callback function fails with Reason or returns an unexpected value Term, this function returns {error, {'EXIT', Reason}} or {error, Term}, respectively. If the event manager has died before this function is called, that is; Msg reports the server's death, this function returns {error,{Reason, EventMgrRef}} where Reason is the exit reason.
check_response/3 ๐ฆ
check_response(Msg, ReqIdCollection, Delete) -> Result
when
Msg :: term(),
ReqIdCollection :: request_id_collection(),
Delete :: boolean(),
Response ::
{reply, Reply :: term()} |
{error, {Reason :: term(), emgr_ref()}},
Result ::
{Response,
Label :: term(),
NewReqIdCollection ::
request_id_collection()} |
no_request | no_reply.
Check if a received message is a request response in a collection. ๐
Check if Msg is a response corresponding to a request identifier stored in ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/3 or send_request/5, and all requests must have been made by the process calling this function.
The Label in the response is the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when storing the request id in a collection, or when sending the request using send_request/5. ๐ท๏ธ
Compared to check_response/2, the returned result or exception associated with a specific request identifier will be wrapped in a 3-tuple {Response, Label, NewReqIdCollection}. Response is the value that would have been produced by check_response/2, Label is the value associated with the specific request identifier and NewReqIdCollection is a possibly modified request identifier collection.
If ReqIdCollection is empty, no_request will be returned.
If Msg does not correspond to any of the request identifiers in ReqIdCollection, no_reply is returned.
If Delete is true, the association with Label has been deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, NewReqIdCollection will equal ReqIdCollection. Note that deleting an association is not for free and that a collection containing already handled requests can still be used by subsequent calls to check_response/3), receive_response/3, and wait_response/3.
However, without deleting handled associations, the above calls will not be able to detect when there are no more outstanding requests to handle, so you will have to keep track of this some other way than relying on a no_request return. Note that if you pass a collection only containing associations of already handled or abandoned requests to check_response/3, it will always return no_reply.
delete_handler/3 ๐
delete_handler(EventMgrRef :: emgr_ref(),
Handler :: handler(),
Args :: term()) ->
term().
Deletes an event handler from an event manager. Bye bestie ๐
This function deletes event handler Handler from event manager EventMgrRef. The event manager calls Module:terminate/2 to terminate the event handler.
Args is any term that is passed as one of the arguments to Module:terminate/2.
The return value is the return value of Module:terminate/2. If the specified event handler is not installed, the function returns {error, module_not_found}. If the callback function fails with Reason, the function returns {'EXIT', Reason}.
notify/2 ๐
notify(EventMgrRef :: emgr_ref(), Event :: term()) -> ok.
Send an asynchronous event notification to an event manager. It's giving fire-and-forget โจ
The event is sent to EventMgrRef, that calls Module:handle_event/2 for each installed event handler to handle the event.
Event is any term that is passed as one of the arguments to Module:handle_event/2.
notify/1 does not fail even if the specified event manager does not exist, unless it is specified as Name.
receive_response/2 ๐
receive_response(ReqId, Timeout) -> Result
when
ReqId :: request_id(),
Timeout :: response_timeout(),
Response ::
{reply, Reply :: term()} |
{error,
{Reason :: term(), emgr_ref()}},
Result :: Response | timeout.
Receive a request response. ๐
Receive a response corresponding to the request identifier ReqId. The request must have been made by send_request/3, and it must have been made from the same process calling this function.
Timeout specifies how long to wait for a response. If no response is received within the specified time, this function returns timeout. Assuming that the server executes on a node supporting aliases (introduced in OTP 24) the request will also be abandoned. That is, no response will be received after a timeout. Otherwise, a stray response might be received at a later time. ๐
The return value Reply is defined in the return value of Module:handle_call/2.
If the specified event handler is not installed, this function returns {error, bad_module}. If the callback function fails with Reason or returns an unexpected value Term, this function returns {error, {'EXIT', Reason}} or {error,Term}, respectively. If the event manager dies before or during the request this function returns {error, {Reason, EventMgrRef}}.
The difference between wait_response/2 and receive_response/2 is that receive_response/2 abandons the request at time-out so that a potential future response is ignored, while wait_response/2 does not.
receive_response/3 ๐
receive_response(ReqIdCollection, Timeout, Delete) -> Result
when
ReqIdCollection ::
request_id_collection(),
Timeout :: response_timeout(),
Delete :: boolean(),
Response ::
{reply, Reply :: term()} |
{error,
{Reason :: term(), emgr_ref()}},
Result ::
{Response,
Label :: term(),
NewReqIdCollection ::
request_id_collection()} |
no_request | timeout.
Receive a request response in a collection. ๐ซถ
Receive a response in ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/3 or send_request/5, and all requests must have been made by the process calling this function.
The Label in the response is the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when adding the request id to a collection, or when sending the request using send_request/5.
Compared to receive_response/2, the returned result or exception tied to one specific request identifier gets wrapped up in a cozy lil 3-tuple {Response, Label, NewReqIdCollection}. Like, unpacking it: Response is exactly the value receive_response/2 would've spit out, Label is the value you associated with that specific request identifier, and NewReqIdCollection is a possibly-modified request identifier collection. Slay. โจ
And if ReqIdCollection is empty? You get no_request back. Nothing more, nothing less. Bestie said "no notes" ๐
Timeout is, of course, the whole "how long do we wait for a response" situation. If nothing shows up inside that window, the function hands you timeout. Now here's the tea โ assuming the server is running on a node that supports aliases (introduced back in OTP 24), every request identified by ReqIdCollection also gets abandoned. Translation: no responses will arrive after the time-out. Otherwise? Stray responses might just roll up later like they weren't supposed to be there. Rude. ๐ญ
The difference between receive_response/3 and wait_response/3 is honestly so important: receive_response/3 abandons the requests at time-out so any potential future responses are just ignored into the void, while wait_response/3 does not do that. Iconic distinction, don't mix them up. ๐ซถ
If Delete is true, the association with Label gets deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, then NewReqIdCollection just equals ReqIdCollection โ no change, no drama. But heads up: deleting an association is not for free, and a collection that's still holding already-handled requests can still be used by subsequent calls to receive_response/3, check_response/3, and wait_response/3. So it's not broken, it's just... heavier.
However (!) โ if you don't delete those handled associations, the calls above will not be able to detect when there are no more outstanding requests to handle. So you'll have to keep track of that some other way than relying on a no_request return. And lowkey the spicy detail: if you pass a collection that only contains associations of already handled or abandoned requests to receive_response/3, it will always block until Timeout expires and then return timeout. Every single time. No cap. ๐
reqids_add(ReqId :: request_id(),
Label :: term(),
ReqIdCollection :: request_id_collection()) ->
NewReqIdCollection :: request_id_collection().
Store a request identifier in a colletion. ๐พโจ
Stores ReqId and associates a Label with the request identifier by adding this info to ReqIdCollection, then hands you back the resulting request identifier collection. Easy.
reqids_new() -> NewReqIdCollection :: request_id_collection().
Create an empty request identifier collection. A blank slate, a fresh start, main character energy. ๐
Returns a new empty request identifier collection. And babes, a request identifier collection can be used to handle multiple outstanding requests at once โ it's the polyamory of request tracking.
Request identifiers of requests made by send_request/3 can be saved in a request identifier collection using reqids_add/3. Then later, that collection of request identifiers can be used to get one response corresponding to a request in the collection โ just pass the collection as an argument to receive_response/3, wait_response/3, or check_response/3. Chef's kiss.
reqids_size/1 can be used to determine the number of request identifiers in a collection. ๐งฎ
reqids_size(ReqIdCollection :: request_id_collection()) ->
non_neg_integer().
Returns the number of request identifiers in ReqIdCollection. That's it. That's the whole function. Sometimes things are simple and that's beautiful. ๐ธ
reqids_to_list(ReqIdCollection :: request_id_collection()) ->
[{ReqId :: request_id(), Label :: term()}].
Convert a request identifier collection to a list. A glow-up from collection-shaped to list-shaped. โจ
Returns a list of {ReqId, Label} tuples which corresponds to all request identifiers with their associated labels inside ReqIdCollection. Every single one, no crumbs left behind.
send_request(EventMgrRef :: emgr_ref(),
Handler :: handler(),
Request :: term()) ->
ReqId :: request_id().
Send an asynchronous call request to an event handler. Fire and forget, but make it trackable. ๐ฅ
This function sends the call request Request to the event handler Handler installed in the event manager identified by EventMgrRef, and returns a request identifier ReqId. That ReqId should later be used with receive_response/2, wait_response/2, or check_response/2 to fetch the actual result of the request. So don't lose it, bestie. ๐
Besides passing the request identifier directly to those functions, it can also be stored in a request identifier collection using reqids_add/3. And a collection of request identifiers can later be used to get one response corresponding to a request in the collection โ pass the collection as an argument to receive_response/3, wait_response/3, or check_response/3. And ngl, if you're about to store the request identifier in a collection anyway, you might wanna consider using send_request/5 instead. Just saying. ๐
The calls gen_event:receive_response(gen_event:send_request(EventMgrRef, Handler, Request), Timeout) can be seen as equivalent to gen_event:call(EventMgrRef, Handler, Request, Timeout), ignoring the error handling. Basically the same vibe, different plumbing.
The event manager calls Module:handle_call/2 to handle the request.
Request may be any term and is passed as one of the arguments to Module:handle_call/2. Anything. A tuple. An atom. A whole vibe. Whatever.
send_request(EventMgrRef :: emgr_ref(),
Handler :: handler(),
Request :: term(),
Label :: term(),
ReqIdCollection :: request_id_collection()) ->
NewReqIdCollection :: request_id_collection().
Send an asynchronous call request to an event handler, storing it in a request identifier collection. Combining two steps into one and we love efficiency in this house ๐
This function sends the call request Request to the event handler Handler installed in the event manager identified by EventMgrRef. The Label will be associated with the request identifier of the operation, and that whole thing gets added to the returned request identifier collection NewReqIdCollection. Bookkeeping? Handled. โ
The collection can later be used to get one response corresponding to a request in the collection by passing the collection as an argument to receive_response/3, wait_response/3, or check_response/3.
Same as calling gen_event:reqids_add(gen_event:send_request(EventMgrRef, Handler, Request), Label, ReqIdCollection), but slightly more efficient. Same energy, less overhead. ๐ฆ
start(EventMgrName :: emgr_name()) -> start_ret();
(Options :: options()) -> start_ret().
Create a stand-alone event manager process, possibly nameless. Free-spirited. Unsupervised in the literal sense only. โจ
Equivalent to start(EventMgrName, Options).
With argument EventMgrName, Options is [].
With argument Options, a nameless event manager is created.
For a description of the arguments and return values, see start_link/2. (Yes bestie, we're cross-referencing, this is a collaborative ecosystem.)
start(EventMgrName :: emgr_name(), Options :: options()) ->
start_ret().
Create a stand-alone event manager process. ๐
The created event manager process is not part of a supervision tree and thus has no supervisor. It's out here living free, no one checking on it, truly independent. ๐
For a description of the arguments and return values, see start_link/2.
start_link(EventMgrName :: emgr_name()) -> start_ret();
(Options :: options()) -> start_ret().
Create an event manager process as part of a supervision tree, possibly nameless. Now this one has a parent. ๐ซถ
Equivalent to start_link(EventMgrName, Options).
With argument EventMgrName, Options is [].
With argument Options, a nameless event manager is created.
For a description of the arguments and return values, see start_link/2.
start_link(EventMgrName :: emgr_name(), Options :: options()) ->
start_ret().
Create an event manager process as part of a supervision tree. The whole point. The main event. ๐
The function is to be called, directly or indirectly, by the supervisor. For example, it ensures that the event manager is linked to the caller (supervisor). So the link is real and it is mutual. ๐
- If option
{hibernate_after, HibernateAfterTimeout}is present, thegen_eventprocess awaits any message forHibernateAfterTimeoutmilliseconds and if no message is received, the process goes into hibernation automatically (by callingproc_lib:hibernate/3). A little nap, as a treat. ๐ด
If the event manager is successfully created, the function returns {ok, Pid} where Pid is the pid/0 of the event manager.
If a process with the specified EventMgrName exists already, the function returns {error,{already_started,OtherPid}}, where OtherPid is the pid of that process, and the event manager process exits with reason normal.
If the event manager fails to start within the specified start timeout {timeout, Time}, which is very unlikely since the start does not interact with other processes, the function returns {error, timeout} and the failed event manager is killed with exit_signal(_, kill). Yeah. Taken out. ๐
If start_link/1,2 returns {error, _}, the started event manager process has terminated. If an 'EXIT' message was delivered to the calling process (due to the process link), that message has been consumed. So no ghost messages lurking.
WARNING: Before OTP 26.0, if the started event manager failed to register its name, this founction could return{error, {already_started, OtherPid}}before the started event manager process had terminated, so starting again might fail because the registered name was not yet unregistered, and an'EXIT'message could arrive later to the process calling this function. But if the start timed out, this function killed the started event manager process and returned{error, timeout}, and then the process link{'EXIT', Pid, killed}message was consumed. The start was made synchronous in OTP 26.0 and a guarantee was implemented that no process link'EXIT'message from a failed start will linger in the caller's inbox. So basically: old behaviour was messy, new behaviour is clean, we stan a synchronous start. ๐
start_monitor(EventMgrNameOrOptions :: emgr_name() | options()) ->
start_mon_ret().
Creates a stand-alone event manager process, monitored, possibly nameless. Monitoring instead of linking โ different flavour of attachment. ๐
Equivalent to start_monitor(EventMgrName, Options).
With argument EventMgrName, Options is [].
With argument Options, a nameless event manager is created.
For a description of the arguments and return values, see start_monitor/2 and start_link/1. (Two refs, because we're thorough like that. ๐
)
๐ซ start_monitor(EventMgtName :: emgr_name(), Options :: options()) -> start_mon_ret(). ๐ซ
start_monitor(EventMgtName :: emgr_name(), Options :: options()) ->
start_mon_ret().
okay so this one โจ creates a stand-alone event manager process, but monitored bestie. Think of it as the same deal as start_link except nobody's holding the leash โ this process is not part of a supervision tree and therefore has no supervisor. A monitor gets atomically set up to the newly created process though, so you will know if it dips. ๐
For the full rundown of arguments and return values, peep start_link/2. But heads up: the return value for a successful start is different from start_link/2. start_monitor/0,1,2 will return {ok, {Pid, Mon}} where Pid is the process identifier of the process, and Mon is a reference to the monitor set up to monitor the process. And if the start is not successful? The caller will be blocked until the DOWN message has been received and removed from the message queue. ๐ญ not the caller catching strays.
๐ stop(EventMgrRef :: emgr_ref(), Reason :: term(), Timeout :: timeout()) -> ok. ๐
stop(EventMgrRef :: emgr_ref(),
Reason :: term(),
Timeout :: timeout()) ->
ok.
Stop an event manager. Simple as that.
It orders the event manager EventMgrRef to exit with the specified Reason, and then waits for it to terminate. Before it actually terminates, gen_event calls Module:terminate(stop,...) for each installed event handler โ so everybody gets to say their goodbyes. ๐ซถ
The function returns ok if the event manager terminates with the expected reason. Any other reason than normal, shutdown, or {shutdown, Term} causes an error report to be issued using logger. ๐จ
Timeout is an integer greater than zero that specifies how many milliseconds to wait for the event manager to terminate, or the atom infinity to wait indefinitely. If the event manager has not terminated within the specified time, the call exits the calling process with reason timeout. โฐ
And if the process does not exist, the call exits the calling process with reason noproc, and with reason {nodedown, Node} if the connection fails to the remote Node where the server runs.
๐ swap_handler(EventMgrRef :: emgr_ref(), OldHandler :: {handler(), term()}, NewHandler :: {handler(), term()}) -> ok | {error, term()}. ๐
swap_handler(EventMgrRef :: emgr_ref(),
OldHandler :: {handler(), term()},
NewHandler :: {handler(), term()}) ->
ok | {error, term()}.
Replace an event handler. Glow-up arc for your handler lineup. ๐
This function replaces an event handler in event manager EventMgrRef.
For a description of OldHandler and NewHandler, see add_handler/3.
So here's the tea โ first the old event handler OldHandler is deleted. The event manager calls OldModule:terminate(Args1, ...), where OldModule is the callback module of OldHandler, and collects the return value. ๐๏ธ
Then the new event handler NewHandler is added and initiated by calling NewModule:init({Args2,Term}), where NewModule is the callback module of NewHandler, and Term is the return value of OldModule:terminate/2. This makes it possible to transfer information from OldHandler to NewHandler. it's giving passing the baton fr fr ๐โโ๏ธ๐จ
Now here's the chaotic part: the new handler is added even if the specified old event handler is not installed, in which case Term = error, or if OldModule:terminate/2 fails with Reason, in which case Term = {'EXIT', Reason}. And the old handler is deleted even if NewModule:init/1 fails. no take-backs. ๐
If there was a supervised connection between OldHandler and a process Pid, there is a supervised connection between NewHandler and Pid instead.
If NewModule:init/1 returns a correct value, this function returns ok. If NewModule:init/1 fails with Reason or returns an unexpected value Term, this function returns {error, {'EXIT', Reason}} or {error, Term}, respectively.
๐ก๏ธ swap_sup_handler(EventMgrRef :: emgr_ref(), OldHandler :: {handler(), term()}, NewHandler :: {handler(), term()}) -> ok | {error, term()}. ๐ก๏ธ
swap_sup_handler(EventMgrRef :: emgr_ref(),
OldHandler :: {handler(), term()},
NewHandler :: {handler(), term()}) ->
ok | {error, term()}.
Replace an event handler, and supervise it. ๐
Replaces an event handler in event manager EventMgrRef in the same way as swap_handler/3, but it also supervises the connection between NewHandler and the calling process.
For a description of the arguments and return values, see swap_handler/3. that's it that's the whole vibe ๐
๐จ sync_notify(EventMgrRef :: emgr_ref(), Event :: term()) -> ok. ๐จ
sync_notify(EventMgrRef :: emgr_ref(), Event :: term()) -> ok.
Send a synchronous event notification to an event manager. โก
The event is sent to EventMgrRef that calls Module:handle_event/2 for each installed event handler to handle the event. This function will return ok after the event has been handled by all event handlers. so you actually wait for the whole group chat to read it, unlike notify. ๐
Event is any term that is passed as one of the arguments to Module:handle_event/2.
โณ wait_response(ReqId, WaitTime) -> Result โณ
wait_response(ReqId, WaitTime) -> Result
when
ReqId :: request_id(),
WaitTime :: response_timeout(),
Response ::
{reply, Reply :: term()} |
{error, {Reason :: term(), emgr_ref()}},
Result :: Response | timeout.
Wait for a request response. (the original man page says "resonse" and honestly same, typos are a mood ๐)
Wait for the response to the request identifier ReqId. The request must have been made by send_request/3, from the same process that called send_request/3. no outsourcing your DMs bestie ๐ต
WaitTime specifies how long to wait for a response. If no response is received within the specified time, the function returns timeout and no cleanup is done. Thus the function can be invoked repeatedly until a reply is returned. ๐
The return value Reply is defined in the return value of Module:handle_call/2.
If the specified event handler is not installed, the function returns {error, bad_module}. If the callback function fails with Reason, or returns an unexpected value Term, this function returns {error,{'EXIT',Reason}} or {error,Term}, respectively. If the event manager dies before or during the request this function returns {error, {Reason, EventMgrRef}}.
The difference between receive_response/2 and wait_response/2 is that receive_response/2 abandons the request at timeout so that a potential future response is ignored, while wait_response/2 does not. ๐ฏ
๐งบ wait_response(ReqIdCollection, WaitTime, Delete) -> Result ๐งบ
wait_response(ReqIdCollection, WaitTime, Delete) -> Result
when
ReqIdCollection :: request_id_collection(),
WaitTime :: response_timeout(),
Delete :: boolean(),
Response ::
{reply, Reply :: term()} |
{error, {Reason :: term(), emgr_ref()}},
Result ::
{Response,
Label :: term(),
NewReqIdCollection ::
request_id_collection()} |
no_request | timeout.
Wait for any request response in a collection. the "whoever texts back first" energy ๐ฒ
Wait for a response in a ReqIdCollection. All request identifiers of ReqIdCollection must correspond to requests that have been made using send_request/3 or send_request/5, and all requests must have been made by the process calling this function.
The Label in the response is the Label associated with the request identifier that the response corresponds to. The Label of a request identifier is associated when adding the request id to a collection, or when sending the request using send_request/5.
Compared to wait_response/2, the returned result or exception associated with a specific request identifier will be wrapped in a 3-tuple {Response, Label, NewReqIdCollection}. Response is the value that would have been produced by wait_response/2, Label is the value associated with the specific request identifier and NewReqIdCollection is a possibly modified request identifier collection.
If ReqIdCollection is empty, no_request will be returned.
If no response is received before the WaitTime has expired, timeout is returned. It is valid to continue waiting for a response as many times as needed up until a response has been received and completed by check_response(), receive_response(), or wait_response(). โฑ๏ธ
The difference between receive_response/3 and wait_response/3 is that receive_response/3 abandons requests at time-out so that potential future responses are ignored, while wait_response/3 does not.
If Delete is true, the association with Label has been deleted from ReqIdCollection in the resulting NewReqIdCollection. If Delete is false, NewReqIdCollection will equal ReqIdCollection. Note that deleting an association is not for free and that a collection containing already handled requests can still be used by subsequent calls to wait_response/3, check_response/3, and receive_response/3.
โ ๏ธ However, without deleting handled associations, the above calls will not be able to detect when there are no more outstanding requests to handle, so you will have to keep track of this some other way than relying on ano_requestreturn. Note that if you pass a collection only containing associations of already handled or abandoned requests to this function, it will always block untilWaitTimeexpires and then returntimeout. ๐
๐ which_handlers(EventMgrRef :: emgr_ref()) -> [handler()]. ๐
which_handlers(EventMgrRef :: emgr_ref()) -> [handler()].
Return all event handlers in an event manager. roster check! ๐ซก
This function returns a list of all event handlers installed in event manager EventMgrRef.
For a description of Handler, see add_handler/3.
๐ CALLBACKS ๐
๐ code_change(OldVsn, State, Extra) ๐
Update the event handler state after code change. โจ
This function is called for an installed event handler that is to update its internal state during a release upgrade/downgrade, that is, when the instruction {update, Module, Change,...}, is specified in the appup file.
For more information, see OTP Design Principles.
For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is {down, Vsn}. Vsn is defined by the vsn attribute(s) of the old version of the callback module Module. If no such attribute is defined, the version is the checksum of the Beam file. ๐
State is the internal state of the event handler.
Extra is passed "as is" from the {advanced, Extra} part of the update instruction.
๐ง glowed up, restructured, and still keeping your State intact โ that's the code_change arc.
...so like, the whole point of this function is to hand back the updated internal state, bestie ๐
โ ๏ธ NOTE: If a release upgrade/downgrade withChange={advanced, Extra}specified in the.appupfile is made whencode_change/3is not implemented the event handler will crash with anundeferror reason. ๐ฑ No cap, that's a whole crash, so implement it, okay?
๐ format_status(Status) ๐
Format/limit the status value โจ
This function gets called by a gen_event process in order to format/limit the server state for debugging and logging purposes.
It gets called in these situations, bestie:
- One of
sys:get_status/1,2is invoked to get thegen_eventstatus. ๐ - The event handler terminates abnormally and
gen_eventlogs an error. ๐
This callback is used to limit the status of the event handler returned by sys:get_status/1,2 or sent to logger.
The callback gets a map Status describing the current status and shall return a map NewStatus with the same keys, but it may transform some values.
Two possible use cases for this callback is to remove sensitive information from the state to prevent it from being printed in log files, or to compact large irrelevant status items that would only clutter the logs. Very main character of you to care about clean logs ๐
Example:
format_status(Status) ->
maps:map(
fun(state,State) ->
maps:remove(private_key, State);
(message,{password, _Pass}) ->
{password, removed};
(_,Value) ->
Value
end, Status).
โ ๏ธ NOTE: This callback is optional, so event handler modules need not export it. If a handler does not export this function, thegen_eventmodule uses the handler state directly for the purposes described below. If this callback is exported but fails, to hide possibly sensitive data, the default function will instead return the fact thatformat_status/1has crashed. ๐
๐ฆ format_status(Opt, StatusData) ๐ฆ
โ ๏ธ Deprecated: the callbackgen_event:format_status(_,_)is deprecated; useformat_status/1instead ๐ (it's giving old news, bestie)
Format/limit the status value โจ
This function is called by a gen_event process in order to format/limit the server state for debugging and logging purposes.
It is called in the following situations:
- One of
sys:get_status/1,2is invoked to get thegen_eventstatus.Optis set to the atomnormalfor this case. - The event handler terminates abnormally and
gen_eventlogs an error.Optis set to the atomterminatefor this case.
This function is useful for changing the form and appearance of the event handler state for these cases. An event handler callback module wishing to change the sys:get_status/1,2 return value as well as how its state appears in termination error logs, exports an instance of format_status/2 that returns a term describing the current state of the event handler.
PDict is the current value of the process dictionary of gen_event.
State is the internal state of the event handler.
The function is to return Status, a term that change the details of the current state of the event handler. Any term is allowed for Status. The gen_event module uses Status as follows:
- When
sys:get_status/1,2is called,gen_eventensures that its return value containsStatusin place of the state term of the event handler. ๐ซถ - When an event handler terminates abnormally,
gen_eventlogsStatusin place of the state term of the event handler. ๐ญ
One use for this function is to return compact alternative state representations to avoid that large state terms are printed in log files.
โ ๏ธ NOTE: This callback is optional, so event handler modules need not export it. If a handler does not export this function, the gen_event module uses the handler state directly for the purposes described below.
๐ธ handle_call(Request, State) ๐ธ
Handle a call ๐
Whenever an event manager receives a request sent using call/3,4, this function is called for the specified event handler to handle the request.
Request is the Request argument of call/3,4.
State is the internal state of the event handler.
The return values are the same as for Module:handle_event/2 except that they also contain a term Reply, which is the reply to the client as the return value of call/3,4. Slay, you get to reply directly ๐
๐ฅ handle_event(Event, State) ๐ฅ
Handle an event ๐
Whenever an event manager receives an event sent using notify/2 or sync_notify/2, this function is called for each installed event handler to handle the event.
Event is the Event argument of notify/2 / sync_notify/2.
State is the internal state of the event handler.
- If
{ok, NewState}or{ok, NewState, hibernate}is returned, the event handler remains in the event manager with the possibly updated internal stateNewState. โจ - If
{ok, NewState, hibernate}is returned, the event manager also goes into hibernation (by callingproc_lib:hibernate/3), waiting for the next event to occur. It is sufficient that one of the event handlers return{ok, NewState, hibernate}for the whole event manager process to hibernate. ๐ด - If
{swap_handler, Args1, NewState, Handler2, Args2}is returned, the event handler is replaced byHandler2by first callingModule:terminate(Args1, NewState)and thenModule2:init({Args2, Term}), whereTermis the return value ofModule:terminate/2. For more information, seeswap_handler/3. ๐ - If
remove_handleris returned, the event handler is deleted by callingModule:terminate(remove_handler, State). ๐
๐ handle_info(Info, State) ๐
Handle an info message (regular process message) ๐ฉ
This function is called for each installed event handler when an event manager receives any other message than an event or a synchronous request (or a system message).
Info is the received message.
In particular, this callback will be made when a process terminated after calling add_sup_handler/3. Any event handler attached to an event manager which in turn has a supervised handler should expect callbacks of the shape Module:handle_info({'EXIT', Pid, Reason}, State).
For a description of State and possible return values, see Module:handle_event/2.
โ ๏ธ NOTE: This callback is optional, so callback modules need not export it. Thegen_eventmodule provides a default implementation of this function that logs about the unexpectedInfomessage, drops it and returns{ok, State}. So chill, it's got you ๐ซถ
๐ง init(InitArgs) ๐ง
Initialize the event handler ๐ฑ
Whenever a new event handler is added to an event manager, this function is called to initialize the event handler.
If the event handler is added because of a call to add_handler/3 or add_sup_handler/3, InitArgs is the Args argument of these functions.
If the event handler replaces another event handler because of a call to swap_handler/3 or swap_sup_handler/3, or because of a swap return tuple from one of the other callback functions, InitArgs is a tuple {Args, Term}, where Args is the argument provided in the function call/return tuple and Term is the result of terminating the old event handler, see swap_handler/3.
If successful, the function returns {ok, State} or {ok, State, hibernate}, where State is the initial internal state of the event handler.
If {ok, State, hibernate} is returned, the event manager goes into hibernation (by calling proc_lib:hibernate/3), waiting for the next event to occur. ๐ด
๐ terminate(Args, State) ๐
Handle event handler termination ๐
Whenever an event handler is deleted from an event manager, this function is called. It is to be the opposite of Module:init/1 and do any necessary cleaning up.
If the event handler is deleted because of a call to delete_handler/3, swap_handler/3, or swap_sup_handler/3, Arg is the Args argument of this function call.
Arg = {stop, Reason}if the event handler has a supervised connection to a process that has terminated with reasonReason. ๐ญArg = stopif the event handler is deleted because the event manager is terminating.- The event manager terminates if it is part of a supervision tree and it is ordered by its supervisor to terminate. Even if it is not part of a supervision tree, it terminates if it receives an
'EXIT'message from its parent. Arg = remove_handlerif the event handler is deleted because another callback function has returnedremove_handleror{remove_handler, Reply}.Arg = {error, Term}if the event handler is deleted because a callback function returned an unexpected valueTerm, orArg = {error, {'EXIT', Reason}}if a callback function failed. ๐
State is the internal state of the event handler.
The function can return any term. If the event handler is deleted because of a call to gen_event:delete_handler/3, the return value of that function becomes the return value of this function. If the event handler is to be replaced with another event handler because of a swap, the return value is passed to the init function of the new event handler. Otherwise the return value is ignored.
โ ๏ธ NOTE: This callback is optional, so callback modules need not export it. The gen_event module provides a default implementation without cleanup. ๐
and that's the whole page, bestie ๐ you ate this one up ngl โจ This lil legend came from Ericsson AB, it's part of stdlib 8.0.4, and the page itself is literally called gen_event(3). Go forth and handle them events like the icon you are ๐
๐
๐ฆ where this page comes from
- ubuntu stonking: erlang-doc 1:29.0.6+dfsg-1 ยท Apache-2.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms