feat: add headless automation protocol and CLI
This commit is contained in:
@@ -12,6 +12,12 @@ prometeu-drivers = { path = "../../console/prometeu-drivers" }
|
||||
prometeu-firmware = { path = "../../console/prometeu-firmware" }
|
||||
prometeu-hal = { path = "../../console/prometeu-hal" }
|
||||
prometeu-system = { path = "../../console/prometeu-system" }
|
||||
prometeu-vm = { path = "../../console/prometeu-vm" }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
base64 = "0.22"
|
||||
png = "0.17"
|
||||
getrandom = "0.3"
|
||||
|
||||
[[bench]]
|
||||
name = "temporal"
|
||||
|
||||
@@ -0,0 +1,406 @@
|
||||
//! 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]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,330 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use prometeu_bytecode::Value as VmValue;
|
||||
use prometeu_hal::InputSignals;
|
||||
use prometeu_system::CrashReport;
|
||||
use prometeu_vm::VmInitError;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use serde_json::{Value, json};
|
||||
use std::io;
|
||||
|
||||
use crate::{CapturedFrame, HostError, HostExecutionStatus, HostState};
|
||||
|
||||
pub const CAPABILITIES: &[&str] = &[
|
||||
"boot",
|
||||
"reset",
|
||||
"set_input",
|
||||
"clear_input",
|
||||
"advance",
|
||||
"capture",
|
||||
"get_state",
|
||||
"get_fault",
|
||||
"cancel",
|
||||
"shutdown",
|
||||
];
|
||||
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct Limits {
|
||||
pub max_frames: u64,
|
||||
pub max_command_bytes: usize,
|
||||
pub max_response_bytes: usize,
|
||||
pub handshake_timeout_ms: u64,
|
||||
pub call_timeout_ms: u64,
|
||||
pub shutdown_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl Default for Limits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
max_frames: 600,
|
||||
max_command_bytes: 64 * 1024,
|
||||
max_response_bytes: 32 * 1024 * 1024,
|
||||
handshake_timeout_ms: 5_000,
|
||||
call_timeout_ms: 60_000,
|
||||
shutdown_timeout_ms: 5_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Limits {
|
||||
pub fn validate(&self) -> io::Result<()> {
|
||||
if self.max_frames == 0
|
||||
|| self.max_command_bytes < 4096
|
||||
|| self.max_response_bytes < 4096
|
||||
|| self.handshake_timeout_ms == 0
|
||||
|| self.call_timeout_ms == 0
|
||||
|| self.shutdown_timeout_ms == 0
|
||||
{
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"limits must be positive and message bounds at least 4096 bytes",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Request {
|
||||
pub request_id: String,
|
||||
pub command: String,
|
||||
pub params: Value,
|
||||
}
|
||||
|
||||
pub(super) fn valid_id(id: &str) -> bool {
|
||||
!id.is_empty() && id.len() <= 128
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Serialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Version {
|
||||
pub major: u32,
|
||||
pub minor: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Initialize {
|
||||
pub protocol_version: Version,
|
||||
pub required_capabilities: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Boot {
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(super) struct Advance {
|
||||
pub frames: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Cancel {
|
||||
pub target_request_id: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub(super) struct Input {
|
||||
up: bool,
|
||||
down: bool,
|
||||
left: bool,
|
||||
right: bool,
|
||||
a: bool,
|
||||
b: bool,
|
||||
x: bool,
|
||||
y: bool,
|
||||
l: bool,
|
||||
r: bool,
|
||||
start: bool,
|
||||
select: bool,
|
||||
touch: bool,
|
||||
touch_x: i32,
|
||||
touch_y: i32,
|
||||
}
|
||||
|
||||
impl From<Input> for InputSignals {
|
||||
fn from(s: Input) -> Self {
|
||||
Self {
|
||||
up_signal: s.up,
|
||||
down_signal: s.down,
|
||||
left_signal: s.left,
|
||||
right_signal: s.right,
|
||||
a_signal: s.a,
|
||||
b_signal: s.b,
|
||||
x_signal: s.x,
|
||||
y_signal: s.y,
|
||||
l_signal: s.l,
|
||||
r_signal: s.r,
|
||||
start_signal: s.start,
|
||||
select_signal: s.select,
|
||||
f_signal: s.touch,
|
||||
x_pos: s.touch_x,
|
||||
y_pos: s.touch_y,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) enum Command {
|
||||
Initialize(Initialize),
|
||||
Boot(Boot),
|
||||
Reset,
|
||||
SetInput(Input),
|
||||
ClearInput,
|
||||
Advance(Advance),
|
||||
Capture,
|
||||
GetState,
|
||||
GetFault,
|
||||
Cancel(Cancel),
|
||||
Shutdown,
|
||||
}
|
||||
|
||||
fn params<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, WireError> {
|
||||
serde_json::from_value(value).map_err(|e| WireError::new("invalid_params", e.to_string()))
|
||||
}
|
||||
|
||||
fn empty(value: &Value) -> Result<(), WireError> {
|
||||
if value.as_object().is_some_and(|v| v.is_empty()) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(WireError::new("invalid_params", "expected an empty params object"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
|
||||
if !valid_id(&req.request_id) {
|
||||
return Err(WireError::new("invalid_request", "requestId must contain 1..128 UTF-8 bytes"));
|
||||
}
|
||||
let command = match req.command.as_str() {
|
||||
"initialize" => Command::Initialize(params(req.params)?),
|
||||
"boot" => {
|
||||
let p: Boot = params(req.params)?;
|
||||
if p.path.trim().is_empty() {
|
||||
return Err(WireError::new("invalid_params", "path is empty"));
|
||||
}
|
||||
Command::Boot(p)
|
||||
}
|
||||
"advance" => Command::Advance(params(req.params)?),
|
||||
"set_input" => Command::SetInput(params(req.params)?),
|
||||
"cancel" => {
|
||||
let p: Cancel = params(req.params)?;
|
||||
if !valid_id(&p.target_request_id) {
|
||||
return Err(WireError::new("invalid_params", "invalid targetRequestId"));
|
||||
}
|
||||
Command::Cancel(p)
|
||||
}
|
||||
"reset" | "clear_input" | "capture" | "get_state" | "get_fault" | "shutdown" => {
|
||||
empty(&req.params)?;
|
||||
match req.command.as_str() {
|
||||
"reset" => Command::Reset,
|
||||
"clear_input" => Command::ClearInput,
|
||||
"capture" => Command::Capture,
|
||||
"get_state" => Command::GetState,
|
||||
"get_fault" => Command::GetFault,
|
||||
_ => Command::Shutdown,
|
||||
}
|
||||
}
|
||||
_ => return Err(WireError::new("unknown_command", "unknown command")),
|
||||
};
|
||||
Ok((req.request_id, command))
|
||||
}
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
pub(super) struct WireError {
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
pub details: Value,
|
||||
}
|
||||
|
||||
impl WireError {
|
||||
pub fn new(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self { code, message: message.into(), details: json!({}) }
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn host_error(error: HostError) -> WireError {
|
||||
let (code, details) = match &error {
|
||||
HostError::AlreadyBooted => ("already_booted", json!({})),
|
||||
HostError::BootFailed { reason, report } => {
|
||||
("boot_failed", json!({"reason":reason,"fault":report.as_ref().map(fault)}))
|
||||
}
|
||||
HostError::InvalidState { operation, status } => {
|
||||
("invalid_state", json!({"operation":operation,"status":status_name(*status)}))
|
||||
}
|
||||
HostError::FrameAdvanceWatchdogExpired { host_tick_limit } => {
|
||||
("watchdog_expired", json!({"hostTickLimit":host_tick_limit}))
|
||||
}
|
||||
HostError::FrameNotPublished { previous } => {
|
||||
("frame_not_published", json!({"previousFrameId":previous.map(|id| id.get())}))
|
||||
}
|
||||
HostError::NoFrameAvailable => ("no_frame_available", json!({})),
|
||||
};
|
||||
WireError { code, message: error.to_string(), details }
|
||||
}
|
||||
|
||||
fn status_name(status: HostExecutionStatus) -> &'static str {
|
||||
match status {
|
||||
HostExecutionStatus::Running => "running",
|
||||
HostExecutionStatus::Paused => "paused",
|
||||
HostExecutionStatus::Terminated => "terminated",
|
||||
HostExecutionStatus::Faulted => "faulted",
|
||||
}
|
||||
}
|
||||
|
||||
fn stack_value(value: &VmValue) -> Value {
|
||||
match value {
|
||||
VmValue::Int32(v) => json!({"kind":"int32","value":v}),
|
||||
VmValue::Int64(v) => json!({"kind":"int64","value":v.to_string()}),
|
||||
VmValue::Float(v) => json!({"kind":"float64","value":v.to_string()}),
|
||||
VmValue::Boolean(v) => json!({"kind":"boolean","value":v}),
|
||||
VmValue::String(v) => json!({"kind":"string","value":v.as_ref()}),
|
||||
VmValue::HeapRef(v) => json!({"kind":"heap_ref","value":v.0}),
|
||||
VmValue::Null => json!({"kind":"null","value":null}),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn state(s: HostState) -> Value {
|
||||
json!({"pc":s.pc,"stackTop":s.stack_top.iter().map(stack_value).collect::<Vec<_>>(),
|
||||
"logicalFrameIndex":s.frame_index,"tickIndex":s.tick_index,"appId":s.app_id,
|
||||
"status":status_name(s.status)})
|
||||
}
|
||||
|
||||
pub(super) fn fault(report: &CrashReport) -> Value {
|
||||
let mut result = json!({"kind":report.kind(),"pc":report.pc(),"summary":report.summary()});
|
||||
match report {
|
||||
CrashReport::VmTrap { trap } => {
|
||||
result["trap"] = json!({"code":trap.code,"opcode":trap.opcode,
|
||||
"message":trap.message,"pc":trap.pc,"span":trap.span});
|
||||
}
|
||||
CrashReport::VmPanic { message, .. } => {
|
||||
result["message"] = json!(message);
|
||||
}
|
||||
CrashReport::VmInit { error } => {
|
||||
let code = match error {
|
||||
VmInitError::InvalidFormat => "invalid_format",
|
||||
VmInitError::UnsupportedFormat => "unsupported_format",
|
||||
VmInitError::ImageLoadFailed(_) => "image_load_failed",
|
||||
VmInitError::LoaderPatchFailed(_) => "loader_patch_failed",
|
||||
VmInitError::EntrypointNotFound => "entrypoint_not_found",
|
||||
VmInitError::VerificationFailed(_) => "verification_failed",
|
||||
};
|
||||
result["initError"] = json!({"code":code,"message":format!("{error:?}")});
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
pub(super) fn capture(c: CapturedFrame) -> Result<Value, WireError> {
|
||||
let frame = c.frame;
|
||||
let width = u32::try_from(frame.width)
|
||||
.map_err(|_| WireError::new("capture_failed", "width exceeds PNG limit"))?;
|
||||
let height = u32::try_from(frame.height)
|
||||
.map_err(|_| WireError::new("capture_failed", "height exceeds PNG limit"))?;
|
||||
let mut rgba = Vec::new();
|
||||
for y in 0..frame.height {
|
||||
for pixel in frame.row(y).ok_or_else(|| WireError::new("capture_failed", "invalid row"))? {
|
||||
rgba.extend_from_slice(&pixel.to_be_bytes());
|
||||
}
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
{
|
||||
let mut encoder = png::Encoder::new(&mut bytes, width, height);
|
||||
encoder.set_color(png::ColorType::Rgba);
|
||||
encoder.set_depth(png::BitDepth::Eight);
|
||||
let mut writer =
|
||||
encoder.write_header().map_err(|e| WireError::new("capture_failed", e.to_string()))?;
|
||||
writer
|
||||
.write_image_data(&rgba)
|
||||
.map_err(|e| WireError::new("capture_failed", e.to_string()))?;
|
||||
writer.finish().map_err(|e| WireError::new("capture_failed", e.to_string()))?;
|
||||
}
|
||||
Ok(json!({"mimeType":"image/png","encoding":"base64","data":STANDARD.encode(bytes),
|
||||
"width":width,"height":height,"stridePixels":frame.stride_pixels,"pixelFormat":"RGBA8888",
|
||||
"logicalFrameIndex":c.logical_frame_index,"frameId":frame.frame_id.get()}))
|
||||
}
|
||||
@@ -6,6 +6,7 @@
|
||||
//! The desktop host's `stepFrame` command still advances on the 60 Hz winit loop.
|
||||
//! That pacing stays in `prometeu-host-desktop-winit` until a later protocol agenda.
|
||||
|
||||
pub mod automation;
|
||||
mod host;
|
||||
|
||||
pub use host::{
|
||||
|
||||
@@ -13,11 +13,26 @@ path = "src/main.rs"
|
||||
name = "prometeu-runtime"
|
||||
path = "src/bin/prometeu-runtime.rs"
|
||||
|
||||
[[bin]]
|
||||
name = "prometeu-headless"
|
||||
path = "src/bin/prometeu-headless.rs"
|
||||
|
||||
[package.metadata.dist]
|
||||
dist = true
|
||||
include = [
|
||||
"../../../devtools/headless-protocol",
|
||||
"../../../docs/specs/runtime/11a-headless-automation-protocol.md",
|
||||
]
|
||||
|
||||
[dependencies]
|
||||
clap = { version = "4.5", features = ["derive"] }
|
||||
prometeu-host-desktop-winit = { path = "../../host/prometeu-host-desktop-winit" }
|
||||
prometeu-host-headless = { path = "../../host/prometeu-host-headless" }
|
||||
|
||||
[dev-dependencies]
|
||||
jsonschema = { version = "0.33", default-features = false }
|
||||
serde_json = "1"
|
||||
prometeu-bytecode = { path = "../../console/prometeu-bytecode" }
|
||||
prometeu-hal = { path = "../../console/prometeu-hal" }
|
||||
base64 = "0.22"
|
||||
png = "0.17"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
use clap::Parser;
|
||||
use prometeu_cli::{HeadlessArgs, run_headless};
|
||||
|
||||
#[derive(Parser)]
|
||||
#[command(
|
||||
name = "prometeu-headless",
|
||||
version,
|
||||
about = "Deterministic headless JSONL automation host"
|
||||
)]
|
||||
struct Cli {
|
||||
#[command(flatten)]
|
||||
options: HeadlessArgs,
|
||||
}
|
||||
|
||||
fn main() -> std::io::Result<()> {
|
||||
run_headless(Cli::parse().options)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Shared CLI options for the dispatcher and its headless executable.
|
||||
use clap::Args;
|
||||
use prometeu_host_headless::automation::Limits;
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct HeadlessArgs {
|
||||
/// Use the versioned JSONL stdin/stdout protocol (required).
|
||||
#[arg(long, required = true)]
|
||||
pub stdio: bool,
|
||||
#[arg(long, default_value_t = 600)]
|
||||
pub max_frames: u64,
|
||||
#[arg(long, default_value_t = 65536)]
|
||||
pub max_command_bytes: usize,
|
||||
#[arg(long, default_value_t = 33554432)]
|
||||
pub max_response_bytes: usize,
|
||||
#[arg(long, default_value_t = 5000)]
|
||||
pub handshake_timeout_ms: u64,
|
||||
#[arg(long, default_value_t = 60000)]
|
||||
pub call_timeout_ms: u64,
|
||||
#[arg(long, default_value_t = 5000)]
|
||||
pub shutdown_timeout_ms: u64,
|
||||
}
|
||||
|
||||
impl HeadlessArgs {
|
||||
pub fn limits(&self) -> Limits {
|
||||
Limits {
|
||||
max_frames: self.max_frames,
|
||||
max_command_bytes: self.max_command_bytes,
|
||||
max_response_bytes: self.max_response_bytes,
|
||||
handshake_timeout_ms: self.handshake_timeout_ms,
|
||||
call_timeout_ms: self.call_timeout_ms,
|
||||
shutdown_timeout_ms: self.shutdown_timeout_ms,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn forwarded_args(&self) -> Vec<String> {
|
||||
vec![
|
||||
"--stdio".into(),
|
||||
"--max-frames".into(),
|
||||
self.max_frames.to_string(),
|
||||
"--max-command-bytes".into(),
|
||||
self.max_command_bytes.to_string(),
|
||||
"--max-response-bytes".into(),
|
||||
self.max_response_bytes.to_string(),
|
||||
"--handshake-timeout-ms".into(),
|
||||
self.handshake_timeout_ms.to_string(),
|
||||
"--call-timeout-ms".into(),
|
||||
self.call_timeout_ms.to_string(),
|
||||
"--shutdown-timeout-ms".into(),
|
||||
self.shutdown_timeout_ms.to_string(),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run_headless(args: HeadlessArgs) -> std::io::Result<()> {
|
||||
prometeu_host_headless::automation::serve(
|
||||
std::io::BufReader::new(std::io::stdin()),
|
||||
std::io::stdout(),
|
||||
args.limits(),
|
||||
env!("CARGO_PKG_VERSION"),
|
||||
)
|
||||
}
|
||||
@@ -19,6 +19,8 @@ struct Cli {
|
||||
|
||||
#[derive(Subcommand)]
|
||||
enum Commands {
|
||||
/// Starts the versioned headless automation process (no native window).
|
||||
Headless(prometeu_cli::HeadlessArgs),
|
||||
/// Executes a cartridge using the available runtime.
|
||||
Run {
|
||||
/// Path to the cartridge (directory or .pmc file).
|
||||
@@ -65,6 +67,11 @@ fn main() {
|
||||
};
|
||||
|
||||
match cli.command {
|
||||
Some(Commands::Headless(options)) => {
|
||||
let args = options.forwarded_args();
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-headless", &borrowed);
|
||||
}
|
||||
Some(Commands::Run { cart }) => {
|
||||
dispatch(&exe_dir, "prometeu-runtime", &["--run", &cart]);
|
||||
}
|
||||
@@ -99,6 +106,7 @@ fn dispatch(exe_dir: &Path, bin_name: &str, args: &[&str]) {
|
||||
"prometeu: command '{}' is not yet available in this distribution on {}",
|
||||
match bin_name {
|
||||
"prometeu-runtime" => "run/debug",
|
||||
"prometeu-headless" => "headless",
|
||||
"prometeuc" => "build/verify c",
|
||||
"prometeup" => "pack/verify p",
|
||||
_ => bin_name,
|
||||
|
||||
@@ -0,0 +1,615 @@
|
||||
use base64::{Engine as _, engine::general_purpose::STANDARD};
|
||||
use prometeu_bytecode::SourceSpan;
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
|
||||
use prometeu_host_headless::{AdvanceFramesStop, HeadlessHost};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, ChildStdin, Command, Stdio};
|
||||
use std::sync::{
|
||||
atomic::{AtomicU64, Ordering},
|
||||
mpsc,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
fn new() -> Self {
|
||||
static COUNTER: AtomicU64 = AtomicU64::new(0);
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"prometeu-protocol-test-{}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos(),
|
||||
COUNTER.fetch_add(1, Ordering::Relaxed)
|
||||
));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
}
|
||||
impl Drop for TempDir {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
struct Client {
|
||||
child: Child,
|
||||
input: Option<ChildStdin>,
|
||||
messages: mpsc::Receiver<Result<Value, String>>,
|
||||
pending: HashMap<String, Value>,
|
||||
next: u64,
|
||||
hello: Value,
|
||||
}
|
||||
|
||||
impl Client {
|
||||
fn new(args: &[&str]) -> Self {
|
||||
Self::spawn(Path::new(env!("CARGO_BIN_EXE_prometeu-headless")), args, None)
|
||||
}
|
||||
|
||||
fn spawn(binary: &Path, args: &[&str], cwd: Option<&Path>) -> Self {
|
||||
let mut command = Command::new(binary);
|
||||
command.args(args).stdin(Stdio::piped()).stdout(Stdio::piped()).stderr(Stdio::inherit());
|
||||
if let Some(cwd) = cwd {
|
||||
command.current_dir(cwd);
|
||||
}
|
||||
let mut child = command.spawn().unwrap();
|
||||
let input = child.stdin.take();
|
||||
let stdout = child.stdout.take().unwrap();
|
||||
let (sender, messages) = mpsc::channel();
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines() {
|
||||
let value = line.map_err(|e| e.to_string()).and_then(|line| {
|
||||
serde_json::from_str(&line)
|
||||
.map_err(|e| format!("non-protocol stdout: {e}: {line}"))
|
||||
});
|
||||
if sender.send(value).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut client =
|
||||
Self { child, input, messages, pending: HashMap::new(), next: 0, hello: Value::Null };
|
||||
client.hello = client.event();
|
||||
assert_eq!(client.hello["type"], "hello");
|
||||
client
|
||||
}
|
||||
|
||||
fn event(&self) -> Value {
|
||||
let message = self
|
||||
.messages
|
||||
.recv_timeout(Duration::from_secs(15))
|
||||
.expect("protocol reply deadline")
|
||||
.unwrap();
|
||||
static SCHEMA: std::sync::OnceLock<jsonschema::Validator> = std::sync::OnceLock::new();
|
||||
let schema = SCHEMA.get_or_init(|| {
|
||||
let value: Value = serde_json::from_str(include_str!(
|
||||
"../../../../devtools/headless-protocol/response.schema.json"
|
||||
))
|
||||
.unwrap();
|
||||
jsonschema::validator_for(&value).unwrap()
|
||||
});
|
||||
if let Err(error) = schema.validate(&message) {
|
||||
panic!("server message violates published schema: {error}: {message}");
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
fn raw(&mut self, bytes: &[u8]) {
|
||||
self.input.as_mut().unwrap().write_all(bytes).unwrap();
|
||||
self.input.as_mut().unwrap().flush().unwrap();
|
||||
}
|
||||
|
||||
fn send(&mut self, command: &str, params: Value) -> String {
|
||||
self.next += 1;
|
||||
let id = format!("q{}", self.next);
|
||||
let mut bytes =
|
||||
serde_json::to_vec(&json!({"requestId":id,"command":command,"params":params})).unwrap();
|
||||
bytes.push(b'\n');
|
||||
self.raw(&bytes);
|
||||
id
|
||||
}
|
||||
|
||||
fn response(&mut self, id: &str) -> Value {
|
||||
if let Some(value) = self.pending.remove(id) {
|
||||
return value;
|
||||
}
|
||||
loop {
|
||||
let message = self.event();
|
||||
if message["type"] == "progress" {
|
||||
continue;
|
||||
}
|
||||
let message_id = message["requestId"].as_str().unwrap().to_owned();
|
||||
if message_id == id {
|
||||
return message;
|
||||
}
|
||||
self.pending.insert(message_id, message);
|
||||
}
|
||||
}
|
||||
|
||||
fn call(&mut self, command: &str, params: Value) -> Value {
|
||||
let id = self.send(command, params);
|
||||
self.response(&id)
|
||||
}
|
||||
|
||||
fn ok(&mut self, command: &str, params: Value) -> Value {
|
||||
let response = self.call(command, params);
|
||||
assert!(response.get("error").is_none(), "{response}");
|
||||
response["result"].clone()
|
||||
}
|
||||
|
||||
fn initialize(&mut self) {
|
||||
self.ok("initialize", json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":["advance","capture","cancel"]}));
|
||||
}
|
||||
|
||||
fn wait_exit(&mut self) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
if let Some(status) = self.child.try_wait().unwrap() {
|
||||
assert!(status.success(), "{status}");
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "process did not exit");
|
||||
std::thread::sleep(Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
|
||||
fn close(&mut self) {
|
||||
self.ok("shutdown", json!({}));
|
||||
self.input.take();
|
||||
self.wait_exit();
|
||||
}
|
||||
}
|
||||
impl Drop for Client {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.child.kill();
|
||||
let _ = self.child.wait();
|
||||
}
|
||||
}
|
||||
|
||||
fn cartridge(code: &str, gfx: bool) -> TempDir {
|
||||
cartridge_bytes(assemble(code).unwrap(), gfx)
|
||||
}
|
||||
|
||||
fn cartridge_bytes(code: Vec<u8>, gfx: bool) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
let module = BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 8,
|
||||
}],
|
||||
code,
|
||||
debug_info: Some(DebugInfo {
|
||||
pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 11, end: 15 })],
|
||||
function_names: vec![(0, "main".into())],
|
||||
}),
|
||||
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
||||
syscalls: if gfx {
|
||||
vec![SyscallDecl {
|
||||
module: "gfx2d".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
}]
|
||||
} else {
|
||||
vec![]
|
||||
},
|
||||
};
|
||||
fs::write(dir.0.join("program.pbx"), module.serialize()).unwrap();
|
||||
fs::write(
|
||||
dir.0.join("manifest.json"),
|
||||
serde_json::to_vec(&json!({"magic":"PMTU","cartridge_version":1,"app_id":41,
|
||||
"title":"Protocol test","app_version":"0.1.0","app_mode":"Game","capabilities":["gfx2d"]}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn colored_cart() -> TempDir {
|
||||
cartridge("PUSH_I64 4278190335\nHOSTCALL 0\nFRAME_SYNC\nRET\n", true)
|
||||
}
|
||||
fn boot(client: &mut Client, dir: &TempDir) {
|
||||
client.ok("boot", json!({"path":dir.0}));
|
||||
}
|
||||
fn png_bytes(capture: &Value) -> Vec<u8> {
|
||||
let bytes = STANDARD.decode(capture["data"].as_str().unwrap()).unwrap();
|
||||
let decoder = png::Decoder::new(std::io::Cursor::new(bytes));
|
||||
let mut reader = decoder.read_info().unwrap();
|
||||
let mut output = vec![0; reader.output_buffer_size()];
|
||||
let info = reader.next_frame(&mut output).unwrap();
|
||||
assert_eq!(info.color_type, png::ColorType::Rgba);
|
||||
assert_eq!(info.width as u64, capture["width"].as_u64().unwrap());
|
||||
assert_eq!(info.height as u64, capture["height"].as_u64().unwrap());
|
||||
output.truncate(info.buffer_size());
|
||||
output
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handshake_versions_capabilities_and_limits_are_explicit() {
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
assert_eq!(c.hello["runtimeVersion"], env!("CARGO_PKG_VERSION"));
|
||||
assert_eq!(c.hello["protocolVersion"], json!({"major":1,"minor":0}));
|
||||
assert_eq!(
|
||||
c.hello["limits"],
|
||||
json!({"maxFrames":600,"maxCommandBytes":65536,"maxResponseBytes":33554432,
|
||||
"handshakeTimeoutMs":5000,"callTimeoutMs":60000,"shutdownTimeoutMs":5000})
|
||||
);
|
||||
assert_eq!(c.call("get_state", json!({}))["error"]["code"], "not_initialized");
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":2,"minor":0},"requiredCapabilities":[]})
|
||||
)["error"]["code"],
|
||||
"incompatible_version"
|
||||
);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":["telepathy"]})
|
||||
)["error"]["code"],
|
||||
"unsupported_capability"
|
||||
);
|
||||
assert_eq!(
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":42},"requiredCapabilities":[]})
|
||||
)["protocolVersion"]["minor"],
|
||||
0
|
||||
);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":[]})
|
||||
)["error"]["code"],
|
||||
"already_initialized"
|
||||
);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_fragmented_and_oversized_commands_do_not_desynchronize() {
|
||||
let mut c = Client::new(&["--stdio", "--max-command-bytes", "4096"]);
|
||||
c.initialize();
|
||||
c.raw(b"not json\n");
|
||||
assert_eq!(c.event()["error"]["code"], "invalid_request");
|
||||
c.raw(&[0xff, b'\n']);
|
||||
assert_eq!(c.event()["error"]["code"], "invalid_request");
|
||||
let mut huge = vec![b' '; 5000];
|
||||
huge.push(b'\n');
|
||||
c.raw(&huge);
|
||||
assert_eq!(c.event()["error"]["code"], "request_too_large");
|
||||
c.raw(b"{\"requestId\":\"fragment\",\"command\":\"get_");
|
||||
assert!(c.messages.try_recv().is_err());
|
||||
c.raw(b"state\",\"params\":{}}\r\n");
|
||||
assert_eq!(c.response("fragment")["result"]["status"], "terminated");
|
||||
assert_eq!(c.call("get_state", json!({"typo":1}))["error"]["code"], "invalid_params");
|
||||
assert_eq!(c.call("advance", json!({"frames":-1}))["error"]["code"], "invalid_params");
|
||||
assert_eq!(c.call("advance", json!({"frames":601}))["error"]["code"], "limit_exceeded");
|
||||
assert_eq!(c.call("missing", json!({}))["error"]["code"], "unknown_command");
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lifecycle_and_capture_match_the_in_process_canonical_oracle() {
|
||||
let dir = colored_cart();
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
c.initialize();
|
||||
assert_eq!(c.call("capture", json!({}))["error"]["code"], "no_frame_available");
|
||||
boot(&mut c, &dir);
|
||||
assert_eq!(c.call("boot", json!({"path":dir.0}))["error"]["code"], "already_booted");
|
||||
let initial = c.ok("get_state", json!({}));
|
||||
assert_eq!(initial, c.ok("get_state", json!({})), "no background ticks");
|
||||
assert_eq!(
|
||||
c.ok("advance", json!({"frames":0})),
|
||||
json!({"requested":0,"completed":0,"stop":"completed"})
|
||||
);
|
||||
c.ok("set_input", json!({"right":true,"touch":true,"touchX":123,"touchY":45}));
|
||||
c.ok("clear_input", json!({}));
|
||||
let outcome = c.ok("advance", json!({"frames":3}));
|
||||
assert_eq!(outcome["completed"], 3);
|
||||
let capture = c.ok("capture", json!({}));
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(dir.0.to_string_lossy()).unwrap();
|
||||
assert_eq!(host.advance_frames(3).unwrap().stop, AdvanceFramesStop::Completed);
|
||||
let expected = host.capture_frame().unwrap();
|
||||
let pixels: Vec<u8> = expected.frame.pixels.iter().flat_map(|v| v.to_be_bytes()).collect();
|
||||
assert_eq!(png_bytes(&capture), pixels);
|
||||
assert_eq!(capture["logicalFrameIndex"], expected.logical_frame_index);
|
||||
assert_eq!(capture["frameId"], expected.frame.frame_id.get());
|
||||
assert_eq!(capture["stridePixels"], expected.frame.stride_pixels);
|
||||
assert_eq!(c.ok("get_fault", json!({})), Value::Null);
|
||||
c.ok("reset", json!({}));
|
||||
assert_eq!(c.call("capture", json!({}))["error"]["code"], "no_frame_available");
|
||||
assert_eq!(c.ok("advance", json!({"frames":1}))["stop"], "terminated");
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":3}));
|
||||
assert_eq!(c.ok("capture", json!({})), capture);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn independent_processes_match_pixels_ids_state_and_fault() {
|
||||
// Color is selected by the real normalized RIGHT-down intrinsic.
|
||||
let mut code = assemble("INTRINSIC 0x2000\nINTRINSIC 0x2013\nINTRINSIC 0x2032\n").unwrap();
|
||||
let jump = code.len() + 2;
|
||||
code.extend(
|
||||
assemble("JMP_IF_FALSE 0\nPUSH_I64 4278190335\nHOSTCALL 0\nFRAME_SYNC\nRET\n").unwrap(),
|
||||
);
|
||||
let blue = code.len() as u32;
|
||||
code[jump..jump + 4].copy_from_slice(&blue.to_le_bytes());
|
||||
code.extend(assemble("PUSH_I64 65535\nHOSTCALL 0\nFRAME_SYNC\nRET\n").unwrap());
|
||||
let dir = cartridge_bytes(code, true);
|
||||
let run = |c: &mut Client| {
|
||||
boot(c, &dir);
|
||||
c.ok("set_input", json!({"right":true}));
|
||||
c.ok("advance", json!({"frames":12}));
|
||||
let held = c.ok("capture", json!({}));
|
||||
assert!(png_bytes(&held).as_chunks::<4>().0.iter().all(|p| *p == [255, 0, 0, 255]));
|
||||
c.ok("clear_input", json!({}));
|
||||
c.ok("advance", json!({"frames":1}));
|
||||
let released = c.ok("capture", json!({}));
|
||||
assert!(png_bytes(&released).as_chunks::<4>().0.iter().all(|p| *p == [0, 0, 255, 255]));
|
||||
(held, released, c.ok("get_state", json!({})), c.ok("get_fault", json!({})))
|
||||
};
|
||||
let mut first = Client::new(&["--stdio"]);
|
||||
first.initialize();
|
||||
let expected = run(&mut first);
|
||||
first.ok("reset", json!({}));
|
||||
assert_eq!(run(&mut first), expected);
|
||||
first.close();
|
||||
let mut second = Client::new(&["--stdio"]);
|
||||
second.initialize();
|
||||
assert_eq!(run(&mut second), expected);
|
||||
second.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_guest_fault_and_host_watchdog_are_distinct_outcomes() {
|
||||
let mut code =
|
||||
assemble("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I32 3\nEQ\n")
|
||||
.unwrap();
|
||||
let jump = code.len() + 2;
|
||||
code.extend(assemble("JMP_IF_FALSE 0\nTRAP\n").unwrap());
|
||||
let next = code.len() as u32;
|
||||
code[jump..jump + 4].copy_from_slice(&next.to_le_bytes());
|
||||
code.extend(assemble("PUSH_I64 255\nHOSTCALL 0\nFRAME_SYNC\nRET\n").unwrap());
|
||||
let dir = cartridge_bytes(code, true);
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
c.initialize();
|
||||
boot(&mut c, &dir);
|
||||
let outcome = c.ok("advance", json!({"frames":5}));
|
||||
assert_eq!(outcome["completed"], 2);
|
||||
assert_eq!(outcome["stop"], "faulted");
|
||||
assert_eq!(outcome["fault"], c.ok("get_fault", json!({})));
|
||||
c.ok("reset", json!({}));
|
||||
let infinite = cartridge("JMP 0\n", false);
|
||||
boot(&mut c, &infinite);
|
||||
let outcome = c.ok("advance", json!({"frames":5}));
|
||||
assert_eq!(outcome["completed"], 0);
|
||||
assert_eq!(outcome["stop"], "host_error");
|
||||
assert_eq!(outcome["error"]["code"], "watchdog_expired");
|
||||
assert_eq!(c.ok("get_fault", json!({})), Value::Null);
|
||||
assert_eq!(c.ok("get_state", json!({}))["status"], "paused");
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn faults_and_boot_failures_are_structured_not_log_parsing() {
|
||||
let dir = cartridge("TRAP\nFRAME_SYNC\nRET\n", false);
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
c.initialize();
|
||||
boot(&mut c, &dir);
|
||||
let result = c.ok("advance", json!({"frames":5}));
|
||||
assert_eq!(result["completed"], 0);
|
||||
assert_eq!(result["stop"], "faulted");
|
||||
assert_eq!(result["fault"]["kind"], "vm_trap");
|
||||
assert!(result["fault"]["trap"]["code"].is_number());
|
||||
assert_eq!(c.ok("get_fault", json!({})), result["fault"]);
|
||||
assert_eq!(c.ok("get_state", json!({}))["status"], "faulted");
|
||||
c.ok("reset", json!({}));
|
||||
fs::write(dir.0.join("program.pbx"), b"not PBX").unwrap();
|
||||
let response = c.call("boot", json!({"path":dir.0}));
|
||||
assert_eq!(response["error"]["code"], "boot_failed");
|
||||
assert_eq!(response["error"]["details"]["fault"]["kind"], "vm_init");
|
||||
assert!(response["error"]["details"]["fault"]["initError"]["code"].is_string());
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn conflicting_work_is_rejected_and_cancellation_reports_partial_progress() {
|
||||
let dir = colored_cart();
|
||||
let mut c = Client::new(&["--stdio", "--max-frames", "100000"]);
|
||||
c.initialize();
|
||||
boot(&mut c, &dir);
|
||||
let advance = c.send("advance", json!({"frames":100000}));
|
||||
assert_eq!(c.event()["type"], "progress");
|
||||
assert_eq!(c.call("reset", json!({}))["error"]["code"], "busy");
|
||||
c.ok("cancel", json!({"targetRequestId":advance}));
|
||||
let response = c.response(&advance);
|
||||
let result = &response["result"];
|
||||
assert_eq!(result["stop"], "canceled");
|
||||
assert!(
|
||||
result["completed"].as_u64().unwrap() >= 1
|
||||
&& result["completed"].as_u64().unwrap() < 100000
|
||||
);
|
||||
assert_eq!(c.ok("get_state", json!({}))["logicalFrameIndex"], result["completed"]);
|
||||
assert_eq!(
|
||||
c.call("cancel", json!({"targetRequestId":advance}))["error"]["code"],
|
||||
"not_cancelable"
|
||||
);
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn shutdown_and_eof_interrupt_active_work_without_resuming_it() {
|
||||
let dir = colored_cart();
|
||||
for explicit in [true, false] {
|
||||
let mut c = Client::new(&["--stdio", "--max-frames", "100000"]);
|
||||
c.initialize();
|
||||
boot(&mut c, &dir);
|
||||
let advance = c.send("advance", json!({"frames":100000}));
|
||||
assert_eq!(c.event()["type"], "progress");
|
||||
if explicit {
|
||||
let shutdown = c.send("shutdown", json!({}));
|
||||
assert_eq!(c.response(&advance)["result"]["stop"], "canceled");
|
||||
assert_eq!(c.response(&shutdown)["result"]["closed"], true);
|
||||
} else {
|
||||
c.input.take();
|
||||
assert_eq!(c.response(&advance)["result"]["stop"], "canceled");
|
||||
}
|
||||
c.wait_exit();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn idle_eof_and_truncated_eof_close_the_process() {
|
||||
for suffix in [b"".as_slice(), b"{\"requestId\":\"partial\"".as_slice()] {
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
c.raw(suffix);
|
||||
c.input.take();
|
||||
if !suffix.is_empty() {
|
||||
assert_eq!(c.event()["error"]["code"], "invalid_request");
|
||||
}
|
||||
c.wait_exit();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dispatcher_works_from_a_relocated_installation_and_other_cwd() {
|
||||
let installation = TempDir::new();
|
||||
let cwd = TempDir::new();
|
||||
let dispatcher = installation.0.join(if cfg!(windows) { "prometeu.exe" } else { "prometeu" });
|
||||
let headless = installation.0.join(if cfg!(windows) {
|
||||
"prometeu-headless.exe"
|
||||
} else {
|
||||
"prometeu-headless"
|
||||
});
|
||||
fs::copy(env!("CARGO_BIN_EXE_prometeu"), &dispatcher).unwrap();
|
||||
fs::copy(env!("CARGO_BIN_EXE_prometeu-headless"), &headless).unwrap();
|
||||
let mut c = Client::spawn(
|
||||
&dispatcher,
|
||||
&[
|
||||
"headless",
|
||||
"--stdio",
|
||||
"--max-frames",
|
||||
"17",
|
||||
"--max-command-bytes",
|
||||
"8192",
|
||||
"--max-response-bytes",
|
||||
"16384",
|
||||
"--handshake-timeout-ms",
|
||||
"1234",
|
||||
"--call-timeout-ms",
|
||||
"2345",
|
||||
"--shutdown-timeout-ms",
|
||||
"3456",
|
||||
],
|
||||
Some(&cwd.0),
|
||||
);
|
||||
assert_eq!(
|
||||
c.hello["limits"],
|
||||
json!({"maxFrames":17,"maxCommandBytes":8192,"maxResponseBytes":16384,
|
||||
"handshakeTimeoutMs":1234,"callTimeoutMs":2345,"shutdownTimeoutMs":3456})
|
||||
);
|
||||
c.initialize();
|
||||
c.close();
|
||||
let help = Command::new(&dispatcher).arg("--help").output().unwrap();
|
||||
let help = String::from_utf8(help.stdout).unwrap();
|
||||
for name in ["run", "debug", "headless"] {
|
||||
assert!(help.contains(name));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_binary_and_invalid_cli_limits_fail_explicitly() {
|
||||
let installation = TempDir::new();
|
||||
let dispatcher = installation.0.join(if cfg!(windows) { "prometeu.exe" } else { "prometeu" });
|
||||
fs::copy(env!("CARGO_BIN_EXE_prometeu"), &dispatcher).unwrap();
|
||||
let result = Command::new(&dispatcher).args(["headless", "--stdio"]).output().unwrap();
|
||||
assert!(!result.status.success());
|
||||
assert!(String::from_utf8_lossy(&result.stderr).contains("headless"));
|
||||
for args in
|
||||
[vec!["--stdio", "--max-frames", "0"], vec!["--stdio", "--max-response-bytes", "1"], vec![]]
|
||||
{
|
||||
let result =
|
||||
Command::new(env!("CARGO_BIN_EXE_prometeu-headless")).args(args).output().unwrap();
|
||||
assert!(!result.status.success());
|
||||
assert!(result.stdout.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn schemas_and_distributed_request_fixtures_are_consistent() {
|
||||
let request: Value = serde_json::from_str(include_str!(
|
||||
"../../../../devtools/headless-protocol/request.schema.json"
|
||||
))
|
||||
.unwrap();
|
||||
let response: Value = serde_json::from_str(include_str!(
|
||||
"../../../../devtools/headless-protocol/response.schema.json"
|
||||
))
|
||||
.unwrap();
|
||||
jsonschema::meta::validate(&request).unwrap();
|
||||
jsonschema::meta::validate(&response).unwrap();
|
||||
let validator = jsonschema::validator_for(&request).unwrap();
|
||||
let valid: Vec<Value> =
|
||||
serde_json::from_str(include_str!("../../../../devtools/headless-protocol/requests.json"))
|
||||
.unwrap();
|
||||
for request in valid {
|
||||
validator.validate(&request).unwrap();
|
||||
}
|
||||
let invalid: Vec<Value> = serde_json::from_str(include_str!(
|
||||
"../../../../devtools/headless-protocol/invalid-requests.json"
|
||||
))
|
||||
.unwrap();
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
c.initialize();
|
||||
for request in invalid {
|
||||
assert!(!validator.is_valid(&request), "{request}");
|
||||
let mut bytes = serde_json::to_vec(&request).unwrap();
|
||||
bytes.push(b'\n');
|
||||
c.raw(&bytes);
|
||||
assert!(c.event().get("error").is_some(), "{request}");
|
||||
}
|
||||
c.close();
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive"]
|
||||
fn packaged_installation_smoke() {
|
||||
let installation = PathBuf::from(
|
||||
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL")
|
||||
.expect("set extracted distribution path"),
|
||||
);
|
||||
for file in [
|
||||
"prometeu",
|
||||
"prometeu-runtime",
|
||||
"prometeu-headless",
|
||||
"headless-protocol/request.schema.json",
|
||||
"headless-protocol/response.schema.json",
|
||||
"11a-headless-automation-protocol.md",
|
||||
] {
|
||||
assert!(installation.join(file).is_file(), "missing packaged {file}");
|
||||
}
|
||||
let cwd = TempDir::new();
|
||||
let dir = colored_cart();
|
||||
let mut c =
|
||||
Client::spawn(&installation.join("prometeu"), &["headless", "--stdio"], Some(&cwd.0));
|
||||
assert_eq!(c.hello["runtimeVersion"], env!("CARGO_PKG_VERSION"));
|
||||
c.initialize();
|
||||
boot(&mut c, &dir);
|
||||
c.ok("advance", json!({"frames":3}));
|
||||
let capture = c.ok("capture", json!({}));
|
||||
assert!(png_bytes(&capture).as_chunks::<4>().0.iter().all(|p| *p == [255, 0, 0, 255]));
|
||||
c.input.take();
|
||||
c.wait_exit();
|
||||
}
|
||||
Reference in New Issue
Block a user