Files

571 lines
19 KiB
Rust

use base64::{Engine as _, engine::general_purpose::STANDARD};
use prometeu_bytecode::Value as VmValue;
use prometeu_hal::InputSignals;
use prometeu_system::CrashReport;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io;
#[cfg(test)]
mod fault_tests;
use crate::{
CapturedFrame, HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction,
MemcardChoice, MemcardMount, PendingWrites, TeardownPolicy,
};
pub const CAPABILITIES: &[&str] = &[
"boot",
"reset",
"set_input",
"clear_input",
"advance",
"capture",
"get_state",
"get_fault",
"log_read",
"cancel",
"shutdown",
"memcard",
"memcard_mount",
"memcard_unmount",
"get_memcard_state",
"memcard_reconcile",
"memcard_continue_in_memory",
];
#[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,
#[serde(default, rename = "memcardChoice", deserialize_with = "present")]
pub memcard_choice: Option<MemcardChoice>,
}
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
T::deserialize(d).map(Some)
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
pub(super) struct Teardown {
#[serde(deserialize_with = "present")]
pub discard_unsaved: Option<bool>,
#[serde(deserialize_with = "present")]
pub pending_writes: Option<PendingWrites>,
}
impl Teardown {
pub fn explicit(&self) -> bool {
self.discard_unsaved.is_some() || self.pending_writes.is_some()
}
pub fn policy(&self) -> TeardownPolicy {
TeardownPolicy {
discard_unsaved: self.discard_unsaved.unwrap_or(false),
pending_writes: self.pending_writes.unwrap_or_default(),
}
}
}
#[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 GetLogs {
// Explicit deserializer makes the nullable field required, including on first read.
#[serde(deserialize_with = "nullable_cursor")]
pub after_sequence: Option<u64>,
pub limit: u16,
}
fn nullable_cursor<'de, D: serde::Deserializer<'de>>(d: D) -> Result<Option<u64>, D::Error> {
Option::<u64>::deserialize(d)
}
#[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(Teardown),
MemcardMount(MemcardMount),
MemcardUnmount,
GetMemcardState,
MemcardReconcile,
MemcardContinueInMemory,
SetInput(Input),
ClearInput,
Advance(Advance),
Capture,
GetState,
GetFault,
GetLogs(GetLogs),
Cancel(Cancel),
Shutdown(Teardown),
}
impl Command {
pub fn needs_memcard(&self) -> bool {
match self {
Self::MemcardMount(_)
| Self::MemcardUnmount
| Self::GetMemcardState
| Self::MemcardReconcile
| Self::MemcardContinueInMemory => true,
Self::Boot(p) => p.memcard_choice.is_some(),
Self::Reset(p) | Self::Shutdown(p) => p.explicit(),
_ => false,
}
}
}
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)?),
"get_logs" => {
let p: GetLogs = params(req.params)?;
if !(1..=1024).contains(&p.limit) {
return Err(WireError::new("invalid_params", "limit must be 1..1024"));
}
Command::GetLogs(p)
}
"reset" => Command::Reset(params(req.params)?),
"shutdown" => Command::Shutdown(params(req.params)?),
"memcard_mount" => {
let p: MemcardMount = params(req.params)?;
if p.path.trim().is_empty()
|| matches!((p.action, p.access), (MediaAction::Create, MediaAccess::ReadOnly))
{
return Err(WireError::new("invalid_params", "invalid media path/action/access"));
}
Command::MemcardMount(p)
}
"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)
}
"clear_input"
| "capture"
| "get_state"
| "get_fault"
| "memcard_unmount"
| "get_memcard_state"
| "memcard_reconcile"
| "memcard_continue_in_memory" => {
empty(&req.params)?;
match req.command.as_str() {
"memcard_unmount" => Command::MemcardUnmount,
"get_memcard_state" => Command::GetMemcardState,
"memcard_reconcile" => Command::MemcardReconcile,
"memcard_continue_in_memory" => Command::MemcardContinueInMemory,
"clear_input" => Command::ClearInput,
"capture" => Command::Capture,
"get_state" => Command::GetState,
"get_fault" => Command::GetFault,
_ => unreachable!(),
}
}
_ => 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::Memcard(e) => {
("memcard_error", json!({"operation":e.operation,"reason":e.reason,"state":e.state}))
}
HostError::AlreadyBooted => ("already_booted", json!({})),
HostError::BootFailed { reason, report } => {
("boot_failed", json!({"reason":reason,"fault":report.as_deref().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":{"index":v.index,"generation":v.generation}})
}
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 logs(
host: &crate::HeadlessHost,
params: GetLogs,
session: &str,
) -> Result<Value, WireError> {
let (events, oldest, newest) =
host.log_snapshot(params.after_sequence, usize::from(params.limit));
if params.after_sequence.is_some_and(|after| newest.is_none_or(|newest| after > newest)) {
return Err(WireError::new("invalid_cursor", "afterSequence exceeds the log stream"));
}
let gap = oldest.is_some_and(|oldest| match params.after_sequence {
None => oldest > 0,
Some(after) => after.checked_add(1).is_some_and(|next| next < oldest),
});
let next = events.last().map(|event| event.seq).or(params.after_sequence);
Ok(
json!({"sessionId":session,"logEpoch":0,"events":events.iter().map(log_event).collect::<Vec<_>>(),
"oldestSequence":oldest,"newestSequence":newest,"nextAfterSequence":next,
"gap":gap,"overflow":oldest.is_some_and(|oldest| oldest > 0)}),
)
}
fn log_event(event: &prometeu_hal::log::LogEvent) -> Value {
use prometeu_hal::log::{LogLevel, LogSource};
let level = match event.level {
LogLevel::Trace => "trace",
LogLevel::Debug => "debug",
LogLevel::Info => "info",
LogLevel::Warn => "warn",
LogLevel::Error => "error",
};
let (source, app_id) = match event.source {
LogSource::Pos => ("pos", None),
LogSource::Hub => ("hub", None),
LogSource::Vm => ("vm", None),
LogSource::Fs => ("fs", None),
LogSource::App { app_id } => ("app", Some(app_id)),
};
json!({"sequence":event.seq,"frame":event.frame,"timestampMs":event.ts_ms,
"level":level,"source":source,"appId":app_id,"tag":event.tag,"message":event.msg})
}
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,"resource":trap.resource});
}
CrashReport::VmPanic { message, .. } => {
result["message"] = json!(message);
}
CrashReport::VmInit { .. } => {
result["initError"] = report.init_diagnostic().expect("initialization report");
}
}
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()}))
}
#[cfg(test)]
mod log_tests {
use super::*;
use prometeu_hal::log::{LogEvent, LogLevel, LogSource};
#[test]
fn oversized_native_event_is_an_error_without_partial_result() {
let event = LogEvent {
seq: 0,
frame: 0,
ts_ms: 0,
level: LogLevel::Error,
source: LogSource::Vm,
tag: 0,
msg: "x".repeat(8192),
};
let output = super::super::Output {
writer: std::sync::Mutex::new(Vec::new()),
session: "session".into(),
limit: 4096,
};
output.reply(Some("logs"), Ok(json!({"events":[log_event(&event)]}))).unwrap();
let bytes = output.writer.into_inner().unwrap();
assert!(bytes.len() <= 4097);
let response: Value = serde_json::from_slice(&bytes).unwrap();
assert_eq!(response["error"]["code"], "response_too_large");
assert_eq!(response["requestId"], "logs");
assert!(response.get("result").is_none());
}
#[test]
fn native_records_preserve_unsigned_maxima_and_typed_sources() {
for (source, name, app_id) in [
(LogSource::Pos, "pos", None),
(LogSource::Hub, "hub", None),
(LogSource::Vm, "vm", None),
(LogSource::Fs, "fs", None),
(LogSource::App { app_id: u32::MAX }, "app", Some(u32::MAX)),
] {
for (level, level_name) in [
(LogLevel::Trace, "trace"),
(LogLevel::Debug, "debug"),
(LogLevel::Info, "info"),
(LogLevel::Warn, "warn"),
(LogLevel::Error, "error"),
] {
let event = LogEvent {
seq: u64::MAX,
frame: u64::MAX,
ts_ms: u64::MAX,
level,
source,
tag: u16::MAX,
msg: "complete native message".into(),
};
let encoded = log_event(&event);
let decoded: Value =
serde_json::from_slice(&serde_json::to_vec(&encoded).unwrap()).unwrap();
for key in ["sequence", "frame", "timestampMs"] {
assert_eq!(decoded[key].as_u64(), Some(u64::MAX));
}
assert_eq!(decoded["level"], level_name);
assert_eq!(decoded["source"], name);
assert_eq!(decoded["appId"], json!(app_id));
assert_eq!(decoded["tag"], u16::MAX);
assert_eq!(decoded["message"], event.msg);
}
}
}
#[test]
fn required_nullable_cursor_and_limit_reject_malformed_values() {
for value in [
json!({"limit":1}),
json!({"afterSequence":null}),
json!({"afterSequence":-1,"limit":1}),
json!({"afterSequence":1.5,"limit":1}),
json!({"afterSequence":"0","limit":1}),
json!({"afterSequence":null,"limit":0}),
json!({"afterSequence":null,"limit":1025}),
json!({"afterSequence":null,"limit":1,"filter":"app"}),
] {
assert!(
parse(Request {
request_id: "logs".into(),
command: "get_logs".into(),
params: value
})
.is_err()
);
}
assert!(
parse(Request {
request_id: "logs".into(),
command: "get_logs".into(),
params: json!({"afterSequence":u64::MAX,"limit":1024})
})
.is_ok()
);
}
}