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};
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#[derive(Debug, thiserror::Error)]
19pub enum RuntimeConstructionError {
20 #[error("backing already claimed")]
22 BackingAlreadyClaimed,
23 #[error(transparent)]
25 Directory(#[from] DirectoryError),
26}
27
28#[derive(Clone, Copy, Debug, Eq, PartialEq, thiserror::Error)]
30pub enum RuntimeGrowError {
31 #[error("allocation page count overflow")]
33 ArithmeticOverflow,
34 #[error("allocation capacity exceeded")]
36 CapacityExceeded,
37 #[error("backing refused growth by {additional_pages} pages")]
39 BackingRefused {
40 additional_pages: u64,
42 },
43 #[error("allocation owner is poisoned")]
45 Poisoned,
46 #[error("allocation directory validation failed")]
48 InvalidDirectory,
49}
50
51#[derive(Debug, thiserror::Error)]
53pub enum RuntimeOpenError {
54 #[error("runtime is not bootstrapped")]
56 NotBootstrapped,
57 #[error("key is not admitted: {0}")]
59 NotAdmitted(StableKey),
60 #[error("allocation {id} already open")]
62 AlreadyOpen {
63 id: u64,
65 },
66 #[error(transparent)]
68 Directory(#[from] DirectoryError),
69}
70
71#[derive(Debug, thiserror::Error)]
73pub enum RuntimeBootstrapError<E> {
74 #[error(transparent)]
76 Admission(#[from] AdmissionError),
77 #[error("host policy rejected allocation")]
79 Policy(E),
80 #[error("bootstrap binding mismatch")]
82 BindingMismatch,
83 #[error("runtime is not bootstrapped")]
85 NotBootstrapped,
86 #[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
98pub struct MemoryRuntime<M: Memory> {
107 owner: Owner<M>,
108 config: StorageConfig,
109 binding: Option<Binding>,
110}
111
112impl<M: Memory> MemoryRuntime<M> {
113 pub fn new(memory: M) -> Result<Self, RuntimeConstructionError>
115 where
116 M: MemoryBacking,
117 {
118 Self::new_with_config(memory, StorageConfig::default())
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 Ok(Self {
133 owner,
134 config,
135 binding: None,
136 })
137 }
138 #[must_use]
140 pub const fn is_bootstrapped(&self) -> bool {
141 self.binding.is_some()
142 }
143 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 #[must_use]
152 pub const fn config(&self) -> StorageConfig {
153 self.config
154 }
155 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 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 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 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 #[must_use]
252 pub fn allocation_id(&self, key: &StableKey) -> Option<AllocationId> {
253 self.owner.allocation_id(key)
254 }
255 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#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
277pub struct MemoryAllocation {
278 pub stable_key: StableKey,
280 pub id: AllocationId,
282 pub pages: u64,
284}
285
286pub struct RuntimeMemory<M: Memory> {
294 lease: Lease<M>,
295}
296impl<M: Memory> RuntimeMemory<M> {
297 #[must_use]
299 pub fn size(&self) -> u64 {
300 self.lease.size()
301 }
302 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 | DirectoryError::Wire(_) => RuntimeGrowError::CapacityExceeded,
310 DirectoryError::Poisoned => RuntimeGrowError::Poisoned,
311 _ => RuntimeGrowError::InvalidDirectory,
312 })
313 }
314 pub fn read(&self, offset: u64, bytes: &mut [u8]) {
316 self.lease.read(offset, bytes);
317 }
318 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}