context.rs
cdk-rsx/crates/cdk-rsx-engine-hylix/src/context.rs
1use crate::{Error, Result, Storage};2#[cfg(not(target_family = "wasm"))]3use std::cell::{Cell, RefCell};45#[derive(Clone, Copy)]6enum Active {7 Read(*const dyn Storage),8 Write(*mut dyn Storage),9}10#[cfg(not(target_family = "wasm"))]11thread_local! {12 static ACTIVE: RefCell<Option<Active>> = const { RefCell::new(None) };13 // Separate from ACTIVE: a collection can acquire a short guard while its14 // explicit retirement already holds with_storage's exclusive byte loan.15 static NEXT_EPOCH: Cell<u64> = const { Cell::new(0) };16 static EPOCH: Cell<u64> = const { Cell::new(0) };17 static LOANS: Cell<usize> = const { Cell::new(0) };18 // IC rollback restores this flag with the entire message. A native host19 // must restore its complete image before explicitly clearing quarantine.20 static QUARANTINED: Cell<bool> = const { Cell::new(false) };21}22#[cfg(target_family = "wasm")]23mod hot;24#[cfg(target_family = "wasm")]25use hot::{ACTIVE, EPOCH, LOANS, NEXT_EPOCH, QUARANTINED};2627/// Identity of this synchronous Hylix frame, distinct even when two providers28/// allocate identical offsets and generations. No provider borrow is granted.29pub fn context_id() -> Result<u64> {30 let epoch = EPOCH.get();31 if epoch == 0 {32 Err(Error::InvalidInput("no Hylix context"))33 } else {34 Ok(epoch)35 }36}3738/// Check that all collection guards ended before a Store frame publishes its39/// buffered module records. This grants no provider borrow or allocation pin.40#[doc(hidden)]41pub fn check_no_loans() -> Result<()> {42 if LOANS.get() == 0 {43 Ok(())44 } else {45 Err(Error::InvalidInput(46 "Hylix context has live collection guards",47 ))48 }49}5051/// One collection guard in the current Hylix frame. The token carries no52/// stable pointer, owning edge or entry registry. A forgotten or escaping token53/// rejects frame finalization before the caller can receive its result.54#[must_use = "a collection guard must retain its Hylix context loan"]55pub struct ContextLoan {56 epoch: u64,57 // The capability and its TLS counter belong to this thread.58 _local: std::marker::PhantomData<std::rc::Rc<()>>,59}60impl ContextLoan {61 pub fn new() -> Result<Self> {62 let epoch = context_id()?;63 LOANS.set(LOANS.get().checked_add(1).ok_or(Error::Overflow)?);64 Ok(Self {65 epoch,66 _local: std::marker::PhantomData,67 })68 }69 pub fn context_id(&self) -> u64 {70 self.epoch71 }72 /// Check before publishing a decoded edit. A guard from an aborted frame73 /// cannot write into another provider or a later frame of the same one.74 pub fn check(&self) -> Result<()> {75 if EPOCH.get() == self.epoch {76 Ok(())77 } else {78 Err(Error::InvalidInput("stale Hylix collection guard"))79 }80 }81}82impl Drop for ContextLoan {83 fn drop(&mut self) {84 if EPOCH.get() == self.epoch {85 LOANS.set(LOANS.get().checked_sub(1).expect("Hylix context loan"));86 }87 }88}8990/// Restore native test-host access after an aborted frame. No production Wasm91/// bypass exists: the IC owns rollback of both stable bytes and transient TLS.92///93/// # Safety94/// The host must first restore the complete provider image and its dependent95/// native state. Every guard from the aborted frame must remain invalid. This96/// function is never a way to recover from a partially committed mutation.97#[cfg(not(target_family = "wasm"))]98pub unsafe fn reset_context_after_rollback() -> Result<()> {99 if EPOCH.get() != 0 {100 return Err(Error::InvalidInput("Hylix context still active"));101 }102 QUARANTINED.set(false);103 Ok(())104}105106struct Reset;107impl Drop for Reset {108 fn drop(&mut self) {109 if LOANS.get() != 0 {110 QUARANTINED.set(true);111 }112 // This frame is over, including on unwinding. Quarantine prevents any113 // fresh frame from treating a forgotten live guard as a successful end.114 EPOCH.set(0);115 LOANS.set(0);116 ACTIVE.with(|active| *active.borrow_mut() = None);117 }118}119fn enter<R>(active: Active, f: impl FnOnce() -> Result<R>) -> Result<R> {120 if QUARANTINED.get() {121 return Err(Error::InvalidInput("Hylix context requires host rollback"));122 }123 ACTIVE.with(|slot| {124 let mut slot = slot125 .try_borrow_mut()126 .map_err(|_| Error::InvalidInput("Hylix context borrowed"))?;127 if slot.is_some() {128 return Err(Error::InvalidInput("Hylix context already active"));129 }130 *slot = Some(active);131 Ok(())132 })?;133 let epoch = NEXT_EPOCH.get().checked_add(1).ok_or_else(|| {134 ACTIVE.with(|slot| *slot.borrow_mut() = None);135 Error::Overflow136 })?;137 NEXT_EPOCH.set(epoch);138 EPOCH.set(epoch);139 let _reset = Reset;140 let result = f();141 if LOANS.get() != 0 {142 QUARANTINED.set(true);143 // Do not return R: it may contain the escaped guard itself. During this144 // unwind its destructor may still release its matching current token.145 // The Wasm executor's trap hook renders string payloads; keep the146 // native typed payload for test-host rollback assertions.147 #[cfg(target_family = "wasm")]148 panic!("Hylix context has live collection guards");149 #[cfg(not(target_family = "wasm"))]150 std::panic::panic_any(Error::InvalidInput(151 "Hylix context has live collection guards",152 ));153 }154 result155}156157/// Discard on unwind; successful updates finish before disarming this guard.158/// This stores no reference that could alias the exclusive operation capability.159struct WorkingFrame {160 provider: *const dyn Storage,161 complete: bool,162}163impl Drop for WorkingFrame {164 fn drop(&mut self) {165 // SAFETY: using/using_read keep the provider alive through this guard;166 // all context operations and their borrowed views have ended first.167 if !self.complete {168 unsafe {169 (&*self.provider).frame_discard();170 }171 }172 }173}174175/// Lend one Store-owned provider for a synchronous frame, then flush only after176/// Store has completed its normal owner retirement and module publication.177pub fn using<R>(storage: &mut dyn Storage, f: impl FnOnce() -> Result<R>) -> Result<R> {178 storage.frame_begin(true)?;179 // SAFETY: both guards are local and end before the provider borrow ends.180 let pointer: *mut (dyn Storage + 'static) =181 unsafe { std::mem::transmute(storage as *mut dyn Storage) };182 let mut working = WorkingFrame {183 provider: pointer,184 complete: false,185 };186 let result = enter(Active::Write(pointer), f);187 // Ordinary returned errors finalize exactly as ordinary successful calls do.188 // Store may already have changed retained ownership. A provider publication189 // failure must abort, rather than returning into a call that could commit it.190 storage191 .frame_finish()192 .unwrap_or_else(|error| panic!("Hylix frame finalization: {error:?}"));193 working.complete = true;194 result195}196pub fn using_read<R>(storage: &dyn Storage, f: impl FnOnce() -> Result<R>) -> Result<R> {197 storage.frame_begin(false)?;198 // SAFETY: same scoped erasure; this frame can never publish stable writes.199 let pointer: *const (dyn Storage + 'static) =200 unsafe { std::mem::transmute(storage as *const dyn Storage) };201 let _working = WorkingFrame {202 provider: pointer,203 complete: false,204 };205 // A query may reuse coherent clean update buffers, but never publishes or206 // leaves newly populated Global buffers attached after this read frame.207 enter(Active::Read(pointer), f)208}209210/// A short exclusive operation. Reentrant storage access fails before another211/// reference is made; collection code must release it before invoking callbacks.212pub fn with_storage<R>(f: impl for<'a> FnOnce(&'a mut dyn Storage) -> Result<R>) -> Result<R> {213 ACTIVE.with(|active| {214 let slot = active215 .try_borrow_mut()216 .map_err(|_| Error::InvalidInput("Hylix context borrowed"))?;217 match *slot {218 Some(Active::Write(pointer)) => {219 // SAFETY: using owns the exclusive provider borrow and this220 // RefCell guard excludes all concurrent/reentrant loans.221 unsafe { f(&mut *pointer) }222 }223 Some(Active::Read(_)) => Err(Error::InvalidInput("read-only Hylix context")),224 None => Err(Error::InvalidInput("no Hylix context")),225 }226 })227}228pub fn with_storage_read<R>(f: impl for<'a> FnOnce(&'a dyn Storage) -> Result<R>) -> Result<R> {229 ACTIVE.with(|active| {230 let slot = active231 .try_borrow()232 .map_err(|_| Error::InvalidInput("Hylix context borrowed"))?;233 let pointer = match *slot {234 Some(Active::Read(pointer)) => pointer,235 Some(Active::Write(pointer)) => pointer as *const dyn Storage,236 None => return Err(Error::InvalidInput("no Hylix context")),237 };238 // SAFETY: the active scope pins its provider; shared RefCell loans239 // exclude a mutable operation for this callback's complete lifetime.240 unsafe { f(&*pointer) }241 })242}