feat(host): expose memcard controls and qualify process persistence
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good

This commit is contained in:
2026-10-30 10:10:07 +00:00
parent dcf6561ea7
commit a4bec5bc45
42 changed files with 4778 additions and 100 deletions
@@ -2,7 +2,7 @@
mod wire;
pub use wire::Limits;
use crate::{AdvanceFrameOutcome, HeadlessHost};
use crate::{AdvanceFrameOutcome, HeadlessHost, PendingWrites, TeardownPolicy};
use serde_json::{Value, json};
use std::io::{self, BufRead, Write};
use std::sync::{Arc, Mutex, mpsc};
@@ -16,7 +16,8 @@ struct Control {
}
enum Job {
Work(String, Command),
Work(String, Command, bool),
Shutdown(String, TeardownPolicy, bool, mpsc::Sender<bool>),
Stop(Option<String>),
ReadError(io::Error),
}
@@ -104,6 +105,7 @@ fn read_commands<R: BufRead, W: Write>(
limits: &Limits,
) -> io::Result<()> {
let mut initialized = false;
let mut memcard = false;
loop {
let bytes = match read_line(&mut input, limits.max_command_bytes)? {
Line::Eof => break,
@@ -142,11 +144,26 @@ fn read_commands<R: BufRead, W: Write>(
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 command.needs_memcard() && !memcard {
output.reply(
Some(&id),
Err(WireError::new(
"unsupported_capability",
"negotiate minor 1.1 and require memcard first",
)),
)?;
continue;
}
if let Command::Shutdown(params) = command {
control.lock().unwrap().canceled = true;
let (tx, rx) = mpsc::channel();
sender
.send(Job::Shutdown(id, params.policy(), memcard, tx))
.map_err(|_| io::Error::other("execution stopped"))?;
if rx.recv().map_err(|_| io::Error::other("execution stopped"))? {
return Ok(());
}
continue;
}
if let Command::Initialize(params) = command {
let result = if initialized {
@@ -159,9 +176,17 @@ fn read_commands<R: BufRead, W: Write>(
.any(|c| !CAPABILITIES.contains(&c.as_str()))
{
Err(WireError::new("unsupported_capability", "required capability unavailable"))
} else if params.protocol_version.minor == 0
&& params.required_capabilities.iter().any(|c| c == "memcard")
{
Err(WireError::new("incompatible_version", "memcard requires protocol minor >= 1"))
} else {
initialized = true;
Ok(json!({"protocolVersion":{"major":1,"minor":0},"capabilities":CAPABILITIES}))
memcard = params.protocol_version.minor >= 1
&& params.required_capabilities.iter().any(|c| c == "memcard");
Ok(
json!({"protocolVersion":{"major":1,"minor":params.protocol_version.minor.min(1)},"capabilities":CAPABILITIES}),
)
};
output.reply(Some(&id), result)?;
continue;
@@ -197,7 +222,9 @@ fn read_commands<R: BufRead, W: Write>(
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"))?;
sender
.send(Job::Work(id, command, memcard))
.map_err(|_| io::Error::other("execution stopped"))?;
}
let mut c = control.lock().unwrap();
c.canceled = true;
@@ -210,14 +237,39 @@ fn execute<W: Write>(
id: &str,
output: &Output<W>,
control: &Mutex<Control>,
memcard: bool,
) -> 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)
let result = if let Some(choice) = p.memcard_choice {
host.boot_with_memcard_choice(p.path, choice.into())
} else {
host.boot(p.path)
};
result.map(|()| wire::state(host.get_state())).map_err(wire::host_error)
}
Command::Reset => {
host.reset();
Ok(wire::state(host.get_state()))
Command::Reset(params) => host
.reset_with_policy(params.policy())
.map(|snapshot| {
let mut state = wire::state(host.get_state());
if memcard {
state["memcard"] = json!(snapshot);
}
state
})
.map_err(wire::host_error),
Command::MemcardMount(p) => {
host.mount_memcard(p).map(|s| json!(s)).map_err(wire::host_error)
}
Command::MemcardUnmount => {
host.unmount_memcard().map(|s| json!(s)).map_err(wire::host_error)
}
Command::GetMemcardState => Ok(json!(host.get_memcard_state())),
Command::MemcardReconcile => {
host.reconcile_memcard().map(|s| json!(s)).map_err(wire::host_error)
}
Command::MemcardContinueInMemory => {
host.continue_memcard_in_memory().map(|s| json!(s)).map_err(wire::host_error)
}
Command::SetInput(p) => {
host.set_input(p.into());
@@ -254,6 +306,10 @@ fn execute<W: Write>(
result["stop"] = json!("terminated");
break;
}
Ok(AdvanceFrameOutcome::ActionRequired) => {
result["stop"] = json!("action_required");
break;
}
Err(error) => {
result["stop"] = json!("host_error");
result["error"] = serde_json::to_value(wire::host_error(error))?;
@@ -283,7 +339,7 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
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},
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":1},
"runtimeVersion":runtime_version,"capabilities":CAPABILITIES,"limits":limits}),
)?;
let control = Arc::new(Mutex::new(Control::default()));
@@ -298,18 +354,58 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
}
});
let mut host = HeadlessHost::new();
while let Ok(job) = receiver.recv() {
loop {
host.poll_memcard();
let job = match receiver.recv_timeout(std::time::Duration::from_millis(5)) {
Ok(job) => job,
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
};
match job {
Job::Work(id, command) => {
let result = execute(&mut host, command, &id, &output, &control)?;
Job::Work(id, command, memcard) => {
let result = match execute(&mut host, command, &id, &output, &control, memcard) {
Ok(result) => result,
Err(error) => {
cleanup_after_loss(&mut host);
return Err(error);
}
};
// 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)?;
if let Err(error) = output.reply(Some(&id), result) {
drop(c);
cleanup_after_loss(&mut host);
return Err(error);
}
c.active = None;
c.advancing = false;
}
Job::Shutdown(id, policy, memcard, ack) => match host.shutdown(policy) {
Ok(snapshot) => {
drop(host);
let mut value = json!({"closed":true});
if memcard {
value["memcard"] = json!(snapshot);
}
output.reply(Some(&id), Ok(value))?;
let _ = ack.send(true);
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
return Ok(());
}
Err(error) => {
if let Err(error) = output.reply(Some(&id), Err(wire::host_error(error))) {
cleanup_after_loss(&mut host);
return Err(error);
}
let _ = ack.send(false);
}
},
Job::Stop(id) => {
let _ = host.shutdown(TeardownPolicy {
discard_unsaved: true,
pending_writes: PendingWrites::Cancel,
});
drop(host);
if let Some(id) = id {
output.reply(Some(&id), Ok(json!({"closed":true})))?;
@@ -317,13 +413,24 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
return Ok(());
}
Job::ReadError(error) => return Err(error),
Job::ReadError(error) => {
let _ = host.shutdown(TeardownPolicy {
discard_unsaved: true,
pending_writes: PendingWrites::Cancel,
});
return Err(error);
}
}
}
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
Ok(())
}
fn cleanup_after_loss(host: &mut HeadlessHost) {
let _ = host
.shutdown(TeardownPolicy { discard_unsaved: true, pending_writes: PendingWrites::Cancel });
}
#[cfg(test)]
mod tests {
use super::*;
@@ -369,7 +476,7 @@ mod tests {
"../../../../../devtools/headless-protocol/requests.json"
))
.unwrap();
assert_eq!(requests.len(), 11);
assert_eq!(requests.len(), 21);
for request in requests {
wire::parse(serde_json::from_value(request).unwrap()).unwrap();
}
@@ -8,7 +8,10 @@ use std::io;
#[cfg(test)]
mod fault_tests;
use crate::{CapturedFrame, HostError, HostExecutionStatus, HostState};
use crate::{
CapturedFrame, HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction,
MemcardChoice, MemcardMount, PendingWrites, TeardownPolicy,
};
pub const CAPABILITIES: &[&str] = &[
"boot",
@@ -21,6 +24,12 @@ pub const CAPABILITIES: &[&str] = &[
"get_fault",
"cancel",
"shutdown",
"memcard",
"memcard_mount",
"memcard_unmount",
"get_memcard_state",
"memcard_reconcile",
"memcard_continue_in_memory",
];
#[derive(Clone, Debug, Serialize)]
@@ -95,6 +104,33 @@ pub(super) struct Initialize {
#[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)]
@@ -155,7 +191,12 @@ impl From<Input> for InputSignals {
pub(super) enum Command {
Initialize(Initialize),
Boot(Boot),
Reset,
Reset(Teardown),
MemcardMount(MemcardMount),
MemcardUnmount,
GetMemcardState,
MemcardReconcile,
MemcardContinueInMemory,
SetInput(Input),
ClearInput,
Advance(Advance),
@@ -163,7 +204,21 @@ pub(super) enum Command {
GetState,
GetFault,
Cancel(Cancel),
Shutdown,
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> {
@@ -192,6 +247,17 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
Command::Boot(p)
}
"advance" => Command::Advance(params(req.params)?),
"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)?;
@@ -200,15 +266,25 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
}
Command::Cancel(p)
}
"reset" | "clear_input" | "capture" | "get_state" | "get_fault" | "shutdown" => {
"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() {
"reset" => Command::Reset,
"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,
_ => Command::Shutdown,
_ => unreachable!(),
}
}
_ => return Err(WireError::new("unknown_command", "unknown command")),
@@ -231,6 +307,9 @@ impl WireError {
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)}))