tobogganSe connecter

louise

The Louise language: compiler, runtime, std, tooling

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

784 lignes · 28246 octetsBrut · Historique
1/// Distribution (ADR 0072; native programs only): actors of several
2/// programs, each a *node* of a cluster, on one host or many, sending each
3/// other messages as they do locally.
4///
5/// // Node b names a counter.
6/// use _ <- result.try(dist.start(config))
7/// let counter = actor.start(0, step)
8/// dist.register(dist.name("counter"), counter)
9///
10/// // Node a finds it and calls it.
11/// let counter_name: Name<Counter> = dist.name("counter")
12/// use counter <- result.try(dist.whereis(counter_name, "b.cluster.example", 5000))
13/// actor.call(counter, Get, 1000)
14///
15/// // Or start an actor on node b, from a `@remote` function.
16/// use pid <- result.try(dist.spawn_on("b.cluster.example", worker, job, 5000))
17///
18/// - **Typed.** A message crosses only if its type is `Wire`: no
19/// functions, resources or `Ref`s (checked when compiling, error
20/// E0706). `whereis` refuses a name registered for another type than
21/// its `Name<m>`'s `m` (`WrongType`), so a subject it gives takes
22/// messages of the type the other node receives. Subjects and
23/// pids inside a message cross too: a reply subject works across nodes.
24/// - **At most once.** A message to a node that is not connected, or lost
25/// with its connection, is gone. A call waits with a timeout
26/// (`actor.call`).
27/// - **Back-pressure.** Each peer has an outbound queue of
28/// `outbound_queue_bytes`: a `send` to a node whose queue is full waits
29/// (the sending actor parks, not its thread) until the queue drains, so
30/// a fast sender cannot grow this node's memory without bound. The
31/// receiving actor's mailbox is not bounded: a slow consumer still
32/// holds what arrived.
33/// - **One build, mutual TLS.** Each node has a certificate for its name
34/// from the cluster's authorities, and connects only to nodes that
35/// have one too, of the same cluster and built from the same types (the
36/// program's *schema*). A refused or lost connection is logged on
37/// stderr, and `whereis` says why (`NotConnected`).
38/// - **The node's identity comes from its environment** (`from_env`): one
39/// build runs as every node. The cluster's policy comes from `[cluster]`
40/// in `louise.toml`, when the package has one (`config`, `from_env`,
41/// `start`).
42/// - **Links, monitors, `kill` and `stop`** work on another node's pids
43/// (`process.owner` of a subject `whereis` gave, or a pid in a message),
44/// in order with the messages the same actor sent. A lost node is
45/// `Crashed("noconnection")` on every link and monitor across it, once;
46/// linking to or monitoring an actor that is gone gives
47/// `Crashed("noproc")`. `monitor_node` follows a node's connection.
48/// - **Spawning on another node runs only `@remote` functions**
49/// (`spawn_on`, `spawn_link_on`, `spawn_monitor_on`): the other node
50/// names its own function by its key, and checks the argument's type
51/// before decoding it. No code crosses. **Any connected node may spawn
52/// any `@remote` function**, with any argument of its type: the
53/// attribute is the allowlist, and what to audit.
54/// - **`peers`** says how each known node is doing: up or why not, the
55/// round-trip time, queued bytes, messages sent, received and dropped.
56/// - **A full mesh from a few seeds**, with `discovery: Mesh`: nodes that
57/// discover tell each other which nodes are up and where (`advertise`),
58/// and dial those they did not know. `connect` adds a node by hand.
59/// - **Back-pressure:** a sender to a node whose outbound queue is full
60/// waits for room (`[cluster]`'s `outbound_queue_bytes`).
61///
62/// The interpreter has no distribution: these functions fail there with
63/// "distribution needs --native".
64///
65/// **Security review needed before production use** (ADR 0072).
66
67import std/actor.{Continue}
68import std/dist/remote
69import std/list
70import std/net
71import std/option
72import std/os
73import std/process.{type Down, type Dynamic, type Pid, type Subject, type proc}
74import std/result
75import std/string
76import std/wire.{type Arg, type Refused}
77
78/// How a node starts: `config`, then record update, or `from_env`.
79///
80/// - `node`: this node's name, a lowercase DNS name its certificate is
81/// valid for (`node-1.cluster.example`).
82/// - `cluster`: nodes of another cluster are refused (a node name's
83/// syntax).
84/// - `listen`: where to listen, `host:port` (`[::1]:4370` for an IPv6
85/// address); port 0 picks a free one, which `start` returns.
86/// - `advertise`: where other nodes can dial this one, `host:port`, which
87/// it tells the nodes it discovers with. `None`: `listen`, unless it is
88/// every interface (`0.0.0.0`, `::`), with the port `start` returns;
89/// then nothing, and only the nodes this one dials reach it.
90/// - `seeds`: nodes to connect to at start, and again whenever their
91/// connection is lost: `name:port`, or `name@host:port` when the name is
92/// not the host's.
93/// - `discovery`: `Seeds`, only the seeds (and `connect`'s nodes) are
94/// dialed; `Mesh`, also every node a peer that discovers too lists.
95/// - `cert`, `key`: this node's certificate chain and key, PEM files.
96/// - `ca`: the cluster's authorities, PEM files: a peer's certificate must
97/// chain to one of them (never to the system's).
98/// - `heartbeat_ms`: a heartbeat goes out to each peer this often (its
99/// echo gives the round-trip time); `node_down_after_ms`: a node silent
100/// this long is down.
101/// - `max_message_bytes`: the largest message payload this node accepts
102/// (1 KiB to 64 MiB); `outbound_queue_bytes`: the message bytes
103/// (payloads and 36-byte headers) queued per peer before senders wait.
104/// - `max_peers`: the connections this node keeps (1 to 4096) before it
105/// refuses a node that is not one of its seeds. Seeds count, and are
106/// never refused.
107///
108/// With `[cluster]` in `louise.toml`, `config` takes its defaults from it,
109/// and `start` refuses another cluster name.
110pub type Config
111{ Config(
112 node: String
113 , cluster: String
114 , listen: String
115 , advertise: Option<String>
116 , seeds: List<String>
117 , discovery: Discovery
118 , cert: String
119 , key: String
120 , ca: List<String>
121 , heartbeat_ms: Int
122 , node_down_after_ms: Int
123 , max_message_bytes: Int
124 , outbound_queue_bytes: Int
125 , max_peers: Int
126 )
127}
128
129/// Which nodes a node dials (`Config`'s `discovery`, `[cluster]`'s, or
130/// `LOUISE_DISCOVERY`: `"seeds"` or `"mesh"`).
131@derive Eq Show Debug
132pub type Discovery
133{ /// Its seeds, and the nodes `connect` names.
134 Seeds
135 /// Also each node that a peer that discovers too lists: from a few
136 /// seeds, every node reaches every other. A node dials at most
137 /// `max_peers` nodes it discovered.
138, Mesh
139}
140
141/// Why a distribution operation failed.
142@derive Eq Show Debug
143pub type DistError
144{ /// `start` was not called, or failed.
145 NotStarted
146 /// `start`: the configuration cannot work, or the node cannot listen.
147, Invalid(String)
148 /// Not connected to `node` (yet, or any more), and why the last
149 /// connection with it failed (empty if none did).
150, NotConnected(node: String, reason: String)
151 /// No live actor of `node` is registered under `name`.
152, NoName(name: String, node: String)
153 /// `name` is registered on `node` for messages of another type, or
154 /// (`spawn_on`) `node`'s `@remote` function `name` takes another type.
155, WrongType(name: String, node: String)
156 /// `spawn_on`: `node` has no `@remote` function `entry` (a build of
157 /// other functions from the same types).
158, UnknownEntry(entry: String, node: String)
159 /// `spawn_on`: `node` did not start `entry`: its argument did not
160 /// decode there, or it cannot spawn.
161, Refused(entry: String, node: String)
162 /// `node` did not answer within the timeout.
163, Timeout(node: String)
164 /// `register`: a live actor holds the name.
165, Taken(String)
166 /// `register`: the subject is another node's.
167, NotLocal
168 /// `spawn_link_on`, `spawn_monitor_on`: `node`'s runtime does not take
169 /// that spawn (an older build). Nothing was asked of it.
170, Unsupported(node: String)
171}
172
173/// A configuration with the defaults: those of `[cluster]` if the
174/// package has one, else listening on every interface on port 4370, a
175/// heartbeat every second, a node down after 10 s, messages of 8 MiB at
176/// most, 64 MiB queued per peer, 256 peers; no seeds, no discovery.
177pub fn config ::
178 node: String
179 cluster: String
180 cert: String
181 key: String
182 ca: List<String>
183 -> Config
184{
185 let c =
186 Config( node: node
187 , cluster: cluster
188 , listen: "0.0.0.0:4370"
189 , advertise: None
190 , seeds: []
191 , discovery: Seeds
192 , cert: cert
193 , key: key
194 , ca: ca
195 , heartbeat_ms: 1000
196 , node_down_after_ms: 10000
197 , max_message_bytes: 8388608
198 , outbound_queue_bytes: 67108864
199 , max_peers: 256
200 )
201 match wire.cluster ()
202 { Some(policy) ->
203 Config( ..c
204 , listen: option.unwrap_or policy.listen c.listen
205 , heartbeat_ms: policy.heartbeat_ms
206 , node_down_after_ms: policy.node_down_after_ms
207 , max_message_bytes: policy.max_message_bytes
208 , outbound_queue_bytes: policy.outbound_queue_bytes
209 , max_peers: policy.max_peers
210 , discovery: if policy.discovery == "mesh" { Mesh } else { Seeds }
211 )
212 , None -> c
213 }
214}
215
216/// The configuration the environment gives, so one build runs as every
217/// node (the defaults of `config` otherwise):
218///
219/// - `LOUISE_NODE`: the node's name;
220/// - `LOUISE_CLUSTER`: the cluster's name. With `[cluster]`, optional: the
221/// manifest names the cluster, and a variable that names another is an
222/// error rather than an override (the manifest is the policy);
223/// - `LOUISE_CERT`, `LOUISE_KEY`: its certificate and key files;
224/// - `LOUISE_CA`: the authorities' files, separated by commas;
225/// - `LOUISE_LISTEN` (optional): `host:port`, over `[cluster]`'s `listen`
226/// (an address is the deployment's, not the cluster's);
227/// - `LOUISE_ADVERTISE` (optional): `host:port`, where other nodes can
228/// dial this one;
229/// - `LOUISE_SEEDS` (optional): seeds, separated by commas;
230/// - `LOUISE_DISCOVERY` (optional): `seeds` or `mesh`, over `[cluster]`'s
231/// `discovery`.
232///
233/// `Error` names a required variable that is not set, a cluster that is
234/// not `[cluster]`'s, or a discovery that is neither.
235pub fn from_env :: -> Result<Config, String> / <io>
236{
237 use node <- result.try (required "LOUISE_NODE")
238 use cluster <- result.try (env_cluster ())
239 use cert <- result.try (required "LOUISE_CERT")
240 use key <- result.try (required "LOUISE_KEY")
241 use ca <- result.try (required "LOUISE_CA")
242 let c = config node cluster cert key (items ca)
243 let c = match os.env "LOUISE_LISTEN"
244 { Some(listen) -> Config(..c, listen: listen), None -> c }
245 let c = match os.env "LOUISE_ADVERTISE"
246 { Some(address) if address != "" -> Config(..c, advertise: Some(address))
247 , _ -> c
248 }
249 let c = match os.env "LOUISE_SEEDS"
250 { Some(seeds) -> Config(..c, seeds: items seeds), None -> c }
251 match os.env "LOUISE_DISCOVERY"
252 { None -> Ok(c)
253 , Some("") -> Ok(c)
254 , Some("seeds") -> Ok(Config(..c, discovery: Seeds))
255 , Some("mesh") -> Ok(Config(..c, discovery: Mesh))
256 , Some(other) ->
257 Error("LOUISE_DISCOVERY: {other:?} is neither \"seeds\" nor \"mesh\"")
258 }
259}
260
261/// The cluster's name: `[cluster]`'s, which `LOUISE_CLUSTER` may repeat
262/// but not change, or else `LOUISE_CLUSTER`.
263fn env_cluster :: -> Result<String, String> / <io>
264{
265 match (wire.cluster (), os.env "LOUISE_CLUSTER")
266 { (None, _) -> required "LOUISE_CLUSTER"
267 , (Some(policy), Some(name)) if name != "" && name != policy.name ->
268 Error("LOUISE_CLUSTER: " <> not_policy name policy)
269 , (Some(policy), _) -> Ok(policy.name)
270 }
271}
272
273fn required :: variable: String -> Result<String, String> / <io>
274{
275 match os.env variable
276 { Some(value) if value != "" -> Ok(value)
277 , _ -> Error(variable <> " is not set")
278 }
279}
280
281/// The non-empty items of a comma-separated list.
282fn items :: text: String -> List<String>
283{
284 list.filter
285 (list.map (string.split text ",") string.trim)
286 fn item { item != "" }
287}
288
289/// Start this node: listen, connect to the seeds, and from then on reach
290/// the actors of the nodes it connects to. `Ok(port)`: the port it listens
291/// on. Once per program; it runs until the program ends, with an actor
292/// that starts the `@remote` functions other nodes ask for (`spawn_on`).
293/// With `[cluster]`, `config.cluster` must be its name.
294pub fn start :: config: Config -> Result<Int, DistError> / <proc, io>
295{
296 use _ <- result.try (of_cluster config.cluster)
297 use listen <- result.try (resolve config.listen)
298 let advertise = match config.advertise
299 { Some(address) -> resolve address, None -> Ok("") }
300 use advertise <- result.try advertise
301 use seeds <- result.try (list.try_map config.seeds seed)
302 let spawner = actor.start () fn _ request { spawn_for request }
303 let started =
304 start_node
305 config.node
306 config.cluster
307 listen
308 advertise
309 seeds
310 config.cert
311 config.key
312 config.ca
313 (wire.definitions ())
314 (wire.schema_hash ())
315 ( config.heartbeat_ms
316 , config.node_down_after_ms
317 , config.max_message_bytes
318 , config.outbound_queue_bytes
319 , config.max_peers
320 , match config.discovery { Seeds -> 0, Mesh -> 1 }
321 )
322 (wire.entries ())
323 spawner
324 match started
325 { Ok(port) -> Ok(port)
326 , Error(why) ->
327 {
328 process.kill (process.owner spawner)
329 Error(Invalid(why))
330 }
331 }
332}
333
334fn not_policy :: cluster: String policy: wire.Cluster -> String
335{
336 "cluster {cluster:?} is not louise.toml's [cluster] name {policy.name:?}"
337}
338
339/// `cluster` is the package's, if it has `[cluster]`.
340fn of_cluster :: cluster: String -> Result<(), DistError>
341{
342 match wire.cluster ()
343 { Some(policy) if policy.name != cluster ->
344 Error(Invalid(not_policy cluster policy))
345 , _ -> Ok(())
346 }
347}
348
349@extern c "tl_dist_start"
350fn start_node ::
351 node: String
352 cluster: String
353 listen: String
354 advertise: String
355 seeds: List<(String, String)>
356 cert: String
357 key: String
358 ca: List<String>
359 table: String
360 schema_hash: String
361 limits: (Int, Int, Int, Int, Int, Int)
362 entries: List<wire.Entry>
363 spawner: Subject<Request>
364 -> Result<Int, String> / <io>
365
366/// Connect to `node` at `address` (`host:port`, the host's first address)
367/// unless connected, and again whenever the connection is lost, as to a
368/// seed: from now until the program ends. Seeds and these nodes are never
369/// refused for `max_peers`. Returns at once: `monitor_node` says when it is
370/// up. `Invalid` for a name that is not a node name, or an address that
371/// does not resolve; `NotStarted` before `start`. This node's own name does
372/// nothing.
373pub fn connect :: node: String address: String -> Result<(), DistError> / <io>
374{
375 use ip <- result.try (resolve address)
376 match connect_raw node ip
377 { 0 -> Ok(())
378 , 1 -> Error(NotStarted)
379 , _ -> Error(Invalid("{node:?} is not a node name"))
380 }
381}
382
383@extern c "tl_dist_connect"
384fn connect_raw :: node: String address: String -> Int / <io>
385
386/// A seed's name and address (`ip:port`).
387fn seed :: text: String -> Result<(String, String), DistError> / <io>
388{
389 match string.split text "@"
390 { [name, address] -> resolve address |> result.map fn a { (name, a) }
391 , [address] ->
392 {
393 use (name, _) <- result.try (split_address address)
394 resolve address |> result.map fn a { (name, a) }
395 }
396 , _ -> Error(Invalid("seed {text:?} is not name:port or name@host:port"))
397 }
398}
399
400/// `host:port` as `ip:port` (`[ip]:port` for IPv6): the host's first
401/// address (a lookup, on the `io` blocking pool).
402fn resolve :: address: String -> Result<String, DistError> / <io>
403{
404 use (host, port) <- result.try (split_address address)
405 match net.resolve host
406 { Ok
407 ( [ip, .._rest]
408 ) -> if string.contains ip ":"
409 {
410 Ok("[" <> ip <> "]:" <> port)
411 }
412 else
413 {
414 Ok(ip <> ":" <> port)
415 }
416 , Ok([]) -> Error(Invalid("no address for " <> host))
417 , Error(e) -> Error(Invalid(e))
418 }
419}
420
421fn split_address :: address: String -> Result<(String, String), DistError>
422{
423 let parts = if string.starts_with address "["
424 {
425 string.split (string.slice address 1 (string.length address)) "]:"
426 }
427 else
428 {
429 string.split address ":"
430 }
431 match parts
432 { [host, port] if host != "" && port != "" -> Ok((host, port))
433 , _ -> Error(Invalid("{address:?} is not host:port"))
434 }
435}
436
437/// A name for subjects of messages `m`, the same on every node: `register`
438/// it on one, `whereis` it from any, which checks that the subject it
439/// names takes `m`s.
440///
441/// Only its text: `m` is phantom, so a `Name` crosses hosts, and one that
442/// came off the wire, of whatever `m`, is just as good. `register` and
443/// `whereis` take `m`'s descriptor from their own `Wire<m>`, never from
444/// the value (ADR 0072).
445pub opaque type Name<m> { Name(text: String) }
446
447/// The name `text` for subjects of messages `m`, which must be able to
448/// cross hosts: `let counter: Name<Counter> = dist.name("counter")`. At
449/// most 255 bytes: `register` and `whereis` panic on a longer one.
450pub fn name :: text: String -> Name<m> where Wire<m>
451{
452 Name(text)
453}
454
455/// The descriptor of `name`'s messages, from the caller's `Wire<m>`.
456fn descriptor :: name: Name<m> none: Option<m> -> String where Wire<m>
457{
458 wire.describe_none none
459}
460
461/// The text of `name`.
462pub fn text :: name: Name<m> -> String
463{
464 name.text
465}
466
467/// Give `name` to `subject`, one of this node's, for every node to find
468/// with `whereis`: until its actor exits. `Taken` while another live
469/// actor's subject holds it.
470pub fn register ::
471 name: Name<m>
472 subject: Subject<m>
473 -> Result<(), DistError> / <io>
474 where Wire<m>
475{
476 match register_raw name.text (descriptor name None) subject
477 { 0 -> Ok(()), code -> Error(failure code "" name.text "") }
478}
479
480@extern c "tl_dist_register"
481fn register_raw :: name: String desc: String subject: Subject<m> -> Int / <io>
482
483/// The subject `node` registered under `name`, asking it and waiting up
484/// to `timeout` milliseconds for its answer (this node's own name: its own
485/// registrations). Send to it, or `actor.call` it, as to a local one.
486pub fn whereis ::
487 name: Name<m>
488 node: String
489 timeout: Int
490 -> Result<Subject<m>, DistError> / <proc, io>
491 where Wire<m>
492{
493 let answers = process.subject ()
494 lookup (process.tag answers) node name.text (descriptor name None)
495 match process.receive answers timeout
496 { Some(Found(subject)) -> Ok(subject)
497 , Some(Failed(code, why)) -> Error(failure code node name.text why)
498 , None -> Error(Timeout(node))
499 }
500}
501
502/// A node's connection, as `monitor_node` reports it.
503@derive Eq Show Debug
504pub type NodeEvent
505{ /// Connected: its actors can be reached.
506 NodeUp(node: String)
507 /// Not connected, and why its last connection failed or was lost (empty
508 /// if none did). Its links and monitors already had their
509 /// `noconnection`.
510, NodeDown(node: String, reason: String)
511}
512
513/// Follow `node`'s connection from now on, on the returned subject, owned
514/// by the calling actor: first its state now (`NodeUp`, or `NodeDown` if
515/// it is not connected, `start` was not called, or failed), then a
516/// `NodeUp` or `NodeDown` each time it changes, until the actor exits.
517/// This node's own name is up. Before `start` (or after it failed) only
518/// that first `NodeDown` comes: subscribe once the node runs. Each call
519/// adds a subscription, kept until the actor exits: call it once per node,
520/// not in a loop.
521pub fn monitor_node :: node: String -> Subject<NodeEvent> / <proc, io>
522{
523 let events = process.subject ()
524 watch_node (process.tag events) node
525 events
526}
527
528/// Send `node`'s events to the running actor's subject `tag`
529/// (`runtime/louise_rt/src/node.rs` builds them: `NodeEvent`'s order is
530/// fixed).
531@extern c "tl_dist_monitor_node"
532fn watch_node :: tag: Int node: String -> () / <io>
533
534/// A node this node knows (a seed, a node it was connected to, a node it
535/// sent to), as `peers` reports it. The counts are since the program
536/// started, across the node's connections.
537///
538/// - `incarnation`: the node's run it is (or was last) connected to, 16
539/// hex digits; `None` if it never was. A restarted node is another.
540/// - `rtt_us`: the round-trip time of the last heartbeat, in
541/// microseconds, while up.
542/// - `queued_bytes`: message bytes waiting to be written to it (headers
543/// included), at most about `outbound_queue_bytes`.
544/// - `sent`: messages written to its connection; `received`: messages it
545/// sent this node.
546/// - `unsent`: messages for it that were not sent: it was not up, or the
547/// connection was lost with them queued, or their sender stopped while
548/// it waited for room.
549/// - `parked`: how many times a sender waited for room in its queue
550/// (back-pressure).
551/// - `dropped`: messages and lookups from it that this node dropped
552/// (undecodable, of a type it does not know, for a previous run).
553@derive Eq Show Debug
554pub type Peer
555{ Peer(
556 node: String
557 , incarnation: Option<String>
558 , state: PeerState
559 , rtt_us: Option<Int>
560 , queued_bytes: Int
561 , sent: Int
562 , received: Int
563 , unsent: Int
564 , parked: Int
565 , dropped: Int
566 )
567}
568
569/// Whether a node is connected; if not, why the last connection with it
570/// failed (empty if none did, or it closed normally).
571@derive Eq Show Debug
572pub type PeerState { Up, Down(reason: String) }
573
574/// Every node this node knows, by name: `[]` before `start`. A snapshot,
575/// read without waiting. It keeps every node that is up and every seed,
576/// and of the others the `max_peers` most recently seen: past those, the
577/// least recently seen is forgotten, its counts with it (a node is seen
578/// when it goes down, and when a message for it or from it is counted).
579pub fn peers :: -> List<Peer> / <io>
580{
581 peers_raw ()
582}
583
584/// `runtime/louise_rt/src/node.rs` builds `Peer`s: the order is fixed.
585@extern c "tl_dist_peers"
586fn peers_raw :: -> List<Peer> / <io>
587
588/// How the runtime answers `whereis` (a `Subject<m>`) and `spawn_on` (a
589/// `Pid`), on the subject it is given (`runtime/louise_rt/src/node.rs`
590/// builds it: the order is fixed).
591type Answer<a> { Found(a), Failed(Int, String) }
592
593@extern c "tl_dist_whereis"
594fn lookup :: tag: Int node: String name: String desc: String -> () / <io>
595
596/// The error of the runtime's code (`node.rs`'s `code`).
597fn failure :: code: Int node: String name: String text: String -> DistError
598{
599 match code
600 { 1 -> NotStarted
601 , 2 -> NotConnected(node, text)
602 , 3 -> NoName(name, node)
603 , 4 -> WrongType(name, node)
604 , 5 -> Taken(name)
605 , 6 -> NotLocal
606 , 7 -> UnknownEntry(name, node)
607 , 10 -> Unsupported(node)
608 , _ -> Refused(name, node)
609 }
610}
611
612/// A `@remote` function, as `std/dist` users name it: `dist.Remote<a>`.
613pub type Remote<a> = remote.Remote<a>
614
615/// Start `entry` on `node` with `args`, asking it and waiting up to
616/// `timeout` milliseconds for its answer: the new actor's pid (this
617/// node's own name: here). The actor is not linked to the caller.
618///
619/// `node` checks that it has `entry` (`UnknownEntry`) and that `args` is
620/// of its argument's type (`WrongType`) before decoding them. On
621/// `Timeout`, the actor may still start.
622pub fn spawn_on ::
623 node: String
624 entry: Remote<a>
625 args: a
626 timeout: Int
627 -> Result<Pid, DistError> / <proc, io>
628 where Wire<a>
629{
630 ask_spawn node entry args timeout Untied 0
631}
632
633/// `spawn_on`, the new actor linked to the caller before it can run, as
634/// `process.spawn_link` does: whenever it exits, the caller gets its exit
635/// signal, and the other way round, even if it exits at once. A caller
636/// that already exited when `node` links it answers `Crashed("noproc")`:
637/// the new actor dies of it.
638///
639/// On `Timeout`, the actor may still start, linked to the caller, which
640/// never learned its pid: its exit still reaches the caller. A node whose
641/// runtime does not take a linked spawn answers `Unsupported` at once.
642pub fn spawn_link_on ::
643 node: String
644 entry: Remote<a>
645 args: a
646 timeout: Int
647 -> Result<Pid, DistError> / <proc, io>
648 where Wire<a>
649{
650 ask_spawn node entry args timeout Linked 0
651}
652
653/// `spawn_on`, the new actor monitored by the caller before it can run, as
654/// `process.spawn_monitor` does: whenever it exits, its `Down` comes on
655/// the subject returned, even if it exits at once. A lost node gives
656/// `Down(Crashed("noconnection"))`; `process.demonitor` stops it.
657///
658/// On `Timeout`, the actor may still start, monitored by nobody: no `Down`
659/// of it comes. An answer that arrives as the wait ends is taken, with
660/// its monitor. A node whose runtime does not take a monitored spawn
661/// answers `Unsupported` at once.
662pub fn spawn_monitor_on ::
663 node: String
664 entry: Remote<a>
665 args: a
666 timeout: Int
667 -> Result<(Pid, Subject<Down>), DistError> / <proc, io>
668 where Wire<a>
669{
670 let downs = process.subject ()
671 ask_spawn node entry args timeout Monitored (process.tag downs)
672 |> result.map fn pid { (pid, downs) }
673}
674
675/// How a spawn's new actor is tied to its asker (`node.rs` reads its
676/// constructor's index: the order is fixed).
677type Tie { Untied, Linked, Monitored }
678
679/// Ask for a spawn, tied as `tie` says (`down`: a monitor's subject's
680/// tag), and wait for its answer.
681fn ask_spawn ::
682 node: String
683 entry: Remote<a>
684 args: a
685 timeout: Int
686 tie: Tie
687 down: Int
688 -> Result<Pid, DistError> / <proc, io>
689 where Wire<a>
690{
691 let answers = process.subject ()
692 let key = remote.key entry
693 request_spawn
694 (process.tag answers)
695 node
696 key
697 (wire.describe args)
698 args
699 tie
700 down
701 let answered = fn answer
702 {
703 match answer
704 { Found(pid) -> Ok(pid)
705 , Failed(code, why) -> Error(failure code node (entry_name key) why)
706 }
707 }
708 match process.receive answers timeout
709 { Some(answer) -> answered answer
710 , None -> match tie
711 { Monitored if !(abandon_spawn (process.tag answers)) ->
712 // The answer came meanwhile, and the monitor with it.
713 answered (process.receive_forever answers)
714 , _ -> Error(Timeout(node))
715 }
716 }
717}
718
719@extern c "tl_dist_spawn"
720fn request_spawn ::
721 tag: Int
722 node: String
723 key: Int
724 desc: String
725 args: a
726 tie: Tie
727 down: Int
728 -> () / <io>
729
730/// Give up waiting for the monitored spawn answered on `tag`: whether it
731/// was given up (its new actor is then not monitored), or answered
732/// meanwhile.
733@extern c "tl_dist_spawn_abandon"
734fn abandon_spawn :: tag: Int -> Bool / <io>
735
736/// The qualified name of the program's `@remote` function `key`.
737fn entry_name :: key: Int -> String
738{
739 list.find (wire.entries ()) fn e { e.key == key }
740 |> option.map fn e { e.name }
741 |> option.unwrap_or ""
742}
743
744/// A spawn another node (or this one) asks of this node, as the runtime
745/// delivers it to the node's spawner (`node.rs` builds it: the order is
746/// fixed). The runtime checked `key` and `arg`'s type against the
747/// program's entries, and decoded `arg`; `asker` and `tag` are where the
748/// answer goes; `tie` how the new actor is tied to the asker, and `down`
749/// the tag of a monitor's `Down`.
750type Request
751{ Request(key: Int, arg: Arg, asker: Pid, tag: Int, tie: Tie, down: Int) }
752
753/// The node's spawner, an actor `start` starts: it runs each `@remote`
754/// function asked, through the compiler's dispatcher (`wire.dispatch`),
755/// and the runtime spawns the body and answers. No code address ever
756/// comes off the wire.
757fn spawn_for :: request: Request -> actor.Next<()> / <io>
758{
759 match request
760 { Request(key, arg, asker, tag, tie, down) ->
761 start_for asker tag tie down (result.map (wire.dispatch key arg) erase)
762 }
763 Continue(())
764}
765
766/// Spawn `body` (the dispatcher's, a `send fn() -> () / <proc, clock,
767/// random, io, ffi>`) for `asker`, tied to it as `tie` says, and answer it
768/// on `tag` with its pid; or with why the dispatcher refused. The runtime
769/// spawns it (`node.rs`): linked to or monitored by a remote asker, its
770/// link frame or its answer must leave before the actor can run.
771@extern c "tl_dist_spawn_for" owned
772fn start_for ::
773 asker: Pid
774 tag: Int
775 tie: Tie
776 down: Int
777 body: Result<Dynamic, Refused>
778 -> () / <io>
779
780/// `body`, as `start_for` takes it: an extern takes no function that
781/// performs `proc` (E0113), and the runtime does not call it, it spawns
782/// it.
783@extern c "tl_coerce"
784fn erase :: body: a -> Dynamic