tobogganSe connecter

louise

Clone avec HTTPS, un jeton personnel en mot de passe, ou avec SSH, une clé ajoutée dans vos paramètres.

462 lignes · 11995 octetsBrut · Historique
1/// Supervisors: restart children that crash ("let it crash", ADR 0004),
2/// within a restart intensity, and stop them in order (ADR 0060).
3
4import std/file.{type fs}
5import std/list
6import std/os.{type Signal}
7import std/process.
8{ type ExitSignal
9, type Pid
10, type Subject
11, type proc
12, Crashed
13, ExitSignal
14, Normal
15, Shutdown
16}
17import std/random.{type random}
18import std/time.{type clock}
19
20pub type Strategy
21{ /// Restart only the child that crashed.
22 OneForOne
23 /// Restart every child when one crashes.
24, OneForAll
25 /// Restart the child that crashed and every child started after it
26 /// (they may depend on it); the ones before it keep running.
27, RestForOne
28}
29
30/// When a child is restarted (OTP's child kinds).
31@derive Eq Show
32pub type Restart
33{ /// Always: after it crashes, and after it returns.
34 Permanent
35 /// After it crashes only: a child that returns (or is stopped with
36 /// `Shutdown`) is done.
37, Transient
38 /// Never.
39, Temporary
40}
41
42/// How to start a child. The child is linked to its supervisor.
43pub type Child
44{ /// Restarted after a crash only (`Transient`), given 5 seconds to stop.
45 Child(
46 name: String
47 , start: send fn() -> () / <proc, clock, random, fs, io, ffi>
48 )
49 /// Restarted as `restart` says, given `shutdown_timeout` milliseconds to
50 /// stop when its supervisor shuts down (then killed).
51, ChildWith(
52 name: String
53 , start: send fn() -> () / <proc, clock, random, fs, io, ffi>
54 , restart: Restart
55 , shutdown_timeout: Int
56 )
57}
58
59/// A supervisor: its children, started in order, its strategy, and its
60/// restart intensity: more than `intensity` restarts within `period_ms`
61/// milliseconds make it give up (crash). A negative `period_ms` counts
62/// restarts over the supervisor's whole life.
63pub type Spec
64{ Spec(
65 strategy: Strategy
66 , children: List<Child>
67 , intensity: Int
68 , period_ms: Int
69 )
70}
71
72/// Run a supervisor in the current actor: start the children, restart
73/// them as `strategy` and their kinds say, and crash itself after
74/// `max_restarts` restarts (over its whole life; `run` takes a window).
75/// Returns when every child is done.
76pub fn supervise ::
77 strategy: Strategy
78 children: List<Child>
79 max_restarts: Int
80 -> () / <proc, io>
81{
82 // Over its whole life: no clock needed.
83 run_with Spec(strategy, children, max_restarts, -1) fn { 0 }
84}
85
86/// Run the supervisor `spec` in the current actor (see `Spec`). It traps
87/// exits: told to stop (`process.stop`, a `Shutdown` exit signal), it
88/// stops its children in reverse start order, each with `Shutdown` and
89/// killed after its `shutdown_timeout`, then returns. Returns too when
90/// every child is done.
91pub fn run :: spec: Spec -> () / <proc, io, clock>
92{
93 run_with spec now_ms
94}
95
96/// The monotonic clock, in milliseconds.
97fn now_ms :: -> Int / <clock>
98{
99 time.in_milliseconds (time.monotonic ())
100}
101
102/// `run`, reading the time from `now` (for the restart window).
103fn run_with :: spec: Spec now: fn() -> Int / <e> -> () / <proc, io | e>
104{
105 process.trap_exits True
106 let exits = process.exits ()
107 watch spec exits (list.map spec.children start_child) [] now
108}
109
110type Running = List<(Pid, Child)>
111
112fn start_child :: child: Child -> (Pid, Child) / <proc>
113{
114 (process.spawn_link (start_of child), child)
115}
116
117fn start_of ::
118 child: Child
119 -> send fn() -> () / <proc, clock, random, fs, io, ffi>
120{
121 match child { Child(_, start) -> start, ChildWith(_, start, _, _) -> start }
122}
123
124fn restart_of :: child: Child -> Restart
125{
126 match child
127 { Child(_, _) -> Transient, ChildWith(_, _, restart, _) -> restart }
128}
129
130fn shutdown_timeout_of :: child: Child -> Int
131{
132 match child { Child(_, _) -> 5000, ChildWith(_, _, _, timeout) -> timeout }
133}
134
135/// `restarts`: when the restarts within the window happened (`now`'s
136/// milliseconds, the latest first).
137fn watch ::
138 spec: Spec
139 exits: Subject<ExitSignal>
140 running: Running
141 restarts: List<Int>
142 now: fn() -> Int / <e>
143 -> () / <proc, io | e>
144{
145 match running
146 { [] -> ()
147 , _ ->
148 {
149 let ExitSignal(pid, reason) = process.receive_forever exits
150 if !is_running running pid
151 {
152 if reason == Shutdown
153 {
154 // Told to stop, by whoever started it.
155 shutdown running exits
156 }
157 else
158 {
159 // A child replaced or killed by a restart: already handled.
160 watch spec exits running restarts now
161 }
162 }
163 else
164 {
165 let child = child_of running pid
166 let done = match (restart_of child, reason)
167 { (Temporary, _) -> True
168 , (Transient, Normal) -> True
169 , (Transient, Shutdown) -> True
170 , _ -> False
171 }
172 if done
173 {
174 watch spec exits (remove running pid) restarts now
175 }
176 else
177 {
178 let restarts = counted restarts spec.period_ms (now ())
179 if list.length restarts > spec.intensity
180 {
181 // Stop the others (the crashed child is gone already).
182 shutdown (remove running pid) exits
183 panic "supervisor: too many restarts"
184 }
185 else
186 {
187 let restarted = match spec.strategy
188 { OneForOne -> restart_one running pid
189 , OneForAll -> restart_all running
190 , RestForOne -> restart_rest running pid
191 }
192 watch spec exits restarted restarts now
193 }
194 }
195 }
196 }
197 }
198}
199
200/// `restarts` with one more `now`, forgetting those older than
201/// `period_ms` (none if it is negative).
202fn counted :: restarts: List<Int> period_ms: Int now: Int -> List<Int>
203{
204 let recent = if period_ms < 0
205 {
206 restarts
207 }
208 else
209 {
210 list.filter restarts fn t { now - t < period_ms }
211 }
212 [now, ..recent]
213}
214
215fn is_running :: running: Running pid: Pid -> Bool
216{
217 use found, entry <- list.fold running False
218 found || entry.0 == pid
219}
220
221fn child_of :: running: Running pid: Pid -> Child
222{
223 match running
224 { [] -> panic "supervisor: not a child"
225 , [entry, ..rest] -> if entry.0 == pid { entry.1 } else { child_of rest pid }
226 }
227}
228
229fn remove :: running: Running pid: Pid -> Running
230{
231 use entry <- list.filter running
232 entry.0 != pid
233}
234
235fn restart_one :: running: Running pid: Pid -> Running / <proc>
236{
237 use entry <- list.map running
238 if entry.0 == pid
239 {
240 start_child entry.1
241 }
242 else
243 {
244 entry
245 }
246}
247
248fn restart_all :: running: Running -> Running / <proc>
249{
250 list.each running fn entry { process.kill entry.0 }
251 restart_kept running
252}
253
254/// Restart `pid` and the children after it, in order; the later ones are
255/// stopped first.
256fn restart_rest :: running: Running pid: Pid -> Running / <proc>
257{
258 match running
259 { [] -> []
260 , [ entry
261 , ..rest
262 ] -> if entry.0 == pid
263 {
264 // Stop the later children last-started first, as OTP does.
265 list.each (list.reverse rest) fn later { process.kill later.0 }
266 restart_kept [entry, ..rest]
267 }
268 else
269 {
270 [entry, ..restart_rest rest pid]
271 }
272 }
273}
274
275/// Start `running`'s children again, but the temporary ones, which are
276/// done.
277fn restart_kept :: running: Running -> Running / <proc>
278{
279 let kept = list.filter running fn entry { restart_of entry.1 != Temporary }
280 list.map kept fn entry { start_child entry.1 }
281}
282
283/// Stop every child, last-started first: each with `Shutdown`, killed if
284/// it is not done within its `shutdown_timeout`.
285fn shutdown :: running: Running exits: Subject<ExitSignal> -> () / <proc>
286{
287 let _ =
288 list.fold
289 (list.reverse running)
290 []
291 fn gone entry
292 {
293 stop_child entry.0 (shutdown_timeout_of entry.1) exits gone
294 }
295 ()
296}
297
298/// Stop `pid`, waiting up to `timeout` milliseconds for its exit signal,
299/// then kill it and wait for it. `gone`: the children whose exit signals
300/// arrived meanwhile (each arrives once); returns it updated.
301fn stop_child ::
302 pid: Pid
303 timeout: Int
304 exits: Subject<ExitSignal>
305 gone: List<Pid>
306 -> List<Pid> / <proc>
307{
308 if list.any gone fn p { p == pid }
309 {
310 gone
311 }
312 else
313 {
314 process.stop pid
315 match wait_exit pid timeout exits gone
316 { (True, gone) -> gone
317 , (False, gone) ->
318 {
319 process.kill pid
320 (wait_exit pid (-1) exits gone).1
321 }
322 }
323 }
324}
325
326/// Wait up to `timeout` milliseconds (negative: forever) for `pid`'s exit
327/// signal: whether it came, and the other children that exited meanwhile.
328fn wait_exit ::
329 pid: Pid
330 timeout: Int
331 exits: Subject<ExitSignal>
332 gone: List<Pid>
333 -> (Bool, List<Pid>) / <proc>
334{
335 match process.receive exits timeout
336 { None -> (False, gone)
337 , Some(ExitSignal(from, _)) -> if from == pid
338 {
339 (True, gone)
340 }
341 else
342 {
343 wait_exit pid timeout exits [from, ..gone]
344 }
345 }
346}
347
348/// How the runtime supervises a program's `main` (ADR 0060): the
349/// `[application]` section of `louise.toml`. `main` is restarted as
350/// `restart` says after it crashes, at most `intensity` times within
351/// `period_ms` milliseconds; on one of `signals`, it is stopped
352/// (`Shutdown`), and killed if it is not done within `shutdown_timeout_ms`.
353pub type Application
354{ Application(
355 restart: Restart
356 , intensity: Int
357 , period_ms: Int
358 , shutdown_timeout_ms: Int
359 , signals: List<Signal>
360 )
361}
362
363/// Run `main` under `app` (the program's root when `louise.toml` has an
364/// `[application]` section; the compiler generates the call). Returns,
365/// and the program exits 0, when `main` returns, or once it stopped after
366/// a signal; a crash beyond the restart intensity (or any crash, for a
367/// `Temporary` main) ends the program with that panic.
368pub fn application ::
369 app: Application
370 main: send fn() -> () / <proc, clock, random, fs, io, ffi>
371 -> () / <proc, io, clock>
372{
373 process.trap_exits True
374 let exits = process.exits ()
375 let signals = os.signals app.signals
376 let events =
377 process.new_selector ()
378 |> process.selecting exits Exited
379 |> process.selecting signals Signalled
380 supervise_main app main events (process.spawn_link main) []
381}
382
383/// What `application` waits for.
384type MainEvent { Exited(ExitSignal), Signalled(Signal) }
385
386fn supervise_main ::
387 app: Application
388 main: send fn() -> () / <proc, clock, random, fs, io, ffi>
389 events: process.Selector<MainEvent>
390 pid: Pid
391 restarts: List<Int>
392 -> () / <proc, io, clock>
393{
394 match process.select_forever events
395 { Signalled(_) -> stop_main pid app.shutdown_timeout_ms events
396 , Exited
397 ( ExitSignal(from, reason)
398 ) -> if from != pid
399 {
400 // Another linked actor: not `main`'s business here.
401 supervise_main app main events pid restarts
402 }
403 else
404 {
405 match (app.restart, reason)
406 { (_, Normal) -> ()
407 , (_, Shutdown) -> ()
408 , (Temporary, _) -> panic (crash_message reason)
409 , _ ->
410 {
411 let restarts = counted restarts app.period_ms (now_ms ())
412 if list.length restarts > app.intensity
413 {
414 panic (crash_message reason)
415 }
416 else
417 {
418 supervise_main app main events (process.spawn_link main) restarts
419 }
420 }
421 }
422 }
423 }
424}
425
426fn crash_message :: reason: process.ExitReason -> String
427{
428 match reason { Crashed(message) -> message, _ -> "main was killed" }
429}
430
431/// Stop `main` (`Shutdown`), waiting up to `timeout` milliseconds for it,
432/// then kill it. Further signals meanwhile are ignored.
433fn stop_main ::
434 pid: Pid
435 timeout: Int
436 events: process.Selector<MainEvent>
437 -> () / <proc>
438{
439 process.stop pid
440 if !main_exited pid timeout events
441 {
442 process.kill pid
443 let _ = main_exited pid (-1) events
444 }
445}
446
447/// Whether `main` (`pid`) exited within `timeout` milliseconds (negative:
448/// forever).
449fn main_exited ::
450 pid: Pid
451 timeout: Int
452 events: process.Selector<MainEvent>
453 -> Bool / <proc>
454{
455 match process.select events timeout
456 { None -> False
457 , Some
458 ( Exited(ExitSignal(from, _))
459 ) -> if from == pid { True } else { main_exited pid timeout events }
460 , Some(Signalled(_)) -> main_exited pid timeout events
461 }
462}