407 lines
15 KiB
Rust
407 lines
15 KiB
Rust
//! Versioned external tooling boundary; the host API itself remains synchronous.
|
|
mod wire;
|
|
pub use wire::Limits;
|
|
|
|
use crate::{AdvanceFrameOutcome, HeadlessHost};
|
|
use serde_json::{Value, json};
|
|
use std::io::{self, BufRead, Write};
|
|
use std::sync::{Arc, Mutex, mpsc};
|
|
use wire::{CAPABILITIES, Command, Request, WireError};
|
|
|
|
#[derive(Default)]
|
|
struct Control {
|
|
active: Option<String>,
|
|
advancing: bool,
|
|
canceled: bool,
|
|
}
|
|
|
|
enum Job {
|
|
Work(String, Command),
|
|
Stop(Option<String>),
|
|
ReadError(io::Error),
|
|
}
|
|
|
|
struct Output<W> {
|
|
writer: Mutex<W>,
|
|
session: String,
|
|
limit: usize,
|
|
}
|
|
|
|
impl<W: Write> Output<W> {
|
|
fn send(&self, value: Value) -> io::Result<()> {
|
|
let mut bytes = serde_json::to_vec(&value)?;
|
|
if bytes.len() > self.limit {
|
|
bytes = serde_json::to_vec(&json!({"type":"response","sessionId":self.session,
|
|
"requestId":value.get("requestId"),"error":{"code":"response_too_large",
|
|
"message":"response exceeds configured limit","details":{"maxResponseBytes":self.limit}}}))?;
|
|
}
|
|
if bytes.len() > self.limit {
|
|
return Err(io::Error::other("response limit cannot contain error"));
|
|
}
|
|
let mut writer = self.writer.lock().map_err(|_| io::Error::other("output poisoned"))?;
|
|
writer.write_all(&bytes)?;
|
|
writer.write_all(b"\n")?;
|
|
writer.flush()
|
|
}
|
|
|
|
fn reply(&self, id: Option<&str>, result: Result<Value, WireError>) -> io::Result<()> {
|
|
let mut value = json!({"type":"response","sessionId":self.session,"requestId":id});
|
|
match result {
|
|
Ok(r) => value["result"] = r,
|
|
Err(e) => value["error"] = serde_json::to_value(e)?,
|
|
}
|
|
self.send(value)
|
|
}
|
|
}
|
|
|
|
enum Line {
|
|
Data(Vec<u8>),
|
|
Oversized,
|
|
Truncated,
|
|
Eof,
|
|
}
|
|
|
|
/// Consume at most one line without ever accumulating more than the configured bound.
|
|
fn read_line(reader: &mut impl BufRead, limit: usize) -> io::Result<Line> {
|
|
let mut bytes = Vec::new();
|
|
let mut oversized = false;
|
|
loop {
|
|
let chunk = reader.fill_buf()?;
|
|
if chunk.is_empty() {
|
|
return Ok(if oversized {
|
|
Line::Oversized
|
|
} else if bytes.is_empty() {
|
|
Line::Eof
|
|
} else {
|
|
Line::Truncated
|
|
});
|
|
}
|
|
let newline = chunk.iter().position(|b| *b == b'\n');
|
|
let length = newline.unwrap_or(chunk.len());
|
|
if !oversized {
|
|
if length > limit.saturating_sub(bytes.len()) {
|
|
oversized = true;
|
|
bytes.clear();
|
|
} else {
|
|
bytes.extend_from_slice(&chunk[..length]);
|
|
}
|
|
}
|
|
reader.consume(length + usize::from(newline.is_some()));
|
|
if newline.is_some() {
|
|
if bytes.last() == Some(&b'\r') {
|
|
bytes.pop();
|
|
}
|
|
return Ok(if oversized { Line::Oversized } else { Line::Data(bytes) });
|
|
}
|
|
}
|
|
}
|
|
|
|
fn read_commands<R: BufRead, W: Write>(
|
|
mut input: R,
|
|
output: &Output<W>,
|
|
control: &Mutex<Control>,
|
|
sender: &mpsc::Sender<Job>,
|
|
limits: &Limits,
|
|
) -> io::Result<()> {
|
|
let mut initialized = false;
|
|
loop {
|
|
let bytes = match read_line(&mut input, limits.max_command_bytes)? {
|
|
Line::Eof => break,
|
|
Line::Truncated => {
|
|
output.reply(None, Err(WireError::new("invalid_request", "EOF before LF")))?;
|
|
break;
|
|
}
|
|
Line::Oversized => {
|
|
output.reply(
|
|
None,
|
|
Err(WireError::new("request_too_large", "command exceeds configured limit")),
|
|
)?;
|
|
continue;
|
|
}
|
|
Line::Data(bytes) => bytes,
|
|
};
|
|
let raw: Value = match serde_json::from_slice(&bytes) {
|
|
Ok(value) => value,
|
|
Err(error) => {
|
|
output.reply(None, Err(WireError::new("invalid_request", error.to_string())))?;
|
|
continue;
|
|
}
|
|
};
|
|
let id = raw
|
|
.get("requestId")
|
|
.and_then(Value::as_str)
|
|
.filter(|id| wire::valid_id(id))
|
|
.map(str::to_owned);
|
|
let request = serde_json::from_value::<Request>(raw)
|
|
.map_err(|e| WireError::new("invalid_request", e.to_string()))
|
|
.and_then(wire::parse);
|
|
let (id, command) = match request {
|
|
Ok(value) => value,
|
|
Err(error) => {
|
|
output.reply(id.as_deref(), Err(error))?;
|
|
continue;
|
|
}
|
|
};
|
|
if let Command::Shutdown = command {
|
|
let mut c = control.lock().unwrap();
|
|
c.canceled = true;
|
|
sender.send(Job::Stop(Some(id))).map_err(|_| io::Error::other("execution stopped"))?;
|
|
return Ok(());
|
|
}
|
|
if let Command::Initialize(params) = command {
|
|
let result = if initialized {
|
|
Err(WireError::new("already_initialized", "session already initialized"))
|
|
} else if params.protocol_version.major != 1 {
|
|
Err(WireError::new("incompatible_version", "protocol major must be 1"))
|
|
} else if params
|
|
.required_capabilities
|
|
.iter()
|
|
.any(|c| !CAPABILITIES.contains(&c.as_str()))
|
|
{
|
|
Err(WireError::new("unsupported_capability", "required capability unavailable"))
|
|
} else {
|
|
initialized = true;
|
|
Ok(json!({"protocolVersion":{"major":1,"minor":0},"capabilities":CAPABILITIES}))
|
|
};
|
|
output.reply(Some(&id), result)?;
|
|
continue;
|
|
}
|
|
if !initialized {
|
|
output.reply(Some(&id), Err(WireError::new("not_initialized", "initialize first")))?;
|
|
continue;
|
|
}
|
|
let mut c = control.lock().unwrap();
|
|
if let Command::Cancel(params) = command {
|
|
let result = if c.advancing && c.active.as_deref() == Some(¶ms.target_request_id) {
|
|
c.canceled = true;
|
|
Ok(json!({"targetRequestId":params.target_request_id,"requested":true}))
|
|
} else {
|
|
Err(WireError::new("not_cancelable", "no matching active advance"))
|
|
};
|
|
output.reply(Some(&id), result)?;
|
|
continue;
|
|
}
|
|
if c.active.is_some() {
|
|
output.reply(Some(&id), Err(WireError::new("busy", "a host operation is active")))?;
|
|
continue;
|
|
}
|
|
if let Command::Advance(params) = &command
|
|
&& params.frames > limits.max_frames
|
|
{
|
|
output.reply(
|
|
Some(&id),
|
|
Err(WireError::new("limit_exceeded", "frames exceeds maxFrames")),
|
|
)?;
|
|
continue;
|
|
}
|
|
c.active = Some(id.clone());
|
|
c.advancing = matches!(command, Command::Advance(_));
|
|
c.canceled = false;
|
|
sender.send(Job::Work(id, command)).map_err(|_| io::Error::other("execution stopped"))?;
|
|
}
|
|
let mut c = control.lock().unwrap();
|
|
c.canceled = true;
|
|
sender.send(Job::Stop(None)).map_err(|_| io::Error::other("execution stopped"))
|
|
}
|
|
|
|
fn execute<W: Write>(
|
|
host: &mut HeadlessHost,
|
|
command: Command,
|
|
id: &str,
|
|
output: &Output<W>,
|
|
control: &Mutex<Control>,
|
|
) -> io::Result<Result<Value, WireError>> {
|
|
Ok(match command {
|
|
Command::Boot(p) => {
|
|
host.boot(p.path).map(|()| wire::state(host.get_state())).map_err(wire::host_error)
|
|
}
|
|
Command::Reset => {
|
|
host.reset();
|
|
Ok(wire::state(host.get_state()))
|
|
}
|
|
Command::SetInput(p) => {
|
|
host.set_input(p.into());
|
|
Ok(json!({}))
|
|
}
|
|
Command::ClearInput => {
|
|
host.clear_input();
|
|
Ok(json!({}))
|
|
}
|
|
Command::GetState => Ok(wire::state(host.get_state())),
|
|
Command::GetFault => Ok(host.get_fault().as_ref().map(wire::fault).unwrap_or(Value::Null)),
|
|
Command::Capture => host.capture_frame().map_err(wire::host_error).and_then(wire::capture),
|
|
Command::Advance(p) => {
|
|
let mut result = json!({"requested":p.frames,"completed":0,"stop":"completed"});
|
|
for completed in 0..p.frames {
|
|
if control.lock().unwrap().canceled {
|
|
result["stop"] = json!("canceled");
|
|
break;
|
|
}
|
|
match host.advance_frame() {
|
|
Ok(AdvanceFrameOutcome::FrameCompleted { .. }) => {
|
|
result["completed"] = json!(completed + 1);
|
|
output.send(
|
|
json!({"type":"progress","sessionId":output.session,"requestId":id,
|
|
"requested":p.frames,"completed":completed + 1}),
|
|
)?;
|
|
}
|
|
Ok(AdvanceFrameOutcome::Faulted(report)) => {
|
|
result["stop"] = json!("faulted");
|
|
result["fault"] = wire::fault(&report);
|
|
break;
|
|
}
|
|
Ok(AdvanceFrameOutcome::Terminated) => {
|
|
result["stop"] = json!("terminated");
|
|
break;
|
|
}
|
|
Err(error) => {
|
|
result["stop"] = json!("host_error");
|
|
result["error"] = serde_json::to_value(wire::host_error(error))?;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
Ok(result)
|
|
}
|
|
_ => unreachable!("reader handles control commands"),
|
|
})
|
|
}
|
|
|
|
/// Serve one process session. The input reader stays responsive while the owner
|
|
/// executes a frame. On fatal output failure the process caller must exit; a
|
|
/// blocking OS stdin reader cannot be joined until that input is closed.
|
|
pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
|
|
input: R,
|
|
writer: W,
|
|
limits: Limits,
|
|
runtime_version: &str,
|
|
) -> io::Result<()> {
|
|
limits.validate()?;
|
|
let mut random = [0u8; 16];
|
|
getrandom::fill(&mut random).map_err(|e| io::Error::other(e.to_string()))?;
|
|
let session: String = random.iter().map(|v| format!("{v:02x}")).collect();
|
|
let output =
|
|
Arc::new(Output { writer: Mutex::new(writer), session, limit: limits.max_response_bytes });
|
|
output.send(
|
|
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":0},
|
|
"runtimeVersion":runtime_version,"capabilities":CAPABILITIES,"limits":limits}),
|
|
)?;
|
|
let control = Arc::new(Mutex::new(Control::default()));
|
|
let (sender, receiver) = mpsc::channel();
|
|
let reader_output = output.clone();
|
|
let reader_control = control.clone();
|
|
let reader = std::thread::spawn(move || {
|
|
if let Err(error) = read_commands(input, &reader_output, &reader_control, &sender, &limits)
|
|
{
|
|
reader_control.lock().unwrap().canceled = true;
|
|
let _ = sender.send(Job::ReadError(error));
|
|
}
|
|
});
|
|
let mut host = HeadlessHost::new();
|
|
while let Ok(job) = receiver.recv() {
|
|
match job {
|
|
Job::Work(id, command) => {
|
|
let result = execute(&mut host, command, &id, &output, &control)?;
|
|
// Release authority under the same lock as response publication:
|
|
// a client reacting to this reply cannot race a stale busy flag.
|
|
let mut c = control.lock().unwrap();
|
|
output.reply(Some(&id), result)?;
|
|
c.active = None;
|
|
c.advancing = false;
|
|
}
|
|
Job::Stop(id) => {
|
|
drop(host);
|
|
if let Some(id) = id {
|
|
output.reply(Some(&id), Ok(json!({"closed":true})))?;
|
|
}
|
|
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
|
|
return Ok(());
|
|
}
|
|
Job::ReadError(error) => return Err(error),
|
|
}
|
|
}
|
|
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
use std::io::{BufReader, Cursor};
|
|
|
|
#[test]
|
|
fn bounded_lines_accept_fragmentation_and_recover_after_oversize() {
|
|
let mut reader = BufReader::with_capacity(2, Cursor::new(b"12345\n123456\nok\r\n"));
|
|
assert!(matches!(read_line(&mut reader, 5).unwrap(), Line::Data(v) if v == b"12345"));
|
|
assert!(matches!(read_line(&mut reader, 5).unwrap(), Line::Oversized));
|
|
assert!(matches!(read_line(&mut reader, 5).unwrap(), Line::Data(v) if v == b"ok"));
|
|
assert!(matches!(read_line(&mut reader, 5).unwrap(), Line::Eof));
|
|
assert!(matches!(read_line(&mut Cursor::new(b"no LF"), 10).unwrap(), Line::Truncated));
|
|
}
|
|
|
|
#[test]
|
|
fn input_snapshot_is_replacement_and_rejects_unknown_fields() {
|
|
let input: wire::Input = serde_json::from_value(json!({"right":true})).unwrap();
|
|
let signals: prometeu_hal::InputSignals = input.into();
|
|
assert!(signals.right_signal);
|
|
assert!(!signals.left_signal);
|
|
assert_eq!(signals.x_pos, 0);
|
|
assert!(serde_json::from_value::<wire::Input>(json!({"rigth":true})).is_err());
|
|
}
|
|
|
|
#[test]
|
|
fn response_limit_counts_the_complete_envelope_and_keeps_correlation() {
|
|
let output =
|
|
Output { writer: Mutex::new(Vec::new()), session: "session".into(), limit: 4096 };
|
|
output.reply(Some("capture"), Ok(json!({"data":"x".repeat(4096)}))).unwrap();
|
|
let bytes = output.writer.into_inner().unwrap();
|
|
assert!(bytes.len() <= 4097);
|
|
let result: Value = serde_json::from_slice(&bytes).unwrap();
|
|
assert_eq!(result["requestId"], "capture");
|
|
assert_eq!(result["sessionId"], "session");
|
|
assert_eq!(result["error"]["code"], "response_too_large");
|
|
assert!(result.get("result").is_none());
|
|
}
|
|
|
|
#[test]
|
|
fn distributed_request_fixtures_are_accepted_by_the_actual_parser() {
|
|
let requests: Vec<Value> = serde_json::from_str(include_str!(
|
|
"../../../../../devtools/headless-protocol/requests.json"
|
|
))
|
|
.unwrap();
|
|
assert_eq!(requests.len(), 11);
|
|
for request in requests {
|
|
wire::parse(serde_json::from_value(request).unwrap()).unwrap();
|
|
}
|
|
}
|
|
|
|
#[test]
|
|
fn capture_preserves_independent_ids_and_excludes_padding_without_channel_loss() {
|
|
use base64::Engine as _;
|
|
use prometeu_hal::app_mode::AppMode;
|
|
use prometeu_hal::{FrameId, OwnedRgba8888Frame, RenderOwnership};
|
|
let frame = OwnedRgba8888Frame::new(
|
|
FrameId::new(91),
|
|
RenderOwnership::new(1, AppMode::Game, 41),
|
|
1,
|
|
2,
|
|
2,
|
|
vec![0x12345678, 0xffffffff, 0xabcdef01, 0xffffffff],
|
|
)
|
|
.unwrap();
|
|
let capture =
|
|
wire::capture(crate::CapturedFrame { logical_frame_index: 7, frame }).unwrap();
|
|
assert_eq!(capture["logicalFrameIndex"], 7);
|
|
assert_eq!(capture["frameId"], 91);
|
|
assert_eq!(capture["stridePixels"], 2);
|
|
let png = base64::engine::general_purpose::STANDARD
|
|
.decode(capture["data"].as_str().unwrap())
|
|
.unwrap();
|
|
let mut reader = png::Decoder::new(Cursor::new(png)).read_info().unwrap();
|
|
let mut bytes = vec![0; reader.output_buffer_size()];
|
|
let info = reader.next_frame(&mut bytes).unwrap();
|
|
assert_eq!((info.width, info.height), (1, 2));
|
|
assert_eq!(&bytes[..info.buffer_size()], &[0x12, 0x34, 0x56, 0x78, 0xab, 0xcd, 0xef, 0x01]);
|
|
}
|
|
}
|