Actors and state machines
actor and machine declarations: typed messages, what may be sent and how the compiler checks it, tell and ask, supervision of a trap, lifecycle and watching, scheduling on a pool, routers and topics, and states with transitions and stashed messages.
Avin’s way to thread safety is no shared data where it can be avoided. An actor owns its state outright, and the only way to reach that state is to send the actor a message. Messages carry immutable values, or hand over the ownership of something mutable, and never a reference that two actors could both change. The compiler checks every message type, so a program that compiles never shares mutable data through a message.
The pieces fit together without special cases: an actor is declared like a class, its messages are a
data type, receiving one is a match, a reply arrives as a Future, and
an actor’s behaviour, where it has distinct phases, is written as a state machine in the same body.
Everything runs on the threads, executors and memory model of avin.threads; the
library is avin.actors.
Declaring an actor
import avin.actors.{ActorRef, spawn}
data CounterMsg
Increment(by: int)
Get(replyTo: ActorRef[int])
Reset
actor Counter(start: int) receives CounterMsg
var count = start
receive
Increment(by) -> count += by
Get(replyTo) -> replyTo.tell(count)
Reset -> count = 0
actor Name(params) receives Mdeclares an actor whose messages are of typeM, usually adatatype whose variants are the messages. An actor may be generic,actor Cache[K: Hash + Sendable, V: Sendable](limit: int) receives CacheMsg[K, V], and its parameters follow the rules for a class’s, with defaults and named arguments.- The body is the actor’s start. Its fields and statements run once, on the actor’s own
execution, before it handles any message: that is where its state is made. The parameters are its
immutable fields, as a class’s plain parameters are, and each one’s type must be
Sendable, which is checked where the actor is declared. Since an actor runs on any of an executor’s workers, nothing its body, its arms or its methods reach may be a module-levelvaror a module-level value that is not sendable. receiveholds the arms that handle a message: exactly amatch‘s arms overM, with patterns, guards and block bodies, and checked for exhaustiveness and for unreachable arms in the same way. A message the actor wants to ignore is handled by an arm that does nothing,_ -> (), so ignoring one is always written down. Each arm’s value is discarded.- Methods in the body are the actor’s own helpers, with the implicit receiver a class’s methods have. They are private: an actor has no members anyone else can call, since only its messages reach it.
selfis the actor’s reference, anActorRef[M], which it hands out so others can reply to it or send it more work. The object holding the actor’s fields is never a value the program sees, so no reference to an actor’s state can escape the actor.
Counter(0) does not start anything. It makes a Behaviour[CounterMsg]: an immutable value
holding the declaration and its arguments, which spawn starts. Keeping the two apart lets the
program say how a new actor is to be supervised and where it runs before it starts, and lets the
runtime start the actor again from the same arguments after a failure (Supervision).
A behaviour is also made without a declaration, from a name and a start:
Behaviour[M](name: string, start: @sendable (ActorRef[M]) -> (M) -> unit). The start runs
once, on the actor’s first turn, is given the actor’s own reference, makes the actor’s state in its
locals and gives back the handler of each message. It is a @sendable
function, so it captures only sendable values and no var, and
reaches no module-level mutable state. An actor declaration is this, written as a class is:
import avin.actors.{Behaviour, spawn}
import avin.threads.Promise
main()
val total = Promise[int]()
val counter = spawn(Behaviour[int]("Counter", me ->
var count = 0
n ->
count += n
if n == 0 then total.complete(count)))
counter.tell(5)
counter tell 2
counter.tell(0)
println(total.future.await())
Starting, telling and asking
import avin.actors.{spawn, AskError}
import avin.time
main() -> int
val counter = spawn(Counter(10))
counter.tell(Increment(5))
counter tell Increment(2)
val answer = counter.ask(r -> Get(r), timeout = time.seconds(1)).await()
answer match
Ok(n) -> n
Err(_) -> 1
spawn[M](behaviour: Behaviour[M], onFailure: Supervision = Escalate, executor: Executor = Executor.shared(), mailbox: Mailbox = Unbounded) -> ActorRef[M]starts the actor and gives back its reference at once; the body runs on the executor’s threads, and messages sent before it has finished queue behind it. Called by code an actor is running,spawnstarts a child of that actor; called anywhere else (main, a thread, a future’s body) it starts a top-level actor.mailboxbounds the messages that may wait.tell(message: M)puts the message in the actor’s mailbox and returns at once; it never waits and never fails. A tell to a full bounded mailbox is dropped as its overflow policy says.!is a reserved spelling in Avin, so there is no operator for it, andtellis written infix where that reads better (counter tell Reset).ask[R: Sendable](make: ActorRef[R] -> M, timeout: Duration) -> Future[Result[R, AskError]]makes a reference that accepts one reply, builds the message around it withmake, sends it, and gives back the future of the reply. The first message to the reply reference completes the future withOk; any later one is dropped.AskErrorisTimedOutwhere no reply arrived withintimeout,Endedwhere the asked actor had already ended, so the message could not be delivered, andFullwhere its bounded mailbox was full, so the question was not put in it. The timeout is required: an ask always ends.- A reply address is an ordinary
ActorRef[R]. An actor that asks another passes the reply referenceaskmakes, or its ownselfwhere its message type isR, or an adapter:adapter[R: Sendable](f: R -> M) -> ActorRef[R], called in an actor, makes a reference whose messages arrive in this actor’s mailbox asfof them, so an actor talks to one with another protocol without widening its own message type.fruns where the message is sent, so it is@sendable; the adapter refers to this actor, equal to itsselfand ending with it. The reference an ask makes is shown asReply#1, the replies numbered apart from the actors, and ends once its ask is answered or has timed out. ActorRef[-M]is contravariant: a reference that accepts everyShapeis also one that acceptsCircles. It compares by the actor it refers to (==andhash), isSendableand is shown as the declaration’s name and a number,Counter#3, the actors of a program being numbered from one in the order they are spawned. It holds no state, so holding one keeps nothing but the reference alive.
Any thread may tell and ask. Inside an actor, waiting for an ask’s future with await holds the
actor: it handles no other message until the reply comes, which is sometimes what is wanted. The
usual way is pipeToSelf[T](future: Future[T], f: T -> M), which sends the actor f of the
value once the future completes, so the actor goes on handling messages meanwhile; a future complete
already sends at once, before anything the actor sends itself after the call. f runs in the
actor’s own turn, so a trap in it fails this actor, not whatever completed the future. An actor
that awaits an ask of itself waits until the timeout.
An adapter’s f runs where the message is sent, so a trap in it is the sender’s: it fails the
actor that sent, or stops the program where main or a thread sent.
Mailboxes and order
A mailbox is a queue, unbounded unless the actor was given a bound. Two messages one sender sends
to one actor arrive in the order they were sent; messages from different senders interleave in any
order. A message sent to an actor that has ended is dropped, since an actor ending while messages
are on their way to it is an ordinary race and not a bug; a program that needs to know when an
actor ends watches it, and an ask of one completes with Ended.
Bounded mailboxes
An unbounded mailbox lets a fast sender grow a slow actor’s memory without limit. An actor spawned
with mailbox = Bounded(capacity, overflow) holds at most capacity of the messages its
references send, and its senders choose how to meet a full one:
import avin.actors.{Bounded, DropOldest, spawn}
import avin.threads.{Future, Promise}
import avin.time
data Reading
Pause(started: Promise[unit], resume: Future[unit])
Value(n: int)
Latest(values: Promise[string])
actor Gauge receives Reading
val values = Buffer[int]()
receive
Pause(started, resume) ->
started.complete(())
resume.await()
Value(n) -> values.append(n)
Latest(p) -> p.complete(s"$values")
main()
val gauge = spawn(Gauge(), mailbox = Bounded(3, DropOldest))
val started = Promise[unit]()
val resume = Promise[unit]()
gauge.tell(Pause(started, resume.future))
started.future.await()
for n in 1 .. 5 do gauge tell Value(n)
println(gauge.offer(Value(6)))
println(gauge.dropped())
resume.complete(())
val latest = Promise[string]()
println(gauge.send(Latest(latest), time.seconds(5)))
println(latest.future.await())
Err(the actor's mailbox was full)
2
Ok(())
[3, 4, 5]
data MailboxisUnbounded, the default, orBounded(capacity: int, overflow: Overflow). A capacity less than one traps inspawn. The bound is the actor’s for its whole life: a restart keeps the mailbox, the messages in it and its bound.tellnever waits, so a tell to a full mailbox is settled by theOverflow:DropNewestdrops the message told, andDropOldestdrops the oldest message waiting that a reference sent, and puts the one told at the back. Either way the message dropped is gone as a message sent to an ended actor is; a question among them times out.offer(message: M) -> Result[unit, SendError]puts the message in only where there is room now, and never waits:Err(Full)where the mailbox is full,Err(Ended)where the actor has ended, the message then put nowhere and its handles still the sender’s. An unbounded mailbox is never full.send(message: M) -> Result[unit, SendError]waits while the mailbox is full until the actor takes a message and there is room, the backpressure a producer that must not outrun its consumer wants;send(message: M, timeout: Duration)waits at mosttimeout, answeringErr(TimedOut)where no room came, and a timeout of zero or less isoffer. A sender waiting when the actor ends is toldErr(Ended). The wait parks only the waiting thread, counts for the deadlock check, and is a cancellation point: a cancelled sender stops there and leaves nothing in the mailbox. Senders waiting are let in as room frees, each sender’s messages in the order it sent them. An actor that sends to its own full mailbox hasErr(Full)at once, since nothing could make room while its turn waits; to an unbounded or roomy one,sendistellthat answers.asknever waits for room and never drops for it: an ask of a full mailbox completes at once withErr(Full), under either policy, rather than waiting out its timeout.dropped() -> longon the reference counts the messages the overflow policy has dropped since the actor started; a refusedofferorsend, and the messages dropped as the actor ends, are not among them.- What the actor arranged for itself is never refused. A watch‘s notice of an end,
a timer‘s message and a
pipeToSelf‘s message are put in the mailbox whatever it holds and do not count against the bound, so a full mailbox drops no notice. A stop, a restart and a child’s failure are not messages, and a full mailbox never holds them back. The messages a stash gives back have passed the bound once, and do not count against it again. SendErrorisFull,TimedOutorEnded;FullandEndedare namesAskErrorhas too, and each is decided by the type expected where it is written.
What may be sent
A message type, an actor’s parameters and every type ask and adapter carry must be
Sendable. Sendable is a trait the compiler decides for each type from its structure; it is
written as a bound like any trait ([T: Sendable]), and ActorRef[M]‘s parameter is bounded by it,
so the check is made once, where the type is named, and never at a send:
| Sendable | Why |
|---|---|
int and the other integers, byte, real, char, bool, unit, string | immutable values |
tuples, data types (Option, Result and Either among them) whose fields are all sendable | immutable values |
List, Vector, ArraySeq, Range, the immutable Map and Set, of sendable elements | immutable, persistent collections |
a class with no var field, whose fields are all sendable, and which is not open or abstract; an object likewise | deeply immutable: no code can change it, and a subclass cannot add a var |
a trait declared : Sendable | every type implementing it is checked to be sendable, at its impl or declaration |
ActorRef[M], Behaviour[M], Future[T] and Promise[T] of a sendable T | made to be handed between threads |
Channel[T] and Atomic[T] of a sendable T, Mutex[T] and RwLock[T] of any T, a mutex’s Condition, Once, WaitGroup, Semaphore, Barrier | synchronization: every access is synchronized, and a mutex’s value is reached only under its lock, so a mutex is the one deliberate door to shared mutable state |
Thread[T] of a sendable T, an Executor | joining a thread and giving an executor work are synchronized |
| a Sysl handle | sent by handing over its ownership, checked when it is used (below) |
Isolated[T] | an object graph nothing else reaches, or an array moved out of the sender’s hands (below) |
a @sendable function type, @sendable (A) -> B | checked where each value is made: it captures only sendable values and no var, and reaches no module-level mutable state |
Not sendable: Array, Buffer, Deque, the mutable maps and sets, a class with a var field
or a field that is not sendable, an open or abstract class, a machine, a
thread Scope, a value of a plain function type, and Any. A plain function value is not sendable
because its type does not say what it captures, and a captured var is shared with the scope that
made it; a closure given to another thread is checked instead by what it captures, where it is
written, and one made as a @sendable function is checked where it is made (what is
shared). The error names the part that is not sendable:
error: `JobMsg` cannot be sent between actors: its variant `Fill` holds a `Buffer[byte]`, which is mutable; send an immutable copy (`toVector`), or the buffer as an `Isolated[Buffer[byte]]`
An Array is not sendable either, however it is used; it crosses without a copy as an
Isolated[Array[T]], made by Isolated.move.
A declaration may also promise Sendable: a trait or a class after : in its header, a data
type in an impl (impl Sendable for Reading). The promise is checked against the structure, and
the error says what breaks it (`Blob` promises to be `Sendable`, but its field `size` is a `var`).
An open or abstract class that promises it is sendable, each subclass being checked in turn, as
each type implementing a trait that promises it is. A generic trait that promises Sendable is
sendable at sendable type arguments, and a type implementing it has the parameters it passes to the
trait taken as sendable when it is checked. A type that implements one through a generic trait,
HashMap[K, V] through Map[K, V], is sendable at sendable arguments for those parameters. The
immutable Map and Set traits promise it, and Vector of sendable elements, and the standard
library’s promises are checked against the structure as every other one is. A few of its types are
safe to share for a reason the structure cannot show, synchronization the runtime does or an owner
every operation checks, and each is marked @trusted_sendable("why") with the reason, so that
nothing is trusted silently: Mutex, Condition, Atomic, Channel and Thread, the lock, the
cell, the pool and the registry inside them and the futures, a running actor, Isolated, and the
connections, listeners and child processes, which belong to one thread at a time. A Future, a Promise, an Executor and a
Once are sendable by their structure, built of those. The mark is the standard library’s alone.
Sendable is only a bound and a promise, never the type of a value.
Handing over ownership
Some mutable things have to move: a socket accepted by a listener goes to the actor that serves the connection, and a large buffer filled by one actor goes to the next.
-
A Sysl handle in a message is handed over. A handle has an owner, the execution that may use it (Sysl bindings), and an actor is an owner. Sending a message to an actor hands every handle it holds that the sender owns to that actor, as the message is put in its mailbox, so the receiver uses it and the sender’s later use of it traps (
`TcpStream` belongs to another thread), whether or not the receiver has used it yet. A handle the sender does not own stays as it is, so one sent twice goes with the first message, and the second receiver’s use traps; a receiver that sends one on hands it over in turn. A message dropped because its actor has ended leaves its handles the sender’s. A reply to anaskcompletes a future, which puts its handles in transit for the code that waits for it. The compiler knows which types can hold a handle, so a send walks the message only for those: a message of numbers and strings, of immutable collections of them or of actors’ references is never walked. The walk follows what the message holds — its fields, a collection’s elements, what a function value captures, anIsolated‘s objects — and stops at what is shared between owners, an actor’s reference, a future, a promise, a channel, a mutex, an atomic, a thread or an executor, whose handles keep their owners. -
A mutable object graph moves inside an
Isolated[T].isolate(body)runs its body, a by-name argument written in place or as a trailing block, and wraps what it returns:val chunk = isolate val b = Buffer[byte]() for i in 0 ..< size do b.append(byte.wrap(i)) b worker tell Fill(chunk)The compiler checks that the body reads nothing from around it that is not sendable, and that nothing it calls, however indirectly, reaches module-level mutable state (a module-level
var, or a module-level value orobjectwhose type is not sendable, alazy valamong them). Avin compiles the whole program, so the second is known for every function, in every module, through every trait method a call may reach, every function value made inside the body and the initializer of everylazy valfield it reads. Every mutable object the body leaves reachable from its result was therefore made inside it, and nothing outside holds one. The body may read avarof the code around it whose type is sendable, since it runs at once, and module-level values that are immutable and sendable; an actor’s own state, its parameters among them, is read through avalcopied first. The receiver gets the objects out withtake() -> T, after which they are ordinary objects it owns; a secondtake, by anyone, traps with`Isolated` was already taken, one atomic compare-and-set deciding which take wins.with[R: Sendable](f: T -> R) -> Rworks on the objects while leaving them isolated,fbeing checked by the body’s rule, so a pipeline of actors can fill, pass, change and pass one buffer without a copy.withholds the objects whilefruns, so atakeor awithof the sameIsolatedmeanwhile, from another thread or from insidef, traps with`Isolated` is in use by `with`, and awithafter the objects are taken traps as a secondtakedoes.The rule is a parameter’s mark,
@isolating, which a program’s own functions may write too (what is shared):isolate[T](@isolating body: -> T) -> Isolated[T], andwith‘sf.Isolatedandisolateare imported fromavin.actors. -
An array the program already holds moves with
Isolated.move(items), with no copy:move[T: Sendable](items: Array[T]) -> Isolated[Array[T]]. A buffer a socket read filled, or one a relay hands back and forth, was not made inside anisolate, and the code that holds it may hold other references to it too, in a field or a closure. So the array itself carries its owner: every array has an owner word beside its length, empty until the array is first moved. A move gives it an owner no running code is, and every use of the array after it, through any reference, traps with`Array` was moved to another owner— reading or writing an element, its length, a slice, a copy into it or out of it, an iterator’s next step, handing it to a Sysl or C binding, and moving it again. The code that takes it out of theIsolatedbecomes its owner, and uses it through any reference it holds;withmakes the code running it the owner whilefruns and moves the array again after. An array taken back by the code that moved it is that code’s again, through the references it kept:val chunk = conn.read(16384)? writer.send(Isolated.move(chunk)) // chunk(0) here traps val again = done.receive().get.take() // the same array, ours again: again === chunkIts elements must be sendable, since they are shared with the receiver as they are; an array of buffers is refused. Only an
Arraymoves this way: a slice is a copy, so one taken before the move stays the sender’s, and aBuffer, a map or any other mutable object moves inside anisolate. An array never moved, which is every array most programs make, pays eight bytes of header and no check beyond its bounds check: a move rewrites the length word so that every index fails that check, and only then is the owner compared.
The cheapest way across stays the plainest: build with a Buffer or a builder, turn the result into
an immutable collection, and send that.
Supervision
A trap reports a bug. In a thread it stops the program, because the state the threads share is in doubt. An actor shares no mutable state, so a trap in one leaves only that actor’s own state in doubt, and the runtime can contain it:
-
A trap in an actor fails the actor: in its body, an arm, a timer’s message, or an
enterorleaveblock. The runtime unwinds the actor’s frames back to the worker running it, drops the message being handled, and reports the trap as it reports any, naming the actor:avin: trap in Counter#3: integer overflow at counter.avin:12:31A trap inside the core library is reported where the actor’s code called it, as any library trap is. The actor’s
Failedreason is the trap’s reason, without its place:Failed(integer overflow). -
Where the trap leaves shared state in doubt, the program stops instead, as it would for a thread: a trap while the actor holds a
Mutex, reads or writes aRwLock, holds a semaphore’s permit inwithPermit, runs a barrier’s action, runs aOncebody or initializes alazy val(each of which other threads may be waiting on), or inside a Sysl call: an Avin function Sysl called back, or a value a binding cannot take. The report still names the actor. A stack that runs out stops the program too, with the sameavin: trap: stack overflowa thread’s does, since it may run out anywhere, inside the runtime or the C library among the places. -
The supervision given to
spawndecides what follows, a value of thedatatypeSupervision:Escalate, the default: the parent fails as if it had trapped, and its own supervision decides. A top-level actor that escalates stops the program, with the trap already reported. So a program that supervises nothing behaves as it would with threads: a bug stops it. The actor that escalated handles nothing more and waits for its parent’s failure to stop it, so a failure escalated to the top stops the program with nostoppingblock run; it endsFailed.Stop: the actor ends, its children first, and its watchers are told it failed.Restart(limit: int, within: Duration): the actor’s children are stopped and waited for, its timers and watches cancelled, itsstoppingblock runs, and its body runs again from the sameBehaviour, so it starts again with fresh state; the messages still in its mailbox stay there, and its reference, number and watchers are unchanged. A restart is reported on standard error after the trap, asavin: restarting Counter#3. A failure that would make more thanlimitrestarts within the lastwithinescalates instead, soRestart(0, …)never restarts. A limit less than zero, or a window not more than zero, traps inspawn.
-
There is no resuming with the old state. The trap stopped the actor part-way through changing its state, so the state is not kept.
-
What was asked of a failed actor. The question whose message trapped is dropped with it, so its ask times out; questions still in the mailbox are dropped and time out where the actor ends, and are answered by the fresh state where it restarts; a question sent once it has ended answers
Ended. A failure escalated to a parent that is already ending or restarting changes nothing, since the parent is stopping its children already.
Lifecycle
- An actor runs until it stops.
stop()in an actor ends it once the current message is handled; what is left in its mailbox is dropped.stop(child)ends one of its own children, and stopping any other actor is an error: an actor that should end on request is sent a message saying so. - Children end first. An ending actor stops each child, and waits for their ends, before it ends itself; an actor’s tree of children is torn down from the leaves.
stoppingis a block in the actor’s body that runs whenever the actor ends or restarts, the place to close handles and tell others. It runs after a failure too, on state the trap may have left half changed, so it does only what is safe on any state. A trap inside it is reported and the actor ends without running it again:Failedwith that trap’s reason, or with the first one where a trap had failed it already, and with no supervision asked, so a block that traps during a restart ends the actor instead. Of severalonStoppingfunctions, those after one that traps do not run.- Watching.
watch(ref, message: M)asks formessagein this actor’s own mailbox when the actorrefends, for whatever reason, andwatch(ref, f: Ending -> M)forfof how it ended;unwatch(ref)stops asking. Watching an actor that has already ended delivers at once.EndingisStoppedorFailed(reason: string); a restart is not an ending. - From outside any actor,
ref.ended() -> Future[Ending]completes when the actor ends, somainwaits for the top-level actor that runs the program withspawn(App()).ended().await(). - An actor is not collected because nothing refers to it: an actor nobody can send to still runs its timers and its children. It ends by stopping, by its parent ending, or with the program.
- The program ends when
mainreturns, as it does with threads, with every actor still running.
An actor also has children() -> Vector[ActorRef[Nothing]], its own reference self and its
parent’s in parent() -> Option[ActorRef[Nothing]], an ActorRef[Nothing] being one that may be
watched and compared but not sent to.
These are the actor’s own methods, those of ActorContext[M] in avin.actors, which the object
holding an actor’s state extends; a field or method of the actor’s own with the same name and
parameters is an error. A behaviour written as a library value makes one in its start from the
reference it is given, ActorContext(me), and ctx.onStopping(f) gives it what a stopping block
is. Made, or called, by any code other than the actor’s own, an ActorContext traps. The details:
children()lists the children that have not ended, in the order they started;parent()isNonefor a top-level actor, and for one a future’s body started, which is not an actor’s code.stop(self)isstop(). Stopping an actor that has ended does nothing, whoever started it.- An actor started while its parent is ending, from its
stoppingblock, is stopped at once, and the parent does not wait for it. - Watching an actor again replaces the earlier watch, so its end is told once. An actor that watches
itself is told nothing, since its mailbox ends with it. The
fofwatch(ref, f)runs in this actor’s own turn, when it takes the message, so a trap in it fails this actor and never the one watched; it is@sendable, since it is carried to the mailbox from wherever the end is known.unwatch, and cancelling a timer, also drop the message already queued and not yet handled. - A
stoppingblock runs once the body has run: the body gives it to the context last. An actor has one. - The state of an actor is never captured by a
@sendablefunction, whatever its fields, since its methods act for the actor that is running; a body that needs a field copies it into aval.
Timers
after(delay: Duration, message: M) -> Timer sends the actor message once delay has passed, and
every(interval: Duration, message: M) -> Timer each time interval passes. cancel() on the
Timer stops it; an actor’s timers are all cancelled when it ends or restarts. A timer’s message is
queued like any other, so it never interrupts an arm.
Timers fire in the order they fall due, those due at the same time in the order they were set; a
delay of zero or less is due at once. A repeating timer is set again an interval after it fires, and
an interval of zero or less traps. A Timer is sendable, and cancel() works from any thread. One
thread the runtime starts with the first timer keeps every actor’s timers.
Scheduling
Actors are many; threads are few. An actor’s messages are handled in turns, and each turn
is a lightweight thread of its own, run by the same workers,
about one per processor, as every other thread. An actor given an executor,
spawn(b, executor = Executor.fixed(1)), runs its turns as tasks on that executor’s workers
instead, which bounds how many of them work at once:
- An actor with messages has one turn queued. A send to an actor with an empty mailbox queues a
turn, which handles its messages one at a time. An actor never runs two turns at once, not
even while a turn is parked and new messages arrive meanwhile, and the handling of each message
happens before the handling of the next, wherever each runs, so an actor’s fields need no lock
and no
Atomic. - Fairness. A turn handles at most 16 messages before the actor’s next turn goes to the back of
the queue, so a busy actor cannot hold a worker from the others. Within one message, a turn is
time-sliced as any thread is: one that computes for a second shares its worker with the other
ready threads at its safepoints, though the actor itself handles nothing else meanwhile. On an
executor of its own, a task is not set aside, so an arm that computes for a second holds that
executor’s place for that second.
The body runs in the actor’s first turn and is not one of the 16; a turn ends early when the
mailbox is empty. An actor’s executor being shut down does not end it: its turns still run there,
on a worker started for them where none is left, so
tellnever fails. - An actor may move between workers, between messages and, where a turn parks, within one. A
turn sets its context’s owner word to the actor before handling its messages, so the handles an
actor owns are its own on any worker and never trap.
spawngives the actor the handles its behaviour reaches that the spawning code owns, as a thread’sspawndoes with its body. - Waiting. A turn that waits, in
await, an ask, asleep, a channel or a lock, parks: its worker runs other actors and threads meanwhile, and the actor handles no other message until the turn goes on. A thousand actors each sleeping in a turn hold no worker between them. A blocking binding holds its worker, and the runtime runs another worker in its place while it does. On an executor of its own, a task that waits inawaitorthreads.blocking(body)leaves its place to another worker of that executor, and one that waits otherwise keeps it. - Cancellation. No scope’s cancellation reaches an actor: one
started by a scope’s thread runs on once that thread is cancelled, and a turn is not a scope’s
thread, so it is never cancelled, though a scope it runs may cancel its own threads. An asker
cancelled while it awaits an
askleaves its question in the mailbox, handled in its turn, the reply going nowhere. - Memory model. A
tellhappens before the handling of the message it sent, and a reply’stellhappens before theawaitorpipeToSelfthat delivers it, joining the edges of the memory model.
Threads, channels and futures
Actors are built on avin.threads and live beside it. Any thread may start, tell and ask actors;
an ask is a future, and a future’s value reaches an actor by pipeToSelf. A Channel is the tool
for a fixed pipeline of threads, and an actor that receives from a channel parks its turn and
handles nothing else while it waits, so between actors, messages are the channel. Locks remain for the state that genuinely
must be shared; a Mutex is sendable for that reason.
Routers
A router is one reference that spreads its messages over a pool of actors started from one behaviour, its routees, so work that one actor would handle in turn is handled by several at once:
import avin.actors.{ActorRef, Router, RoundRobin}
import avin.time
data Job
Square(n: int, replyTo: ActorRef[string])
actor Squarer receives Job
receive
Square(n, replyTo) -> replyTo.tell(s"$self: ${n * n}")
main()
val pool = Router.pool(3, Squarer(), RoundRobin)
for n in 1 .. 4
println(pool.ask(r -> Square(n, r), timeout = time.seconds(5)).await())
Ok(Squarer#2: 1)
Ok(Squarer#3: 4)
Ok(Squarer#4: 9)
Ok(Squarer#2: 16)
Router.pool[M: Sendable](size: int, behaviour: Behaviour[M], routing: Routing[M] = RoundRobin, onFailure: Supervision = Escalate, executor: Executor = Executor.shared(), mailbox: Mailbox = Unbounded) -> ActorRef[M]starts a router andsizeroutees ofbehaviour, the router’s children, and gives back the router’s reference at once. The router is a child of the code that callspool, asspawn‘s actor is, and its reference is shown asRouter#n, the router numbered before its routees. A size less than one, aRestartthatspawnwould refuse, and a bounded mailbox’s capacity less than one, trap in the calling code.- Each message sent to the router goes to one routee, chosen by the
Routing:RoundRobin, the default: each routee in turn.AtRandom: any routee, each equally likely.SmallestMailbox: the routee with the fewest messages waiting in its mailbox, the next in turn among equals, so a free routee takes work that round robin would queue behind a busy one. The message a routee is handling does not count as waiting.ByKey(key: @sendable (M) -> long): by the keykeygives the message, so every message with one key goes to one routee for as long as that routee lives; the keys spread over the pool, and a routee that ends moves only its own keys to the others.
- Order. Two messages one sender sends that go to one routee arrive in the order they were sent,
so with
ByKey, each key’s messages from one sender are handled in order. - A bounded pool. A
Boundedmailbox bounds the router’s own mailbox and each routee’s, at the same capacity. The router waits for room in the routee it chose rather than drop, handling nothing else meanwhile, so once the routees are full the router’s own mailbox fills, and there the overflow policy,offer,send,askanddropped()act as for any bounded mailbox: a pool ofnroutees of capacitycholds at most(n + 1) × cmessages waiting, and one more the router is placing.RoundRobin,AtRandomandByKeywait on the routee they chose;SmallestMailboxwaits only when every routee is full, and its count is the bounded mailbox’s own. - An ask through a router is answered by the routee that takes the question; the reply goes to
the asker’s reply reference as any reply does. An ask of a router that has ended answers
Ended. - Supervision as a group. Each routee is supervised by
onFailureand runs onexecutor. A routee that restarts keeps its place in the pool and its mailbox; one that ends, whether it stopped itself or failed underStop, leaves the pool, a message the router finds it no longer accepts going to another routee; and the router stops once no routee is left. A routee’s failure underEscalatefails the router, which escalates in turn: a top-level router stops the program. - Lifecycle. The router ends as any actor does: stopped by its parent with
stop(router), or with its parent, and a router that ends stops its routees first, so its end is known once theirs are.
Topics
A topic carries events from any number of publishers to every actor subscribed:
import avin.actors.{Topic, spawn}
import avin.threads.Channel
actor Log(out: Channel[string]) receives string
receive
line -> out.send(s"$self: $line")
main()
val news = Topic[string]()
val out = Channel[string]()
news.subscribe(spawn(Log(out)))
news.publish("one")
news.publish("two")
println(out.receive().get)
println(out.receive().get)
println(news.subscribers)
Log#1: one
Log#1: two
[Log#1]
Topic[E: Sendable]()makes one. A topic is not an actor; it is a sendable object any thread may use, sent to actors in messages as any sendable value is.subscribe(subscriber: ActorRef[E])subscribes an actor from now on; an actor of another protocol subscribes an adapter. An actor is subscribed once, however many of its references are given: subscribing it again keeps its first place and the reference given last.unsubscribe(subscriber: ActorRef[Nothing])stops telling it; an actor not subscribed is left as it is.publish(event: E)tells the event to every actor subscribed, in the order they subscribed, and returns at once; with nobody subscribed it does nothing. A subscriber is told one publisher’s events in the order published; the events of different publishers interleave in any order. An event holding a Sysl handle goes with the first subscriber’s copy, as a handle sent twice does.- A subscriber that ends leaves the topic of itself: its end is watched from the moment it subscribes, so a topic keeps no ended actor for longer than it takes to hear of the end, and an actor that had ended already when it subscribed is not kept.
subscribers -> Vector[ActorRef[E]]is the actors subscribed now, in the order they subscribed.
State machines
machine declares a type whose objects move between declared states, driven by events:
data DoorEvent
Open
Close
Lock(code: int)
Unlock(code: int)
machine Door receives DoorEvent
var opened = 0
state Closed
Open ->
opened += 1
Opened
Lock(code) -> Locked(code)
state Opened
enter
println("open")
Close -> Closed
state Locked(code: int)
Unlock(c) if c == code -> Closed
receive
_ -> stay
-
Each
statedeclares a state, optionally with parameters, the data that state holds; its arms,enterandleaveblocks read them by name. The machine’s own fields and parameters are the data every state shares. A machine is declared like a class, generic and with parameters, and its other methods are ordinary methods. -
An arm’s value is the next state: a state written as a constructor (
Locked(code)), orstay, which keeps the current state and its data. There is no separate transition statement: what an arm yields is where the machine goes. -
The first
stateis where the machine starts, and takes no parameters. -
enterruns when the machine moves into the state, andleavewhen it moves out,leavebeforeenter. An arm yielding a state, even the current one, is a transition and runs both;stayruns neither. The first state’senterruns when the machine is made, after the body. The arm runs first; inleave,state()still answers the state being left, and inenterthe new one. -
receiveholds the arms every state shares, tried after the current state’s own. Every state must handle every event: the compiler checks, state by state, that its own arms and the shared ones together cover the event type, as amatchis checked, guarded arms not counting. A state’s own arm that its arms above it already cover, and a shared arm the shared arms above it already cover, is never reached and is an error; a shared arm that a state’s own arms cover is not, since a state overrides a shared arm by handling the event itself. Without its sharedreceive,Doorwould be refused:error: state `Locked` of `Door` does not handle `Open`, `Close`, `Lock(_)` or `Unlock(_)` where the guard is false -
Using a machine.
Door()makes one in its first state.handle(event) -> Door.Stateapplies one event and answers the new state, andstate() -> Door.Statereads the current one, whereDoor.Stateis adatatype the declaration makes, with a variant for each state and the state’s parameters as its fields, so a program matches on it:door.state() is Locked(_). Its variants are names of the machine’s module, as every variant is, and may share a name with another machine’s state or an event’s variant, as variants of different types may: an arm’s result is its own machine’s state, an event passed tohandleis the event type’s, anddoor.state() is Idlematches againstDoor.State. A machine is a mutable object, so it is not sendable; handling an event from inside one of its own arms,enterorleaveblocks traps, as taking a held mutex does.
An actor’s states
An actor’s body takes the same state blocks, so an actor with phases is written as a machine
driven by its mailbox. Each message is an event, the arms yield the next state, and enter,
leave, stay and the check that every state handles every message work as they do in a machine:
data ConnMsg
Connect(host: string)
Connected(socket: Socket)
Send(bytes: Vector[byte])
Closed
actor Connection receives ConnMsg
var pending = Vector[Vector[byte]]()
state Idle
Connect(host) ->
pipeToSelf(openSocket(host), s -> Connected(s))
Connecting
state Connecting
Connected(socket) ->
for b in pending do socket.write(b)
pending = Vector()
Ready(socket)
Send(bytes) ->
pending = pending :+ bytes
stay
state Ready(socket: Socket)
leave
socket.close()
Send(bytes) ->
socket.write(bytes)
stay
Closed -> Idle
receive
_ -> stay
An actor with states needs no receive block; its shared arms, where it has them, yield states as
a machine’s do. Its first state’s enter runs after the body, when the actor starts. A message that
arrives, a timer that falls due or a reply piped to itself is handled by the state current when it
is handled, not the one that asked for it. Only a transition runs leave: an actor that stops or
fails runs its stopping block, where state() answers the state it ended in. A trap in an
enter or leave fails the actor as one in an arm does. A restarted actor starts again in its
first state. The actor’s State type, its states and state() are its own, private to its module
as the actor’s state is. Its states share names as a machine’s do, with a message’s variant, another
actor’s state or a machine’s: an arm’s result is the actor’s own state, an arm’s pattern the message
type’s, and a bare name nothing decides is refused, naming the qualified forms (Ev.Idle,
Connection.State.Idle). An actor without state blocks is one whose arms all stay, which is why
its arms yield nothing.
Setting messages aside
A message an actor cannot handle in its present state is set aside in a Stash and given back
once the state changes, which is what Connection above does by hand with pending:
import avin.actors.{ActorRef, Stash, spawn}
import avin.time
data Msg
Write(text: string)
Ready
Show(replyTo: ActorRef[string])
actor Writer receives Msg
val waiting = Stash(self, 100)
val written = Buffer[string]()
state Starting
Write(text) ->
waiting.add(Write(text))
stay
Ready -> Running
state Running
enter
waiting.unstashAll()
Write(text) ->
written.append(text)
stay
receive
Show(replyTo) ->
replyTo.tell(s"$written")
stay
_ -> stay
main()
val w = spawn(Writer())
w.tell(Write("a"))
w.tell(Write("b"))
w.tell(Ready)
w.tell(Write("c"))
println(w.ask(r -> Show(r), timeout = time.seconds(5)).await())
Ok([a, b, c])
Stash[M: Sendable](owner: ActorRef[M], capacity: int)is made by the actor’s own code from its own reference,selfin a declaration or the reference a behaviour’s start is given; made by any other code it traps, as anActorContextdoes. A capacity less than one traps.add(message: M)sets a message aside. Adding to a full stash traps, failing the actor, whose supervision decides what follows; an actor that would rather drop or answer the message readsisFullfirst.lengthandisEmptysay what it holds, andcapacityhow much it may.unstashAll()gives back every message held, in the order they were added, in front of every message waiting in the mailbox, so the actor handles them next and the messages that arrived meanwhile after them, and leaves the stash empty. Messages given back while others given back earlier still wait go in front of those. A message given back that the actor still cannot handle is added again, behind the ones added since. Given back from a state’senter, they are handled by that state, the usual place.clear()drops what the stash holds.- A stash is the actor’s state. Its messages are lost where the actor ends or restarts, as its fields are, and a question among them times out; messages already given back are in the mailbox, which a restart keeps, so the fresh state handles them.
- Under a bounded mailbox, a message stashed has left the mailbox and made
room, and the messages
unstashAllgives back do not count against the bound, which they passed once already: however many come back, none is dropped.
Keywords
actor and machine are keywords only where a declaration starts, before the declaration’s name;
receives only after an actor’s or machine’s header; and state, receive, enter, leave,
stopping and stay only inside an actor’s or a machine’s body, at the start of a line (stay as
an arm’s value). Everywhere else they are ordinary names, so a variable called state stays legal.