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::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> {
106 owner: Owner<M>,
107 config: StorageConfig,
108 binding: Option<Binding>,
109}
110
111impl<M: Memory> MemoryRuntime<M> {
112 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 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 #[must_use]
142 pub const fn is_bootstrapped(&self) -> bool {
143 self.binding.is_some()
144 }
145
146 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 #[must_use]
157 pub const fn config(&self) -> StorageConfig {
158 self.config
159 }
160
161 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 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 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 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 #[must_use]
266 pub fn allocation_id(&self, key: &StableKey) -> Option<AllocationId> {
267 self.owner.allocation_id(key)
268 }
269
270 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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
293pub struct MemoryAllocation {
294 pub stable_key: StableKey,
296 pub id: AllocationId,
298 pub pages: u64,
300}
301
302pub struct RuntimeMemory<M: Memory> {
310 lease: Lease<M>,
311}
312
313impl<M: Memory> RuntimeMemory<M> {
314 #[must_use]
316 pub fn size(&self) -> u64 {
317 self.lease.size()
318 }
319
320 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 pub fn read(&self, offset: u64, bytes: &mut [u8]) {
335 self.lease.read(offset, bytes);
336 }
337
338 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}