1use std::process::Stdio;
30use std::time::Duration;
31
32use serde::{Deserialize, Serialize};
33use tokio::io::AsyncWriteExt;
34use tokio::process::Command;
35use unitype_core::check::CheckedWorkspace;
36use unitype_core::ir::Type;
37use unitype_core::value::Value;
38
39use crate::environment::{Environment, Reach};
40use crate::error::ExecError;
41use crate::implementation::Implementation;
42
43pub const PROTOCOL_VERSION: &str = "1";
45
46const STDERR_KEPT: usize = 8 * 1024;
48
49#[derive(Debug, Serialize, Deserialize)]
51pub struct Request {
52 pub unitype: String,
54 pub kind: String,
57 pub signature: String,
59 pub entry: String,
61 pub args: Vec<serde_json::Value>,
63}
64
65#[derive(Debug, Serialize, Deserialize)]
67pub struct Response {
68 pub ok: bool,
70 #[serde(default)]
72 pub value: Option<serde_json::Value>,
73 #[serde(default)]
75 pub error: Option<ResponseError>,
76}
77
78#[derive(Debug, Serialize, Deserialize)]
80pub struct ResponseError {
81 #[serde(default)]
83 pub code: String,
84 pub message: String,
86}
87
88pub async fn invoke(
92 ws: &CheckedWorkspace,
93 environment: &Environment,
94 implementation: &Implementation,
95 args: Vec<Value>,
96 params: &[Type],
97 expected: &Type,
98) -> Result<Value, ExecError> {
99 let Reach::Subprocess {
100 command,
101 args: argv,
102 cwd,
103 env,
104 timeout_ms,
105 ..
106 } = &environment.reach
107 else {
108 return Err(ExecError::Unreachable {
109 environment: environment.id.to_string(),
110 detail: "this is not a subprocess environment".into(),
111 });
112 };
113
114 let mut body = request_line(ws, implementation, &args, params)?;
118 body.push(b'\n');
119
120 let mut process = Command::new(command);
121 process
122 .args(argv)
123 .envs(env)
124 .stdin(Stdio::piped())
125 .stdout(Stdio::piped())
126 .stderr(Stdio::piped())
127 .kill_on_drop(true);
130 if let Some(dir) = cwd {
131 process.current_dir(dir);
132 }
133
134 let mut child = crate::spawn::spawn(&mut process).map_err(|source| ExecError::Unreachable {
135 environment: environment.id.to_string(),
136 detail: format!("could not start `{command}`: {source}"),
137 })?;
138
139 let mut stdin = child.stdin.take().expect("stdin was piped");
140 stdin
141 .write_all(&body)
142 .await
143 .map_err(|source| ExecError::Protocol {
144 id: implementation.id.to_string(),
145 detail: format!("could not send the request: {source}"),
146 })?;
147 drop(stdin);
149
150 let output = tokio::time::timeout(Duration::from_millis(*timeout_ms), child.wait_with_output())
151 .await
152 .map_err(|_| ExecError::Timeout {
153 id: implementation.id.to_string(),
154 millis: *timeout_ms,
155 })?
156 .map_err(|source| ExecError::Unreachable {
157 environment: environment.id.to_string(),
158 detail: format!("could not read from `{command}`: {source}"),
159 })?;
160
161 if !output.status.success() {
162 return Err(ExecError::Failed {
163 id: implementation.id.to_string(),
164 message: format!(
165 "exited with {}{}",
166 output
167 .status
168 .code()
169 .map(|c| c.to_string())
170 .unwrap_or_else(|| "a signal".into()),
171 tail(&output.stderr),
172 ),
173 });
174 }
175
176 let text = String::from_utf8_lossy(&output.stdout);
177 read_answer_with(ws, implementation, &text, expected, &tail(&output.stderr))
178}
179
180pub(crate) fn request_line(
189 ws: &CheckedWorkspace,
190 implementation: &Implementation,
191 args: &[Value],
192 params: &[Type],
193) -> Result<Vec<u8>, ExecError> {
194 let encoded: Vec<serde_json::Value> = args
195 .iter()
196 .enumerate()
197 .map(|(i, a)| match params.get(i) {
198 Some(ty) => ws.typed_json(a, ty),
199 None => a.to_json(),
200 })
201 .collect::<Result<_, _>>()
202 .map_err(|e| ExecError::Protocol {
203 id: implementation.id.to_string(),
204 detail: format!("an argument could not be encoded: {e}"),
205 })?;
206
207 let request = Request {
208 unitype: PROTOCOL_VERSION.to_string(),
209 kind: "invoke".to_string(),
210 signature: implementation.proves.to_string(),
211 entry: implementation.entry.clone(),
212 args: encoded,
213 };
214 Ok(serde_json::to_vec(&request).expect("a request serializes"))
215}
216
217pub(crate) fn read_answer(
219 ws: &CheckedWorkspace,
220 implementation: &Implementation,
221 text: &str,
222 expected: &Type,
223) -> Result<Value, ExecError> {
224 read_answer_with(ws, implementation, text, expected, "")
225}
226
227fn read_answer_with(
230 ws: &CheckedWorkspace,
231 implementation: &Implementation,
232 text: &str,
233 expected: &Type,
234 context: &str,
235) -> Result<Value, ExecError> {
236 let response: Response = serde_json::from_str(text).map_err(|source| ExecError::Protocol {
237 id: implementation.id.to_string(),
238 detail: format!("could not read the response: {source}{context}"),
239 })?;
240
241 if !response.ok {
242 let reported = response
243 .error
244 .map(|e| e.message)
245 .unwrap_or_else(|| "it said it failed but did not say why".to_string());
246 return Err(ExecError::Failed {
247 id: implementation.id.to_string(),
248 message: reported,
249 });
250 }
251
252 let Some(json) = response.value else {
253 return Err(ExecError::Protocol {
254 id: implementation.id.to_string(),
255 detail: "it said it worked but sent nothing back".into(),
256 });
257 };
258
259 ws.read(&json, expected)
262 .map_err(|source| ExecError::Protocol {
263 id: implementation.id.to_string(),
264 detail: format!(
265 "what it sent back is not a `{}`: {source}",
266 describe(expected)
267 ),
268 })
269}
270
271fn describe(ty: &Type) -> String {
272 unitype_core::canon::canonical_string(ty)
273}
274
275fn tail(stderr: &[u8]) -> String {
277 let text = String::from_utf8_lossy(stderr);
278 let trimmed = text.trim();
279 if trimmed.is_empty() {
280 return String::new();
281 }
282 let kept = if trimmed.len() > STDERR_KEPT {
283 &trimmed[trimmed.len() - STDERR_KEPT..]
284 } else {
285 trimmed
286 };
287 format!("; it said: {kept}")
288}
289
290#[cfg(test)]
291mod tests {
292 use super::*;
293 use std::collections::BTreeMap;
294 use unitype_core::check::check_workspace;
295 use unitype_core::{BigO, Ident, ImplProfile, Workspace};
296
297 fn ws() -> CheckedWorkspace {
298 check_workspace(
299 Workspace::from_json(
300 r#"{"universes":[{"name":"demo","functions":[
301 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#,
302 )
303 .expect("reads"),
304 )
305 .expect("checks")
306 }
307
308 fn shell(script: &str, timeout_ms: u64) -> Environment {
311 Environment {
312 id: Ident::new("shell").unwrap(),
313 language: Ident::new("sh").unwrap(),
314 doc: None,
315 reach: Reach::Subprocess {
316 command: "/bin/sh".into(),
317 args: vec!["-c".into(), script.into()],
318 cwd: None,
319 env: BTreeMap::new(),
320 timeout_ms,
321 persistent: false,
322 },
323 meta: unitype_core::Metadata::default(),
324 }
325 }
326
327 fn implementation() -> Implementation {
328 Implementation::new(
329 "sort.shell",
330 "demo::sort".parse().unwrap(),
331 Ident::new("shell").unwrap(),
332 "bubble_sort",
333 ImplProfile::new(BigO::ON2, BigO::O1),
334 )
335 }
336
337 const PATIENT: u64 = 30_000;
341
342 async fn run(script: &str) -> Result<Value, ExecError> {
343 run_with(script, PATIENT).await
344 }
345
346 async fn run_with(script: &str, timeout_ms: u64) -> Result<Value, ExecError> {
347 let ws = ws();
348 invoke(
349 &ws,
350 &shell(script, timeout_ms),
351 &implementation(),
352 vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
353 &[Type::I64.list()],
354 &Type::I64.list(),
355 )
356 .await
357 }
358
359 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
378 async fn a_long_lived_child_does_not_hold_another_call_s_input_open() {
379 let thief = tokio::spawn(run_with(
383 r#"cat > /dev/null; sleep 2; echo '{"ok":true,"value":[]}'"#,
384 30_000,
385 ));
386
387 let victims = (0..48).map(|n| async move {
388 run_with(
389 &format!(r#"cat > /dev/null; echo '{{"ok":true,"value":[{n}]}}'"#),
390 900,
391 )
392 .await
393 });
394
395 for (n, got) in futures_join(victims).await.into_iter().enumerate() {
396 assert_eq!(
397 got.unwrap_or_else(|e| panic!("call {n} should have answered: {e}")),
398 Value::List(vec![Value::Int(n as i64)]),
399 "each call got its own answer, not somebody else's"
400 );
401 }
402 thief.await.expect("it did not panic").expect("it answers");
403 }
404
405 async fn futures_join<F>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output>
410 where
411 F: std::future::Future + Send + 'static,
412 F::Output: Send + 'static,
413 {
414 let handles: Vec<_> = futures.into_iter().map(tokio::spawn).collect();
415 let mut out = Vec::with_capacity(handles.len());
416 for handle in handles {
417 out.push(handle.await.expect("the call did not panic"));
418 }
419 out
420 }
421
422 #[tokio::test]
423 async fn a_program_that_answers_is_believed() {
424 let out = run(r#"cat > /dev/null; echo '{"ok":true,"value":[1,3]}'"#)
425 .await
426 .expect("answers");
427 assert_eq!(out, Value::List(vec![Value::Int(1), Value::Int(3)]));
428 }
429
430 #[tokio::test]
431 async fn the_request_reaches_the_program_intact() {
432 let ws = ws();
435 let out = invoke(
436 &ws,
437 &shell(
438 r#"body=$(cat); printf '{"ok":true,"value":%s}' "$(printf '%s' "$body" | sed 's/\\/\\\\/g; s/"/\\"/g; s/^/"/; s/$/"/')""#,
439 PATIENT,
440 ),
441 &implementation(),
442 vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
443 &[Type::I64.list()],
444 &Type::String,
445 )
446 .await
447 .expect("answers");
448
449 let Value::Str(seen) = out else {
450 panic!("expected the request back as a string, got {out:?}");
451 };
452 assert!(seen.contains(r#""unitype":"1""#), "{seen}");
453 assert!(seen.contains(r#""signature":"demo::sort""#), "{seen}");
454 assert!(seen.contains(r#""entry":"bubble_sort""#), "{seen}");
455 assert!(
456 seen.contains("[3,1]"),
457 "the arguments should be there: {seen}"
458 );
459 }
460
461 #[test]
462 fn an_argument_is_sent_written_against_its_type() {
463 let ws = ws();
467 let pair = Value::Tuple(vec![Value::Int(1), Value::Str("a".into())]);
468 let pair_type = Type::Tuple {
469 items: vec![Type::I64, Type::String],
470 };
471 let line = request_line(
472 &ws,
473 &implementation(),
474 std::slice::from_ref(&pair),
475 &[pair_type],
476 )
477 .expect("encodes");
478 let sent: serde_json::Value = serde_json::from_slice(&line).expect("JSON");
479 assert_eq!(sent["args"], serde_json::json!([[1, "a"]]));
480
481 let untyped = request_line(&ws, &implementation(), &[pair], &[]).expect("encodes");
482 let sent: serde_json::Value = serde_json::from_slice(&untyped).expect("JSON");
483 assert_eq!(sent["args"], serde_json::json!([{"$tuple": [1, "a"]}]));
484 }
485
486 #[tokio::test]
487 async fn a_program_that_is_not_there_is_an_environment_problem() {
488 let ws = ws();
489 let err = invoke(
490 &ws,
491 &Environment::subprocess("nope", "sh", "unitype_no_such_program", &[]),
492 &implementation(),
493 vec![Value::List(vec![])],
494 &[Type::I64.list()],
495 &Type::I64.list(),
496 )
497 .await
498 .unwrap_err();
499
500 assert!(
501 err.is_environmental(),
502 "nothing is wrong with the proof; the machine is missing it: {err}"
503 );
504 }
505
506 #[tokio::test]
507 async fn a_program_reporting_its_own_failure_is_quoted() {
508 let err = run(r#"cat > /dev/null; echo '{"ok":false,"error":{"code":"bad","message":"list was too long"}}'"#)
509 .await
510 .unwrap_err();
511 assert!(err.to_string().contains("list was too long"), "{err}");
512 assert!(
513 !err.is_environmental(),
514 "the program worked; what it was asked to do did not"
515 );
516 }
517
518 #[tokio::test]
519 async fn a_program_that_crashes_has_its_last_words_kept() {
520 let err = run(r#"cat > /dev/null; echo "something went badly" >&2; exit 3"#)
521 .await
522 .unwrap_err();
523 let message = err.to_string();
524 assert!(message.contains("exited with 3"), "{message}");
525 assert!(message.contains("something went badly"), "{message}");
526 }
527
528 #[tokio::test]
529 async fn a_program_that_talks_nonsense_is_a_protocol_failure() {
530 let err = run(r#"cat > /dev/null; echo 'not json at all'"#)
531 .await
532 .unwrap_err();
533 assert!(matches!(err, ExecError::Protocol { .. }), "{err}");
534 assert!(
535 !err.is_environmental(),
536 "a program that cannot speak the protocol will not learn by being asked again"
537 );
538 }
539
540 #[tokio::test]
541 async fn a_program_that_answers_with_the_wrong_shape_is_caught_here_too() {
542 let err = run(r#"cat > /dev/null; echo '{"ok":true,"value":"not a list"}'"#)
543 .await
544 .unwrap_err();
545 assert!(err.to_string().contains("is not a"), "{err}");
546 }
547
548 #[tokio::test]
549 async fn a_program_that_never_answers_is_given_up_on() {
550 let err = run_with(r#"cat > /dev/null; sleep 30"#, 150)
551 .await
552 .unwrap_err();
553 assert!(matches!(err, ExecError::Timeout { .. }), "{err}");
554 assert!(
555 err.is_environmental(),
556 "a hung machine is worth trying around"
557 );
558 }
559
560 #[tokio::test]
561 async fn closing_the_input_is_what_tells_the_program_to_get_on_with_it() {
562 let out = run(r#"cat > /dev/null && echo '{"ok":true,"value":[7]}'"#)
565 .await
566 .expect("answers");
567 assert_eq!(out, Value::List(vec![Value::Int(7)]));
568 }
569}