← Cookbook Actors and concurrency Advanced · Pooka 0.5.0

Supervise a worker

Things break. A supervisor's only job is to notice, sweep up, and put a fresh one in its place, so the rest of the program can carry on.

You will use

  • pooka add pooka_otp
  • pooka/otp/supervisor: actor_child, spec, start, shutdown
  • pooka/otp: a Key to find the newest actor after a restart

The whole program

src/main.pooka
module main

import pooka/int
import pooka/io
import pooka/otp.{Key, LogLevel}
import pooka/otp/supervisor.{Strategy}

/// A kettle keeps count of the cups it has poured, until it cracks.
actor Kettle {
  var cups: Int = 0

  be pour(count: Int) {
    cups += count
  }

  be crack() {
    panic as "the kettle cracked"
  }

  poured() -> Int {
    cups
  }
}

say(line: String) -> Nil {
  io.println(line)
  Nil
}

main() {
  // OTP reports every crash in detail. Keep this example's output short.
  otp.set_log_level(LogLevel.Critical)

  // Where the supervisor keeps the newest kettle, across restarts.
  let kettles: Key(Kettle) = otp.key("kettle")
  let children = [
    supervisor.actor_child("kettle", kettles, fn() { Kettle() })
  ]
  let assert Ok(tree) = supervisor.start(
    supervisor.spec(Strategy.OneForOne, children)
  )

  let assert Some(kettle) = otp.get(kettles)
  kettle.pour(3)
  say("poured " + int.to_string(kettle.poured()) + " cups")

  kettle.crack()
  otp.sleep(100)

  let assert Some(new_kettle) = otp.get(kettles)
  say("a new kettle has poured " + int.to_string(new_kettle.poured()) + " cups")
  new_kettle.pour(1)
  say("and now " + int.to_string(new_kettle.poured()))

  supervisor.shutdown(tree)
}

Run it

Add the package first:

$ pooka add pooka_otp
$ pooka run
poured 3 cups
a new kettle has poured 0 cups
and now 1

How it works

  1. Describe the child. supervisor.actor_child("kettle", kettles, fn() { Kettle() }) tells the supervisor how to make a kettle, and where to keep it: under the key kettles.
  2. Start the tree. supervisor.start starts a real OTP supervisor with the OneForOne strategy: when a child crashes, start that child again and leave any others alone.
  3. Crash on purpose. crack() panics inside the actor. The actor's process dies; the supervisor sees it and starts a new kettle.
  4. Find the newest one. The old kettle is gone, so ask the key again: otp.get(kettles) returns the replacement. It starts with fresh state, which is why it has poured 0 cups.
  5. Quiet, for the example. OTP logs every crash in detail, which is what you want in a real program. otp.set_log_level(LogLevel.Critical) keeps this example's output short.

A supervisor does not prevent the fall. It just makes sure someone gets back up.

Try next: crash the kettle in a loop. After too many restarts in a short time, the supervisor gives up too; spec(…).with_intensity(restarts, seconds) sets the limit. The pooka_otp documentation covers servers, nested trees and applications.