/// Stateful actors in the style of OTP's gen_server. /// /// let counter = actor.start(0, fn(n, msg) { ... }) /// let value = actor.call(counter, Get, 1000) import std/option import std/process.{type Subject, type proc} import std/random.{type random} import std/time.{type clock} /// What a message handler decides. pub type Next { Continue(s), Stop } /// Start an actor with state `init`; `on_message` processes each message. /// Returns the subject to send it messages. pub fn start :: init: s on_message: send fn(s, msg) -> Next / -> Subject / where Send { let ready = process.subject () { use <- process.spawn let inbox = process.subject () process.send ready inbox serve inbox init on_message } process.receive_forever ready } fn serve :: inbox: Subject state: s on_message: fn(s, msg) -> Next / -> () / { match on_message state (process.receive_forever inbox) { Continue(next) -> serve inbox next on_message, Stop -> () } } /// Why `try_call` got no answer. @derive Eq Show pub type CallError { /// No reply within the timeout: the actor is busy, stuck, or stopped. Timeout } /// Send a request carrying a reply subject and wait up to `timeout` /// milliseconds for the answer: `Error(Timeout)` without one. /// /// A reply that arrives after the timeout stays in the caller's mailbox /// until the caller stops: the process API cannot close a subject yet. pub fn try_call :: to: Subject request: fn(Subject) -> msg timeout: Int -> Result / where Send { let reply = process.subject () process.send to (request reply) process.receive reply timeout |> option.to_result Timeout } /// `try_call` for an actor that must answer: panics after `timeout` /// milliseconds without a reply. pub fn call :: to: Subject request: fn(Subject) -> msg timeout: Int -> r / where Send { match try_call to request timeout { Ok(answer) -> answer , Error(Timeout) -> panic "actor.call: no reply within the timeout" } } /// Send a message without waiting. pub fn cast :: to: Subject message: msg -> () / where Send { process.send to message }