Actor (std)
std/actor is written in Agentica, on top of Task and Channel: import Actor from "std/actor". An actor is a task that owns its state and handles the messages of one inbox, one at a time, so its state needs no lock and no ATS table.
- An
Actor.Behaviour[S, M]is a struct of functions, the contract of an actor, since Agentica has no traits:initmakes the first state andhandletakes the state and a message and gives the next step.Sis the state andMthe message type, an enum of your own. Actor.startruns it in a task of its own and gives anActor.Ref[S, M]. Itsaddressis theAddress[M]of the inbox: data that a table, a message or a struct can hold.cast,callandsendtake that address;stoptakes theRef.- A module usually hides the message enum behind its own functions (
Counter.add,Counter.get), and keeps the addresses of its actors by name in a constant table, one per message type. There is no registry inside the library. - There are no methods: call
Actor.cast(address, message).
Actor.start #
Actor.start(behaviour: Actor.Behaviour[S, M], options: Actor.Options = Actor.Options()) -> Actor.Ref[S, M]
Actor.Behaviour(init: Fn[S], handle: Fn[S, M, Actor.Step[S]], terminate: Optional[Fn[S, Void]] = none, timeout: Optional[Actor.Timeout[S]] = none)
Actor.Options(capacity: Int = 1024)
Actor.continue(state: S) -> Actor.Step[S]
Actor.done(state: S) -> Actor.Step[S]Starts the actor in a task of its own. The task runs init, then takes the messages of the inbox in the order they came and gives each to handle with the state. The handler ends with Actor.continue(state) to keep going with that state, or Actor.done(state) to end the actor: it then handles no more messages and runs terminate with the last state. capacity is how many messages the inbox holds before cast and call wait for room (1 to 1048576, else RUNTIME-INVALID-COUNT).
The task owns the inbox, so the inbox closes when the actor ends in any way: it stopped, gave done, crashed or was cancelled. A runtime error in a handler is a crash of the actor’s task (see Task): its diagnostic prints at once, terminate does not run, and the messages left in the inbox are lost. A crash that nothing observes fails the run when main returns (1 task crash was not observed); Actor.stop, Task.await(actor.task) or a Task.monitor of actor.task observes it.
The actor’s task is a child of the task that calls start: a crash or cancel of that task cancels the actor too. Start a long-lived actor from main or a supervisor.
A Ref has three fields: address, inbox (the Channel[M]) and task. Send through address. The inbox is there only for Task.monitor: never receive from it, which would take a message from the actor.
Actor.inbox #
Actor.inbox() -> Channel[M]The inbox of the running actor, as Erlang’s self(): init, a handler, terminate or a timeout can monitor a task into it, Task.monitor(task, inbox) do |down| Msg.Down(down) end, or give out inbox.address. Never receive from it. M comes from the expected type, inbox: Channel[Msg] = Actor.inbox, and is not checked: it must be the actor’s message type, or a value sent through it crashes the actor’s handler with RUNTIME-INTERNAL. Called outside an actor’s task, also in a task the actor spawned, it is RUNTIME-UNWRAP-ERROR (actor: not in an actor).
Actor.cast and Actor.call #
Actor.cast(address: Address[M], message: M, timeout_ms: Int = 5000) -> Result[Void]
Actor.call(address: Address[M], timeout_ms: Int, make: Fn[Channel[R], M]) -> Result[R]
Actor.reply(channel: Channel[R], value: R) -> Boolcast puts a message in the inbox and returns; it waits at most timeout_ms for room when the inbox is full. call makes a reply channel, builds the message around it with the block, sends it and waits for the answer, all within timeout_ms. The handler answers with Actor.reply(channel, value), which never waits, gives whether the caller gets the value and closes the channel: a call has one answer, so a second one gives false. A call that gives up closes its reply channel, so a later reply gives false and the value is still the actor’s to keep (a pool puts the worker back); an answer that came just before the call gave up is returned by the call. So an answer is never lost: either the call returns it, or reply gives false. The one exception is a caller that is cancelled while it waits: its channel stays open, and reply gives true for a value nobody reads. Each call has its own reply channel, so an answer never reaches a later call. A timeout_ms of 0 tries once: cast sends only when there is room, and call(address, 0) still puts the message in the inbox, then usually gives actor: timeout. Give call a timeout above 0; a negative one is RUNTIME-INVALID-DURATION.
Errors: actor: timeout (kind channel.timeout) when the inbox stays full or the answer does not come in time, and address: gone (kind channel.gone) when the actor has ended. A call whose actor crashes or ends before it answers waits for its timeout. A call to the actor’s own address from its handler, or two actors that call each other, wait for their timeouts too, since an actor handles one message at a time; send the work to another task instead.
The type of the answer comes from the expected type (the result type of the function that returns the call, or an annotation), or else from the block: in Msg.Get(reply) the variant’s payload makes reply a Channel[Int], so puts(Actor.call(address, 1000) do |reply| Msg.Get(reply) end) works too.
import Actor from "std/actor"
enum Msg
Add(Int)
Get(Channel[Int])
end
def handle(count: Int, msg: Msg) -> Actor.Step[Int]
case msg
Msg.Add(n) -> Actor.continue(count + n)
Msg.Get(reply) ->
Actor.reply(reply, count)
Actor.continue(count)
end
end
def zero() -> Int = 0
def total(address: Address[Msg]) -> Result[Int] = Actor.call(address, 1000) do |reply| Msg.Get(reply) end
def main() -> Void
actor = Actor.start(Actor.Behaviour(init: &zero, handle: &handle))
for n in 1..4
_ = Actor.cast(actor.address, Msg.Add(n))
end
puts(total(actor.address))
puts(Actor.stop(actor, 1000))
puts(total(actor.address))
endok(10)
ok()
error("address: gone", kind: "channel.gone")Actor.send and Actor.await #
Actor.send(address: Address[M], make: Fn[Channel[R], M], timeout_ms: Int = 5000) -> Result[Actor.Request[R]]
Actor.await(request: Actor.Request[R], timeout_ms: Int) -> Result[R]The two halves of call, for requests to several actors at once: send each request first, then await the answers in order, so the waits overlap. send makes a reply channel, builds the message around it with the block, waits at most timeout_ms for room in the inbox and gives an Actor.Request[R]; its errors are those of cast. await waits at most timeout_ms for the answer and keeps the guarantees of call: an await that gives up closes the reply channel, so a later reply gives false, and an answer that came just before is returned. A request has one answer: a second await gives actor: timeout at once. call(address, timeout_ms) do ... end is a send and an await within one timeout_ms. send takes make before timeout_ms, so with the block form pass the timeout by name: Actor.send(address, timeout_ms: 100) do |reply| Msg.Get(reply) end.
import Actor from "std/actor"
enum Msg
Work(Int, Channel[Int])
end
def handle(state: Int, msg: Msg) -> Actor.Step[Int]
case msg
Msg.Work(n, reply) ->
Task.sleep(300)
Actor.reply(reply, n * 10)
Actor.continue(state)
end
end
def main() -> Void
behaviour: Actor.Behaviour[Int, Msg] = Actor.Behaviour(init: -> { 0 }, handle: &handle)
shards = [Actor.start(behaviour), Actor.start(behaviour)]
started = Time.monotonic_ms
first = Actor.send(shards[0].address) do |reply| Msg.Work(1, reply) end
second = Actor.send(shards[1].address) do |reply| Msg.Work(2, reply) end
puts(Actor.await(first.unwrap!, 1000))
puts(Actor.await(second.unwrap!, 1000))
# Two calls one by one take at least 600 ms.
puts(Time.monotonic_ms - started < 600)
for shard in shards
_ = Actor.stop(shard, 1000)
end
endok(10)
ok(20)
trueActor.stop #
Actor.stop(actor: Actor.Ref[S, M], timeout_ms: Int) -> Result[Void]Closes the inbox and waits at most timeout_ms for the actor to end: it handles the messages already in its inbox (so a call that is waiting there gets its answer), runs terminate and ends. A cast, call or send after the close gives error("address: gone"). An actor still running after timeout_ms is cancelled and stop gives actor: timeout (kind task.timeout). An actor that crashed gives its task crashed: ... error, and stopping it observes the crash. Stopping an actor that has ended gives how it ended. timeout_ms must be above 0, else RUNTIME-INVALID-DURATION.
Only the holder of the Ref can stop the actor. To stop it through an address, give the message enum a Stop variant whose handler gives Actor.done(state).
Names and addresses #
A module keeps the addresses of its actors in a constant ATS table and wraps the messages in its own functions, so callers never see the enum. A caller that looks the name up on each call reaches the actor that holds the name now.
import Actor from "std/actor"
module Counter
def start(name: String, initial: Int) -> Result[Void]
actor = Actor.start(Actor.Behaviour(init: -> { initial }, handle: &handle))
return ok() if NAMES.put_new(name, actor.address)
_ = Actor.stop(actor, 1000)
error("counter: #{name} is taken")
end
def add(name: String, n: Int) -> Result[Void]
address = try NAMES.get(name)
Actor.cast(address, Msg.Add(n))
end
def get(name: String) -> Result[Int]
address = try NAMES.get(name)
Actor.call(address, 1000) do |reply| Msg.Get(reply) end
end
def stop(name: String) -> Result[Void]
address = try NAMES.get(name)
NAMES.delete(name)
Actor.cast(address, Msg.Stop)
end
private
NAMES: ATS[String, Address[Msg]] = ATS.new()
enum Msg
Add(Int)
Get(Channel[Int])
Stop
end
def handle(count: Int, msg: Msg) -> Actor.Step[Int]
case msg
Msg.Add(n) -> Actor.continue(count + n)
Msg.Get(reply) ->
Actor.reply(reply, count)
Actor.continue(count)
Msg.Stop -> Actor.done(count)
end
end
end
def main() -> Void
_ = Counter.start("visits", 100)
puts(Counter.start("visits", 0))
_ = Counter.add("visits", 5)
puts(Counter.get("visits"))
puts(Counter.stop("visits"))
puts(Counter.get("visits").ok?)
enderror("counter: visits is taken")
ok(105)
ok()
falseActor.Timeout #
Actor.Timeout(after_ms: Fn[S, Optional[Int]], handle: Fn[S, Actor.Step[S]])A receive timeout wakes the actor when no message came in time, with no timer task. After init and after each message (or timeout), the actor calls after_ms with its state: some(ms) waits at most that long for the next message, and none waits without a limit. When no message comes in that time, handle runs with the state, in place of a message, and gives the next step as a message handler does. A message starts the wait again, as a receive ... after does in Erlang. For a deadline that messages must not push back, keep the deadline in the state and give what is left of it: some(deadline - Time.monotonic_ms), done in the message handler too once it has passed. A wait of 0 or less takes only a message that is already in the inbox, as Erlang’s after 0 does: with none there, handle runs at once. So a deadline that passed while a message was handled runs the timeout next. An after_ms that always gives 0 or less keeps the actor busy, as a loop that never waits does. A stop or a crash with a wait pending leaves nothing behind, and an actor that a supervisor starts again waits from its new init.
import Actor from "std/actor"
enum Msg
Get(Channel[Int])
end
def handle(ticks: Int, msg: Msg) -> Actor.Step[Int]
case msg
Msg.Get(reply) ->
Actor.reply(reply, ticks)
Actor.continue(ticks)
end
end
# Three ticks, 10 ms apart when no message comes, then no more.
def after_ms(ticks: Int) -> Optional[Int]
return none if ticks == 3
some(10)
end
def tick(ticks: Int) -> Actor.Step[Int] = Actor.continue(ticks + 1)
def main() -> Void
timeout = Actor.Timeout(after_ms: &after_ms, handle: &tick)
actor = Actor.start(Actor.Behaviour(init: -> { 0 }, handle: &handle, timeout: some(timeout)))
Task.sleep(100)
puts(Actor.call(actor.address, 1000) do |reply| Msg.Get(reply) end)
puts(Actor.stop(actor, 1000))
endok(3)
ok()Monitors and timers #
There is no select: whatever an actor waits for comes in as a variant of its message enum. Task.monitor(task, actor.inbox) do |down| Msg.Down(down) end sends a notice into the inbox when the task ends; a notice that finds the inbox full still goes in, past its capacity. To wake when no message came, give the behaviour an Actor.Timeout; a timer that sends a message of its own is a task that sleeps, then casts to the address.
import Actor from "std/actor"
enum Msg
Down(TaskDown)
Tick
Seen(Channel[Int])
end
def handle(seen: Int, msg: Msg) -> Actor.Step[Int]
case msg
Msg.Down(_) -> Actor.continue(seen + 1)
Msg.Tick -> Actor.continue(seen + 10)
Msg.Seen(reply) ->
Actor.reply(reply, seen)
Actor.continue(seen)
end
end
def zero() -> Int = 0
def tick(address: Address[Msg]) -> Result[Void]
Task.sleep(10)
Actor.cast(address, Msg.Tick)
end
# The notice and the tick come from tasks of their own: ask until both are in.
def seen(address: Address[Msg]) -> Result[Int]
for _ in 1..100
count: Int = try Actor.call(address, 1000) do |reply| Msg.Seen(reply) end
return ok(count) if count == 11
Task.sleep(10)
end
error("not seen")
end
def main() -> Void
actor = Actor.start(Actor.Behaviour(init: &zero, handle: &handle))
worker = Task.spawn do 42 end
Task.monitor(worker, actor.inbox) do |down| Msg.Down(down) end
timer = Task.spawn(&tick, actor.address)
_ = Task.await(worker)
_ = Task.await(timer)
puts(seen(actor.address))
puts(Actor.stop(actor, 1000))
endok(11)
ok()