use std::io::{Read, Write};
use std::process::{Command, Stdio};
use std::thread::{self, JoinHandle};
use std::time::{Duration, Instant};
use serde_json::Value;
use super::adapter::{PARENT_ENV, SESSION_ENV};
use super::file::FILE_VERB;
use super::plan::Checked;
use super::text::say;
const CALL: Duration = Duration::from_secs(30);
const OUTPUT_BYTES: usize = 64 << 10;
fn reader(stream: Option<impl Read + Send + 'static>) -> JoinHandle<String> {
thread::spawn(move || {
let Some(mut stream) = stream else {
return String::new();
};
let mut kept = Vec::new();
let mut chunk = [0u8; 8192];
while let Ok(n) = stream.read(&mut chunk) {
if n == 0 {
break;
}
let room = OUTPUT_BYTES.saturating_sub(kept.len());
kept.extend_from_slice(&chunk[..n.min(room)]);
}
String::from_utf8_lossy(&kept).into_owned()
})
}
pub enum Failure {
Slow(String),
Failed(String),
}
impl Failure {
pub fn text(&self) -> &str {
match self {
Self::Slow(text) | Self::Failed(text) => text,
}
}
}
pub fn call(plan: &Checked, native: &str, event: &str, fields: Value) -> Result<Value, Failure> {
let exe = std::env::current_exe().map_err(|error| Failure::Failed(error.to_string()))?;
let mut command = Command::new(exe);
command
.arg(FILE_VERB)
.current_dir(&plan.directory)
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.env_remove(super::CHILD_ENV)
.env_remove(PARENT_ENV)
.env_remove(SESSION_ENV);
super::ending::restore_sigterm(&mut command);
let mut child = command
.spawn()
.map_err(|error| Failure::Failed(error.to_string()))?;
let body = serde_json::json!({
"plan": plan.wire,
"session": native,
"event": event,
"fields": fields,
})
.to_string();
let mut stdin = child.stdin.take();
let writer = thread::spawn(move || {
if let Some(stdin) = stdin.as_mut() {
let _ = stdin.write_all(body.as_bytes());
}
});
let (out, err) = (reader(child.stdout.take()), reader(child.stderr.take()));
let deadline = Instant::now() + CALL;
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break Some(status),
Ok(None) if Instant::now() < deadline => thread::sleep(Duration::from_millis(5)),
_ => {
let _ = child.kill();
let _ = child.wait();
break None;
}
}
};
let _ = writer.join();
let (out, err) = (
out.join().unwrap_or_default(),
err.join().unwrap_or_default(),
);
let Some(status) = status else {
let seconds = CALL.as_secs().to_string();
return Err(Failure::Slow(say("record_slow", &[("seconds", &seconds)])));
};
let envelope = out
.lines()
.rev()
.find_map(|line| serde_json::from_str::<Value>(line).ok());
match envelope {
Some(envelope) if status.success() => Ok(envelope),
Some(envelope) if envelope["error"].is_string() => Err(Failure::Failed(
envelope["error"].as_str().unwrap_or_default().to_string(),
)),
_ => Err(Failure::Failed(err.trim().to_string())),
}
}