tobogganSe connecter

louise

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

85 lignes · 2319 octetsBrut · Historique
1/// Stateful actors in the style of OTP's gen_server.
2///
3/// let counter = actor.start(0, fn(n, msg) { ... })
4/// let value = actor.call(counter, Get, 1000)
5
6import std/option
7import std/process.{type Subject, type proc}
8import std/random.{type random}
9import std/time.{type clock}
10
11/// What a message handler decides.
12pub type Next<s> { Continue(s), Stop }
13
14/// Start an actor with state `init`; `on_message` processes each message.
15/// Returns the subject to send it messages.
16pub fn start ::
17 init: s
18 on_message: send fn(s, msg) -> Next<s> / <proc, clock, random, io, ffi>
19 -> Subject<msg> / <proc>
20 where Send<s>
21{
22 let ready = process.subject ()
23 {
24 use <- process.spawn
25 let inbox = process.subject ()
26 process.send ready inbox
27 serve inbox init on_message
28 }
29 process.receive_forever ready
30}
31
32fn serve ::
33 inbox: Subject<msg>
34 state: s
35 on_message: fn(s, msg) -> Next<s> / <proc, clock, random, io, ffi>
36 -> () / <proc, clock, random, io, ffi>
37{
38 match on_message state (process.receive_forever inbox)
39 { Continue(next) -> serve inbox next on_message, Stop -> () }
40}
41
42/// Why `try_call` got no answer.
43@derive Eq Show
44pub type CallError
45{ /// No reply within the timeout: the actor is busy, stuck, or stopped.
46 Timeout
47}
48
49/// Send a request carrying a reply subject and wait up to `timeout`
50/// milliseconds for the answer: `Error(Timeout)` without one.
51///
52/// A reply that arrives after the timeout stays in the caller's mailbox
53/// until the caller stops: the process API cannot close a subject yet.
54pub fn try_call ::
55 to: Subject<msg>
56 request: fn(Subject<r>) -> msg
57 timeout: Int
58 -> Result<r, CallError> / <proc>
59 where Send<msg>
60{
61 let reply = process.subject ()
62 process.send to (request reply)
63 process.receive reply timeout |> option.to_result Timeout
64}
65
66/// `try_call` for an actor that must answer: panics after `timeout`
67/// milliseconds without a reply.
68pub fn call ::
69 to: Subject<msg>
70 request: fn(Subject<r>) -> msg
71 timeout: Int
72 -> r / <proc>
73 where Send<msg>
74{
75 match try_call to request timeout
76 { Ok(answer) -> answer
77 , Error(Timeout) -> panic "actor.call: no reply within the timeout"
78 }
79}
80
81/// Send a message without waiting.
82pub fn cast :: to: Subject<msg> message: msg -> () / <proc> where Send<msg>
83{
84 process.send to message
85}