unitype_runtime/environment.rs
1//! Where code runs.
2//!
3//! An implementation does not run in a language, it runs in an **environment**:
4//! a browser, a Node process, a Python interpreter, this Rust process, a
5//! WebAssembly sandbox, something already running on another machine. The
6//! language says what the code is written in; the environment says where it
7//! executes and what else is available to it there.
8//!
9//! Keeping the two apart matters because the same code can run in more than one
10//! place. A Python implementation might be reached by starting an interpreter,
11//! or by asking one that is already running, or by loading CPython compiled to
12//! WebAssembly. Same proof, same language, three ways of getting to it — and
13//! nothing about the proof changes.
14//!
15//! # How an environment comes to hold anything
16//!
17//! An environment loads a module, and the module **registers as an execution
18//! source**: it announces which propositions it can prove and how to reach each
19//! one. Nothing is discovered by scanning or convention. That is why a program
20//! embedding this can be a standalone binary or a library inside someone else's
21//! application without either arrangement being a special case — in both, some
22//! module said what it could do.
23
24use std::collections::BTreeMap;
25use std::path::PathBuf;
26
27use serde::{Deserialize, Serialize};
28use unitype_core::{Ident, Metadata};
29
30/// How this process gets to an environment.
31///
32/// Separate from the environment itself: it is the road, not the destination.
33#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
34#[serde(tag = "k", rename_all = "snake_case")]
35pub enum Reach {
36 /// The environment is this process.
37 ///
38 /// Implementations here are Rust functions compiled in, or bodies the
39 /// interpreter walks. Nothing is serialized and nothing is spawned.
40 Here,
41 /// A child process, started when needed and spoken to over its standard
42 /// streams.
43 Subprocess {
44 /// The program to run.
45 command: String,
46 /// Its arguments.
47 #[serde(default)]
48 args: Vec<String>,
49 /// Where to run it, relative to the manifest that declared it.
50 #[serde(default, skip_serializing_if = "Option::is_none")]
51 cwd: Option<PathBuf>,
52 /// Environment variables to set.
53 #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
54 env: BTreeMap<String, String>,
55 /// How long to wait before giving up.
56 #[serde(default = "default_timeout")]
57 timeout_ms: u64,
58 /// Keep the process alive between calls.
59 ///
60 /// Starting an interpreter costs more than most calls do — around
61 /// twenty milliseconds for Python — so a program calling repeatedly
62 /// pays that over and over for nothing. A worker pays it once.
63 ///
64 /// The cost is that state now survives between calls, which is exactly
65 /// what one process per call was free of. Off by default for that reason:
66 /// a module that holds nothing between calls says so.
67 #[serde(default)]
68 persistent: bool,
69 },
70 /// A WebAssembly module instantiated in this process.
71 ///
72 /// The only environment that is actually a sandbox: a guest gets memory and
73 /// nothing else — no files, no sockets, no clock — and runs on a budget, so
74 /// a proof that never finishes stops rather than taking this process with
75 /// it. There is no operating system process to kill here, which is why the
76 /// budget matters more than a timeout would.
77 Wasm {
78 /// The module to load.
79 module: PathBuf,
80 /// How much work the guest may do before it is stopped.
81 #[serde(default, skip_serializing_if = "Option::is_none")]
82 fuel: Option<u64>,
83 },
84 /// Something already running that this process talks to.
85 Remote {
86 /// Where to find it.
87 endpoint: String,
88 /// How long to wait before giving up.
89 #[serde(default = "default_timeout")]
90 timeout_ms: u64,
91 },
92}
93
94fn default_timeout() -> u64 {
95 30_000
96}
97
98impl Reach {
99 /// A short name for this way of reaching an environment.
100 pub fn kind(&self) -> &'static str {
101 match self {
102 Reach::Here => "here",
103 Reach::Subprocess { .. } => "subprocess",
104 Reach::Wasm { .. } => "wasm",
105 Reach::Remote { .. } => "remote",
106 }
107 }
108
109 /// How long to wait for an answer, where waiting is a thing that happens.
110 pub fn timeout_ms(&self) -> Option<u64> {
111 match self {
112 Reach::Subprocess { timeout_ms, .. } | Reach::Remote { timeout_ms, .. } => {
113 Some(*timeout_ms)
114 }
115 Reach::Here | Reach::Wasm { .. } => None,
116 }
117 }
118
119 /// Whether the process is kept alive between calls.
120 pub fn is_persistent(&self) -> bool {
121 matches!(
122 self,
123 Reach::Subprocess {
124 persistent: true,
125 ..
126 }
127 )
128 }
129
130 /// Roughly what it costs to get there, ascending.
131 ///
132 /// Used only to break ties between proofs that are otherwise equally good,
133 /// on the reasoning that not leaving the process beats leaving it. A worker
134 /// already running costs less to reach than one that has to be started.
135 pub fn overhead(&self) -> u8 {
136 match self {
137 Reach::Here => 0,
138 Reach::Wasm { .. } => 1,
139 Reach::Subprocess {
140 persistent: true, ..
141 } => 2,
142 Reach::Subprocess { .. } => 3,
143 Reach::Remote { .. } => 4,
144 }
145 }
146}
147
148/// A place implementations run.
149#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
150pub struct Environment {
151 /// What this environment is called, referred to by implementations.
152 pub id: Ident,
153 /// The language whose code runs here.
154 pub language: Ident,
155 /// Prose describing it.
156 #[serde(default, skip_serializing_if = "Option::is_none")]
157 pub doc: Option<String>,
158 /// How this process gets to it.
159 pub reach: Reach,
160 /// Non-identifying annotations.
161 #[serde(default, skip_serializing_if = "Metadata::is_empty")]
162 pub meta: Metadata,
163}
164
165impl Environment {
166 /// The environment that is this process.
167 ///
168 /// Every registry has one: it is where compiled-in Rust functions live, and
169 /// where the interpreter walks bodies.
170 pub fn here() -> Self {
171 Self {
172 id: Ident::new("here").expect("a valid name"),
173 language: Ident::new("rust").expect("a valid name"),
174 doc: Some(
175 "This process. Compiled-in functions and interpreted bodies run here.".to_string(),
176 ),
177 reach: Reach::Here,
178 meta: Metadata::default(),
179 }
180 }
181
182 /// An environment reached by starting a program.
183 pub fn subprocess(id: &str, language: &str, command: &str, args: &[&str]) -> Self {
184 Self {
185 id: Ident::new(id).expect("a valid name"),
186 language: Ident::new(language).expect("a valid name"),
187 doc: None,
188 reach: Reach::Subprocess {
189 command: command.to_string(),
190 args: args.iter().map(|s| s.to_string()).collect(),
191 cwd: None,
192 env: BTreeMap::new(),
193 timeout_ms: default_timeout(),
194 persistent: false,
195 },
196 meta: Metadata::default(),
197 }
198 }
199
200 /// An environment reached by loading a WebAssembly module.
201 ///
202 /// The language is what the guest was written in, which is worth keeping
203 /// even though the host cannot tell: a route printed for a person should
204 /// say a proof came from Rust or from Go, not that it came from bytecode.
205 pub fn wasm(id: &str, language: &str, module: impl Into<PathBuf>) -> Self {
206 Self {
207 id: Ident::new(id).expect("a valid name"),
208 language: Ident::new(language).expect("a valid name"),
209 doc: None,
210 reach: Reach::Wasm {
211 module: module.into(),
212 fuel: None,
213 },
214 meta: Metadata::default(),
215 }
216 }
217
218 /// Whether this environment is this process.
219 pub fn is_here(&self) -> bool {
220 matches!(self.reach, Reach::Here)
221 }
222}
223
224#[cfg(test)]
225mod tests {
226 use super::*;
227
228 #[test]
229 fn this_process_is_always_an_environment() {
230 let here = Environment::here();
231 assert!(here.is_here());
232 assert_eq!(here.reach.overhead(), 0);
233 assert_eq!(
234 here.reach.timeout_ms(),
235 None,
236 "there is nothing to wait for"
237 );
238 }
239
240 #[test]
241 fn staying_in_the_process_costs_less_than_leaving_it() {
242 let ordered = [
243 Reach::Here,
244 Reach::Wasm {
245 module: "x.wasm".into(),
246 fuel: None,
247 },
248 Reach::Subprocess {
249 command: "python3".into(),
250 args: vec![],
251 cwd: None,
252 env: BTreeMap::new(),
253 timeout_ms: 1000,
254 persistent: true,
255 },
256 Reach::Subprocess {
257 command: "python3".into(),
258 args: vec![],
259 cwd: None,
260 env: BTreeMap::new(),
261 timeout_ms: 1000,
262 persistent: false,
263 },
264 Reach::Remote {
265 endpoint: "https://elsewhere".into(),
266 timeout_ms: 1000,
267 },
268 ];
269 for pair in ordered.windows(2) {
270 assert!(
271 pair[0].overhead() < pair[1].overhead(),
272 "{} should cost less than {}",
273 pair[0].kind(),
274 pair[1].kind()
275 );
276 }
277 }
278
279 #[test]
280 fn the_same_language_can_be_reached_more_than_one_way() {
281 // Which is the point of keeping the two apart: a Python proof does not
282 // change because it is reached differently.
283 let spawned = Environment::subprocess("py_local", "python", "python3", &["-u"]);
284 let hosted = Environment {
285 id: Ident::new("py_remote").unwrap(),
286 language: Ident::new("python").unwrap(),
287 doc: None,
288 reach: Reach::Remote {
289 endpoint: "http://localhost:9000".into(),
290 timeout_ms: 5_000,
291 },
292 meta: Metadata::default(),
293 };
294 assert_eq!(spawned.language, hosted.language);
295 assert_ne!(spawned.reach.kind(), hosted.reach.kind());
296 }
297
298 #[test]
299 fn a_worker_already_running_is_cheaper_to_reach_than_one_that_must_start() {
300 let started_each_time = Environment::subprocess("py", "python", "python3", &[]);
301 let mut kept_alive = started_each_time.clone();
302 if let Reach::Subprocess { persistent, .. } = &mut kept_alive.reach {
303 *persistent = true;
304 }
305 assert!(kept_alive.reach.is_persistent());
306 assert!(!started_each_time.reach.is_persistent());
307 assert!(kept_alive.reach.overhead() < started_each_time.reach.overhead());
308 }
309
310 #[test]
311 fn a_process_is_started_afresh_unless_asked_otherwise() {
312 // Keeping a process alive means state survives between calls, which is
313 // a thing to opt into rather than discover.
314 let manifest: Environment = serde_json::from_str(
315 r#"{"id":"py","language":"python",
316 "reach":{"k":"subprocess","command":"python3"}}"#,
317 )
318 .expect("reads");
319 assert!(!manifest.reach.is_persistent());
320 }
321
322 #[test]
323 fn an_environment_round_trips_through_json() {
324 let env = Environment::subprocess("node", "typescript", "node", &["harness.js"]);
325 let text = serde_json::to_string(&env).unwrap();
326 assert_eq!(serde_json::from_str::<Environment>(&text).unwrap(), env);
327 }
328
329 #[test]
330 fn waiting_has_a_limit_wherever_waiting_happens() {
331 let env = Environment::subprocess("py", "python", "python3", &[]);
332 assert_eq!(env.reach.timeout_ms(), Some(30_000));
333 }
334}