1mod 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#[derive(Debug, thiserror::Error)]
18pub enum RuntimeConstructionError {
19 #[error("backing already claimed")]
21 BackingAlreadyClaimed,
22 #[error(transparent)]
24 Directory(#[from] DirectoryError),
25}
26
27#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
29pub enum RuntimeGrowError {
30 #[error("allocation page count overflow")]
32 ArithmeticOverflow,
33 #[error("allocation capacity exceeded")]
35 CapacityExceeded,
36 #[error("backing refused growth by {additional_pages} pages")]
38 BackingRefused {
39 additional_pages: u64,
41 },
42 #[error("allocation owner is poisoned")]
44 Poisoned,
45 #[error("allocation directory validation failed")]
47 InvalidDirectory,
48}
49
50#[derive(Debug, thiserror::Error)]
52pub enum RuntimeOpenError {
53 #[error("runtime is not bootstrapped")]
55 NotBootstrapped,
56 #[error("key is not admitted: {0}")]
58 NotAdmitted(StableKey),
59 #[error("allocation {id} already open")]
61 AlreadyOpen {
62 id: u64,
64 },
65 #[error(transparent)]
67 Directory(#[from] DirectoryError),
68}
69
70#[derive(Debug, thiserror::Error)]
72pub enum RuntimeBootstrapError<E> {
73 #[error(transparent)]
75 Admission(#[from] AdmissionError),
76 #[error("host policy rejected allocation")]
78 Policy(E),
79 #[error("bootstrap binding mismatch")]
81 BindingMismatch,
82 #[error("runtime is not bootstrapped")]
84 NotBootstrapped,
85 #[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
97pub struct MemoryRuntime<M: Memory> {
103 owner: Owner<M>,
104 config: StorageConfig,
105 binding: Option<Binding>,
106}
107
108impl<M: Memory> MemoryRuntime<M> {
109 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 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 #[must_use]
138 pub const fn is_bootstrapped(&self) -> bool {
139 self.binding.is_some()
140 }
141
142 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 #[must_use]
152 pub const fn config(&self) -> StorageConfig {
153 self.config
154 }
155
156 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 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 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 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 #[must_use]
257 pub fn allocation_id(&self, key: &StableKey) -> Option<AllocationId> {
258 self.owner.allocation_id(key)
259 }
260
261 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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
280pub struct MemoryAllocation {
281 pub stable_key: StableKey,
283 pub id: AllocationId,
285 pub pages: u64,
287}
288
289pub struct RuntimeMemory<M: Memory> {
294 lease: Lease<M>,
295}
296
297impl<M: Memory> RuntimeMemory<M> {
298 #[must_use]
300 pub fn size(&self) -> u64 {
301 self.lease.size()
302 }
303
304 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 pub fn read(&self, offset: u64, bytes: &mut [u8]) {
319 self.lease.read(offset, bytes);
320 }
321
322 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}