ifc_lite_geometry/resource/
mod.rs1mod account;
4#[cfg(feature = "retained-runtime")]
5mod budget;
6#[cfg(all(feature = "retained-runtime", test))]
7pub use budget::test_clock as budget_test_clock;
8#[cfg(feature = "retained-runtime")]
9pub use budget::{budget_checkpoint, budget_deadline_fired, BudgetStart, ProductBudget};
10#[cfg(any(
12 all(
13 test,
14 any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
15 ),
16 feature = "retained-runtime"
17))]
18#[cfg_attr(not(test), allow(dead_code))]
19mod owned;
20#[cfg(feature = "retained-runtime")]
21pub(crate) use owned::OwnedResourceContext;
22mod pool;
23mod storage;
24pub(crate) use storage::reserve_headers;
25pub mod mesh;
26pub use account::{ExecutionAccount, Reservation, Usage};
27pub use pool::{ModelResourcePool, RequestAdmission};
28use std::cell::{Cell, RefCell};
29
30#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
32pub enum ExecutionPolicy {
33 #[default]
34 Compatibility,
35 Bounded(ResourceLimits),
36 Strict(ResourceLimits),
38}
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
41pub struct ResourceLimits {
42 pub work: Option<u64>,
43 pub copy_bytes: Option<u64>,
44 pub output_bytes: Option<u64>,
45 pub occurrences: Option<u64>,
46 pub live_bytes: Option<u64>,
47}
48#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
49pub struct Cost {
50 pub work: u64,
51 pub copy_bytes: u64,
52 pub output_bytes: u64,
53 pub occurrences: u64,
54 pub live_bytes: u64,
55}
56pub use ifc_lite_core::resource_stop::{Dimension, ProgramStop, RefusalReason, ResourceFailure};
57thread_local! {
58 static CURRENT: RefCell<Option<ExecutionAccount>> = const { RefCell::new(None) };
59 static SOURCE_STOP: RefCell<Option<ifc_lite_core::execution_owner::SourceStopHandle>> = const { RefCell::new(None) };
60 static TERMINAL: Cell<Option<Option<ProgramStop>>> = const { Cell::new(None) };
61}
62struct TerminalScope;
63impl Drop for TerminalScope {
64 fn drop(&mut self) {
65 TERMINAL.with(|slot| slot.set(None));
66 }
67}
68fn terminal_scope() -> Option<TerminalScope> {
69 TERMINAL.with(|slot| {
70 if slot.get().is_some() {
71 None
72 } else {
73 slot.set(Some(None));
74 Some(TerminalScope)
75 }
76 })
77}
78
79pub fn with_terminal_scope<T>(
83 operation: impl FnOnce() -> Result<T, ProgramStop>,
84) -> Result<T, ProgramStop> {
85 let _terminal = terminal_scope();
86 check_current()?;
87 let result = operation();
88 check_current()?;
89 result
90}
91
92static STOP_EVENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
98
99pub fn stop_events() -> u64 {
101 STOP_EVENTS.load(std::sync::atomic::Ordering::SeqCst)
102}
103
104pub fn ambient_scope_active() -> bool {
110 let owned = {
111 #[cfg(any(
112 all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")),
113 feature = "retained-runtime"
114 ))]
115 {
116 owned::OWNED.with(|slot| slot.borrow().is_some())
117 }
118 #[cfg(not(any(
119 all(test, any(not(target_arch = "wasm32"), feature = "wasm_source_capture")),
120 feature = "retained-runtime"
121 )))]
122 {
123 false
124 }
125 };
126 owned
127 || CURRENT.with(|slot| slot.borrow().is_some())
128 || SOURCE_STOP.with(|slot| slot.borrow().is_some())
129 || TERMINAL.with(|slot| slot.get().is_some())
130}
131
132pub fn current_account() -> Option<ExecutionAccount> {
133 CURRENT.with(|slot| slot.borrow().clone())
134}
135pub fn is_active() -> bool {
136 CURRENT.with(|slot| slot.borrow().is_some())
137}
138pub fn check_current() -> Result<(), ProgramStop> {
139 let source = SOURCE_STOP.with(|slot| {
140 slot.borrow()
141 .as_ref()
142 .map_or(Ok(()), |source| source.check())
143 });
144 if let Err(error) = source {
145 return Err(stop(error));
146 }
147 let account = CURRENT.with(|slot| match slot.borrow().as_ref() {
148 Some(a) => a.check(),
149 None => Ok(()),
150 });
151 if let Err(error) = account {
152 return Err(stop(error));
153 }
154 if let Some(error) = current_terminal() {
155 return Err(error);
156 }
157 #[cfg(feature = "retained-runtime")]
158 if let Some(account) = current_account() {
159 account.check_allowance().map_err(stop)?;
160 }
161 Ok(())
162}
163fn current_terminal() -> Option<ProgramStop> {
164 TERMINAL.with(|slot| slot.get().flatten())
165}
166
167#[inline]
170pub fn is_stopped() -> bool {
171 let source_stopped = SOURCE_STOP.with_borrow(|source| {
172 source
173 .as_ref()
174 .is_some_and(|source| source.check().is_err())
175 });
176 if source_stopped || CURRENT.with_borrow(Option::is_some) {
177 check_active_stop()
180 } else {
181 current_terminal().is_some()
182 }
183}
184
185#[cold]
186#[inline(never)]
187fn check_active_stop() -> bool {
188 check_current().is_err()
189}
190
191#[cfg(feature = "retained-runtime")]
195pub(crate) fn source_step() -> crate::Result<()> {
196 budget::source_step()
197}
198
199pub fn charge(cost: Cost) -> Result<Reservation, ProgramStop> {
200 check_current()?;
201 match current_account() {
202 Some(account) => account.prepare(cost).map_err(stop),
203 None => Ok(Reservation::empty()),
204 }
205}
206pub fn stop(error: ProgramStop) -> ProgramStop {
207 STOP_EVENTS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
208 #[cfg(feature = "retained-runtime")]
211 if error == ProgramStop::Cancelled && budget_deadline_fired() {
212 return error;
213 }
214 let prior_source = SOURCE_STOP.with(|slot| {
215 slot.borrow()
216 .as_ref()
217 .and_then(|source| source.check().err())
218 });
219 let error = prior_source.unwrap_or(error);
220 let error = current_account().map_or(error, |account| account.stop(error));
221 let source = SOURCE_STOP.with(|slot| slot.borrow().as_ref().map(|source| source.stop(error)));
222 let error = source.unwrap_or(error);
223 #[cfg(any(
224 all(
225 test,
226 any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
227 ),
228 feature = "retained-runtime"
229 ))]
230 let error = owned::record_stop(error);
231 TERMINAL.with(|slot| match (source, slot.get()) {
232 (Some(_), Some(_)) => {
235 slot.set(Some(Some(error)));
236 error
237 }
238 (_, Some(Some(first))) => first,
239 (_, Some(None)) => {
240 slot.set(Some(Some(error)));
241 error
242 }
243 (_, None) => error,
244 })
245}
246pub fn refused(
247 dimension: Dimension,
248 requested: u64,
249 remaining: u64,
250 reason: RefusalReason,
251) -> ProgramStop {
252 stop(ProgramStop::ResourceRefused(ResourceFailure {
253 dimension,
254 requested,
255 remaining,
256 reason,
257 }))
258}
259pub fn overflow() -> ProgramStop {
260 refused(
261 Dimension::Representation,
262 u64::MAX,
263 0,
264 RefusalReason::Overflow,
265 )
266}
267pub fn allocation_failure() -> ProgramStop {
268 refused(Dimension::LiveBytes, 0, 0, RefusalReason::Allocation)
269}
270
271#[cfg(test)]
272mod boolean_tests;
273#[cfg(test)]
274mod tests;
275
276pub(crate) fn observe<T>(result: crate::Result<T>) -> crate::Result<T> {
279 if let Err(crate::Error::ProgramStopped(error)) = &result {
280 stop(*error);
281 }
282 check_current()?;
283 result
284}
285
286pub fn current_source_context() -> Option<ifc_lite_core::execution_owner::SourceResourceContext> {
289 current_account().and_then(|account| account.source_context())
290}
291pub fn account_from_source_context(
292 context: &ifc_lite_core::execution_owner::SourceResourceContext,
293) -> Result<ExecutionAccount, ProgramStop> {
294 ExecutionAccount::from_source_context(context).ok_or_else(|| {
295 refused(
296 Dimension::Coverage,
297 0,
298 0,
299 RefusalReason::UnsupportedCoverage,
300 )
301 })
302}
303
304pub fn detached<T>(operation: impl FnOnce() -> T) -> T {
319 struct Restore {
320 account: Option<ExecutionAccount>,
321 source: Option<ifc_lite_core::execution_owner::SourceStopHandle>,
322 terminal: Option<Option<ProgramStop>>,
323 #[cfg(any(
324 all(
325 test,
326 any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
327 ),
328 feature = "retained-runtime"
329 ))]
330 owned: Option<owned::OwnedResourceContext>,
331 }
332 impl Drop for Restore {
333 fn drop(&mut self) {
334 CURRENT.with(|slot| *slot.borrow_mut() = self.account.take());
335 SOURCE_STOP.with(|slot| *slot.borrow_mut() = self.source.take());
336 TERMINAL.with(|slot| slot.set(self.terminal));
337 #[cfg(any(
338 all(
339 test,
340 any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
341 ),
342 feature = "retained-runtime"
343 ))]
344 owned::OWNED.with(|slot| *slot.borrow_mut() = self.owned.take());
345 }
346 }
347 let _restore = Restore {
348 account: CURRENT.with(|slot| slot.borrow_mut().take()),
349 source: SOURCE_STOP.with(|slot| slot.borrow_mut().take()),
350 terminal: TERMINAL.with(Cell::take),
351 #[cfg(any(
352 all(
353 test,
354 any(not(target_arch = "wasm32"), feature = "wasm_source_capture")
355 ),
356 feature = "retained-runtime"
357 ))]
358 owned: owned::OWNED.with(|slot| slot.borrow_mut().take()),
359 };
360 operation()
361}
362
363pub fn with_source_stop<T>(
366 source: ifc_lite_core::execution_owner::SourceStopHandle,
367 operation: impl FnOnce() -> T,
368) -> T {
369 struct Restore {
370 source: Option<ifc_lite_core::execution_owner::SourceStopHandle>,
371 terminal: Option<Option<ProgramStop>>,
372 }
373 impl Drop for Restore {
374 fn drop(&mut self) {
375 SOURCE_STOP.with(|slot| *slot.borrow_mut() = self.source.take());
376 TERMINAL.with(|slot| slot.set(self.terminal));
377 }
378 }
379 let _restore = Restore {
380 source: SOURCE_STOP.with(|slot| slot.borrow_mut().replace(source)),
381 terminal: TERMINAL.with(|slot| slot.replace(Some(None))),
382 };
383 operation()
387}
388
389#[cfg(all(feature = "retained-runtime", any(target_arch = "wasm32", test)))]
390mod budget_monotonic;