feat(runtime): implement shared transactional memcard with async saves
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good
This commit is contained in:
@@ -0,0 +1,363 @@
|
||||
//! External SO/Hub choices prepare the snapshot before any game boot execution.
|
||||
use super::{
|
||||
MemcardService,
|
||||
image::*,
|
||||
session::Session,
|
||||
transaction::{Card, PublicationControl},
|
||||
};
|
||||
use prometeu_hal::memcard::MemcardStorage;
|
||||
use std::sync::{Arc, Mutex, mpsc};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
pub const DEFAULT_SNAPSHOT_BUDGET: usize = 5 * 1024 * 1024;
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Choice {
|
||||
Persistent,
|
||||
MemoryFresh,
|
||||
MemoryExisting,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum PreparationState {
|
||||
Idle,
|
||||
Pending,
|
||||
Ready,
|
||||
Failed(Error),
|
||||
}
|
||||
enum Prepared {
|
||||
Card(Result<Card>),
|
||||
Session(Session, Result<()>),
|
||||
Replacement(Session, Result<()>),
|
||||
Maintenance(Card, Result<()>),
|
||||
}
|
||||
pub struct Admission {
|
||||
installed: Option<Card>,
|
||||
receiver: Option<mpsc::Receiver<Prepared>>,
|
||||
admitted: Option<Instant>,
|
||||
control: Option<Arc<PublicationControl>>,
|
||||
pub state: PreparationState,
|
||||
pub snapshot_budget: usize,
|
||||
faulted: bool,
|
||||
}
|
||||
impl Default for Admission {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
installed: None,
|
||||
receiver: None,
|
||||
admitted: None,
|
||||
control: None,
|
||||
state: PreparationState::Idle,
|
||||
snapshot_budget: DEFAULT_SNAPSHOT_BUDGET,
|
||||
faulted: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl MemcardService {
|
||||
pub fn host_faulted(&self) -> bool {
|
||||
self.admission.faulted || self.session.host_faulted()
|
||||
}
|
||||
pub fn card_installed(&self) -> bool {
|
||||
self.admission.installed.is_some()
|
||||
}
|
||||
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())
|
||||
})
|
||||
}
|
||||
pub fn card_has_game(&self, app_id: u32) -> bool {
|
||||
self.admission
|
||||
.installed
|
||||
.as_ref()
|
||||
.is_some_and(|c| c.catalog.games.iter().any(|g| g.app_id == app_id))
|
||||
}
|
||||
pub fn uninstall_card(&mut self) -> Result<()> {
|
||||
if self.session.mode().is_some()
|
||||
|| self.session.has_in_flight()
|
||||
|| self.admission.receiver.is_some()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
self.admission.installed = None;
|
||||
self.admission.state = PreparationState::Idle;
|
||||
Ok(())
|
||||
}
|
||||
pub fn mount_card(&mut self, storage: Box<dyn MemcardStorage>) -> Result<()> {
|
||||
self.mount_card_with(move || Ok(storage))
|
||||
}
|
||||
pub fn mount_card_with(
|
||||
&mut self,
|
||||
open: impl FnOnce() -> Result<Box<dyn MemcardStorage>> + Send + 'static,
|
||||
) -> Result<()> {
|
||||
if self.admission.installed.is_some()
|
||||
|| self.admission.receiver.is_some()
|
||||
|| self.session.mode().is_some()
|
||||
|| self.session.has_in_flight()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.admission.faulted {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
let (tx, rx) = mpsc::channel();
|
||||
self.lane
|
||||
.submit_memcard_commit_write(move |_| {
|
||||
let _ = tx.send(Prepared::Card(open().and_then(Card::mount)));
|
||||
crate::AsyncWorkJobOutcome::Completed
|
||||
})
|
||||
.map_err(|_| Error::InvalidState)?;
|
||||
self.admission.receiver = Some(rx);
|
||||
self.admission.admitted = Some(Instant::now());
|
||||
self.admission.state = PreparationState::Pending;
|
||||
Ok(())
|
||||
}
|
||||
pub fn choose_for_game(
|
||||
&mut self,
|
||||
app_id: u32,
|
||||
count: usize,
|
||||
choice: Choice,
|
||||
created_at: u64,
|
||||
) -> Result<()> {
|
||||
if self.admission.receiver.is_some()
|
||||
|| self.session.mode().is_some()
|
||||
|| self.session.has_in_flight()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.admission.faulted {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
if choice != Choice::MemoryFresh && self.admission.installed.is_none() {
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
if Session::required_bytes(count)? > self.admission.snapshot_budget {
|
||||
return Err(Error::OutOfMemory);
|
||||
}
|
||||
if let Some(card) = &self.admission.installed {
|
||||
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.storage_read_only() || card.write_blocked {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
if count.saturating_sub(owned)
|
||||
> card.current().slots.iter().filter(|s| !s.assigned).count()
|
||||
{
|
||||
return Err(Error::NoSpace);
|
||||
}
|
||||
}
|
||||
if choice == Choice::MemoryExisting && owned == 0 {
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
}
|
||||
let handoff = Arc::new(Mutex::new(self.admission.installed.take()));
|
||||
let worker_handoff = handoff.clone();
|
||||
let control = Arc::new(PublicationControl::default());
|
||||
let worker_control = control.clone();
|
||||
let budget = self.admission.snapshot_budget;
|
||||
let (tx, rx) = mpsc::channel();
|
||||
let submitted = self.lane.submit_memcard_commit_write(move |_| {
|
||||
let mut card = worker_handoff.lock().unwrap().take();
|
||||
let mut session = Session::default();
|
||||
let result = (|| {
|
||||
if worker_control.canceled() {
|
||||
session.retain_idle_card_opt(card.take());
|
||||
return Err(Error::Canceled);
|
||||
}
|
||||
match choice {
|
||||
Choice::MemoryFresh => {
|
||||
session.start_memory_with_card(app_id, count, budget, card.take())?;
|
||||
}
|
||||
Choice::MemoryExisting => {
|
||||
session.load_card_memory(card.take().unwrap(), app_id, count, budget)?;
|
||||
}
|
||||
Choice::Persistent => {
|
||||
let mut card = card.take().unwrap();
|
||||
if card.storage_read_only() || card.write_blocked {
|
||||
session.retain_idle_card(card);
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
if card.catalog.games.iter().any(|g| g.app_id == app_id) {
|
||||
if let Err(e) = card.grow(app_id, count, &worker_control) {
|
||||
session.retain_idle_card(card);
|
||||
return Err(e);
|
||||
}
|
||||
session.load_card(card, app_id, count, budget)?;
|
||||
} else {
|
||||
session.prepare_new_card(card, app_id, count, created_at, budget)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
session.begin_boot();
|
||||
Ok(())
|
||||
})();
|
||||
let _ = tx.send(Prepared::Session(session, result));
|
||||
crate::AsyncWorkJobOutcome::Completed
|
||||
});
|
||||
if submitted.is_err() {
|
||||
self.admission.installed = handoff.lock().unwrap().take();
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
self.admission.control = Some(control);
|
||||
self.admission.receiver = Some(rx);
|
||||
self.admission.admitted = Some(Instant::now());
|
||||
self.admission.state = PreparationState::Pending;
|
||||
Ok(())
|
||||
}
|
||||
/// Whole-game removal is only available outside a resident game session.
|
||||
pub fn remove_game(&mut self, app_id: u32) -> Result<()> {
|
||||
self.maintain_card(move |card, control| card.remove_game(app_id, control))
|
||||
}
|
||||
pub fn revalidate_card(&mut self) -> Result<()> {
|
||||
self.maintain_card(|card, control| card.revalidate(control))
|
||||
}
|
||||
pub fn reintegrate_block(&mut self, block: u8) -> Result<()> {
|
||||
self.maintain_card(move |card, control| card.reintegrate(block, control))
|
||||
}
|
||||
fn maintain_card(
|
||||
&mut self,
|
||||
operation: impl FnOnce(&mut Card, &PublicationControl) -> Result<()> + Send + 'static,
|
||||
) -> Result<()> {
|
||||
if self.admission.receiver.is_some()
|
||||
|| self.session.mode().is_some()
|
||||
|| self.session.has_in_flight()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.admission.faulted {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
let card = self.admission.installed.take().ok_or(Error::InvalidState)?;
|
||||
let handoff = Arc::new(Mutex::new(Some(card)));
|
||||
let worker = handoff.clone();
|
||||
let control = Arc::new(PublicationControl::default());
|
||||
let worker_control = control.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
if self
|
||||
.lane
|
||||
.submit_memcard_commit_write(move |_| {
|
||||
let mut card = worker.lock().unwrap().take().unwrap();
|
||||
let result = operation(&mut card, &worker_control);
|
||||
let _ = tx.send(Prepared::Maintenance(card, result));
|
||||
crate::AsyncWorkJobOutcome::Completed
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
self.admission.installed = handoff.lock().unwrap().take();
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
self.admission.control = Some(control);
|
||||
self.admission.receiver = Some(rx);
|
||||
self.admission.admitted = Some(Instant::now());
|
||||
self.admission.state = PreparationState::Pending;
|
||||
Ok(())
|
||||
}
|
||||
/// Caller must suspend gameplay and obtain the player's keep-RAM/load-existing choice.
|
||||
/// Once admitted, the resident continuation must wait for `PreparationState::Ready`.
|
||||
pub fn replace_card(
|
||||
&mut self,
|
||||
storage: Box<dyn MemcardStorage>,
|
||||
load_existing: bool,
|
||||
) -> Result<()> {
|
||||
if self.admission.receiver.is_some()
|
||||
|| self.session.has_in_flight()
|
||||
|| self.session.is_boot_active()
|
||||
{
|
||||
return Err(Error::Busy);
|
||||
}
|
||||
if self.admission.faulted {
|
||||
return Err(Error::ReadOnly);
|
||||
}
|
||||
let handoff = Arc::new(Mutex::new(Some(std::mem::take(&mut self.session))));
|
||||
let worker = handoff.clone();
|
||||
let control = Arc::new(PublicationControl::default());
|
||||
let worker_control = control.clone();
|
||||
let (tx, rx) = mpsc::channel();
|
||||
if self
|
||||
.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 _ = tx.send(Prepared::Replacement(session, result));
|
||||
crate::AsyncWorkJobOutcome::Completed
|
||||
})
|
||||
.is_err()
|
||||
{
|
||||
self.session = handoff.lock().unwrap().take().unwrap();
|
||||
return Err(Error::InvalidState);
|
||||
}
|
||||
self.admission.control = Some(control);
|
||||
self.admission.receiver = Some(rx);
|
||||
self.admission.admitted = Some(Instant::now());
|
||||
self.admission.state = PreparationState::Pending;
|
||||
Ok(())
|
||||
}
|
||||
pub fn poll(&mut self, now: Instant) {
|
||||
self.session.poll(now);
|
||||
if let Some(rx) = &self.admission.receiver {
|
||||
match rx.try_recv() {
|
||||
Ok(prepared) => {
|
||||
if !self.admission.faulted {
|
||||
self.admission.state = match prepared {
|
||||
Prepared::Card(Ok(card)) => {
|
||||
self.admission.installed = Some(card);
|
||||
PreparationState::Ready
|
||||
}
|
||||
Prepared::Maintenance(card, result) => {
|
||||
self.admission.installed = Some(card);
|
||||
match result {
|
||||
Ok(()) => PreparationState::Ready,
|
||||
Err(e) => PreparationState::Failed(e),
|
||||
}
|
||||
}
|
||||
Prepared::Replacement(session, result) => {
|
||||
self.session = session;
|
||||
match result {
|
||||
Ok(()) => PreparationState::Ready,
|
||||
Err(e) => PreparationState::Failed(e),
|
||||
}
|
||||
}
|
||||
Prepared::Session(session, Ok(())) => {
|
||||
self.session = session;
|
||||
PreparationState::Ready
|
||||
}
|
||||
Prepared::Card(Err(e)) => PreparationState::Failed(e),
|
||||
Prepared::Session(mut session, Err(e)) => {
|
||||
session.end_session();
|
||||
self.admission.installed = session.take_idle_card().ok().flatten();
|
||||
PreparationState::Failed(e)
|
||||
}
|
||||
};
|
||||
} else if let Prepared::Replacement(session, _) = prepared {
|
||||
self.session = session;
|
||||
}
|
||||
self.admission.receiver = None;
|
||||
self.admission.control = None;
|
||||
}
|
||||
Err(mpsc::TryRecvError::Disconnected) => {
|
||||
self.admission.state = PreparationState::Failed(Error::InvalidState);
|
||||
self.admission.receiver = None;
|
||||
}
|
||||
Err(mpsc::TryRecvError::Empty) => {
|
||||
if self.admission.admitted.is_some_and(|at| {
|
||||
now.saturating_duration_since(at) >= Duration::from_millis(500)
|
||||
}) && let Some(control) = &self.admission.control
|
||||
{
|
||||
control.cancel();
|
||||
}
|
||||
if self.admission.admitted.is_some_and(|at| {
|
||||
now.saturating_duration_since(at) >= Duration::from_secs(1)
|
||||
}) {
|
||||
self.admission.faulted = true;
|
||||
self.admission.state = PreparationState::Failed(Error::Indeterminate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.session.mode().is_none()
|
||||
&& !self.session.has_in_flight()
|
||||
&& self.admission.installed.is_none()
|
||||
&& let Ok(card) = self.session.take_idle_card()
|
||||
{
|
||||
self.admission.installed = card;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user