unitype_runtime/
worker.rs1use std::collections::HashMap;
28use std::process::Stdio;
29use std::sync::Arc;
30use std::time::Duration;
31
32use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
33use tokio::process::{Child, ChildStdin, ChildStdout, Command};
34use tokio::sync::Mutex;
35use unitype_core::Ident;
36use unitype_core::check::CheckedWorkspace;
37use unitype_core::ir::Type;
38use unitype_core::value::Value;
39
40use crate::environment::{Environment, Reach};
41use crate::error::ExecError;
42use crate::implementation::Implementation;
43use crate::subprocess::request_line;
44
45struct Worker {
47 child: Child,
48 stdin: ChildStdin,
49 stdout: Lines<BufReader<ChildStdout>>,
50}
51
52impl Worker {
53 fn start(environment: &Environment) -> Result<Self, ExecError> {
59 let Reach::Subprocess {
60 command,
61 args,
62 cwd,
63 env,
64 ..
65 } = &environment.reach
66 else {
67 return Err(ExecError::Unreachable {
68 environment: environment.id.to_string(),
69 detail: "this is not a subprocess environment".into(),
70 });
71 };
72
73 let mut process = Command::new(command);
74 process
75 .args(args)
76 .envs(env)
77 .stdin(Stdio::piped())
78 .stdout(Stdio::piped())
79 .stderr(Stdio::inherit())
80 .kill_on_drop(true);
81 if let Some(dir) = cwd {
82 process.current_dir(dir);
83 }
84
85 let mut child =
86 crate::spawn::spawn(&mut process).map_err(|source| ExecError::Unreachable {
87 environment: environment.id.to_string(),
88 detail: format!("could not start `{command}`: {source}"),
89 })?;
90
91 let stdin = child.stdin.take().expect("stdin was piped");
92 let stdout = BufReader::new(child.stdout.take().expect("stdout was piped")).lines();
93 Ok(Self {
94 child,
95 stdin,
96 stdout,
97 })
98 }
99
100 async fn exchange(&mut self, line: &[u8]) -> Result<String, ExecError> {
102 self.stdin
103 .write_all(line)
104 .await
105 .map_err(|e| ExecError::Protocol {
106 id: "worker".into(),
107 detail: format!("could not send the request: {e}"),
108 })?;
109 self.stdin.flush().await.map_err(|e| ExecError::Protocol {
110 id: "worker".into(),
111 detail: format!("could not send the request: {e}"),
112 })?;
113
114 match self.stdout.next_line().await {
115 Ok(Some(answer)) => Ok(answer),
116 Ok(None) => Err(ExecError::Unreachable {
118 environment: "worker".into(),
119 detail: "it stopped without answering".into(),
120 }),
121 Err(e) => Err(ExecError::Protocol {
122 id: "worker".into(),
123 detail: format!("could not read the response: {e}"),
124 }),
125 }
126 }
127}
128
129#[derive(Default)]
135pub struct Workers {
136 lanes: Mutex<HashMap<Ident, Arc<Mutex<Option<Worker>>>>>,
137}
138
139impl Workers {
140 pub fn new() -> Self {
142 Self::default()
143 }
144
145 pub async fn invoke(
148 &self,
149 ws: &CheckedWorkspace,
150 environment: &Environment,
151 implementation: &Implementation,
152 args: Vec<Value>,
153 params: &[Type],
154 expected: &Type,
155 ) -> Result<Value, ExecError> {
156 let lane = {
157 let mut lanes = self.lanes.lock().await;
158 Arc::clone(
159 lanes
160 .entry(environment.id.clone())
161 .or_insert_with(|| Arc::new(Mutex::new(None))),
162 )
163 };
164 let mut held = lane.lock().await;
165
166 if held.is_none() {
167 *held = Some(Worker::start(environment)?);
168 }
169 let worker = held.as_mut().expect("just started");
170
171 let mut line = request_line(ws, implementation, &args, params)?;
172 line.push(b'\n');
173
174 let timeout = environment.reach.timeout_ms().unwrap_or(30_000);
175 let answer = match tokio::time::timeout(
176 Duration::from_millis(timeout),
177 worker.exchange(&line),
178 )
179 .await
180 {
181 Ok(Ok(answer)) => answer,
182 Ok(Err(failure)) => {
183 *held = None;
186 return Err(failure);
187 }
188 Err(_) => {
189 if let Some(mut dead) = held.take() {
192 let _ = dead.child.start_kill();
193 }
194 return Err(ExecError::Timeout {
195 id: implementation.id.to_string(),
196 millis: timeout,
197 });
198 }
199 };
200
201 crate::subprocess::read_answer(ws, implementation, &answer, expected).inspect_err(
202 |failure| {
203 if matches!(failure, ExecError::Protocol { .. }) {
206 *held = None;
207 }
208 },
209 )
210 }
211
212 pub async fn shutdown(&self) {
217 let mut lanes = self.lanes.lock().await;
218 for lane in lanes.values() {
219 if let Some(mut worker) = lane.lock().await.take() {
220 let _ = worker.child.start_kill();
221 }
222 }
223 lanes.clear();
224 }
225
226 pub async fn running(&self) -> usize {
228 let lanes = self.lanes.lock().await;
229 let mut count = 0;
230 for lane in lanes.values() {
231 if lane.lock().await.is_some() {
232 count += 1;
233 }
234 }
235 count
236 }
237}