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::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///
98/// MemoryRuntime
99/// One custodian of named allocations on a backing. Bootstrap validates namespace
100/// grants and host policy, commits bindings, then permits exclusive leases.
101/// Omitted retained names keep their allocation, but require current admission
102/// before opening. IDs are opaque u64 values, never selected by applications.
103///
104
105pub struct MemoryRuntime<M: Memory> {
106    owner: Owner<M>,
107    config: StorageConfig,
108    binding: Option<Binding>,
109}
110
111impl<M: Memory> MemoryRuntime<M> {
112    /// Claim backing and create or read its owned directory. Never reset nonempty backing.
113    pub fn new(memory: M) -> Result<Self, RuntimeConstructionError>
114    where
115        M: MemoryBacking,
116    {
117        Self::new_with_config(memory, StorageConfig::default())
118    }
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
133        Ok(Self {
134            owner,
135            config,
136            binding: None,
137        })
138    }
139
140    /// Whether current host authority has been committed.
141    #[must_use]
142    pub const fn is_bootstrapped(&self) -> bool {
143        self.binding.is_some()
144    }
145
146    /// Current durable directory generation, after bootstrap admission.
147    pub fn committed_generation(&self) -> Result<u64, RuntimeOpenError> {
148        if self.binding.is_none() {
149            return Err(RuntimeOpenError::NotBootstrapped);
150        }
151
152        Ok(self.owner.generation())
153    }
154
155    /// Effective resource admission limits.
156    #[must_use]
157    pub const fn config(&self) -> StorageConfig {
158        self.config
159    }
160
161    /// Admit a complete declaration set, retaining omitted historical bindings.
162    pub fn bootstrap<P: RuntimeBootstrapPolicy>(
163        &mut self,
164        source: &SealedDeclarationSnapshot,
165        grants: &AllocationGrants,
166        policy: &P,
167    ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
168        if self.binding.is_some() {
169            return self.verify_bootstrap(source, grants, policy);
170        }
171        self.owner.verify()?;
172        let policy_identity = policy.runtime_bootstrap_identity();
173        let bindings = self.owner.bindings();
174        let mut admission =
175            BootstrapAdmission::new(source, grants, &bindings, self.config.allocations)?;
176        let result = policy.prepare_bootstrap(&mut admission);
177        let requests = admission.complete()?;
178        result.map_err(RuntimeBootstrapError::Policy)?;
179        for request in &requests {
180            policy
181                .validate_allocation(request.stable_key())
182                .map_err(RuntimeBootstrapError::Policy)?;
183        }
184        let admitted: BTreeSet<_> = requests
185            .into_iter()
186            .map(|request| request.stable_key().clone())
187            .collect();
188        self.owner.bind(admitted.iter().cloned().collect())?;
189        self.binding = Some(Binding {
190            source: source.clone(),
191            grants: grants.clone(),
192            policy: policy_identity,
193            admitted,
194        });
195
196        Ok(self.owner.generation())
197    }
198
199    /// Compare the complete established binding without IO or policy callbacks.
200    pub fn verify_bootstrap<P: RuntimeBootstrapPolicy>(
201        &self,
202        source: &SealedDeclarationSnapshot,
203        grants: &AllocationGrants,
204        policy: &P,
205    ) -> Result<u64, RuntimeBootstrapError<P::Error>> {
206        let binding = self
207            .binding
208            .as_ref()
209            .ok_or(RuntimeBootstrapError::NotBootstrapped)?;
210        if binding.source != *source
211            || binding.grants != *grants
212            || binding.policy != policy.runtime_bootstrap_identity()
213        {
214            return Err(RuntimeBootstrapError::BindingMismatch);
215        }
216
217        Ok(self.owner.generation())
218    }
219
220    /// Open one currently admitted name, preserving custody through detached handles.
221    ///
222    /// # Panics
223    /// Propagates backing failures or a broken internal binding invariant.
224    pub fn open_memory(&self, key: &StableKey) -> Result<RuntimeMemory<M>, RuntimeOpenError> {
225        let binding = self
226            .binding
227            .as_ref()
228            .ok_or(RuntimeOpenError::NotBootstrapped)?;
229        if !binding.admitted.contains(key) {
230            return Err(RuntimeOpenError::NotAdmitted(key.clone()));
231        }
232        let lease = self.owner.lease(key).map_err(|error| match error {
233            DirectoryError::AlreadyOpen => RuntimeOpenError::AlreadyOpen {
234                id: self.allocation_id(key).unwrap().get(),
235            },
236            error => RuntimeOpenError::Directory(error),
237        })?;
238
239        Ok(RuntimeMemory { lease })
240    }
241
242    /// Verify component requirements against current host admission without IO.
243    pub fn verify_authority(
244        &self,
245        requirements: &SealedDeclarationSnapshot,
246        authority: &str,
247    ) -> Result<(), RuntimeOpenError> {
248        let binding = self
249            .binding
250            .as_ref()
251            .ok_or(RuntimeOpenError::NotBootstrapped)?;
252        for request in requirements.requests() {
253            if request.authority() != authority
254                || !binding.admitted.contains(request.stable_key())
255                || binding.grants.check(request).is_err()
256            {
257                return Err(RuntimeOpenError::NotAdmitted(request.stable_key().clone()));
258            }
259        }
260
261        Ok(())
262    }
263
264    /// Resolve a retained identity for diagnostics; this grants no access.
265    #[must_use]
266    pub fn allocation_id(&self, key: &StableKey) -> Option<AllocationId> {
267        self.owner.allocation_id(key)
268    }
269
270    /// Observe checked directory entries and actual logical extents.
271    pub fn memory_allocations(&self) -> Result<Vec<MemoryAllocation>, DirectoryError> {
272        self.owner.verify()?;
273
274        Ok(self
275            .owner
276            .bindings()
277            .into_iter()
278            .map(|(stable_key, id, pages)| MemoryAllocation {
279                stable_key,
280                id,
281                pages,
282            })
283            .collect())
284    }
285}
286
287///
288/// MemoryAllocation
289/// Passive diagnostic entry; no lease or allocation authority is carried.
290///
291
292#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
293pub struct MemoryAllocation {
294    /// Durable name.
295    pub stable_key: StableKey,
296    /// Opaque identity.
297    pub id: AllocationId,
298    /// Logical extent in Wasm pages.
299    pub pages: u64,
300}
301
302///
303/// RuntimeMemory
304/// Exclusive non-cloneable allocation lease. IO trusts custody between checked
305/// boundaries; growth commits the directory before publishing its new extent.
306/// A detached lease retains the backing claim until it is dropped.
307///
308
309pub struct RuntimeMemory<M: Memory> {
310    lease: Lease<M>,
311}
312
313impl<M: Memory> RuntimeMemory<M> {
314    /// Logical page extent.
315    #[must_use]
316    pub fn size(&self) -> u64 {
317        self.lease.size()
318    }
319
320    /// Reserve additional zero-filled logical pages without exposing backing.
321    pub fn grow(&self, pages: u64) -> Result<u64, RuntimeGrowError> {
322        self.lease.try_grow(pages).map_err(|error| match error {
323            DirectoryError::ArithmeticOverflow => RuntimeGrowError::ArithmeticOverflow,
324            DirectoryError::Growth => RuntimeGrowError::BackingRefused {
325                additional_pages: pages,
326            },
327            DirectoryError::Budget => RuntimeGrowError::CapacityExceeded,
328            DirectoryError::Poisoned => RuntimeGrowError::Poisoned,
329            _ => RuntimeGrowError::InvalidDirectory,
330        })
331    }
332
333    /// Read a completely bounds-checked logical range.
334    pub fn read(&self, offset: u64, bytes: &mut [u8]) {
335        self.lease.read(offset, bytes);
336    }
337
338    /// Write a completely bounds-checked logical range.
339    pub fn write(&self, offset: u64, bytes: &[u8]) {
340        self.lease.write(offset, bytes);
341    }
342}
343
344impl<M: Memory> Memory for RuntimeMemory<M> {
345    fn size(&self) -> u64 {
346        self.size()
347    }
348
349    fn grow(&self, pages: u64) -> i64 {
350        self.grow(pages)
351            .map_or(-1, |previous| i64::try_from(previous).expect("page count"))
352    }
353
354    fn read(&self, offset: u64, bytes: &mut [u8]) {
355        self.read(offset, bytes);
356    }
357
358    fn write(&self, offset: u64, bytes: &[u8]) {
359        self.write(offset, bytes);
360    }
361}