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