feat(host): expose memcard controls and qualify process persistence
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
This commit is contained in:
@@ -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)}))
|
||||
|
||||
@@ -11,6 +11,12 @@ use prometeu_hal::{
|
||||
RuntimePlatform, TelemetryPlatform, WallClock,
|
||||
};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
||||
#[path = "memcard.rs"]
|
||||
mod memcard;
|
||||
pub use memcard::{
|
||||
MediaAccess, MediaAction, MemcardChoice, MemcardFailure, MemcardMount, MemcardState,
|
||||
PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
const BOOT_TICK_LIMIT: usize = 5000;
|
||||
const HOST_FRAME_ADVANCE_TICK_LIMIT: usize = 100_000;
|
||||
@@ -46,6 +52,7 @@ pub enum AdvanceFrameOutcome {
|
||||
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -53,6 +60,7 @@ pub enum AdvanceFramesStop {
|
||||
Completed,
|
||||
Faulted(CrashReport),
|
||||
Terminated,
|
||||
ActionRequired,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
@@ -64,6 +72,7 @@ pub struct AdvanceFramesOutcome {
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum HostError {
|
||||
Memcard(Box<MemcardFailure>),
|
||||
AlreadyBooted,
|
||||
BootFailed { reason: String, report: Option<Box<CrashReport>> },
|
||||
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
||||
@@ -75,6 +84,7 @@ pub enum HostError {
|
||||
impl fmt::Display for HostError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::Memcard(error) => write!(f, "{}: {}", error.operation, error.reason),
|
||||
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
||||
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
||||
Self::InvalidState { operation, status } => {
|
||||
@@ -104,6 +114,7 @@ pub struct HeadlessHost {
|
||||
boot_attempted: bool,
|
||||
last_completed_frame: Option<CompletedFrame>,
|
||||
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
|
||||
media: memcard::MediaSelection,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -153,6 +164,7 @@ impl HeadlessHost {
|
||||
boot_attempted: false,
|
||||
last_completed_frame: None,
|
||||
controlled_wall_clock,
|
||||
media: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -189,15 +201,20 @@ impl HeadlessHost {
|
||||
return Err(HostError::AlreadyBooted);
|
||||
}
|
||||
self.boot_attempted = true;
|
||||
self.media.choice = choice;
|
||||
self.media.boot_phase = "loading";
|
||||
let path = path.into();
|
||||
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||
|
||||
let boot_deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
|
||||
let mut choice_submitted = false;
|
||||
for _ in 0..BOOT_TICK_LIMIT {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.media.boot_phase = "running";
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
let report = self.get_fault();
|
||||
let reason = report
|
||||
.as_ref()
|
||||
@@ -206,33 +223,55 @@ impl HeadlessHost {
|
||||
return Err(HostError::BootFailed { reason, report: report.map(Box::new) });
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "cartridge did not load".to_string(),
|
||||
report: None,
|
||||
});
|
||||
}
|
||||
let progress = self.firmware.os.memcard().lane.progress_stamp();
|
||||
if let FirmwareState::LoadCartridge(step) = &self.firmware.state
|
||||
&& step.cartridge.memcard_slots.is_none()
|
||||
&& choice.is_some()
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", "invalid_state"));
|
||||
}
|
||||
if choice_submitted
|
||||
&& let prometeu_system::memcard::admission::PreparationState::Failed(error) =
|
||||
self.firmware.os.memcard().admission.state
|
||||
{
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
let waiting = matches!(&self.firmware.state,FirmwareState::LoadCartridge(step) if step.needs_memcard_choice());
|
||||
if waiting {
|
||||
let Some(choice) = choice else {
|
||||
return Err(HostError::BootFailed {
|
||||
reason: "Memory-card choice required; use boot_with_memcard_choice".into(),
|
||||
report: None,
|
||||
});
|
||||
self.media.boot_phase = "choice_required";
|
||||
return Err(self.memcard_error("boot", "choice_required"));
|
||||
};
|
||||
self.signals = InputSignals::default();
|
||||
self.tick_once();
|
||||
self.signals = match choice {
|
||||
prometeu_system::memcard::admission::Choice::Persistent => {
|
||||
InputSignals { a_signal: true, ..Default::default() }
|
||||
}
|
||||
prometeu_system::memcard::admission::Choice::MemoryFresh => {
|
||||
InputSignals { x_signal: true, ..Default::default() }
|
||||
}
|
||||
prometeu_system::memcard::admission::Choice::MemoryExisting => {
|
||||
InputSignals { y_signal: true, ..Default::default() }
|
||||
if self.firmware.os.memcard().preparation_active() {
|
||||
self.poll_memcard();
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.lane
|
||||
.wait_for_progress(progress, std::time::Duration::from_millis(5));
|
||||
continue;
|
||||
}
|
||||
let created_at = self.platform.wall_clock().utc_unix_seconds();
|
||||
let result = match &mut self.firmware.state {
|
||||
FirmwareState::LoadCartridge(step) => {
|
||||
step.choose_memcard(&mut self.firmware.os, choice, created_at)
|
||||
}
|
||||
_ => unreachable!(),
|
||||
};
|
||||
if let Err(error) = result {
|
||||
self.media.boot_phase = "failed";
|
||||
return Err(self.memcard_error("boot", memcard::error_name(error)));
|
||||
}
|
||||
choice_submitted = true;
|
||||
self.media.boot_phase = "preparing";
|
||||
}
|
||||
self.tick_once();
|
||||
self.signals = InputSignals::default();
|
||||
@@ -251,6 +290,7 @@ impl HeadlessHost {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
Ok(())
|
||||
} else {
|
||||
self.media.boot_phase = "failed";
|
||||
Err(HostError::BootFailed {
|
||||
reason: "boot did not reach the game".to_string(),
|
||||
report: self.get_fault().map(Box::new),
|
||||
@@ -258,7 +298,10 @@ impl HeadlessHost {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
pub fn reset(&mut self) -> Result<(), HostError> {
|
||||
self.reset_with_policy(TeardownPolicy::default()).map(|_| ())
|
||||
}
|
||||
fn reset_inner(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
self.firmware.change_state(
|
||||
FirmwareState::Reset(ResetStep),
|
||||
@@ -296,7 +339,11 @@ impl HeadlessHost {
|
||||
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let start = self.firmware.os.vm().logical_frame_index();
|
||||
@@ -305,6 +352,11 @@ impl HeadlessHost {
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
|
||||
for _ in 0..HOST_FRAME_ADVANCE_TICK_LIMIT {
|
||||
// A controlled lifecycle slice can consume the runtime step marker
|
||||
// without closing a logical frame. This operation still owns the
|
||||
// request until its first frame or an explicit stop boundary.
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
self.tick_once();
|
||||
if let Some(report) = self.get_fault() {
|
||||
self.finish_frame_advance();
|
||||
@@ -312,7 +364,11 @@ impl HeadlessHost {
|
||||
}
|
||||
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
self.finish_frame_advance();
|
||||
return Ok(AdvanceFrameOutcome::Terminated);
|
||||
return Ok(if self.host_action_required() {
|
||||
AdvanceFrameOutcome::ActionRequired
|
||||
} else {
|
||||
AdvanceFrameOutcome::Terminated
|
||||
});
|
||||
}
|
||||
|
||||
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
||||
@@ -360,6 +416,13 @@ impl HeadlessHost {
|
||||
stop: AdvanceFramesStop::Terminated,
|
||||
});
|
||||
}
|
||||
AdvanceFrameOutcome::ActionRequired => {
|
||||
return Ok(AdvanceFramesOutcome {
|
||||
requested: count,
|
||||
completed,
|
||||
stop: AdvanceFramesStop::ActionRequired,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
||||
@@ -416,6 +479,8 @@ impl HeadlessHost {
|
||||
fn execution_status(&mut self) -> HostExecutionStatus {
|
||||
if self.fault_is_visible() {
|
||||
HostExecutionStatus::Faulted
|
||||
} else if self.host_action_required() {
|
||||
HostExecutionStatus::Paused
|
||||
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
HostExecutionStatus::Terminated
|
||||
} else if self.firmware.os.vm().paused() {
|
||||
@@ -432,7 +497,9 @@ impl HeadlessHost {
|
||||
|
||||
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let status = self.execution_status();
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
|
||||
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused)
|
||||
&& !self.host_action_required()
|
||||
{
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::InvalidState { operation, status })
|
||||
@@ -463,6 +530,11 @@ impl RenderSubmissionSink for HeadlessPlatform {
|
||||
let frame_id = submission.frame_id;
|
||||
let ownership = submission.ownership;
|
||||
self.hardware.submit_render_submission(submission)?;
|
||||
// Host dialogs use their own producer and may reuse FrameId::ZERO.
|
||||
// Capture/advance observe only canonical game publications.
|
||||
if ownership.app_mode != prometeu_hal::app_mode::AppMode::Game {
|
||||
return Ok(());
|
||||
}
|
||||
let (width, height) = self.hardware.gfx.size();
|
||||
let pixels = self.hardware.gfx.front_buffer().to_vec();
|
||||
let frame = OwnedRgba8888Frame::packed(frame_id, ownership, width, height, pixels)
|
||||
|
||||
@@ -11,5 +11,6 @@ mod host;
|
||||
|
||||
pub use host::{
|
||||
AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost,
|
||||
HostError, HostExecutionStatus, HostState,
|
||||
HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction, MemcardChoice,
|
||||
MemcardFailure, MemcardMount, MemcardState, PendingWrites, TeardownPolicy,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,480 @@
|
||||
//! Public native host controls; all image policy stays in the shared system service.
|
||||
use super::{HeadlessHost, HostError};
|
||||
use prometeu_drivers::memcard::FileMemcard;
|
||||
use prometeu_firmware::FirmwareState;
|
||||
use prometeu_hal::memcard::{MemcardIoError, MemcardStorage};
|
||||
use prometeu_system::memcard::{
|
||||
admission::{Choice, PreparationState},
|
||||
image::{Error, IMAGE_BYTES},
|
||||
session::{Mode, RequestReason, RequestState},
|
||||
transaction::Card,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
path::PathBuf,
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MediaAction {
|
||||
Open,
|
||||
Create,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MediaAccess {
|
||||
ReadWrite,
|
||||
ReadOnly,
|
||||
}
|
||||
#[derive(Debug, Clone, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct MemcardMount {
|
||||
pub path: String,
|
||||
pub action: MediaAction,
|
||||
pub access: MediaAccess,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum PendingWrites {
|
||||
#[default]
|
||||
Wait,
|
||||
Cancel,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Default, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
|
||||
pub struct TeardownPolicy {
|
||||
pub discard_unsaved: bool,
|
||||
pub pending_writes: PendingWrites,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, Deserialize)]
|
||||
#[serde(rename_all = "snake_case")]
|
||||
pub enum MemcardChoice {
|
||||
Persistent,
|
||||
MemoryFresh,
|
||||
MemoryExisting,
|
||||
}
|
||||
impl From<MemcardChoice> for Choice {
|
||||
fn from(c: MemcardChoice) -> Self {
|
||||
match c {
|
||||
MemcardChoice::Persistent => Self::Persistent,
|
||||
MemcardChoice::MemoryFresh => Self::MemoryFresh,
|
||||
MemcardChoice::MemoryExisting => Self::MemoryExisting,
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) fn choice_name(c: Choice) -> &'static str {
|
||||
match c {
|
||||
Choice::Persistent => "persistent",
|
||||
Choice::MemoryFresh => "memory_fresh",
|
||||
Choice::MemoryExisting => "memory_existing",
|
||||
}
|
||||
}
|
||||
pub(super) fn error_name(e: Error) -> &'static str {
|
||||
match e {
|
||||
Error::Io(e) => match e {
|
||||
MemcardIoError::Unavailable => "unavailable",
|
||||
MemcardIoError::ReadOnly => "read_only",
|
||||
MemcardIoError::InvalidRange => "invalid_range",
|
||||
MemcardIoError::NoSpace => "no_space",
|
||||
MemcardIoError::Unsupported => "unsupported",
|
||||
MemcardIoError::Busy => "busy",
|
||||
MemcardIoError::AccessDenied => "access_denied",
|
||||
MemcardIoError::AlreadyExists => "already_exists",
|
||||
MemcardIoError::Indeterminate => "indeterminate",
|
||||
MemcardIoError::IoError => "io_error",
|
||||
},
|
||||
Error::Corrupt => "corrupt",
|
||||
Error::Unsupported => "unsupported",
|
||||
Error::NoSpace => "no_space",
|
||||
Error::InvalidRange => "invalid_range",
|
||||
Error::CounterExhausted => "counter_exhausted",
|
||||
Error::ReadOnly => "read_only",
|
||||
Error::Indeterminate => "indeterminate",
|
||||
Error::Busy => "busy",
|
||||
Error::Canceled => "canceled",
|
||||
Error::OutOfMemory => "out_of_memory",
|
||||
Error::AccessDenied => "access_denied",
|
||||
Error::InvalidState => "invalid_state",
|
||||
Error::IdentityMismatch => "identity_mismatch",
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MemcardState {
|
||||
pub media: MediaState,
|
||||
pub session: SessionState,
|
||||
pub dirty: bool,
|
||||
pub dirty_slots: Vec<usize>,
|
||||
pub request: Option<RequestObservation>,
|
||||
pub io: IoState,
|
||||
pub recovery: RecoveryState,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct MediaState {
|
||||
pub path: Option<PathBuf>,
|
||||
pub card_id: Option<String>,
|
||||
pub access: Option<MediaAccess>,
|
||||
pub mount_epoch: String,
|
||||
pub preparation: &'static str,
|
||||
pub error: Option<&'static str>,
|
||||
pub recovered: bool,
|
||||
pub degraded: bool,
|
||||
pub write_blocked: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct SessionState {
|
||||
pub app_id: Option<u32>,
|
||||
pub choice: Option<&'static str>,
|
||||
pub mode: Option<&'static str>,
|
||||
pub boot_attempted: bool,
|
||||
pub boot_phase: &'static str,
|
||||
pub resident: bool,
|
||||
pub action_required: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RequestObservation {
|
||||
pub id: String,
|
||||
pub state: &'static str,
|
||||
pub reason: &'static str,
|
||||
pub storage_error: Option<&'static str>,
|
||||
pub operation: &'static str,
|
||||
pub slot: Option<usize>,
|
||||
pub retained: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
pub struct IoState {
|
||||
pub active: bool,
|
||||
pub deferred: bool,
|
||||
pub phase: &'static str,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct RecoveryState {
|
||||
pub removal_pending: bool,
|
||||
pub reconciliation_required: bool,
|
||||
pub restart_required: bool,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct MemcardFailure {
|
||||
pub operation: &'static str,
|
||||
pub reason: &'static str,
|
||||
pub state: MemcardState,
|
||||
}
|
||||
#[derive(Default)]
|
||||
pub(super) struct MediaSelection {
|
||||
path: Option<PathBuf>,
|
||||
access: Option<MediaAccess>,
|
||||
card_id: Option<[u8; 16]>,
|
||||
error: Option<&'static str>,
|
||||
pub choice: Option<Choice>,
|
||||
pub boot_phase: &'static str,
|
||||
shutdown_failed: bool,
|
||||
}
|
||||
|
||||
impl HeadlessHost {
|
||||
/// Poll only native work. This does not tick firmware or execute guest code.
|
||||
pub fn poll_memcard(&mut self) {
|
||||
self.firmware.os.poll_background_io(&mut self.platform);
|
||||
}
|
||||
pub(super) fn memcard_error(
|
||||
&mut self,
|
||||
operation: &'static str,
|
||||
reason: &'static str,
|
||||
) -> HostError {
|
||||
HostError::Memcard(Box::new(MemcardFailure {
|
||||
operation,
|
||||
reason,
|
||||
state: self.get_memcard_state(),
|
||||
}))
|
||||
}
|
||||
pub fn get_memcard_state(&mut self) -> MemcardState {
|
||||
let resident = self.firmware.os.lifecycle().resident_game_task().is_some();
|
||||
let service = self.firmware.os.memcard();
|
||||
let d = service.session_diagnostics();
|
||||
let preparation = service.preparation_active();
|
||||
let host_faulted = service.host_faulted() || self.media.shutdown_failed;
|
||||
let (state, error) = match service.admission.state {
|
||||
PreparationState::Idle => ("idle", None),
|
||||
PreparationState::Pending => ("pending", None),
|
||||
PreparationState::Ready => ("ready", None),
|
||||
PreparationState::Failed(e) => ("failed", Some(error_name(e))),
|
||||
};
|
||||
let id = d.card_id.or(service.installed_card_id()).or(self.media.card_id);
|
||||
let health = if d.mode.is_some() {
|
||||
d.health
|
||||
} else {
|
||||
service.installed_health().unwrap_or((false, false, false))
|
||||
};
|
||||
let phase = if preparation {
|
||||
"preparing"
|
||||
} else if d.request.as_ref().is_some_and(|r| r.deferred) {
|
||||
"deferred"
|
||||
} else if d.io_active {
|
||||
if service.lane.telemetry().active_job_id == service.session.pending_job() {
|
||||
"running"
|
||||
} else {
|
||||
"queued"
|
||||
}
|
||||
} else if d.request.is_some() {
|
||||
"returned"
|
||||
} else {
|
||||
"idle"
|
||||
};
|
||||
MemcardState {
|
||||
media: MediaState {
|
||||
path: self.media.path.clone(),
|
||||
access: self.media.access,
|
||||
card_id: id.map(|id| id.iter().map(|v| format!("{v:02x}")).collect()),
|
||||
mount_epoch: d.epoch.to_string(),
|
||||
preparation: state,
|
||||
error: error.or(self.media.error),
|
||||
recovered: health.0,
|
||||
degraded: health.1,
|
||||
write_blocked: health.2,
|
||||
},
|
||||
session: SessionState {
|
||||
app_id: d.app_id,
|
||||
choice: self.media.choice.map(choice_name),
|
||||
mode: d.mode.map(|m| match m {
|
||||
Mode::Persistent => "persistent",
|
||||
Mode::MemoryOnly => "memory_only",
|
||||
}),
|
||||
boot_attempted: self.boot_attempted,
|
||||
boot_phase: if self.media.boot_phase.is_empty() {
|
||||
"idle"
|
||||
} else {
|
||||
self.media.boot_phase
|
||||
},
|
||||
resident,
|
||||
action_required: d.mode.is_some()
|
||||
&& resident
|
||||
&& (d.removal_pending
|
||||
|| host_faulted
|
||||
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_))),
|
||||
},
|
||||
dirty: !d.dirty_slots.is_empty(),
|
||||
dirty_slots: d.dirty_slots,
|
||||
request: d.request.map(|r| RequestObservation {
|
||||
id: r.result.id.to_string(),
|
||||
state: match r.result.state {
|
||||
RequestState::Pending => "pending",
|
||||
RequestState::Success => "success",
|
||||
RequestState::Failure => "failure",
|
||||
RequestState::Indeterminate => "indeterminate",
|
||||
RequestState::MemoryOnly => "memory_only",
|
||||
},
|
||||
reason: match r.result.reason {
|
||||
RequestReason::None => "none",
|
||||
RequestReason::Timeout => "timeout",
|
||||
RequestReason::RestartRequired => "restart_required",
|
||||
RequestReason::Storage(e) => error_name(e),
|
||||
},
|
||||
storage_error: r.storage_error.map(error_name),
|
||||
operation: r.operation,
|
||||
slot: r.slot,
|
||||
retained: r.retained,
|
||||
}),
|
||||
io: IoState {
|
||||
active: preparation || d.io_active,
|
||||
deferred: phase == "deferred",
|
||||
phase,
|
||||
},
|
||||
recovery: RecoveryState {
|
||||
removal_pending: d.removal_pending,
|
||||
reconciliation_required: d.reconciliation_required,
|
||||
restart_required: host_faulted,
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn mount_memcard(&mut self, options: MemcardMount) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if self.firmware.os.lifecycle().resident_game_task().is_some() {
|
||||
return Err(self.memcard_error("memcard_mount", "invalid_state"));
|
||||
}
|
||||
if options.path.trim().is_empty()
|
||||
|| matches!(
|
||||
(options.action, options.access),
|
||||
(MediaAction::Create, MediaAccess::ReadOnly)
|
||||
)
|
||||
{
|
||||
return Err(self.memcard_error("memcard_mount", "invalid_state"));
|
||||
}
|
||||
let path = std::path::absolute(&options.path)
|
||||
.map_err(|_| self.memcard_error("memcard_mount", "unavailable"))?;
|
||||
// Do not change selection when admission is refused as busy.
|
||||
let open_path = path.clone();
|
||||
let result = self.firmware.os.memcard().mount_card_with(move || {
|
||||
let io = match options.action {
|
||||
MediaAction::Open => {
|
||||
FileMemcard::open(&open_path, options.access == MediaAccess::ReadOnly)?
|
||||
}
|
||||
MediaAction::Create => FileMemcard::create(&open_path, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})?,
|
||||
};
|
||||
Ok(Box::new(io) as Box<dyn MemcardStorage>)
|
||||
});
|
||||
result.map_err(|e| self.memcard_error("memcard_mount", error_name(e)))?;
|
||||
self.media.path = Some(path);
|
||||
self.media.access = Some(options.access);
|
||||
self.media.error = None;
|
||||
self.media.card_id = None;
|
||||
if let Err(error) = self.wait_preparation("memcard_mount") {
|
||||
if let HostError::Memcard(e) = &error {
|
||||
self.media.error = Some(e.reason);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
self.media.card_id = self.firmware.os.memcard().installed_card_id();
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn unmount_memcard(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if self.firmware.os.lifecycle().resident_game_task().is_some() {
|
||||
return Err(self.memcard_error("memcard_unmount", "invalid_state"));
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.uninstall_card()
|
||||
.map_err(|e| self.memcard_error("memcard_unmount", error_name(e)))?;
|
||||
self.media = MediaSelection { boot_phase: self.media.boot_phase, ..Default::default() };
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
fn wait_preparation(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
self.poll_memcard();
|
||||
match self.firmware.os.memcard().admission.state {
|
||||
PreparationState::Ready => return Ok(()),
|
||||
PreparationState::Failed(e) => {
|
||||
let reason = if self.firmware.os.memcard().host_faulted() {
|
||||
"restart_required"
|
||||
} else {
|
||||
error_name(e)
|
||||
};
|
||||
return Err(self.memcard_error(operation, reason));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
return Err(self.memcard_error(operation, "restart_required"));
|
||||
}
|
||||
let lane = self.firmware.os.memcard().lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
pub fn prepare_teardown(
|
||||
&mut self,
|
||||
policy: TeardownPolicy,
|
||||
operation: &'static str,
|
||||
) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if matches!(policy.pending_writes, PendingWrites::Cancel) {
|
||||
self.firmware.os.memcard().cancel_pending();
|
||||
}
|
||||
let deadline = Instant::now() + Duration::from_secs(2);
|
||||
loop {
|
||||
self.poll_memcard();
|
||||
let state = self.get_memcard_state();
|
||||
if !state.io.active && !state.io.deferred {
|
||||
break;
|
||||
}
|
||||
if state.recovery.restart_required || Instant::now() >= deadline {
|
||||
return Err(self.memcard_error(operation, "restart_required"));
|
||||
}
|
||||
let lane = self.firmware.os.memcard().lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
if self.get_memcard_state().dirty && !policy.discard_unsaved {
|
||||
return Err(self.memcard_error(operation, "unsaved_changes"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn reset_with_policy(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
|
||||
self.prepare_teardown(policy, "reset")?;
|
||||
self.reset_inner();
|
||||
self.media.choice = None;
|
||||
self.media.boot_phase = "idle";
|
||||
self.poll_memcard();
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn shutdown(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
|
||||
let state = self.prepare_teardown(policy, "shutdown")?;
|
||||
if self.firmware.os.stop_background_io().is_err() {
|
||||
self.media.shutdown_failed = true;
|
||||
return Err(self.memcard_error("shutdown", "restart_required"));
|
||||
}
|
||||
self.firmware.os.memcard().session.end_session();
|
||||
self.firmware.os.memcard().poll(Instant::now());
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.uninstall_card()
|
||||
.map_err(|e| self.memcard_error("shutdown", error_name(e)))?;
|
||||
Ok(state)
|
||||
}
|
||||
pub fn reconcile_memcard(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if !self.suspended_for_memcard() {
|
||||
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
|
||||
}
|
||||
let path = self
|
||||
.media
|
||||
.path
|
||||
.clone()
|
||||
.ok_or_else(|| self.memcard_error("memcard_reconcile", "invalid_state"))?;
|
||||
let read_only = self.media.access == Some(MediaAccess::ReadOnly);
|
||||
self.firmware
|
||||
.os
|
||||
.memcard()
|
||||
.reconcile_card_with(move || {
|
||||
Ok(Box::new(FileMemcard::open(&path, read_only)?) as Box<dyn MemcardStorage>)
|
||||
})
|
||||
.map_err(|e| self.memcard_error("memcard_reconcile", error_name(e)))?;
|
||||
self.wait_preparation("memcard_reconcile")?;
|
||||
self.media.error = None;
|
||||
if !self.firmware.resume_resident_game_from_home() {
|
||||
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
pub fn continue_memcard_in_memory(&mut self) -> Result<MemcardState, HostError> {
|
||||
self.poll_memcard();
|
||||
if !self.suspended_for_memcard() {
|
||||
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
|
||||
}
|
||||
self.firmware
|
||||
.os
|
||||
.detach_memcard()
|
||||
.map_err(|e| self.memcard_error("memcard_continue_in_memory", error_name(e)))?;
|
||||
if !self.firmware.resume_resident_game_from_home() {
|
||||
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
|
||||
}
|
||||
Ok(self.get_memcard_state())
|
||||
}
|
||||
fn suspended_for_memcard(&mut self) -> bool {
|
||||
let Some(task) = self.firmware.os.lifecycle().resident_game_task() else { return false };
|
||||
self.firmware.os.lifecycle().task_state(task)
|
||||
== Some(prometeu_system::task::TaskState::Suspended)
|
||||
&& (self.firmware.os.memcard().session.removal_pending()
|
||||
|| self.firmware.os.memcard().session.diagnostics().reconciliation_required
|
||||
|| self.firmware.os.memcard().session.host_faulted())
|
||||
}
|
||||
pub(super) fn host_action_required(&mut self) -> bool {
|
||||
self.firmware.os.memcard().session.mode().is_some()
|
||||
&& self.firmware.os.lifecycle().resident_game_task().is_some()
|
||||
&& (self.firmware.os.memcard().session.removal_pending()
|
||||
|| self.firmware.os.memcard().host_faulted()
|
||||
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "memcard_tests.rs"]
|
||||
mod tests;
|
||||
@@ -0,0 +1,209 @@
|
||||
use super::*;
|
||||
use crate::{AdvanceFrameOutcome, HostExecutionStatus};
|
||||
use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program};
|
||||
use std::{fs, sync::mpsc};
|
||||
|
||||
struct Fixture {
|
||||
root: PathBuf,
|
||||
image: PathBuf,
|
||||
cart: PathBuf,
|
||||
}
|
||||
impl Fixture {
|
||||
fn new(kind: MemcardFixture) -> Self {
|
||||
let root = std::env::temp_dir().join(format!(
|
||||
"native-memcard-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
let cart = root.join("cart");
|
||||
fs::create_dir_all(&cart).unwrap();
|
||||
fs::write(cart.join("program.pbx"), memcard_program(kind)).unwrap();
|
||||
fs::write(cart.join("manifest.json"),r#"{"magic":"PMTU","cartridge_version":1,"app_id":42,"title":"Native memcard","app_version":"1","app_mode":"Game","capabilities":["memcard"],"memcard_slots":1}"#).unwrap();
|
||||
let image = root.join("save.pmc");
|
||||
Self { root, image, cart }
|
||||
}
|
||||
fn mount(&self, host: &mut HeadlessHost) {
|
||||
host.mount_memcard(MemcardMount {
|
||||
path: self.image.to_string_lossy().into_owned(),
|
||||
action: MediaAction::Create,
|
||||
access: MediaAccess::ReadWrite,
|
||||
})
|
||||
.unwrap();
|
||||
host.boot_with_memcard_choice(self.cart.to_string_lossy(), Choice::Persistent).unwrap();
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.root);
|
||||
}
|
||||
}
|
||||
fn settle(host: &mut HeadlessHost) {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
host.poll_memcard();
|
||||
if !host.get_memcard_state().io.active {
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "IO did not cease");
|
||||
let lane = host.firmware.os.memcard().lane.clone();
|
||||
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
|
||||
}
|
||||
}
|
||||
fn pause_for_media(host: &mut HeadlessHost) {
|
||||
let task = host.firmware.os.lifecycle().resident_game_task().unwrap();
|
||||
host.firmware.os.lifecycle().suspend_task(task).unwrap();
|
||||
assert_eq!(
|
||||
host.firmware.os.lifecycle().task_state(task),
|
||||
Some(prometeu_system::task::TaskState::Suspended)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn same_media_recovery_rejects_replacement_and_preserves_ram_continuation() {
|
||||
let f = Fixture::new(MemcardFixture::Dirty);
|
||||
let mut host = HeadlessHost::new();
|
||||
f.mount(&mut host);
|
||||
assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. }));
|
||||
settle(&mut host);
|
||||
let context = host.firmware.os.memcard().session.context();
|
||||
host.firmware.os.memcard().session.notify_removal();
|
||||
pause_for_media(&mut host);
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||
assert_eq!(host.advance_frame().unwrap(), AdvanceFrameOutcome::ActionRequired);
|
||||
let old = f.root.join("old.pmc");
|
||||
fs::rename(&f.image, &old).unwrap();
|
||||
let replacement = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})
|
||||
.unwrap();
|
||||
drop(replacement);
|
||||
let error = host.reconcile_memcard().unwrap_err();
|
||||
assert!(matches!(error,HostError::Memcard(e) if e.reason=="identity_mismatch"));
|
||||
let mut bytes = [0; 4];
|
||||
host.firmware.os.memcard().session.read(context, 0, 0, &mut bytes).unwrap();
|
||||
assert_eq!(bytes, [0, 127, 128, 255]);
|
||||
fs::rename(&f.image, f.root.join("other.pmc")).unwrap();
|
||||
fs::rename(&old, &f.image).unwrap();
|
||||
let restored = host.reconcile_memcard().unwrap();
|
||||
assert!(restored.dirty);
|
||||
assert!(!restored.recovery.reconciliation_required);
|
||||
assert_eq!(host.firmware.os.memcard().session.context(), context);
|
||||
assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. }));
|
||||
assert_eq!(host.get_state().stack_top.last(), Some(&prometeu_bytecode::Value::Int64(301)));
|
||||
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot() {
|
||||
let f = Fixture::new(MemcardFixture::Dirty);
|
||||
let mut host = HeadlessHost::new();
|
||||
f.mount(&mut host);
|
||||
host.advance_frame().unwrap();
|
||||
settle(&mut host);
|
||||
let context = host.firmware.os.memcard().session.context();
|
||||
host.firmware.os.memcard().session.notify_removal();
|
||||
pause_for_media(&mut host);
|
||||
let ram = host.continue_memcard_in_memory().unwrap();
|
||||
assert_eq!(ram.session.mode, Some("memory_only"));
|
||||
assert!(ram.dirty);
|
||||
assert_eq!(host.firmware.os.memcard().session.context(), context);
|
||||
host.advance_frame().unwrap();
|
||||
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
|
||||
}
|
||||
|
||||
struct GateStore {
|
||||
file: FileMemcard,
|
||||
inside_publication: bool,
|
||||
payload_seen: bool,
|
||||
fired: bool,
|
||||
entered: mpsc::Sender<()>,
|
||||
continue_io: mpsc::Receiver<()>,
|
||||
}
|
||||
impl MemcardStorage for GateStore {
|
||||
fn len(&self) -> Result<u64, MemcardIoError> {
|
||||
self.file.len()
|
||||
}
|
||||
fn read_only(&self) -> bool {
|
||||
false
|
||||
}
|
||||
fn read_at(&mut self, o: u64, b: &mut [u8]) -> Result<(), MemcardIoError> {
|
||||
self.file.read_at(o, b)
|
||||
}
|
||||
fn sync(&mut self) -> Result<(), MemcardIoError> {
|
||||
self.file.sync()
|
||||
}
|
||||
fn write_at(&mut self, o: u64, b: &[u8]) -> Result<(), MemcardIoError> {
|
||||
let payload = o >= prometeu_system::memcard::image::DATA_OFFSET;
|
||||
self.payload_seen |= payload;
|
||||
let publication = self.payload_seen && (o == 8192 || o == 12288);
|
||||
if !self.fired && if self.inside_publication { publication } else { payload } {
|
||||
self.fired = true;
|
||||
if self.inside_publication {
|
||||
self.file.write_at(o, b)?;
|
||||
}
|
||||
self.entered.send(()).unwrap();
|
||||
self.continue_io.recv_timeout(Duration::from_secs(10)).unwrap();
|
||||
return Err(MemcardIoError::IoError);
|
||||
}
|
||||
self.file.write_at(o, b)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile() {
|
||||
for inside_publication in [false, true] {
|
||||
let f = Fixture::new(MemcardFixture::Write);
|
||||
let file = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})
|
||||
.unwrap();
|
||||
let (entered_tx, entered) = mpsc::channel();
|
||||
let (continue_io, release_rx) = mpsc::channel();
|
||||
let mut host = HeadlessHost::new();
|
||||
host.media.path = Some(f.image.clone());
|
||||
host.media.access = Some(MediaAccess::ReadWrite);
|
||||
host.install_memcard(Box::new(GateStore {
|
||||
file,
|
||||
inside_publication,
|
||||
payload_seen: false,
|
||||
fired: false,
|
||||
entered: entered_tx,
|
||||
continue_io: release_rx,
|
||||
}))
|
||||
.unwrap();
|
||||
host.boot_with_memcard_choice(f.cart.to_string_lossy(), Choice::Persistent).unwrap();
|
||||
host.advance_frame().unwrap();
|
||||
entered.recv_timeout(Duration::from_secs(3)).unwrap();
|
||||
host.firmware.os.memcard().poll(Instant::now() + Duration::from_secs(2));
|
||||
let before = host.get_memcard_state();
|
||||
assert!(before.io.active);
|
||||
assert!(before.recovery.restart_required);
|
||||
assert_eq!(
|
||||
before.request.as_ref().unwrap().state,
|
||||
if inside_publication { "indeterminate" } else { "failure" }
|
||||
);
|
||||
assert!(
|
||||
matches!(host.shutdown(TeardownPolicy{discard_unsaved:true,..Default::default()}),Err(HostError::Memcard(e)) if e.reason=="restart_required")
|
||||
);
|
||||
assert!(matches!(FileMemcard::open(&f.image, false), Err(MemcardIoError::Busy)));
|
||||
continue_io.send(()).unwrap();
|
||||
settle(&mut host);
|
||||
let returned = host.get_memcard_state().request;
|
||||
let original = before.request.as_ref().unwrap();
|
||||
let late = returned.as_ref().unwrap();
|
||||
assert_eq!(
|
||||
(&late.id, late.state, late.reason),
|
||||
(&original.id, original.state, original.reason),
|
||||
"late completion cannot rewrite the original result"
|
||||
);
|
||||
assert_eq!(late.storage_error, Some("io_error"));
|
||||
pause_for_media(&mut host);
|
||||
let restored = host.reconcile_memcard().unwrap();
|
||||
assert_eq!(
|
||||
restored.request, returned,
|
||||
"recovery must not consume or rewrite the guest result"
|
||||
);
|
||||
assert!(!restored.recovery.restart_required);
|
||||
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -61,7 +61,7 @@ fn thousand_reset_reload_cycles_release_session_owners_and_preserve_controls() {
|
||||
));
|
||||
assert_eq!(&*host.get_state().stack_top, &[Value::Int32(73)]);
|
||||
assert!(host.get_fault().is_none());
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.firmware.os.sessions().vm_session_count(), 0);
|
||||
assert_eq!(
|
||||
observer.diagnostic_snapshot().used,
|
||||
|
||||
@@ -37,7 +37,7 @@ fn controlled_civil_time_is_independent_of_frames_pause_and_reset() {
|
||||
host.controlled_wall_clock().unwrap().set(10);
|
||||
host.advance_frame().expect("frame after clock adjustment");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
host.boot(&cartridge).expect("reboot");
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
|
||||
@@ -57,7 +57,7 @@ fn injected_civil_clock_remains_the_runtime_source_across_lifecycle() {
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), u64::MAX);
|
||||
clock.set(42);
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 42);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
clock.advance(3);
|
||||
assert_eq!(host.wall_clock().utc_unix_seconds(), 45);
|
||||
}
|
||||
@@ -290,7 +290,7 @@ fn two_runs_match_oracle() {
|
||||
fn reset_matches_fresh_host() {
|
||||
let mut host = boot_color();
|
||||
let _ = run_on(&mut host);
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||
host.boot(color_cartridge()).expect("reboot");
|
||||
@@ -357,7 +357,7 @@ fn batch_stops_early_on_fault_and_reports_partial_progress() {
|
||||
#[test]
|
||||
fn advance_after_reset_reports_termination_without_ticking() {
|
||||
let mut host = boot_color();
|
||||
host.reset();
|
||||
host.reset().expect("reset");
|
||||
let before = host.get_state().tick_index;
|
||||
|
||||
assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated);
|
||||
|
||||
Reference in New Issue
Block a user