Skip to main content

unitype_runtime/
worker.rs

1//! Keeping a process alive between calls.
2//!
3//! Starting an interpreter costs more than most calls do — around twenty
4//! milliseconds for Python, against microseconds of actual work — so a program
5//! calling repeatedly pays that over and over for nothing. A worker pays it
6//! once and then answers as fast as a pipe allows.
7//!
8//! # What changes, and what does not
9//!
10//! The messages are the same ones §7.1 of the protocol specifies. What changes
11//! is only the framing: with the stream staying open, end of input can no
12//! longer mean end of message, so each message is a line. A child that reads
13//! lines works either way — one-shot, the parent closes the stream and the loop
14//! ends after a single message — which is why the generated harnesses do that
15//! and need no mode of their own.
16//!
17//! # What it costs
18//!
19//! State survives between calls. That is the whole saving and the whole risk:
20//! a module holding something over from the last call is now able to get it
21//! wrong, where one process per call could not. Hence off by default, and hence
22//! this: a worker that fails, times out, or dies is **dropped rather than
23//! reused**. Once an exchange goes wrong the stream's position is unknown, and
24//! a stale answer read as the next call's result would be far worse than
25//! starting again.
26
27use 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
45/// One live process, and the ends of its pipes.
46struct Worker {
47    child: Child,
48    stdin: ChildStdin,
49    stdout: Lines<BufReader<ChildStdout>>,
50}
51
52impl Worker {
53    /// Starts one.
54    ///
55    /// Its error stream is inherited rather than piped: nothing here reads it,
56    /// and an unread pipe fills up and stops the child. Inheriting also puts a
57    /// worker's complaints where a person will see them.
58    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    /// Sends one message and reads one back.
101    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            // The stream ended, which for a worker means it died.
117            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/// The workers this process is keeping alive, one lane per environment.
130///
131/// A lane is locked for the length of an exchange, so calls into one worker
132/// queue up — which they must, since two messages down one pipe have no way to
133/// be told apart. Different environments do not wait on each other.
134#[derive(Default)]
135pub struct Workers {
136    lanes: Mutex<HashMap<Ident, Arc<Mutex<Option<Worker>>>>>,
137}
138
139impl Workers {
140    /// A pool holding nothing yet.
141    pub fn new() -> Self {
142        Self::default()
143    }
144
145    /// Runs an implementation on the worker for its environment, starting one
146    /// if there is not already one running.
147    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                // Something went wrong mid-exchange, so where the stream sits
184                // is anybody's guess. Start again next time.
185                *held = None;
186                return Err(failure);
187            }
188            Err(_) => {
189                // Same reasoning, and more urgently: a late answer arriving
190                // after a timeout would be read as the *next* call's result.
191                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                // A worker that cannot speak the protocol will not learn by
204                // being asked again.
205                if matches!(failure, ExecError::Protocol { .. }) {
206                    *held = None;
207                }
208            },
209        )
210    }
211
212    /// Stops every worker.
213    ///
214    /// Dropping the pool does this too, since each child is killed with its
215    /// handle; this is for stopping them at a moment of your choosing.
216    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    /// How many workers are running.
227    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}