Skip to main content

ic_storage/runtime/
mod.rs

1//! Named allocation admission and exclusive leases over the owned directory.
2mod admission;
3mod custody;
4mod directory_model;
5
6use crate::{Memory, StableKey};
7pub use admission::{
8    AdmissionError, AllocationGrants, BootstrapAdmission, GenericAllocationPolicy, MemoryAuthority,
9    MemoryRequest, PolicyIdentity, RuntimeBootstrapPolicy, SealedDeclarationSnapshot,
10};
11pub use custody::{BackingIdentity, MemoryBacking};
12pub use directory_model::Error as DirectoryError;
13use directory_model::leases::{Lease, Owner};
14pub use directory_model::{AllocationId, StorageConfig};
15use std::collections::BTreeSet;
16
17/// Construction refuses aliased or malformed backing without resetting it.
18#[derive(Debug, thiserror::Error)]
19pub enum RuntimeConstructionError {
20    /// Another runtime or detached lease retains custody.
21    #[error("backing already claimed")]
22    BackingAlreadyClaimed,
23    /// The current owned directory could not be loaded or initialized.
24    #[error(transparent)]
25    Directory(#[from] DirectoryError),
26}
27
28/// Allocation growth failures before authority publication.
29#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
30pub enum RuntimeGrowError {
31    /// Requested page arithmetic overflowed.
32    #[error("allocation page count overflow")]
33    ArithmeticOverflow,
34    /// The configured allocation or directory resource budget was exceeded.
35    #[error("allocation capacity exceeded")]
36    CapacityExceeded,
37    /// Physical backing capacity was refused.
38    #[error("backing refused growth by {additional_pages} pages")]
39    BackingRefused {
40        /// Requested additional pages.
41        additional_pages: u64,
42    },
43    /// A previous backing failure poisoned this owner.
44    #[error("allocation owner is poisoned")]
45    Poisoned,
46    /// Directory validation failed at a checked boundary.
47    #[error("allocation directory validation failed")]
48    InvalidDirectory,
49}
50
51/// A key cannot be opened until current host admission succeeds.
52#[derive(Debug, thiserror::Error)]
53pub enum RuntimeOpenError {
54    /// Bootstrap has not committed current authority.
55    #[error("runtime is not bootstrapped")]
56    NotBootstrapped,
57    /// The key is absent from the current admitted declarations.
58    #[error("key is not admitted: {0}")]
59    NotAdmitted(StableKey),
60    /// An exclusive lease for this allocation is already alive.
61    #[error("allocation {id} already open")]
62    AlreadyOpen {
63        /// Allocation with an existing lease.
64        id: u64,
65    },
66    /// The directory refused opening.
67    #[error(transparent)]
68    Directory(#[from] DirectoryError),
69}
70
71/// Bootstrap failed before current authority could be published.
72#[derive(Debug, thiserror::Error)]
73pub enum RuntimeBootstrapError<E> {
74    /// Host declarations or namespace grants were invalid.
75    #[error(transparent)]
76    Admission(#[from] AdmissionError),
77    /// The host's policy rejected the preparation or an allocation.
78    #[error("host policy rejected allocation")]
79    Policy(E),
80    /// Current bootstrap inputs differ from the established binding.
81    #[error("bootstrap binding mismatch")]
82    BindingMismatch,
83    /// A shared verification cannot bootstrap an uninitialized owner.
84    #[error("runtime is not bootstrapped")]
85    NotBootstrapped,
86    /// Durable directory commitment failed.
87    #[error(transparent)]
88    Directory(#[from] DirectoryError),
89}
90
91struct Binding {
92    source: SealedDeclarationSnapshot,
93    grants: AllocationGrants,
94    policy: PolicyIdentity,
95    admitted: BTreeSet<StableKey>,
96}
97
98///
99/// MemoryRuntime
100///
101/// One custodian of named allocations on a backing. Bootstrap validates namespace
102/// grants and host policy, commits bindings, then permits exclusive leases.
103/// Omitted retained names keep their allocation, but require current admission
104/// before opening. IDs are opaque u64 values, never selected by applications.
105///
106pub struct MemoryRuntime<M: Memory> {
107    owner: Owner<M>,
108    config: StorageConfig,
109    binding: Option<Binding>,
110}
111
112impl<M: Memory> MemoryRuntime<M> {
113    /// Claim backing and create or read its owned directory. Never reset nonempty backing.
114    pub fn new(memory: M) -> Result<Self, RuntimeConstructionError>
115    where
116        M: MemoryBacking,
117    {
118        Self::new_with_config(memory, StorageConfig::default())
119    }
120    /// Use explicit directory resource limits; reopening revalidates under those limits.
121    pub fn new_with_config(
122        memory: M,
123        config: StorageConfig,
124    ) -> Result<Self, RuntimeConstructionError>
125    where
126        M: MemoryBacking,
127    {
128        let owner = Owner::init(memory, config).map_err(|error| match error {
129            DirectoryError::AlreadyClaimed => RuntimeConstructionError::BackingAlreadyClaimed,
130            error => RuntimeConstructionError::Directory(error),
131        })?;
132        Ok(Self {
133            owner,
134            config,
135            binding: None,
136        })
137    }
138    /// Whether current host authority has been committed.
139    #[must_use]
140    pub const fn is_bootstrapped(&self) -> bool {
141        self.binding.is_some()
142    }
143    /// Current durable directory generation, after bootstrap admission.
144    pub fn committed_generation(&self) -> Result<u64, RuntimeOpenError> {
145        if self.binding.is_none() {
146            return Err(RuntimeOpenError::NotBootstrapped);
147        }
148        Ok(self.owner.generation())
149    }
150    /// Effective resource admission limits.
151    #[must_use]
152    pub const fn config(&self) -> StorageConfig {
153        self.config
154    }
155    /// Admit a complete declaration set, retaining omitted historical bindings.
156    pub fn bootstrap<P: RuntimeBootstrapPolicy>(
157        &mut self,
158        source: &SealedDeclarationSnapshot,
159        grants: &AllocationGrants,
160        policy: &P,
161    ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
162        if self.binding.is_some() {
163            return self.verify_bootstrap(source, grants, policy);
164        }
165        self.owner.verify()?;
166        let policy_identity = policy.runtime_bootstrap_identity();
167        let bindings = self.owner.bindings();
168        let mut admission =
169            BootstrapAdmission::new(source, grants, &bindings, self.config.allocations)?;
170        let result = policy.prepare_bootstrap(&mut admission);
171        let requests = admission.complete()?;
172        result.map_err(RuntimeBootstrapError::Policy)?;
173        for request in &requests {
174            policy
175                .validate_allocation(request.stable_key())
176                .map_err(RuntimeBootstrapError::Policy)?;
177        }
178        let admitted: BTreeSet<_> = requests
179            .into_iter()
180            .map(|request| request.stable_key().clone())
181            .collect();
182        self.owner.bind(admitted.iter().cloned().collect())?;
183        self.binding = Some(Binding {
184            source: source.clone(),
185            grants: grants.clone(),
186            policy: policy_identity,
187            admitted,
188        });
189        Ok(self.owner.generation())
190    }
191    /// Compare the complete established binding without IO or policy callbacks.
192    pub fn verify_bootstrap<P: RuntimeBootstrapPolicy>(
193        &self,
194        source: &SealedDeclarationSnapshot,
195        grants: &AllocationGrants,
196        policy: &P,
197    ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
198        let binding = self
199            .binding
200            .as_ref()
201            .ok_or(RuntimeBootstrapError::NotBootstrapped)?;
202        if binding.source != *source
203            || binding.grants != *grants
204            || binding.policy != policy.runtime_bootstrap_identity()
205        {
206            return Err(RuntimeBootstrapError::BindingMismatch);
207        }
208        Ok(self.owner.generation())
209    }
210    /// Open one currently admitted name, preserving custody through detached handles.
211    ///
212    /// # Panics
213    /// Propagates backing failures or a broken internal binding invariant.
214    pub fn open_memory(&self, key: &StableKey) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
215        let binding = self
216            .binding
217            .as_ref()
218            .ok_or(RuntimeOpenError::NotBootstrapped)?;
219        if !binding.admitted.contains(key) {
220            return Err(RuntimeOpenError::NotAdmitted(key.clone()));
221        }
222        let lease = self.owner.lease(key).map_err(|error| match error {
223            DirectoryError::AlreadyOpen => RuntimeOpenError::AlreadyOpen {
224                id: self.allocation_id(key).unwrap().get(),
225            },
226            error => RuntimeOpenError::Directory(error),
227        })?;
228        Ok(RuntimeMemory { lease })
229    }
230    /// Verify component requirements against current host admission without IO.
231    pub fn verify_authority(
232        &self,
233        requirements: &SealedDeclarationSnapshot,
234        authority: &str,
235    ) -> Result<(), RuntimeOpenError> {
236        let binding = self
237            .binding
238            .as_ref()
239            .ok_or(RuntimeOpenError::NotBootstrapped)?;
240        for request in requirements.requests() {
241            if request.authority() != authority
242                || !binding.admitted.contains(request.stable_key())
243                || binding.grants.check(request).is_err()
244            {
245                return Err(RuntimeOpenError::NotAdmitted(request.stable_key().clone()));
246            }
247        }
248        Ok(())
249    }
250    /// Resolve a retained identity for diagnostics; this grants no access.
251    #[must_use]
252    pub fn allocation_id(&self, key: &StableKey) -> Option<AllocationId> {
253        self.owner.allocation_id(key)
254    }
255    /// Observe checked directory entries and actual logical extents.
256    pub fn memory_allocations(&self) -> Result<Vec<MemoryAllocation>, DirectoryError> {
257        self.owner.verify()?;
258        Ok(self
259            .owner
260            .bindings()
261            .into_iter()
262            .map(|(stable_key, id, pages)| MemoryAllocation {
263                stable_key,
264                id,
265                pages,
266            })
267            .collect())
268    }
269}
270
271///
272/// MemoryAllocation
273///
274/// Passive diagnostic entry; no lease or allocation authority is carried.
275///
276#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
277pub struct MemoryAllocation {
278    /// Durable name.
279    pub stable_key: StableKey,
280    /// Opaque identity.
281    pub id: AllocationId,
282    /// Logical extent in Wasm pages.
283    pub pages: u64,
284}
285
286///
287/// RuntimeMemory
288///
289/// Exclusive non-cloneable allocation lease. IO trusts custody between checked
290/// boundaries; growth commits the directory before publishing its new extent.
291/// A detached lease retains the backing claim until it is dropped.
292///
293pub struct RuntimeMemory<M: Memory> {
294    lease: Lease<M>,
295}
296impl<M: Memory> RuntimeMemory<M> {
297    /// Logical page extent.
298    #[must_use]
299    pub fn size(&self) -> u64 {
300        self.lease.size()
301    }
302    /// Reserve additional zero-filled logical pages without exposing backing.
303    pub fn grow(&self, pages: u64) -> Result<u64, RuntimeGrowError> {
304        self.lease.try_grow(pages).map_err(|error| match error {
305            DirectoryError::ArithmeticOverflow => RuntimeGrowError::ArithmeticOverflow,
306            DirectoryError::Growth => RuntimeGrowError::BackingRefused {
307                additional_pages: pages,
308            },
309            DirectoryError::Budget => RuntimeGrowError::CapacityExceeded,
310            DirectoryError::Poisoned => RuntimeGrowError::Poisoned,
311            _ => RuntimeGrowError::InvalidDirectory,
312        })
313    }
314    /// Read a completely bounds-checked logical range.
315    pub fn read(&self, offset: u64, bytes: &mut [u8]) {
316        self.lease.read(offset, bytes);
317    }
318    /// Write a completely bounds-checked logical range.
319    pub fn write(&self, offset: u64, bytes: &[u8]) {
320        self.lease.write(offset, bytes);
321    }
322}
323impl<M: Memory> Memory for RuntimeMemory<M> {
324    fn size(&self) -> u64 {
325        self.size()
326    }
327    fn grow(&self, pages: u64) -> i64 {
328        self.grow(pages)
329            .map_or(-1, |previous| i64::try_from(previous).expect("page count"))
330    }
331    fn read(&self, offset: u64, bytes: &mut [u8]) {
332        self.read(offset, bytes);
333    }
334    fn write(&self, offset: u64, bytes: &[u8]) {
335        self.write(offset, bytes);
336    }
337}