Lifecycle

This page covers what happens around messages: lifecycle hooks, switching behaviour, stashing, death watch, timers, mailboxes, passivation and shutdown.

Two ways to write an actor

Most actors are classes (instance Actor), described in Actors. Underneath them is the engine’s behaviour: a route, a first state, a receive function and the rest of an actor’s settings, built with the functions of Actor.Behavior. A class’s behaviour is behaviorOf params.

Lifecycle hooks are set on a behaviour. Write an actor as a behaviour when it needs them:

import Actor.Behavior as B
import Actor.Address as A
import Actor.System as Sys

data Line = Say String | Said (Reply [String])

@B.withRoute("console")
@B.onPreStart(opened)
console :: Behavior Line [String]
console = B.actor (\u -> []) printing

opened :: Ctx Line -> [String] -> [String]
opened ctx lines = Cons "opened" lines

printing :: Ctx Line -> [String] -> Line -> Turn Line [String]
printing ctx lines msg = case msg of
  Say text -> B.continue (Cons text lines)
  Said r   -> B.after (A.respond r (L.reverse lines)) (B.continue lines)
let c = Sys.spawnActor system console in    -- an ActorRef Line under /user
A.tellRef c (Say "hello")
A.askRef c (\r -> Said r)                   -- Right ["opened", "hello"]
A.routeOf c                                 -- "/user/console"

B.actor initial receive makes a behaviour; the attributes above the binding decorate it, like a class’s.

Lifecycle hooks

Hook Signature When
onPreStart Ctx msg -> state -> state Before the first message; it may change the first state
onPostStop Ctx msg -> state -> () After the actor stopped taking messages
onPreRestart Ctx msg -> state -> Fault -> () Before a restart, with the old state and the failure
onPostRestart Ctx msg -> state -> Fault -> state After a restart, with the fresh state; it may change it

Startup

The actor registers with the system, onPreStart runs, then messages are handled.

Restart

onPreRestart sees the old state and the failure; the state is replaced by initial; onPostRestart may adjust it; the actor’s first methods come back. Messages waiting in the mailbox stay; only the failed message is gone.

Stop

An actor stops after the message it is handling. Its children stop first (each one waited for), then onPostStop runs; askers still waiting are answered ActorStopped; the registry, the parent and the watchers are told.

Become and unbecome

become methods state sends the next messages to other methods; become receive state goes back to the first ones. unbecome state returns to the methods before the last become.

Message stashing

stash state keeps the current message for later. unstash brings back the oldest, unstashAll all of them, and becomeUnstashing methods state switches methods and replays every stashed message first. Together they let an actor hold messages until it is ready:

data Door    = Door { openings :: Int }
data DoorMsg = Open | Close | Knock (Reply String)

instance Actor Door where
  type Message Door = DoorMsg
  receive ctx d msg = case msg of
    Open    -> becomeUnstashing doorOpen d { openings = d.openings + 1 }
    Close   -> continue d
    Knock r -> stash d

doorOpen :: Context Door -> Door -> DoorMsg -> Step Door
doorOpen ctx d msg = case msg of
  Open    -> continue d
  Close   -> become receive d
  Knock r -> respond r "come in" >> continue d

A knock on a closed door waits: askWithin 200 door (\r -> Knock r) times out. Once the door is opened, a knock is answered "come in", and so is every knock that was stashed.

Death watch

An actor can be told when another stops. Sys.watch takes the watcher’s context (ctxOf ctx inside a class), the watched actor’s reference and the message to be told:

data Watcher    = Watcher { gone :: Int }
data WatcherMsg = Follow (ActorRef Idle) (Reply ()) | Gone | Losses (Reply Int)

instance Actor Watcher where
  type Message Watcher = WatcherMsg
  receive ctx w msg = case msg of
    Follow target r -> Sys.watch (ctxOf ctx) target Gone >> respond r () >> continue w
    Gone            -> continue w { gone = w.gone + 1 }
    Losses r        -> respond r w.gone >> continue w

The watcher is told Gone once the target stops, or at once if it had stopped already. Sys.unwatch takes a watch back. From outside an actor (a test), Sys.watching target watcher message does the same.

Follow answers once the watch is in place, so a caller can ask Follow and then stop the target knowing the stop will be seen.

Timers

import Actor.Timer as Tm

scheduleOnce   :: Int -> ActorRef msg -> msg -> Timer   -- told once, after ms
scheduleRepeat :: Int -> ActorRef msg -> msg -> Timer   -- told every ms, until cancelled or the actor stops
cancel         :: Timer -> ()
case Tm.scheduleRepeat 100 (refOf pulse) Tick of
  timer -> case T.sleepMillis 550 of
    _ -> case Tm.cancel timer of
      _ -> ask pulse (\r -> Ticks r)        -- Right 5

A timer is a fiber that sleeps, parking only itself. A cancelled timer tells nothing more; a timer whose actor stopped ends on its own.

Bind a timer with case … of, as above, so it is started before the code that follows runs.

Mailboxes

Attribute Mailbox
none In order, unbounded
@mailbox(n) In order; past n waiting messages the oldest is dropped
@backpressure(n) In order; past n the sender waits for room
@priority(weight) The heaviest message first, in order within one weight

On a behaviour the same are B.withCapacity n, B.withBackpressure n, B.withPriority weight and B.inMailbox m.

Passivation

@passivateAfter(ms) stops an actor after ms milliseconds without a message. An actor hosted by route is made again the next time its route is asked, so passivation frees idle actors without losing their address.

Graceful shutdown

Sys.stopActor ref          -- stop one actor (it finishes its current message)
Sys.stopAndWait ref        -- the same, and wait until it has stopped
terminate address          -- stopActor for a class's address
Sys.shutdown system        -- stop everything under the root
Sys.shutdownAndWait system -- the same, and wait: each parent waits for its children, the root last

Sys.deadLetters system lists the messages that reached stopped actors, and Sys.processes system "*" the running actors.

Where next