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:
@@ -13,7 +13,8 @@ fn io_error(e: std::io::Error) -> Error {
|
||||
use std::io::ErrorKind as K;
|
||||
match e.kind() {
|
||||
K::NotFound => Error::Unavailable,
|
||||
K::PermissionDenied => Error::ReadOnly,
|
||||
K::PermissionDenied => Error::AccessDenied,
|
||||
K::AlreadyExists => Error::AlreadyExists,
|
||||
K::StorageFull => Error::NoSpace,
|
||||
K::InvalidInput | K::UnexpectedEof => Error::InvalidRange,
|
||||
K::Unsupported => Error::Unsupported,
|
||||
@@ -21,8 +22,15 @@ fn io_error(e: std::io::Error) -> Error {
|
||||
}
|
||||
}
|
||||
impl FileMemcard {
|
||||
fn lock(file: &File) -> Result<(), Error> {
|
||||
file.try_lock().map_err(|error| match error {
|
||||
std::fs::TryLockError::WouldBlock => Error::Busy,
|
||||
std::fs::TryLockError::Error(error) => io_error(error),
|
||||
})
|
||||
}
|
||||
pub fn open(path: &Path, read_only: bool) -> Result<Self, Error> {
|
||||
let file = OpenOptions::new().read(true).write(!read_only).open(path).map_err(io_error)?;
|
||||
Self::lock(&file)?;
|
||||
let length = file.metadata().map_err(io_error)?.len();
|
||||
Ok(Self { file, length, read_only })
|
||||
}
|
||||
@@ -47,7 +55,9 @@ impl FileMemcard {
|
||||
.create_new(true)
|
||||
.open(&temporary)
|
||||
.map_err(io_error)?;
|
||||
let mut published = false;
|
||||
let result = (|| {
|
||||
Self::lock(&file)?;
|
||||
let mut card = Self { file, length, read_only: false };
|
||||
let zeros = [0u8; 65_536];
|
||||
let mut offset = 0;
|
||||
@@ -64,6 +74,7 @@ impl FileMemcard {
|
||||
card.sync()?;
|
||||
// hard_link publishes without replacing a user file; parent sync makes the name durable.
|
||||
std::fs::hard_link(&temporary, path).map_err(io_error)?;
|
||||
published = true;
|
||||
File::open(parent).and_then(|f| f.sync_all()).map_err(io_error)?;
|
||||
Ok(card)
|
||||
})();
|
||||
@@ -71,10 +82,10 @@ impl FileMemcard {
|
||||
std::fs::remove_file(&temporary).and_then(|()| File::open(parent)?.sync_all());
|
||||
match result {
|
||||
Ok(card) => {
|
||||
cleanup.map_err(io_error)?;
|
||||
cleanup.map_err(|_| Error::Indeterminate)?;
|
||||
Ok(card)
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(e) => Err(if published { Error::Indeterminate } else { e }),
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
|
||||
@@ -48,6 +48,25 @@ impl LoadCartridgeStep {
|
||||
pub fn needs_memcard_choice(&self) -> bool {
|
||||
self.awaiting_memcard && !self.preparing_memcard
|
||||
}
|
||||
/// Typed host and UI admission share this single policy boundary.
|
||||
pub fn choose_memcard(
|
||||
&mut self,
|
||||
os: &mut prometeu_system::SystemOS,
|
||||
choice: prometeu_system::memcard::admission::Choice,
|
||||
created_at: u64,
|
||||
) -> prometeu_system::memcard::image::Result<()> {
|
||||
if !self.needs_memcard_choice() {
|
||||
return Err(prometeu_system::memcard::image::Error::InvalidState);
|
||||
}
|
||||
os.memcard().choose_for_game(
|
||||
self.cartridge.app_id,
|
||||
self.cartridge.memcard_slots.unwrap() as usize,
|
||||
choice,
|
||||
created_at,
|
||||
)?;
|
||||
self.preparing_memcard = true;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn new_game_switch(cartridge: Cartridge) -> Self {
|
||||
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
|
||||
@@ -128,13 +147,8 @@ impl LoadCartridgeStep {
|
||||
Choice::MemoryExisting
|
||||
};
|
||||
let created_at = ctx.platform.wall_clock().utc_unix_seconds();
|
||||
match ctx.os.memcard().choose_for_game(
|
||||
self.cartridge.app_id,
|
||||
self.cartridge.memcard_slots.unwrap() as usize,
|
||||
choice,
|
||||
created_at,
|
||||
) {
|
||||
Ok(()) => self.preparing_memcard = true,
|
||||
match self.choose_memcard(ctx.os, choice, created_at) {
|
||||
Ok(()) => {}
|
||||
Err(error) => self.memcard_message = Self::preparation_message(error),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,6 +6,10 @@ pub enum MemcardIoError {
|
||||
InvalidRange,
|
||||
NoSpace,
|
||||
Unsupported,
|
||||
Busy,
|
||||
AccessDenied,
|
||||
AlreadyExists,
|
||||
Indeterminate,
|
||||
IoError,
|
||||
}
|
||||
|
||||
|
||||
@@ -64,6 +64,14 @@ impl SystemOS {
|
||||
pub fn memcard(&mut self) -> &mut MemcardService {
|
||||
&mut self.memcard
|
||||
}
|
||||
/// A successful return confirms the shared worker has stopped and joined.
|
||||
pub fn stop_background_io(&mut self) -> Result<(), crate::AsyncWorkLaneError> {
|
||||
if let Some(controller) = &mut self.io_controller {
|
||||
controller.stop()?;
|
||||
}
|
||||
self.io_controller = None;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Host/player operations are admitted only while gameplay is suspended.
|
||||
pub fn replace_memcard(
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! shared IO worker owns storage during a publication. Legacy per-slot files are
|
||||
//! intentionally neither read nor migrated by this service.
|
||||
pub mod admission;
|
||||
pub mod diagnostics;
|
||||
pub mod guest;
|
||||
pub mod image;
|
||||
pub mod session;
|
||||
|
||||
@@ -37,6 +37,7 @@ pub struct Admission {
|
||||
pub state: PreparationState,
|
||||
pub snapshot_budget: usize,
|
||||
faulted: bool,
|
||||
replacement_observation: Option<super::diagnostics::SessionDiagnostics>,
|
||||
}
|
||||
impl Default for Admission {
|
||||
fn default() -> Self {
|
||||
@@ -48,10 +49,26 @@ impl Default for Admission {
|
||||
state: PreparationState::Idle,
|
||||
snapshot_budget: DEFAULT_SNAPSHOT_BUDGET,
|
||||
faulted: false,
|
||||
replacement_observation: None,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl MemcardService {
|
||||
pub fn session_diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
|
||||
self.admission.replacement_observation.clone().unwrap_or_else(|| self.session.diagnostics())
|
||||
}
|
||||
pub fn preparation_active(&self) -> bool {
|
||||
self.admission.receiver.is_some()
|
||||
}
|
||||
pub fn installed_card_id(&self) -> Option<[u8; 16]> {
|
||||
self.admission.installed.as_ref().map(|c| c.current().card_id)
|
||||
}
|
||||
pub fn cancel_pending(&mut self) {
|
||||
self.session.cancel_pending();
|
||||
if let Some(control) = &self.admission.control {
|
||||
control.cancel();
|
||||
}
|
||||
}
|
||||
pub fn host_faulted(&self) -> bool {
|
||||
self.admission.faulted || self.session.host_faulted()
|
||||
}
|
||||
@@ -60,7 +77,11 @@ impl MemcardService {
|
||||
}
|
||||
pub fn installed_health(&self) -> Option<(bool, bool, bool)> {
|
||||
self.admission.installed.as_ref().map(|card| {
|
||||
(card.recovered, card.degraded, card.write_blocked || card.storage_read_only())
|
||||
(
|
||||
card.recovered,
|
||||
card.degraded,
|
||||
card.write_blocked || card.storage_read_only() || card.uncertain,
|
||||
)
|
||||
})
|
||||
}
|
||||
pub fn card_has_game(&self, app_id: u32) -> bool {
|
||||
@@ -135,6 +156,9 @@ impl MemcardService {
|
||||
let owned =
|
||||
card.catalog.games.iter().find(|g| g.app_id == app_id).map_or(0, |g| g.slots.len());
|
||||
if choice == Choice::Persistent {
|
||||
if card.uncertain {
|
||||
return Err(Error::Indeterminate);
|
||||
}
|
||||
if card.storage_read_only() || card.write_blocked {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
@@ -171,6 +195,10 @@ impl MemcardService {
|
||||
}
|
||||
Choice::Persistent => {
|
||||
let mut card = card.take().unwrap();
|
||||
if card.uncertain {
|
||||
session.retain_idle_card(card);
|
||||
return Err(Error::Indeterminate);
|
||||
}
|
||||
if card.storage_read_only() || card.write_blocked {
|
||||
session.retain_idle_card(card);
|
||||
return Err(Error::ReadOnly);
|
||||
@@ -256,9 +284,24 @@ impl MemcardService {
|
||||
&mut self,
|
||||
storage: Box<dyn MemcardStorage>,
|
||||
load_existing: bool,
|
||||
) -> Result<()> {
|
||||
self.replace_card_job(move |session, control| {
|
||||
session.replace_storage(storage, load_existing, control)
|
||||
})
|
||||
}
|
||||
pub fn reconcile_card_with(
|
||||
&mut self,
|
||||
open: impl FnOnce() -> Result<Box<dyn MemcardStorage>> + Send + 'static,
|
||||
) -> Result<()> {
|
||||
self.replace_card_job(move |session, control| session.reconcile_storage_with(open, control))
|
||||
}
|
||||
fn replace_card_job(
|
||||
&mut self,
|
||||
operation: impl FnOnce(&mut Session, &PublicationControl) -> Result<()> + Send + 'static,
|
||||
) -> Result<()> {
|
||||
if self.admission.receiver.is_some()
|
||||
|| self.session.has_in_flight()
|
||||
|| self.session.io_active()
|
||||
|| self.session.has_deferred_write()
|
||||
|| self.session.is_boot_active()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
@@ -266,6 +309,7 @@ impl MemcardService {
|
||||
if self.admission.faulted {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
self.admission.replacement_observation = Some(self.session.diagnostics());
|
||||
let handoff = Arc::new(Mutex::new(Some(std::mem::take(&mut self.session))));
|
||||
let worker = handoff.clone();
|
||||
let control = Arc::new(PublicationControl::default());
|
||||
@@ -275,13 +319,14 @@ impl MemcardService {
|
||||
.lane
|
||||
.submit_memcard_commit_write(move |_| {
|
||||
let mut session = worker.lock().unwrap().take().unwrap();
|
||||
let result = session.replace_storage(storage, load_existing, &worker_control);
|
||||
let result = operation(&mut session, &worker_control);
|
||||
let _ = tx.send(Prepared::Replacement(session, result));
|
||||
crate::AsyncWorkJobOutcome::Completed
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
self.session = handoff.lock().unwrap().take().unwrap();
|
||||
self.admission.replacement_observation = None;
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
self.admission.control = Some(control);
|
||||
@@ -331,6 +376,7 @@ impl MemcardService {
|
||||
}
|
||||
self.admission.receiver = None;
|
||||
self.admission.control = None;
|
||||
self.admission.replacement_observation = None;
|
||||
}
|
||||
Err(mpsc::TryRecvError::Disconnected) => {
|
||||
self.admission.state = PreparationState::Failed(Error::InvalidState);
|
||||
@@ -361,3 +407,37 @@ impl MemcardService {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use prometeu_drivers::memcard::FileMemcard;
|
||||
use prometeu_hal::memcard::MemcardIoError;
|
||||
|
||||
#[test]
|
||||
fn idle_uncertain_media_remains_blocked_before_another_persistent_admission() {
|
||||
let path = std::env::temp_dir().join(format!(
|
||||
"memcard-uncertain-idle-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
let io = FileMemcard::create(&path, IMAGE_BYTES, |io, id| {
|
||||
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
|
||||
})
|
||||
.unwrap();
|
||||
let mut card = Card::mount(Box::new(io)).unwrap();
|
||||
card.uncertain = true;
|
||||
let mut service = MemcardService::new();
|
||||
// An ended session returns its backend to the same installed-card state.
|
||||
service.admission.installed = Some(card);
|
||||
assert_eq!(service.installed_health(), Some((false, false, true)));
|
||||
assert_eq!(
|
||||
service.choose_for_game(42, 1, Choice::Persistent, 0),
|
||||
Err(Error::Indeterminate)
|
||||
);
|
||||
assert!(service.card_installed());
|
||||
assert_eq!(service.lane.pending_depth(), 0);
|
||||
service.uninstall_card().unwrap();
|
||||
std::fs::remove_file(path).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Read-only native observations. These do not consume the guest request entry.
|
||||
use super::{
|
||||
image::Error,
|
||||
session::{Mode, RequestResult},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct RequestDiagnostics {
|
||||
pub result: RequestResult,
|
||||
pub storage_error: Option<Error>,
|
||||
pub slot: Option<usize>,
|
||||
pub operation: &'static str,
|
||||
pub retained: bool,
|
||||
pub io_active: bool,
|
||||
pub deferred: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct SessionDiagnostics {
|
||||
pub app_id: Option<u32>,
|
||||
pub card_id: Option<[u8; 16]>,
|
||||
pub epoch: u64,
|
||||
pub mode: Option<Mode>,
|
||||
pub health: (bool, bool, bool),
|
||||
pub dirty_slots: Vec<usize>,
|
||||
pub request: Option<RequestDiagnostics>,
|
||||
pub io_active: bool,
|
||||
pub removal_pending: bool,
|
||||
pub reconciliation_required: bool,
|
||||
pub restart_required: bool,
|
||||
}
|
||||
@@ -31,12 +31,14 @@ pub fn status(e: Error) -> i64 {
|
||||
use prometeu_hal::memcard::MemcardIoError as I;
|
||||
match e {
|
||||
Error::NoSpace | Error::Io(I::NoSpace) => 3,
|
||||
Error::AccessDenied => 4,
|
||||
Error::AccessDenied
|
||||
| Error::IdentityMismatch
|
||||
| Error::Io(I::AccessDenied | I::AlreadyExists) => 4,
|
||||
Error::Corrupt => 5,
|
||||
Error::Indeterminate => 6,
|
||||
Error::Indeterminate | Error::Io(I::Indeterminate) => 6,
|
||||
Error::Io(I::Unavailable) => 7,
|
||||
Error::InvalidState | Error::Canceled => 8,
|
||||
Error::Busy => 9,
|
||||
Error::Busy | Error::Io(I::Busy) => 9,
|
||||
Error::ReadOnly | Error::CounterExhausted | Error::Io(I::ReadOnly) => 10,
|
||||
Error::InvalidRange | Error::Io(I::InvalidRange) => 11,
|
||||
Error::Unsupported | Error::Io(I::Unsupported) => 12,
|
||||
|
||||
@@ -29,6 +29,7 @@ pub enum Error {
|
||||
OutOfMemory,
|
||||
AccessDenied,
|
||||
InvalidState,
|
||||
IdentityMismatch,
|
||||
}
|
||||
impl From<MemcardIoError> for Error {
|
||||
fn from(e: MemcardIoError) -> Self {
|
||||
|
||||
@@ -71,12 +71,14 @@ struct Request {
|
||||
job: AsyncWorkJobId,
|
||||
released: bool,
|
||||
saves_payload: bool,
|
||||
worker_returned: bool,
|
||||
}
|
||||
/// Main-lane control; the Card moves into the single worker while its source is protected.
|
||||
#[derive(Default)]
|
||||
pub struct Session {
|
||||
card_id: Option<[u8; 16]>,
|
||||
uncertain_target: Option<Map>,
|
||||
known_card_exclusions: Option<([u8; 16], [bool; BLOCK_COUNT])>,
|
||||
health: (bool, bool, bool),
|
||||
context: u64,
|
||||
epoch: u64,
|
||||
@@ -100,6 +102,82 @@ pub struct Session {
|
||||
deferred: Option<(u64, usize, u64, Instant)>,
|
||||
}
|
||||
impl Session {
|
||||
/// IO ownership, independent of a completed result retained for guest release.
|
||||
pub fn io_active(&self) -> bool {
|
||||
self.request.as_ref().is_some_and(|r| !r.worker_returned)
|
||||
}
|
||||
pub fn has_deferred_write(&self) -> bool {
|
||||
self.deferred.is_some()
|
||||
}
|
||||
pub fn cancel_pending(&mut self) {
|
||||
if let Some(r) = &self.request {
|
||||
r.control.cancel();
|
||||
}
|
||||
if let Some((id, local, ..)) = self.deferred.take() {
|
||||
self.slots[local].protected = false;
|
||||
self.memory_result = Some(RequestResult {
|
||||
id,
|
||||
state: RequestState::Failure,
|
||||
reason: RequestReason::Storage(Error::Canceled),
|
||||
});
|
||||
}
|
||||
}
|
||||
pub fn diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
|
||||
use super::diagnostics::{RequestDiagnostics, SessionDiagnostics};
|
||||
let request = if let Some((id, local, ..)) = self.deferred {
|
||||
Some(RequestDiagnostics {
|
||||
result: RequestResult {
|
||||
id,
|
||||
state: RequestState::Pending,
|
||||
reason: RequestReason::None,
|
||||
},
|
||||
storage_error: None,
|
||||
slot: Some(local),
|
||||
operation: "commit",
|
||||
retained: true,
|
||||
io_active: false,
|
||||
deferred: true,
|
||||
})
|
||||
} else if let Some(r) = &self.request {
|
||||
Some(RequestDiagnostics {
|
||||
result: r.result,
|
||||
storage_error: r.worker_error,
|
||||
slot: r.saves_payload.then_some(r.local),
|
||||
operation: if r.saves_payload { "commit" } else { "presentation" },
|
||||
retained: !r.released,
|
||||
io_active: self.io_active(),
|
||||
deferred: false,
|
||||
})
|
||||
} else {
|
||||
self.memory_result.map(|result| RequestDiagnostics {
|
||||
result,
|
||||
storage_error: None,
|
||||
slot: None,
|
||||
operation: "commit",
|
||||
retained: true,
|
||||
io_active: false,
|
||||
deferred: false,
|
||||
})
|
||||
};
|
||||
SessionDiagnostics {
|
||||
app_id: self.mode.map(|_| self.app_id),
|
||||
card_id: self.card_id,
|
||||
epoch: self.epoch,
|
||||
mode: self.mode,
|
||||
health: self.health(),
|
||||
dirty_slots: self
|
||||
.slots
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, s)| s.data.read().ok().filter(|s| s.dirty).map(|_| i))
|
||||
.collect(),
|
||||
request,
|
||||
io_active: self.io_active(),
|
||||
removal_pending: self.removal_pending,
|
||||
reconciliation_required: self.reconcile_blocked,
|
||||
restart_required: self.faulted,
|
||||
}
|
||||
}
|
||||
pub fn context(&self) -> u64 {
|
||||
self.context
|
||||
}
|
||||
@@ -531,6 +609,7 @@ impl Session {
|
||||
job,
|
||||
released: !saves_payload,
|
||||
saves_payload,
|
||||
worker_returned: false,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
@@ -674,6 +753,7 @@ impl Session {
|
||||
job,
|
||||
released: false,
|
||||
saves_payload: true,
|
||||
worker_returned: false,
|
||||
});
|
||||
Ok(id)
|
||||
}
|
||||
@@ -692,6 +772,7 @@ impl Session {
|
||||
let Some(r) = &mut self.request else { return };
|
||||
match r.receiver.try_recv() {
|
||||
Ok(completion) => {
|
||||
r.worker_returned = true;
|
||||
r.worker_error = completion.result.error;
|
||||
let current =
|
||||
self.mode.is_some() && r.session == self.context && r.epoch == self.epoch;
|
||||
@@ -819,7 +900,7 @@ impl Session {
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
r.released = true;
|
||||
if self.card.is_some() {
|
||||
if r.worker_returned {
|
||||
self.request = None;
|
||||
}
|
||||
Ok(())
|
||||
@@ -833,7 +914,7 @@ impl Session {
|
||||
r.control.cancel();
|
||||
r.released = true;
|
||||
}
|
||||
if self.card.is_some() {
|
||||
if !self.io_active() {
|
||||
self.request = None;
|
||||
}
|
||||
self.removal_pending = false;
|
||||
@@ -869,7 +950,23 @@ impl Session {
|
||||
load_existing: bool,
|
||||
control: &PublicationControl,
|
||||
) -> Result<()> {
|
||||
if self.has_in_flight() || self.boot_active || self.mode.is_none() {
|
||||
self.replace_storage_with(move || Ok(storage), load_existing, false, control)
|
||||
}
|
||||
pub(super) fn reconcile_storage_with(
|
||||
&mut self,
|
||||
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
|
||||
control: &PublicationControl,
|
||||
) -> Result<()> {
|
||||
self.replace_storage_with(open, false, true, control)
|
||||
}
|
||||
fn replace_storage_with(
|
||||
&mut self,
|
||||
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
|
||||
load_existing: bool,
|
||||
same_only: bool,
|
||||
control: &PublicationControl,
|
||||
) -> Result<()> {
|
||||
if self.io_active() || self.deferred.is_some() || self.boot_active || self.mode.is_none() {
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.icon.is_empty()
|
||||
@@ -882,11 +979,18 @@ impl Session {
|
||||
{
|
||||
self.uncertain_target = card.attempted_publication.clone();
|
||||
}
|
||||
let known = self.card.as_ref().map(|c| (c.current().card_id, c.known_exclusions()));
|
||||
if let Some(card) = &self.card {
|
||||
self.known_card_exclusions = Some((card.current().card_id, card.known_exclusions()));
|
||||
}
|
||||
let known = self.known_card_exclusions;
|
||||
self.card.take(); // Release the old scratch before mounting another image.
|
||||
self.scratch = None;
|
||||
self.reconcile_blocked = true;
|
||||
self.card = Some(Card::mount(storage)?);
|
||||
let candidate = Card::mount(open()?)?;
|
||||
if same_only && self.card_id != Some(candidate.current().card_id) {
|
||||
return Err(Error::IdentityMismatch);
|
||||
}
|
||||
self.card = Some(candidate);
|
||||
let card = self.card.as_mut().unwrap();
|
||||
let same = self.card_id == Some(card.current().card_id);
|
||||
if let Some((id, known)) = known
|
||||
@@ -973,14 +1077,15 @@ impl Session {
|
||||
Ok(())
|
||||
}
|
||||
pub fn detach(&mut self) -> Result<()> {
|
||||
if self.deferred.is_some()
|
||||
|| self
|
||||
.request
|
||||
.as_ref()
|
||||
.is_some_and(|r| r.result.state == RequestState::Pending || self.card.is_none())
|
||||
{
|
||||
if self.deferred.is_some() || self.io_active() {
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.card.is_none() && self.scratch.is_none() {
|
||||
let mut scratch = Vec::new();
|
||||
scratch.try_reserve_exact(SLOT_BYTES).map_err(|_| Error::OutOfMemory)?;
|
||||
scratch.resize(SLOT_BYTES, 0);
|
||||
self.scratch = Some(scratch);
|
||||
}
|
||||
self.mode = Some(Mode::MemoryOnly);
|
||||
self.removal_pending = false;
|
||||
self.reconcile_blocked = false;
|
||||
|
||||
@@ -107,4 +107,5 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
pub mod memcard_fixture;
|
||||
pub mod program;
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
//! Neutral PBX/ABI fixture. No source-language frontend or compiler is involved.
|
||||
use crate::program::{TestProgram, scalar_catalog};
|
||||
use prometeu_bytecode::{
|
||||
assembler::assemble,
|
||||
model::{ConstantPoolEntry, SyscallDecl},
|
||||
registry::*,
|
||||
};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum MemcardFixture {
|
||||
Write,
|
||||
Read,
|
||||
Dirty,
|
||||
}
|
||||
#[derive(Default)]
|
||||
struct Code {
|
||||
bytes: Vec<u8>,
|
||||
labels: BTreeMap<&'static str, u32>,
|
||||
fixups: Vec<(usize, &'static str)>,
|
||||
}
|
||||
impl Code {
|
||||
fn emit(&mut self, text: &str) {
|
||||
self.bytes.extend(assemble(text).expect("fixture assembly"));
|
||||
}
|
||||
fn mark(&mut self, name: &'static str) {
|
||||
self.labels.insert(name, self.bytes.len() as u32);
|
||||
}
|
||||
fn jump(&mut self, op: &str, name: &'static str) {
|
||||
self.fixups.push((self.bytes.len() + 2, name));
|
||||
self.emit(&format!("{op} 0"));
|
||||
}
|
||||
fn check(&mut self, value: i64, int32: bool) {
|
||||
self.emit(&format!("PUSH_{} {value}\nEQ", if int32 { "I32" } else { "I64" }));
|
||||
let resume = self.bytes.len() + 8; // conditional jump followed by a terminal trap
|
||||
self.emit(&format!("JMP_IF_TRUE {resume}\nTRAP"));
|
||||
}
|
||||
fn finish(mut self) -> Vec<u8> {
|
||||
for (offset, label) in self.fixups {
|
||||
self.bytes[offset..offset + 4].copy_from_slice(&self.labels[label].to_le_bytes());
|
||||
}
|
||||
self.bytes
|
||||
}
|
||||
}
|
||||
|
||||
/// Stack oracle at a completed frame: 100 pending, 101 durable SUCCESS,
|
||||
/// 104 MEMORY_ONLY, 201 exact existing readback, 301 dirty/uncommitted RAM.
|
||||
/// Read never writes or submits a commit; a missing/wrong payload traps.
|
||||
pub fn memcard_program(kind: MemcardFixture) -> Vec<u8> {
|
||||
let mut main = Code::default();
|
||||
main.emit("HOSTCALL 0");
|
||||
main.check(0, true);
|
||||
main.emit("PUSH_I64 4\nARRAY_NEW 9\nSET_GLOBAL 1");
|
||||
if matches!(kind, MemcardFixture::Read) {
|
||||
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL 1");
|
||||
main.check(4, false);
|
||||
main.check(0, false);
|
||||
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
|
||||
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nARRAY_GET 9"));
|
||||
main.check(value, true);
|
||||
}
|
||||
main.mark("done");
|
||||
main.emit("PUSH_I64 201\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "done");
|
||||
} else {
|
||||
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
|
||||
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nPUSH_I32 {value}\nARRAY_SET 9"));
|
||||
}
|
||||
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL 2");
|
||||
main.check(4, false);
|
||||
main.check(0, false);
|
||||
if matches!(kind, MemcardFixture::Dirty) {
|
||||
main.mark("done");
|
||||
main.emit("PUSH_I64 301\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "done");
|
||||
} else {
|
||||
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nHOSTCALL 3\nSET_GLOBAL 2");
|
||||
main.check(0, false);
|
||||
main.mark("query");
|
||||
main.emit("GET_GLOBAL 0\nGET_GLOBAL 2\nHOSTCALL 4\nPOP_N 1\nSET_GLOBAL 3");
|
||||
main.check(0, false);
|
||||
main.emit("GET_GLOBAL 3\nPUSH_I64 100\nADD\nFRAME_SYNC\nPOP_N 1");
|
||||
main.jump("JMP", "query");
|
||||
}
|
||||
}
|
||||
main.mark("error");
|
||||
main.emit("TRAP");
|
||||
let mut code = main.finish();
|
||||
let main_len = code.len() as u32;
|
||||
let hook = if matches!(kind, MemcardFixture::Read) {
|
||||
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I32 0\nRET").unwrap()
|
||||
} else {
|
||||
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I64 560\nARRAY_NEW 9\nSET_GLOBAL 1\nGET_LOCAL 0\nPUSH_CONST 0\nPUSH_I64 1\nPUSH_I32 1\nPUSH_I32 1\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 560\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nRET").unwrap()
|
||||
};
|
||||
let hook_len = hook.len() as u32;
|
||||
code.extend(hook);
|
||||
let mut types = scalar_catalog();
|
||||
types.push(TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) });
|
||||
let mut imports = vec![("bootstrap", 0, 1)];
|
||||
if !matches!(kind, MemcardFixture::Read) {
|
||||
imports.push(("presentation", 8, 1));
|
||||
}
|
||||
match kind {
|
||||
MemcardFixture::Read => imports.push(("slot_read", 6, 2)),
|
||||
MemcardFixture::Dirty => imports.push(("slot_write", 6, 2)),
|
||||
MemcardFixture::Write => {
|
||||
imports.extend([("slot_write", 6, 2), ("slot_commit", 2, 2), ("query", 2, 3)])
|
||||
}
|
||||
}
|
||||
let syscalls = imports
|
||||
.into_iter()
|
||||
.map(|(name, arg_slots, ret_slots)| SyscallDecl {
|
||||
module: "mem".into(),
|
||||
name: name.into(),
|
||||
version: 1,
|
||||
arg_slots,
|
||||
ret_slots,
|
||||
})
|
||||
.collect();
|
||||
TestProgram {
|
||||
const_pool: vec![ConstantPoolEntry::String("Neutral persistence fixture".into())],
|
||||
code,
|
||||
functions: vec![
|
||||
FunctionDecl { code_len: main_len, max_stack_slots: 32, ..Default::default() },
|
||||
FunctionDecl {
|
||||
lifecycle_role: LifecycleRole::MemcardBoot,
|
||||
code_offset: main_len,
|
||||
code_len: hook_len,
|
||||
max_stack_slots: 32,
|
||||
signature: Signature {
|
||||
parameters: vec![NamedType { type_id: TypeId(0), name: None }],
|
||||
results: vec![TypeId(1)],
|
||||
},
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
syscalls,
|
||||
..Default::default()
|
||||
}
|
||||
.serialize_with_types(types)
|
||||
}
|
||||
@@ -63,10 +63,13 @@ impl TestProgram {
|
||||
}
|
||||
}
|
||||
pub fn serialize(&self) -> Vec<u8> {
|
||||
self.serialize_with_types(scalar_catalog())
|
||||
}
|
||||
pub fn serialize_with_types(&self, types: Vec<TypeDecl>) -> Vec<u8> {
|
||||
let mut budget = LoadBudget::new(Default::default());
|
||||
let registry = Registry::resolve(
|
||||
RegistryDeclarations {
|
||||
types: scalar_catalog(),
|
||||
types,
|
||||
functions: self.functions.clone(),
|
||||
implementations: vec![],
|
||||
},
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -2,6 +2,28 @@
|
||||
use clap::Args;
|
||||
use prometeu_host_headless::automation::Limits;
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct DesktopMediaArgs {
|
||||
/// Explicit memory-card image used by the desktop host.
|
||||
#[arg(long, value_name = "PATH")]
|
||||
pub memcard: Option<String>,
|
||||
/// Create a new image; never replace an existing destination.
|
||||
#[arg(long, requires = "memcard")]
|
||||
pub create_memcard: bool,
|
||||
}
|
||||
impl DesktopMediaArgs {
|
||||
pub fn forwarded_args(&self) -> Vec<String> {
|
||||
let mut args = Vec::new();
|
||||
if let Some(path) = &self.memcard {
|
||||
args.extend(["--memcard".into(), path.clone()]);
|
||||
}
|
||||
if self.create_memcard {
|
||||
args.push("--create-memcard".into());
|
||||
}
|
||||
args
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Args, Debug)]
|
||||
pub struct HeadlessArgs {
|
||||
/// Use the versioned JSONL stdin/stdout protocol (required).
|
||||
|
||||
@@ -25,6 +25,8 @@ enum Commands {
|
||||
Run {
|
||||
/// Path to the cartridge (directory or .pmc file).
|
||||
cart: String,
|
||||
#[command(flatten)]
|
||||
media: prometeu_cli::DesktopMediaArgs,
|
||||
},
|
||||
/// Executes a cartridge in Assisted Mode (Debug).
|
||||
/// The runtime will wait for a DevTools connection before starting.
|
||||
@@ -34,6 +36,8 @@ enum Commands {
|
||||
/// TCP port for the DevTools server (default: 7777).
|
||||
#[arg(long, default_value_t = 7777)]
|
||||
port: u16,
|
||||
#[command(flatten)]
|
||||
media: prometeu_cli::DesktopMediaArgs,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -72,15 +76,17 @@ fn main() {
|
||||
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]);
|
||||
Some(Commands::Run { cart, media }) => {
|
||||
let mut args = vec!["--run".into(), cart];
|
||||
args.extend(media.forwarded_args());
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
|
||||
}
|
||||
Some(Commands::Debug { cart, port }) => {
|
||||
dispatch(
|
||||
&exe_dir,
|
||||
"prometeu-runtime",
|
||||
&["--debug", &cart, "--port", &port.to_string()],
|
||||
);
|
||||
Some(Commands::Debug { cart, port, media }) => {
|
||||
let mut args = vec!["--debug".into(), cart, "--port".into(), port.to_string()];
|
||||
args.extend(media.forwarded_args());
|
||||
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
|
||||
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
|
||||
}
|
||||
None => {
|
||||
use clap::CommandFactory;
|
||||
|
||||
@@ -16,6 +16,8 @@ use std::sync::{
|
||||
mpsc,
|
||||
};
|
||||
use std::time::{Duration, Instant};
|
||||
#[path = "support/memcard_process.rs"]
|
||||
mod memcard_process;
|
||||
|
||||
struct TempDir(PathBuf);
|
||||
impl TempDir {
|
||||
@@ -241,7 +243,7 @@ fn png_bytes(capture: &Value) -> Vec<u8> {
|
||||
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["protocolVersion"], json!({"major":1,"minor":1}));
|
||||
assert_eq!(
|
||||
c.hello["limits"],
|
||||
json!({"maxFrames":600,"maxCommandBytes":65536,"maxResponseBytes":33554432,
|
||||
@@ -267,7 +269,7 @@ fn handshake_versions_capabilities_and_limits_are_explicit() {
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":42},"requiredCapabilities":[]})
|
||||
)["protocolVersion"]["minor"],
|
||||
0
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
use super::*;
|
||||
use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program};
|
||||
|
||||
fn card(kind: MemcardFixture, version: &str) -> TempDir {
|
||||
let dir = TempDir::new();
|
||||
fs::write(dir.0.join("program.pbx"), memcard_program(kind)).unwrap();
|
||||
fs::write(
|
||||
dir.0.join("manifest.json"),
|
||||
serde_json::to_vec(&json!({
|
||||
"magic":"PMTU","cartridge_version":1,"app_id":4294967295u32,
|
||||
"title":"Neutral persistence","app_version":version,"app_mode":"Game",
|
||||
"capabilities":["memcard"],"memcard_slots":1
|
||||
}))
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
dir
|
||||
}
|
||||
fn start_at(binary: &Path) -> Client {
|
||||
let mut c = Client::spawn(binary, &["headless", "--stdio"], Some(&std::env::temp_dir()));
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
c
|
||||
}
|
||||
fn start() -> Client {
|
||||
start_at(Path::new(env!("CARGO_BIN_EXE_prometeu")))
|
||||
}
|
||||
fn mount(c: &mut Client, path: &Path, action: &str, access: &str) -> Value {
|
||||
c.ok("memcard_mount", json!({"path":path,"action":action,"access":access}))
|
||||
}
|
||||
fn launch(c: &mut Client, dir: &TempDir, choice: &str) {
|
||||
c.ok("boot", json!({"path":dir.0,"memcardChoice":choice}));
|
||||
}
|
||||
fn oracle(c: &mut Client, expected: i64) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
loop {
|
||||
let advance = c.ok("advance", json!({"frames":1}));
|
||||
assert_eq!(
|
||||
advance["stop"],
|
||||
"completed",
|
||||
"{advance}; state={}; mem={}; fault={}",
|
||||
c.ok("get_state", json!({})),
|
||||
c.ok("get_memcard_state", json!({})),
|
||||
c.ok("get_fault", json!({}))
|
||||
);
|
||||
let state = c.ok("get_state", json!({}));
|
||||
let top = state["stackTop"].as_array().unwrap();
|
||||
if top.last().and_then(|v| v["value"].as_str()) == Some(&expected.to_string()) {
|
||||
return;
|
||||
}
|
||||
assert!(Instant::now() < deadline, "oracle {expected} not reached: {state}");
|
||||
}
|
||||
}
|
||||
fn reason(c: &mut Client, command: &str, params: Value, expected: &str) -> Value {
|
||||
let error = c.call(command, params)["error"].clone();
|
||||
assert_eq!(error["code"], "memcard_error", "{error}");
|
||||
assert_eq!(error["details"]["reason"], expected, "{error}");
|
||||
error["details"]["state"].clone()
|
||||
}
|
||||
fn persistence(binary: &Path) {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let write = card(MemcardFixture::Write, "1");
|
||||
let mut first = start_at(binary);
|
||||
let mounted = mount(&mut first, &image, "create", "read_write");
|
||||
assert_eq!(mounted["media"]["cardId"].as_str().unwrap().len(), 32);
|
||||
launch(&mut first, &write, "persistent");
|
||||
oracle(&mut first, 101);
|
||||
let saved = first.ok("get_memcard_state", json!({}));
|
||||
assert_eq!(saved["request"]["state"], "success");
|
||||
assert_eq!(saved["request"]["retained"], true);
|
||||
assert_eq!(saved["dirty"], false);
|
||||
assert_eq!(saved["io"]["active"], false);
|
||||
first.close();
|
||||
let bytes = fs::read(&image).unwrap();
|
||||
for version in ["1", "2"] {
|
||||
let read = card(MemcardFixture::Read, version);
|
||||
let mut next = start_at(binary);
|
||||
mount(&mut next, &image, "open", "read_write");
|
||||
launch(&mut next, &read, "persistent");
|
||||
oracle(&mut next, 201);
|
||||
assert_eq!(next.ok("get_state", json!({}))["appId"], 4294967295u32);
|
||||
assert_eq!(
|
||||
next.ok("get_memcard_state", json!({}))["request"],
|
||||
Value::Null,
|
||||
"reader must not submit a save"
|
||||
);
|
||||
next.close();
|
||||
assert!(fs::read(&image).unwrap() == bytes, "readback must not rewrite the image");
|
||||
}
|
||||
let read = card(MemcardFixture::Read, "2");
|
||||
let mut memory = start_at(binary);
|
||||
mount(&mut memory, &image, "open", "read_only");
|
||||
reason(&mut memory, "boot", json!({"path":read.0,"memcardChoice":"persistent"}), "read_only");
|
||||
memory.ok("reset", json!({}));
|
||||
launch(&mut memory, &read, "memory_existing");
|
||||
oracle(&mut memory, 201);
|
||||
assert_eq!(memory.ok("get_memcard_state", json!({}))["session"]["mode"], "memory_only");
|
||||
memory.close();
|
||||
assert!(fs::read(&image).unwrap() == bytes);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn memcard_public_distinct_process_save_readback_and_version_identity() {
|
||||
persistence(Path::new(env!("CARGO_BIN_EXE_prometeu")));
|
||||
}
|
||||
#[test]
|
||||
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive"]
|
||||
fn packaged_memcard_process_persistence() {
|
||||
let installation = PathBuf::from(
|
||||
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL").expect("extracted distribution"),
|
||||
);
|
||||
persistence(&installation.join("prometeu"));
|
||||
}
|
||||
#[test]
|
||||
fn memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save() {
|
||||
let dirty = card(MemcardFixture::Dirty, "1");
|
||||
let mut c = start();
|
||||
launch(&mut c, &dirty, "memory_fresh");
|
||||
oracle(&mut c, 301);
|
||||
for command in ["shutdown", "reset"] {
|
||||
let state = reason(&mut c, command, json!({}), "unsaved_changes");
|
||||
assert_eq!(state["dirty"], true);
|
||||
assert_eq!(state["session"]["resident"], true);
|
||||
assert_eq!(c.ok("get_state", json!({}))["appId"], 4294967295u32);
|
||||
}
|
||||
let reset = c.ok("reset", json!({"discardUnsaved":true,"pendingWrites":"cancel"}));
|
||||
assert_eq!(reset["memcard"]["dirty"], false);
|
||||
let write = card(MemcardFixture::Write, "1");
|
||||
launch(&mut c, &write, "memory_fresh");
|
||||
oracle(&mut c, 104);
|
||||
let state = c.ok("get_memcard_state", json!({}));
|
||||
assert_eq!(state["request"]["state"], "memory_only");
|
||||
assert_eq!(state["dirty"], true);
|
||||
assert_eq!(state["io"]["active"], false);
|
||||
assert_eq!(state["media"]["path"], Value::Null);
|
||||
c.ok("shutdown", json!({"discardUnsaved":true}));
|
||||
c.wait_exit();
|
||||
}
|
||||
#[test]
|
||||
fn memcard_media_errors_and_negotiation_never_select_a_fallback() {
|
||||
let root = TempDir::new();
|
||||
let missing = root.0.join("missing.pmc");
|
||||
let mut old = Client::new(&["--stdio"]);
|
||||
old.initialize();
|
||||
assert_eq!(
|
||||
old.call("memcard_mount", json!({"path":missing,"action":"create","access":"read_write"}))
|
||||
["error"]["code"],
|
||||
"unsupported_capability"
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
old.close();
|
||||
let mut c = Client::new(&["--stdio"]);
|
||||
assert_eq!(
|
||||
c.call(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":["memcard"]})
|
||||
)["error"]["code"],
|
||||
"incompatible_version"
|
||||
);
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":missing,"action":"open","access":"read_write"}),
|
||||
"unavailable",
|
||||
);
|
||||
assert!(!missing.exists());
|
||||
let cart = card(MemcardFixture::Write, "1");
|
||||
reason(&mut c, "boot", json!({"path":cart.0}), "choice_required");
|
||||
assert_eq!(c.ok("get_state", json!({}))["logicalFrameIndex"], 0);
|
||||
c.ok("reset", json!({}));
|
||||
let corrupt = root.0.join("corrupt.pmc");
|
||||
let mut bytes = vec![0; 5_259_264];
|
||||
bytes[..8].copy_from_slice(b"PMCARD1\0");
|
||||
bytes[8] = 1;
|
||||
fs::write(&corrupt, &bytes).unwrap();
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":corrupt,"action":"open","access":"read_write"}),
|
||||
"corrupt",
|
||||
);
|
||||
assert!(fs::read(&corrupt).unwrap() == bytes);
|
||||
assert_eq!(c.ok("get_memcard_state", json!({}))["session"]["mode"], Value::Null);
|
||||
c.close();
|
||||
}
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_process_ownership_covers_aliases_readers_and_release() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let hard = root.0.join("hard.pmc");
|
||||
let sym = root.0.join("sym.pmc");
|
||||
let mut owner = start();
|
||||
mount(&mut owner, &image, "create", "read_write");
|
||||
fs::hard_link(&image, &hard).unwrap();
|
||||
std::os::unix::fs::symlink(&image, &sym).unwrap();
|
||||
let bytes = fs::read(&image).unwrap();
|
||||
let mut contender = start();
|
||||
for path in [&image, &hard, &sym] {
|
||||
for access in ["read_only", "read_write"] {
|
||||
reason(
|
||||
&mut contender,
|
||||
"memcard_mount",
|
||||
json!({"path":path,"action":"open","access":access}),
|
||||
"busy",
|
||||
);
|
||||
}
|
||||
}
|
||||
reason(
|
||||
&mut contender,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"create","access":"read_write"}),
|
||||
"already_exists",
|
||||
);
|
||||
assert!(fs::read(&image).unwrap() == bytes);
|
||||
owner.ok("memcard_unmount", json!({}));
|
||||
mount(&mut contender, &image, "open", "read_only");
|
||||
reason(
|
||||
&mut owner,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"open","access":"read_only"}),
|
||||
"busy",
|
||||
);
|
||||
contender.close();
|
||||
mount(&mut owner, &image, "open", "read_write");
|
||||
owner.close();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_creation_race_and_process_death_release_real_ownership() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("race.pmc");
|
||||
// Kill the actual storage-owning process rather than its dispatcher parent.
|
||||
let mut a = Client::new(&["--stdio"]);
|
||||
let mut b = Client::new(&["--stdio"]);
|
||||
for c in [&mut a, &mut b] {
|
||||
c.ok(
|
||||
"initialize",
|
||||
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
|
||||
);
|
||||
}
|
||||
let params = json!({"path":image,"action":"create","access":"read_write"});
|
||||
let aid = a.send("memcard_mount", params.clone());
|
||||
let bid = b.send("memcard_mount", params);
|
||||
let ar = a.response(&aid);
|
||||
let br = b.response(&bid);
|
||||
assert_ne!(
|
||||
ar.get("result").is_some(),
|
||||
br.get("result").is_some(),
|
||||
"exactly one creator must win"
|
||||
);
|
||||
let (winner, loser, error) =
|
||||
if ar.get("result").is_some() { (&mut a, &mut b, br) } else { (&mut b, &mut a, ar) };
|
||||
assert_eq!(error["error"]["details"]["reason"], "already_exists");
|
||||
let before = fs::read(&image).unwrap();
|
||||
winner.child.kill().unwrap();
|
||||
winner.child.wait().unwrap();
|
||||
mount(loser, &image, "open", "read_write");
|
||||
loser.close();
|
||||
assert!(fs::read(&image).unwrap() == before);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn memcard_access_denial_is_typed_and_does_not_create_or_modify_media() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("denied.pmc");
|
||||
let mut creator = start();
|
||||
mount(&mut creator, &image, "create", "read_write");
|
||||
creator.close();
|
||||
let before = fs::read(&image).unwrap();
|
||||
fs::set_permissions(&image, fs::Permissions::from_mode(0o0)).unwrap();
|
||||
let mut c = start();
|
||||
reason(
|
||||
&mut c,
|
||||
"memcard_mount",
|
||||
json!({"path":image,"action":"open","access":"read_write"}),
|
||||
"access_denied",
|
||||
);
|
||||
c.close();
|
||||
fs::set_permissions(&image, fs::Permissions::from_mode(0o600)).unwrap();
|
||||
assert!(fs::read(&image).unwrap() == before);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let installation = TempDir::new();
|
||||
let dispatcher = installation.0.join("prometeu");
|
||||
fs::copy(env!("CARGO_BIN_EXE_prometeu"), &dispatcher).unwrap();
|
||||
let runtime = installation.0.join("prometeu-runtime");
|
||||
fs::write(&runtime, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n").unwrap();
|
||||
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o755)).unwrap();
|
||||
for command in ["run", "debug"] {
|
||||
let output = Command::new(&dispatcher)
|
||||
.args([command, "cartridge", "--memcard", "image with spaces.pmc", "--create-memcard"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert!(output.status.success());
|
||||
let actual = String::from_utf8(output.stdout).unwrap();
|
||||
let mut expected = vec![format!("--{command}"), "cartridge".into()];
|
||||
if command == "debug" {
|
||||
expected.extend(["--port".into(), "7777".into()]);
|
||||
}
|
||||
expected.extend([
|
||||
"--memcard".into(),
|
||||
"image with spaces.pmc".into(),
|
||||
"--create-memcard".into(),
|
||||
]);
|
||||
assert_eq!(actual.lines().collect::<Vec<_>>(), expected);
|
||||
}
|
||||
assert!(
|
||||
!Command::new(&dispatcher)
|
||||
.args(["run", "cartridge", "--create-memcard"])
|
||||
.output()
|
||||
.unwrap()
|
||||
.status
|
||||
.success()
|
||||
);
|
||||
}
|
||||
#[test]
|
||||
fn memcard_idle_observation_never_advances_guest_counters() {
|
||||
let root = TempDir::new();
|
||||
let image = root.0.join("save.pmc");
|
||||
let cart = card(MemcardFixture::Write, "1");
|
||||
let mut c = start();
|
||||
mount(&mut c, &image, "create", "read_write");
|
||||
launch(&mut c, &cart, "persistent");
|
||||
c.ok("advance", json!({"frames":1}));
|
||||
let before = c.ok("get_state", json!({}));
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
loop {
|
||||
let state = c.ok("get_memcard_state", json!({}));
|
||||
if !state["io"]["active"].as_bool().unwrap() {
|
||||
assert_eq!(state["request"]["state"], "success");
|
||||
break;
|
||||
}
|
||||
assert!(Instant::now() < deadline);
|
||||
}
|
||||
let after = c.ok("get_state", json!({}));
|
||||
for field in ["pc", "logicalFrameIndex", "tickIndex", "stackTop"] {
|
||||
assert_eq!(before[field], after[field], "{field}");
|
||||
}
|
||||
c.close();
|
||||
}
|
||||
Reference in New Issue
Block a user