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, deserialize_with = "present_value")]
76 pub value: Option<serde_json::Value>,
77 #[serde(default)]
79 pub error: Option<ResponseError>,
80}
81
82fn present_value<'de, D: serde::Deserializer<'de>>(
85 d: D,
86) -> Result<Option<serde_json::Value>, D::Error> {
87 serde_json::Value::deserialize(d).map(Some)
88}
89
90#[derive(Debug, Serialize, Deserialize)]
92pub struct ResponseError {
93 #[serde(default)]
95 pub code: String,
96 pub message: String,
98}
99
100pub async fn invoke(
104 ws: &CheckedWorkspace,
105 environment: &Environment,
106 implementation: &Implementation,
107 args: Vec<Value>,
108 params: &[Type],
109 expected: &Type,
110) -> Result<Value, ExecError> {
111 let Reach::Subprocess {
112 command,
113 args: argv,
114 cwd,
115 env,
116 timeout_ms,
117 ..
118 } = &environment.reach
119 else {
120 return Err(ExecError::Unreachable {
121 environment: environment.id.to_string(),
122 detail: "this is not a subprocess environment".into(),
123 });
124 };
125
126 let mut body = request_line(ws, implementation, &args, params)?;
130 body.push(b'\n');
131
132 let mut process = Command::new(command);
133 process
134 .args(argv)
135 .envs(env)
136 .stdin(Stdio::piped())
137 .stdout(Stdio::piped())
138 .stderr(Stdio::piped())
139 .kill_on_drop(true);
142 if let Some(dir) = cwd {
143 process.current_dir(dir);
144 }
145
146 let mut child = crate::spawn::spawn(&mut process).map_err(|source| ExecError::Unreachable {
147 environment: environment.id.to_string(),
148 detail: format!("could not start `{command}`: {source}"),
149 })?;
150
151 let mut stdin = child.stdin.take().expect("stdin was piped");
152 stdin
153 .write_all(&body)
154 .await
155 .map_err(|source| ExecError::Protocol {
156 id: implementation.id.to_string(),
157 detail: format!("could not send the request: {source}"),
158 })?;
159 drop(stdin);
161
162 let output = tokio::time::timeout(Duration::from_millis(*timeout_ms), child.wait_with_output())
163 .await
164 .map_err(|_| ExecError::Timeout {
165 id: implementation.id.to_string(),
166 millis: *timeout_ms,
167 })?
168 .map_err(|source| ExecError::Unreachable {
169 environment: environment.id.to_string(),
170 detail: format!("could not read from `{command}`: {source}"),
171 })?;
172
173 if !output.status.success() {
174 return Err(ExecError::Failed {
175 id: implementation.id.to_string(),
176 message: format!(
177 "exited with {}{}",
178 output
179 .status
180 .code()
181 .map(|c| c.to_string())
182 .unwrap_or_else(|| "a signal".into()),
183 tail(&output.stderr),
184 ),
185 });
186 }
187
188 let text = String::from_utf8_lossy(&output.stdout);
189 read_answer_with(ws, implementation, &text, expected, &tail(&output.stderr))
190}
191
192pub(crate) fn request_line(
201 ws: &CheckedWorkspace,
202 implementation: &Implementation,
203 args: &[Value],
204 params: &[Type],
205) -> Result<Vec<u8>, ExecError> {
206 let encoded: Vec<serde_json::Value> = args
207 .iter()
208 .enumerate()
209 .map(|(i, a)| match params.get(i) {
210 Some(ty) => ws.typed_json(a, ty),
211 None => a.to_json(),
212 })
213 .collect::<Result<_, _>>()
214 .map_err(|e| ExecError::Protocol {
215 id: implementation.id.to_string(),
216 detail: format!("an argument could not be encoded: {e}"),
217 })?;
218
219 let request = Request {
220 unitype: PROTOCOL_VERSION.to_string(),
221 kind: "invoke".to_string(),
222 signature: implementation.proves.to_string(),
223 entry: implementation.entry.clone(),
224 args: encoded,
225 };
226 Ok(serde_json::to_vec(&request).expect("a request serializes"))
227}
228
229pub(crate) fn read_answer(
231 ws: &CheckedWorkspace,
232 implementation: &Implementation,
233 text: &str,
234 expected: &Type,
235) -> Result<Value, ExecError> {
236 read_answer_with(ws, implementation, text, expected, "")
237}
238
239fn read_answer_with(
242 ws: &CheckedWorkspace,
243 implementation: &Implementation,
244 text: &str,
245 expected: &Type,
246 context: &str,
247) -> Result<Value, ExecError> {
248 let response: Response = serde_json::from_str(text).map_err(|source| ExecError::Protocol {
249 id: implementation.id.to_string(),
250 detail: format!("could not read the response: {source}{context}"),
251 })?;
252
253 if !response.ok {
254 let reported = response
255 .error
256 .map(|e| e.message)
257 .unwrap_or_else(|| "it said it failed but did not say why".to_string());
258 return Err(ExecError::Failed {
259 id: implementation.id.to_string(),
260 message: reported,
261 });
262 }
263
264 let Some(json) = response.value else {
265 return Err(ExecError::Protocol {
266 id: implementation.id.to_string(),
267 detail: "it said it worked but sent nothing back".into(),
268 });
269 };
270
271 ws.read(&json, expected)
274 .map_err(|source| ExecError::Protocol {
275 id: implementation.id.to_string(),
276 detail: format!(
277 "what it sent back is not a `{}`: {source}",
278 describe(expected)
279 ),
280 })
281}
282
283fn describe(ty: &Type) -> String {
284 unitype_core::canon::canonical_string(ty)
285}
286
287fn tail(stderr: &[u8]) -> String {
289 let text = String::from_utf8_lossy(stderr);
290 let trimmed = text.trim();
291 if trimmed.is_empty() {
292 return String::new();
293 }
294 let kept = if trimmed.len() > STDERR_KEPT {
295 &trimmed[trimmed.len() - STDERR_KEPT..]
296 } else {
297 trimmed
298 };
299 format!("; it said: {kept}")
300}
301
302#[cfg(test)]
303mod tests {
304 use super::*;
305 use std::collections::BTreeMap;
306 use unitype_core::check::check_workspace;
307 use unitype_core::{BigO, Ident, ImplProfile, Workspace};
308
309 fn ws() -> CheckedWorkspace {
310 check_workspace(
311 Workspace::from_json(
312 r#"{"universes":[{"name":"demo","functions":[
313 {"name":"sort","params":[{"name":"xs","ty":"[i64]"}],"ret":"[i64]"}]}]}"#,
314 )
315 .expect("reads"),
316 )
317 .expect("checks")
318 }
319
320 fn shell(script: &str, timeout_ms: u64) -> Environment {
323 Environment {
324 id: Ident::new("shell").unwrap(),
325 language: Ident::new("sh").unwrap(),
326 doc: None,
327 reach: Reach::Subprocess {
328 command: "/bin/sh".into(),
329 args: vec!["-c".into(), script.into()],
330 cwd: None,
331 env: BTreeMap::new(),
332 timeout_ms,
333 persistent: false,
334 },
335 meta: unitype_core::Metadata::default(),
336 }
337 }
338
339 fn implementation() -> Implementation {
340 Implementation::new(
341 "sort.shell",
342 "demo::sort".parse().unwrap(),
343 Ident::new("shell").unwrap(),
344 "bubble_sort",
345 ImplProfile::new(BigO::ON2, BigO::O1),
346 )
347 }
348
349 #[test]
350 fn an_absent_answer_is_an_answer_and_no_answer_is_not() {
351 let ws = ws();
352 let maybe = Type::I64.optional();
353 let absent = read_answer(
354 &ws,
355 &implementation(),
356 r#"{"ok":true,"value":null}"#,
357 &maybe,
358 )
359 .expect("null is what a proposition returning `T?` answers");
360 assert_eq!(absent, Value::Null);
361
362 let none = read_answer(&ws, &implementation(), r#"{"ok":true}"#, &maybe)
363 .expect_err("no value at all is a broken exchange");
364 assert!(none.to_string().contains("sent nothing back"), "{none}");
365 }
366
367 const PATIENT: u64 = 30_000;
371
372 async fn run(script: &str) -> Result<Value, ExecError> {
373 run_with(script, PATIENT).await
374 }
375
376 async fn run_with(script: &str, timeout_ms: u64) -> Result<Value, ExecError> {
377 let ws = ws();
378 invoke(
379 &ws,
380 &shell(script, timeout_ms),
381 &implementation(),
382 vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
383 &[Type::I64.list()],
384 &Type::I64.list(),
385 )
386 .await
387 }
388
389 #[tokio::test(flavor = "multi_thread", worker_threads = 8)]
408 async fn a_long_lived_child_does_not_hold_another_call_s_input_open() {
409 let thief = tokio::spawn(run_with(
413 r#"cat > /dev/null; sleep 2; echo '{"ok":true,"value":[]}'"#,
414 30_000,
415 ));
416
417 let victims = (0..48).map(|n| async move {
418 run_with(
419 &format!(r#"cat > /dev/null; echo '{{"ok":true,"value":[{n}]}}'"#),
420 900,
421 )
422 .await
423 });
424
425 for (n, got) in futures_join(victims).await.into_iter().enumerate() {
426 assert_eq!(
427 got.unwrap_or_else(|e| panic!("call {n} should have answered: {e}")),
428 Value::List(vec![Value::Int(n as i64)]),
429 "each call got its own answer, not somebody else's"
430 );
431 }
432 thief.await.expect("it did not panic").expect("it answers");
433 }
434
435 async fn futures_join<F>(futures: impl IntoIterator<Item = F>) -> Vec<F::Output>
440 where
441 F: std::future::Future + Send + 'static,
442 F::Output: Send + 'static,
443 {
444 let handles: Vec<_> = futures.into_iter().map(tokio::spawn).collect();
445 let mut out = Vec::with_capacity(handles.len());
446 for handle in handles {
447 out.push(handle.await.expect("the call did not panic"));
448 }
449 out
450 }
451
452 #[tokio::test]
453 async fn a_program_that_answers_is_believed() {
454 let out = run(r#"cat > /dev/null; echo '{"ok":true,"value":[1,3]}'"#)
455 .await
456 .expect("answers");
457 assert_eq!(out, Value::List(vec![Value::Int(1), Value::Int(3)]));
458 }
459
460 #[tokio::test]
461 async fn the_request_reaches_the_program_intact() {
462 let ws = ws();
465 let out = invoke(
466 &ws,
467 &shell(
468 r#"body=$(cat); printf '{"ok":true,"value":%s}' "$(printf '%s' "$body" | sed 's/\\/\\\\/g; s/"/\\"/g; s/^/"/; s/$/"/')""#,
469 PATIENT,
470 ),
471 &implementation(),
472 vec![Value::List(vec![Value::Int(3), Value::Int(1)])],
473 &[Type::I64.list()],
474 &Type::String,
475 )
476 .await
477 .expect("answers");
478
479 let Value::Str(seen) = out else {
480 panic!("expected the request back as a string, got {out:?}");
481 };
482 assert!(seen.contains(r#""unitype":"1""#), "{seen}");
483 assert!(seen.contains(r#""signature":"demo::sort""#), "{seen}");
484 assert!(seen.contains(r#""entry":"bubble_sort""#), "{seen}");
485 assert!(
486 seen.contains("[3,1]"),
487 "the arguments should be there: {seen}"
488 );
489 }
490
491 #[test]
492 fn an_argument_is_sent_written_against_its_type() {
493 let ws = ws();
497 let pair = Value::Tuple(vec![Value::Int(1), Value::Str("a".into())]);
498 let pair_type = Type::Tuple {
499 items: vec![Type::I64, Type::String],
500 };
501 let line = request_line(
502 &ws,
503 &implementation(),
504 std::slice::from_ref(&pair),
505 &[pair_type],
506 )
507 .expect("encodes");
508 let sent: serde_json::Value = serde_json::from_slice(&line).expect("JSON");
509 assert_eq!(sent["args"], serde_json::json!([[1, "a"]]));
510
511 let untyped = request_line(&ws, &implementation(), &[pair], &[]).expect("encodes");
512 let sent: serde_json::Value = serde_json::from_slice(&untyped).expect("JSON");
513 assert_eq!(sent["args"], serde_json::json!([{"$tuple": [1, "a"]}]));
514 }
515
516 #[tokio::test]
517 async fn a_program_that_is_not_there_is_an_environment_problem() {
518 let ws = ws();
519 let err = invoke(
520 &ws,
521 &Environment::subprocess("nope", "sh", "unitype_no_such_program", &[]),
522 &implementation(),
523 vec![Value::List(vec![])],
524 &[Type::I64.list()],
525 &Type::I64.list(),
526 )
527 .await
528 .unwrap_err();
529
530 assert!(
531 err.is_environmental(),
532 "nothing is wrong with the proof; the machine is missing it: {err}"
533 );
534 }
535
536 #[tokio::test]
537 async fn a_program_reporting_its_own_failure_is_quoted() {
538 let err = run(r#"cat > /dev/null; echo '{"ok":false,"error":{"code":"bad","message":"list was too long"}}'"#)
539 .await
540 .unwrap_err();
541 assert!(err.to_string().contains("list was too long"), "{err}");
542 assert!(
543 !err.is_environmental(),
544 "the program worked; what it was asked to do did not"
545 );
546 }
547
548 #[tokio::test]
549 async fn a_program_that_crashes_has_its_last_words_kept() {
550 let err = run(r#"cat > /dev/null; echo "something went badly" >&2; exit 3"#)
551 .await
552 .unwrap_err();
553 let message = err.to_string();
554 assert!(message.contains("exited with 3"), "{message}");
555 assert!(message.contains("something went badly"), "{message}");
556 }
557
558 #[tokio::test]
559 async fn a_program_that_talks_nonsense_is_a_protocol_failure() {
560 let err = run(r#"cat > /dev/null; echo 'not json at all'"#)
561 .await
562 .unwrap_err();
563 assert!(matches!(err, ExecError::Protocol { .. }), "{err}");
564 assert!(
565 !err.is_environmental(),
566 "a program that cannot speak the protocol will not learn by being asked again"
567 );
568 }
569
570 #[tokio::test]
571 async fn a_program_that_answers_with_the_wrong_shape_is_caught_here_too() {
572 let err = run(r#"cat > /dev/null; echo '{"ok":true,"value":"not a list"}'"#)
573 .await
574 .unwrap_err();
575 assert!(err.to_string().contains("is not a"), "{err}");
576 }
577
578 #[tokio::test]
579 async fn a_program_that_never_answers_is_given_up_on() {
580 let err = run_with(r#"cat > /dev/null; sleep 30"#, 150)
581 .await
582 .unwrap_err();
583 assert!(matches!(err, ExecError::Timeout { .. }), "{err}");
584 assert!(
585 err.is_environmental(),
586 "a hung machine is worth trying around"
587 );
588 }
589
590 #[tokio::test]
591 async fn closing_the_input_is_what_tells_the_program_to_get_on_with_it() {
592 let out = run(r#"cat > /dev/null && echo '{"ok":true,"value":[7]}'"#)
595 .await
596 .expect("answers");
597 assert_eq!(out, Value::List(vec![Value::Int(7)]));
598 }
599}