use std::collections::HashMap;
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader, Lines};
use tokio::process::{Child, ChildStdin, ChildStdout, Command};
use tokio::sync::Mutex;
use unitype_core::Ident;
use unitype_core::check::CheckedWorkspace;
use unitype_core::ir::Type;
use unitype_core::value::Value;
use crate::environment::{Environment, Reach};
use crate::error::ExecError;
use crate::implementation::Implementation;
use crate::subprocess::request_line;
struct Worker {
child: Child,
stdin: ChildStdin,
stdout: Lines<BufReader<ChildStdout>>,
}
impl Worker {
fn start(environment: &Environment) -> Result<Self, ExecError> {
let Reach::Subprocess {
command,
args,
cwd,
env,
..
} = &environment.reach
else {
return Err(ExecError::Unreachable {
environment: environment.id.to_string(),
detail: "this is not a subprocess environment".into(),
});
};
let mut process = Command::new(command);
process
.args(args)
.envs(env)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::inherit())
.kill_on_drop(true);
if let Some(dir) = cwd {
process.current_dir(dir);
}
let mut child =
crate::spawn::spawn(&mut process).map_err(|source| ExecError::Unreachable {
environment: environment.id.to_string(),
detail: format!("could not start `{command}`: {source}"),
})?;
let stdin = child.stdin.take().expect("stdin was piped");
let stdout = BufReader::new(child.stdout.take().expect("stdout was piped")).lines();
Ok(Self {
child,
stdin,
stdout,
})
}
async fn exchange(&mut self, line: &[u8]) -> Result<String, ExecError> {
self.stdin
.write_all(line)
.await
.map_err(|e| ExecError::Protocol {
id: "worker".into(),
detail: format!("could not send the request: {e}"),
})?;
self.stdin.flush().await.map_err(|e| ExecError::Protocol {
id: "worker".into(),
detail: format!("could not send the request: {e}"),
})?;
match self.stdout.next_line().await {
Ok(Some(answer)) => Ok(answer),
Ok(None) => Err(ExecError::Unreachable {
environment: "worker".into(),
detail: "it stopped without answering".into(),
}),
Err(e) => Err(ExecError::Protocol {
id: "worker".into(),
detail: format!("could not read the response: {e}"),
}),
}
}
}
#[derive(Default)]
pub struct Workers {
lanes: Mutex<HashMap<Ident, Arc<Mutex<Option<Worker>>>>>,
}
impl Workers {
pub fn new() -> Self {
Self::default()
}
pub async fn invoke(
&self,
ws: &CheckedWorkspace,
environment: &Environment,
implementation: &Implementation,
args: Vec<Value>,
params: &[Type],
expected: &Type,
) -> Result<Value, ExecError> {
let lane = {
let mut lanes = self.lanes.lock().await;
Arc::clone(
lanes
.entry(environment.id.clone())
.or_insert_with(|| Arc::new(Mutex::new(None))),
)
};
let mut held = lane.lock().await;
if held.is_none() {
*held = Some(Worker::start(environment)?);
}
let worker = held.as_mut().expect("just started");
let mut line = request_line(ws, implementation, &args, params)?;
line.push(b'\n');
let timeout = environment.reach.timeout_ms().unwrap_or(30_000);
let answer = match tokio::time::timeout(
Duration::from_millis(timeout),
worker.exchange(&line),
)
.await
{
Ok(Ok(answer)) => answer,
Ok(Err(failure)) => {
*held = None;
return Err(failure);
}
Err(_) => {
if let Some(mut dead) = held.take() {
let _ = dead.child.start_kill();
}
return Err(ExecError::Timeout {
id: implementation.id.to_string(),
millis: timeout,
});
}
};
crate::subprocess::read_answer(ws, implementation, &answer, expected).inspect_err(
|failure| {
if matches!(failure, ExecError::Protocol { .. }) {
*held = None;
}
},
)
}
pub async fn shutdown(&self) {
let mut lanes = self.lanes.lock().await;
for lane in lanes.values() {
if let Some(mut worker) = lane.lock().await.take() {
let _ = worker.child.start_kill();
}
}
lanes.clear();
}
pub async fn running(&self) -> usize {
let lanes = self.lanes.lock().await;
let mut count = 0;
for lane in lanes.values() {
if lane.lock().await.is_some() {
count += 1;
}
}
count
}
}