/// Actors: lightweight processes that share nothing and talk by messages /// (ADR 0004). The `proc` effect is handled by the runtime around `main` /// and around every actor, so tests can also handle it themselves. import std/list import std/random.{type random} import std/time.{type clock} /// Identifies an actor. @builtin pub type Pid /// Where messages of type `msg` are sent: an actor plus a tag that keeps /// different message types apart. Only the owner can receive from it. /// /// Opaque (ADR 0072): only `subject` makes one, so a subject's tag always /// carries messages of its type, which `select` relies on, and which /// distribution relies on across hosts. `owner` and `tag` read it. pub opaque type Subject { Subject(owner: Pid, tag: Int) /// Owned by an actor on another node: only the runtime makes one, when /// a subject comes off the wire. `wire` is its message type's index in /// the node's type registry. The runtime reads both constructors /// (`process.rs`), so their order and fields are fixed. , Remote(owner: Pid, tag: Int, wire: Int) } /// The actor that owns `subject`: the only one that can receive from it. pub fn owner :: subject: Subject -> Pid { match subject { Subject(owner, _) -> owner, Remote(owner, _, _) -> owner } } /// The tag that tells `subject`'s messages apart in its owner's mailbox. pub fn tag :: subject: Subject -> Int { match subject { Subject(_, tag) -> tag, Remote(_, tag, _) -> tag } } /// Why an actor stopped. @derive Eq Show pub type ExitReason { Normal , Killed , Crashed(String) /// Asked to stop (`stop`), not crashed: a supervisor's orderly shutdown /// (ADR 0060). , Shutdown } /// Sent to a monitoring actor when the monitored one stops. pub type Down { Down(pid: Pid, reason: ExitReason) } /// Delivered to a linked actor that traps exits. pub type ExitSignal { ExitSignal(pid: Pid, reason: ExitReason) } pub effect proc { /// Start an actor running `body`. It gets the runtime's handlers of /// `proc`, `clock` and `random`, not the caller's (ADR 0036). fn spawn :: body: send fn() -> () / -> Pid /// The current actor. fn self :: -> Pid /// A new subject owned by the current actor. fn subject :: -> Subject /// Put `message` in the mailbox of `to`'s owner. It must be sendable /// (ADR 0004, Revision 6): no `Ref`, no resource that is not /// `@thread_safe`. For a local sender, a send in progress at its exit /// delivers before its exit's local `Down`; a send started after its kill /// drops the message instead. fn send :: to: Subject message: m -> () where Send /// The oldest message on `from`, waiting up to `timeout` milliseconds /// (`0`: don't wait, negative: forever). fn receive :: from: Subject timeout: Int -> Option /// Link with `pid`: when either stops abnormally, the other stops too /// (or, if it traps exits, receives an `ExitSignal`). fn link :: pid: Pid -> () /// Receive a `Down` message on the returned subject when `pid` stops. fn monitor :: pid: Pid -> Subject /// Stop `pid` with reason `Killed`. fn kill :: pid: Pid -> () fn trap_exits :: on: Bool -> () /// Where trapped exit signals arrive. fn exits :: -> Subject fn sleep :: milliseconds: Int -> () /// The oldest message on any of these subject tags, with its tag (see /// `select`, which checks the subjects are the caller's). fn receive_any :: tags: List timeout: Int -> Option<(Int, Dynamic)> /// Start an actor linked to the current one. Spawning and linking are /// one step, so even a child that stops at once is linked. fn spawn_link :: body: send fn() -> () / -> Pid /// Start an actor monitored by the current one: its `Down` message /// arrives on the returned subject. Spawning and monitoring are one /// step, so the reason is the real one even if the actor stops at once. fn spawn_monitor :: body: send fn() -> () / -> (Pid, Subject) /// Ask `pid` to stop (ADR 0060): if it traps exits, it gets /// `ExitSignal(self(), Shutdown)`, to clean up and return; otherwise it /// stops at once with reason `Shutdown`, which its links and monitors /// see. Unknown or exited pids are ignored. fn stop :: pid: Pid -> () /// Stop monitoring `pid`: `down` is the subject `monitor pid` (or /// `spawn_monitor`) returned. From now on no `Down` arrives on it; one /// that already arrived stays (`demonitor_flush` drops it, too). Any /// other pid or subject is ignored; `down` must be the caller's. fn demonitor :: pid: Pid down: Subject -> () /// Remove the link with `pid`: once it returns, the link has no effect /// on the caller (until a new `link`), and the caller's exit none on /// `pid`. An `ExitSignal` that already arrived stays. No link, or a pid /// that is gone: nothing. fn unlink :: pid: Pid -> () } /// `demonitor`, then drop the `Down` that may already have arrived on /// `down` (Erlang's `demonitor(ref, [flush])`): afterwards, `down` holds no /// message. pub fn demonitor_flush :: pid: Pid down: Subject -> () / { demonitor pid down let _ = receive down 0 } /// A message whose type is known only to the subject it was sent on. /// Programs never see one: `select` turns it back into its type. @builtin pub type Dynamic /// Receives from several subjects at once, mapping each one's messages to /// one type (as in Gleam OTP): /// /// let selector = process.new_selector() /// |> process.selecting(replies, Number(_)) /// |> process.selecting(process.exits(), Exited(_)) /// match process.select(selector, 1000) { ... } /// /// Opaque: an entry pairs a subject's tag with a map that reads its /// messages as that subject's type, and only `selecting` may pair them. /// Rebuilt by a program, an entry could read one subject's message as /// another's type. pub opaque type Selector { Selector(entries: List<(Pid, Int, fn(Dynamic) -> m)>) } pub fn new_selector :: -> Selector { Selector([]) } /// Also receive from `from`, mapping its messages with `map`. pub fn selecting :: selector: Selector from: Subject map: fn(a) -> m -> Selector { // Sound: every message under `from`'s tag was sent as an `a`. Selector( [ (owner from, tag from, fn message { map (coerce message) }) , ..selector.entries ] ) } /// The oldest message on any of the selector's subjects, mapped, waiting /// up to `timeout` milliseconds (`0`: don't wait, negative: forever). pub fn select :: selector: Selector timeout: Int -> Option / { let me = self () let entries = selector.entries if list.any entries fn e { let (owner, _, _) = e !pid_eq owner me } { panic "select on a subject owned by another actor" } else { match receive_any (list.map entries fn e { e.1 }) timeout { Some((tag, message)) -> Some(dispatch entries tag message), None -> None } } } /// `select` waiting as long as it takes. pub fn select_forever :: selector: Selector -> m / { match select selector (-1) { Some(message) -> message, None -> panic "select_forever: no message" } } fn dispatch :: entries: List<(Pid, Int, fn(Dynamic) -> m)> tag: Int message: Dynamic -> m { match entries { [ (_, t, map) , ..rest ] -> if t == tag { map message } else { dispatch rest tag message } , [] -> panic "select: a message for no subject" } } @extern c "tl_coerce" fn coerce :: x: a -> b @extern c "tl_pid_eq" fn pid_eq :: a: Pid b: Pid -> Bool impl Eq { fn eq :: a b { pid_eq a b } } /// Wait for the next message on `from`, however long it takes. pub fn receive_forever :: from: Subject -> m / { match receive from (-1) { Some(message) -> message, None -> panic "receive_forever: no message" } }