/// Supervisors: restart children that crash ("let it crash", ADR 0004), /// within a restart intensity, and stop them in order (ADR 0060). import std/list import std/os.{type Signal} import std/process. { type ExitSignal , type Pid , type Subject , type proc , Crashed , ExitSignal , Normal , Shutdown } import std/random.{type random} import std/time.{type clock} pub type Strategy { /// Restart only the child that crashed. OneForOne /// Restart every child when one crashes. , OneForAll /// Restart the child that crashed and every child started after it /// (they may depend on it); the ones before it keep running. , RestForOne } /// When a child is restarted (OTP's child kinds). @derive Eq Show pub type Restart { /// Always: after it crashes, and after it returns. Permanent /// After it crashes only: a child that returns (or is stopped with /// `Shutdown`) is done. , Transient /// Never. , Temporary } /// How to start a child. The child is linked to its supervisor. pub type Child { /// Restarted after a crash only (`Transient`), given 5 seconds to stop. Child(name: String, start: send fn() -> () / ) /// Restarted as `restart` says, given `shutdown_timeout` milliseconds to /// stop when its supervisor shuts down (then killed). , ChildWith( name: String , start: send fn() -> () / , restart: Restart , shutdown_timeout: Int ) } /// A supervisor: its children, started in order, its strategy, and its /// restart intensity: more than `intensity` restarts within `period_ms` /// milliseconds make it give up (crash). A negative `period_ms` counts /// restarts over the supervisor's whole life. pub type Spec { Spec( strategy: Strategy , children: List , intensity: Int , period_ms: Int ) } /// Run a supervisor in the current actor: start the children, restart /// them as `strategy` and their kinds say, and crash itself after /// `max_restarts` restarts (over its whole life; `run` takes a window). /// Returns when every child is done. pub fn supervise :: strategy: Strategy children: List max_restarts: Int -> () / { // Over its whole life: no clock needed. run_with Spec(strategy, children, max_restarts, -1) fn { 0 } } /// Run the supervisor `spec` in the current actor (see `Spec`). It traps /// exits: told to stop (`process.stop`, a `Shutdown` exit signal), it /// stops its children in reverse start order, each with `Shutdown` and /// killed after its `shutdown_timeout`, then returns. Returns too when /// every child is done. pub fn run :: spec: Spec -> () / { run_with spec now_ms } /// The monotonic clock, in milliseconds. fn now_ms :: -> Int / { time.in_milliseconds (time.monotonic ()) } /// `run`, reading the time from `now` (for the restart window). fn run_with :: spec: Spec now: fn() -> Int / -> () / { process.trap_exits True let exits = process.exits () watch spec exits (list.map spec.children start_child) [] now } type Running = List<(Pid, Child)> fn start_child :: child: Child -> (Pid, Child) / { (process.spawn_link (start_of child), child) } fn start_of :: child: Child -> send fn() -> () / { match child { Child(_, start) -> start, ChildWith(_, start, _, _) -> start } } fn restart_of :: child: Child -> Restart { match child { Child(_, _) -> Transient, ChildWith(_, _, restart, _) -> restart } } fn shutdown_timeout_of :: child: Child -> Int { match child { Child(_, _) -> 5000, ChildWith(_, _, _, timeout) -> timeout } } /// `restarts`: when the restarts within the window happened (`now`'s /// milliseconds, the latest first). fn watch :: spec: Spec exits: Subject running: Running restarts: List now: fn() -> Int / -> () / { match running { [] -> () , _ -> { let ExitSignal(pid, reason) = process.receive_forever exits if !is_running running pid { if reason == Shutdown { // Told to stop, by whoever started it. shutdown running exits } else { // A child replaced or killed by a restart: already handled. watch spec exits running restarts now } } else { let child = child_of running pid let done = match (restart_of child, reason) { (Temporary, _) -> True , (Transient, Normal) -> True , (Transient, Shutdown) -> True , _ -> False } if done { watch spec exits (remove running pid) restarts now } else { let restarts = counted restarts spec.period_ms (now ()) if list.length restarts > spec.intensity { // Stop the others (the crashed child is gone already). shutdown (remove running pid) exits panic "supervisor: too many restarts" } else { let restarted = match spec.strategy { OneForOne -> restart_one running pid , OneForAll -> restart_all running , RestForOne -> restart_rest running pid } watch spec exits restarted restarts now } } } } } } /// `restarts` with one more `now`, forgetting those older than /// `period_ms` (none if it is negative). fn counted :: restarts: List period_ms: Int now: Int -> List { let recent = if period_ms < 0 { restarts } else { list.filter restarts fn t { now - t < period_ms } } [now, ..recent] } fn is_running :: running: Running pid: Pid -> Bool { use found, entry <- list.fold running False found || entry.0 == pid } fn child_of :: running: Running pid: Pid -> Child { match running { [] -> panic "supervisor: not a child" , [entry, ..rest] -> if entry.0 == pid { entry.1 } else { child_of rest pid } } } fn remove :: running: Running pid: Pid -> Running { use entry <- list.filter running entry.0 != pid } fn restart_one :: running: Running pid: Pid -> Running / { use entry <- list.map running if entry.0 == pid { start_child entry.1 } else { entry } } fn restart_all :: running: Running -> Running / { list.each running fn entry { process.kill entry.0 } restart_kept running } /// Restart `pid` and the children after it, in order; the later ones are /// stopped first. fn restart_rest :: running: Running pid: Pid -> Running / { match running { [] -> [] , [ entry , ..rest ] -> if entry.0 == pid { // Stop the later children last-started first, as OTP does. list.each (list.reverse rest) fn later { process.kill later.0 } restart_kept [entry, ..rest] } else { [entry, ..restart_rest rest pid] } } } /// Start `running`'s children again, but the temporary ones, which are /// done. fn restart_kept :: running: Running -> Running / { let kept = list.filter running fn entry { restart_of entry.1 != Temporary } list.map kept fn entry { start_child entry.1 } } /// Stop every child, last-started first: each with `Shutdown`, killed if /// it is not done within its `shutdown_timeout`. fn shutdown :: running: Running exits: Subject -> () / { let _ = list.fold (list.reverse running) [] fn gone entry { stop_child entry.0 (shutdown_timeout_of entry.1) exits gone } () } /// Stop `pid`, waiting up to `timeout` milliseconds for its exit signal, /// then kill it and wait for it. `gone`: the children whose exit signals /// arrived meanwhile (each arrives once); returns it updated. fn stop_child :: pid: Pid timeout: Int exits: Subject gone: List -> List / { if list.any gone fn p { p == pid } { gone } else { process.stop pid match wait_exit pid timeout exits gone { (True, gone) -> gone , (False, gone) -> { process.kill pid (wait_exit pid (-1) exits gone).1 } } } } /// Wait up to `timeout` milliseconds (negative: forever) for `pid`'s exit /// signal: whether it came, and the other children that exited meanwhile. fn wait_exit :: pid: Pid timeout: Int exits: Subject gone: List -> (Bool, List) / { match process.receive exits timeout { None -> (False, gone) , Some(ExitSignal(from, _)) -> if from == pid { (True, gone) } else { wait_exit pid timeout exits [from, ..gone] } } } /// How the runtime supervises a program's `main` (ADR 0060): the /// `[application]` section of `louise.toml`. `main` is restarted as /// `restart` says after it crashes, at most `intensity` times within /// `period_ms` milliseconds; on one of `signals`, it is stopped /// (`Shutdown`), and killed if it is not done within `shutdown_timeout_ms`. pub type Application { Application( restart: Restart , intensity: Int , period_ms: Int , shutdown_timeout_ms: Int , signals: List ) } /// Run `main` under `app` (the program's root when `louise.toml` has an /// `[application]` section; the compiler generates the call). Returns, /// and the program exits 0, when `main` returns, or once it stopped after /// a signal; a crash beyond the restart intensity (or any crash, for a /// `Temporary` main) ends the program with that panic. pub fn application :: app: Application main: send fn() -> () / -> () / { process.trap_exits True let exits = process.exits () let signals = os.signals app.signals let events = process.new_selector () |> process.selecting exits Exited |> process.selecting signals Signalled supervise_main app main events (process.spawn_link main) [] } /// What `application` waits for. type MainEvent { Exited(ExitSignal), Signalled(Signal) } fn supervise_main :: app: Application main: send fn() -> () / events: process.Selector pid: Pid restarts: List -> () / { match process.select_forever events { Signalled(_) -> stop_main pid app.shutdown_timeout_ms events , Exited ( ExitSignal(from, reason) ) -> if from != pid { // Another linked actor: not `main`'s business here. supervise_main app main events pid restarts } else { match (app.restart, reason) { (_, Normal) -> () , (_, Shutdown) -> () , (Temporary, _) -> panic (crash_message reason) , _ -> { let restarts = counted restarts app.period_ms (now_ms ()) if list.length restarts > app.intensity { panic (crash_message reason) } else { supervise_main app main events (process.spawn_link main) restarts } } } } } } fn crash_message :: reason: process.ExitReason -> String { match reason { Crashed(message) -> message, _ -> "main was killed" } } /// Stop `main` (`Shutdown`), waiting up to `timeout` milliseconds for it, /// then kill it. Further signals meanwhile are ignored. fn stop_main :: pid: Pid timeout: Int events: process.Selector -> () / { process.stop pid if !main_exited pid timeout events { process.kill pid let _ = main_exited pid (-1) events } } /// Whether `main` (`pid`) exited within `timeout` milliseconds (negative: /// forever). fn main_exited :: pid: Pid timeout: Int events: process.Selector -> Bool / { match process.select events timeout { None -> False , Some ( Exited(ExitSignal(from, _)) ) -> if from == pid { True } else { main_exited pid timeout events } , Some(Signalled(_)) -> main_exited pid timeout events } }