ifc_lite_geometry/resource/
account.rs

1// SPDX-License-Identifier: MPL-2.0
2use super::pool::PoolPermit;
3use super::*;
4use std::sync::{
5    atomic::{AtomicBool, Ordering},
6    Arc, Mutex,
7};
8
9#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
10pub struct Usage {
11    pub work: u64,
12    pub copy_bytes: u64,
13    pub output_bytes: u64,
14    pub occurrences: u64,
15    pub live_bytes: u64,
16    pub peak_live_bytes: u64,
17}
18#[derive(Debug, Default)]
19struct State {
20    usage: Usage,
21    terminal: Option<ProgramStop>,
22}
23#[derive(Debug)]
24struct Inner {
25    limits: ResourceLimits,
26    state: Mutex<State>,
27    cancelled: AtomicBool,
28    _model: Option<PoolPermit>,
29}
30/// Clone shares one deterministic request allowance, including reentered calls.
31/// Holding an account retains all storage transferred with Reservation::retain.
32#[derive(Debug, Clone, Default)]
33pub struct ExecutionAccount(
34    Option<Arc<Inner>>,
35    #[cfg(feature = "retained-runtime")] pub(super) Option<Arc<super::budget::Allowance>>,
36);
37impl ExecutionAccount {
38    pub fn new(policy: ExecutionPolicy) -> Self {
39        match policy {
40            ExecutionPolicy::Compatibility => Self::default(),
41            ExecutionPolicy::Bounded(limits) => Self::bounded(limits, None),
42            ExecutionPolicy::Strict(limits) => {
43                let account = Self::bounded(limits, None);
44                account.stop(ProgramStop::ResourceRefused(ResourceFailure {
45                    dimension: Dimension::Coverage,
46                    requested: 0,
47                    remaining: 0,
48                    reason: RefusalReason::UnsupportedCoverage,
49                }));
50                account
51            }
52        }
53    }
54    pub(super) fn bounded(limits: ResourceLimits, model: Option<PoolPermit>) -> Self {
55        Self(Some(Arc::new(Inner {
56            limits,
57            state: Mutex::new(State::default()),
58            cancelled: AtomicBool::new(false),
59            _model: model,
60        })), #[cfg(feature = "retained-runtime")] None)
61    }
62    pub(super) fn source_context(
63        &self,
64    ) -> Option<ifc_lite_core::execution_owner::SourceResourceContext> {
65        #[cfg(feature = "retained-runtime")]
66        if self.1.is_some() {
67            return Some(ifc_lite_core::execution_owner::SourceResourceContext::new(Arc::new(self.clone())));
68        }
69        self.0.as_ref().map(|inner| {
70            ifc_lite_core::execution_owner::SourceResourceContext::new(Arc::clone(inner))
71        })
72    }
73    pub(super) fn from_source_context(
74        context: &ifc_lite_core::execution_owner::SourceResourceContext,
75    ) -> Option<Self> {
76        #[cfg(feature = "retained-runtime")]
77        if let Some(account) = context.downcast::<Self>() { return Some((*account).clone()); }
78        context.downcast::<Inner>().map(|inner| Self(Some(inner), #[cfg(feature = "retained-runtime")] None))
79    }
80    pub fn usage(&self) -> Usage {
81        self.0.as_ref().map_or(Usage::default(), |inner| {
82            inner.state.lock().unwrap_or_else(|e| e.into_inner()).usage
83        })
84    }
85    pub fn cancel(&self) {
86        if let Some(inner) = &self.0 {
87            inner.cancelled.store(true, Ordering::Release);
88        }
89    }
90    pub fn check(&self) -> Result<(), ProgramStop> {
91        let Some(inner) = &self.0 else { return Ok(()) };
92        let mut state = inner.state.lock().unwrap_or_else(|e| e.into_inner());
93        if state.terminal.is_none() && inner.cancelled.load(Ordering::Acquire) {
94            state.terminal = Some(ProgramStop::Cancelled);
95        }
96        state.terminal.map_or(Ok(()), Err)
97    }
98    pub fn stop(&self, error: ProgramStop) -> ProgramStop {
99        #[cfg(feature = "retained-runtime")]
100        if let Some(local) = self.overlay_stop() { return local; }
101        let Some(inner) = &self.0 else { return error };
102        let mut state = inner.state.lock().unwrap_or_else(|e| e.into_inner());
103        *state.terminal.get_or_insert(error)
104    }
105    /// A lexical child inherits the active account; it cannot reset allowances.
106    /// The guard restores TLS on errors and panic, and never crosses a reply.
107    pub fn scope<T>(&self, run: impl FnOnce() -> T) -> T {
108        let _terminal = terminal_scope();
109        if is_active() || self.0.is_none() {
110            return run();
111        }
112        struct Restore;
113        impl Drop for Restore {
114            fn drop(&mut self) {
115                CURRENT.with(|slot| *slot.borrow_mut() = None);
116            }
117        }
118        CURRENT.with(|slot| *slot.borrow_mut() = Some(self.clone()));
119        let _restore = Restore;
120        run()
121    }
122    /// Install the account attached to the actual validated source owner. A
123    /// worker-local account cannot replace that owner's deterministic allowance.
124    /// The caller first installs the matching source terminal capability.
125    pub fn source_scope<T>(&self, run: impl FnOnce() -> T) -> T {
126        if self.0.is_none() {
127            return self.scope(run);
128        }
129        let _terminal = terminal_scope();
130        struct Restore(Option<ExecutionAccount>);
131        impl Drop for Restore {
132            fn drop(&mut self) {
133                CURRENT.with(|slot| *slot.borrow_mut() = self.0.take());
134            }
135        }
136        let _restore = Restore(CURRENT.with(|slot| slot.borrow_mut().replace(self.clone())));
137        // Select actual source authority before reading account/terminal state;
138        // a stopped unrelated worker account cannot poison this source domain.
139        let _ = super::check_current();
140        let result = run();
141        let _ = super::check_current();
142        result
143    }
144    pub fn prepare(&self, cost: Cost) -> Result<Reservation, ProgramStop> {
145        self.prepare_inner(cost).map_err(super::stop)
146    }
147    pub(super) fn prepare_inner(&self, cost: Cost) -> Result<Reservation, ProgramStop> {
148        self.check()?;
149        // The local allowance admits BEFORE either original accounting or growth.
150        // This is an overlay on the same original Arc/pool, never a new owner.
151        #[cfg(feature = "retained-runtime")]
152        let allowance = self.1.as_ref().map(|allowance| allowance.account.prepare_inner(cost))
153            .transpose()?.map(Box::new);
154        let Some(inner) = &self.0 else {
155            return Ok(Reservation::empty());
156        };
157        let mut state = inner.state.lock().unwrap_or_else(|e| e.into_inner());
158        if let Some(stop) = state.terminal {
159            return Err(stop);
160        }
161        let old = state.usage;
162        let dimensions = [
163            (Dimension::Work, old.work, cost.work, inner.limits.work),
164            (
165                Dimension::CopyBytes,
166                old.copy_bytes,
167                cost.copy_bytes,
168                inner.limits.copy_bytes,
169            ),
170            (
171                Dimension::OutputBytes,
172                old.output_bytes,
173                cost.output_bytes,
174                inner.limits.output_bytes,
175            ),
176            (
177                Dimension::Occurrences,
178                old.occurrences,
179                cost.occurrences,
180                inner.limits.occurrences,
181            ),
182            (
183                Dimension::LiveBytes,
184                old.live_bytes,
185                cost.live_bytes,
186                inner.limits.live_bytes,
187            ),
188        ];
189        for (dimension, used, requested, limit) in dimensions {
190            let next = used.checked_add(requested);
191            if next.is_none_or(|next| limit.is_some_and(|limit| next > limit)) {
192                let failure = ProgramStop::ResourceRefused(ResourceFailure {
193                    dimension,
194                    requested,
195                    remaining: limit.unwrap_or(u64::MAX).saturating_sub(used),
196                    reason: if next.is_none() {
197                        RefusalReason::Overflow
198                    } else {
199                        RefusalReason::Limit
200                    },
201                });
202                state.terminal = Some(failure);
203                return Err(failure);
204            }
205        }
206        state.usage = Usage {
207            work: old.work + cost.work,
208            copy_bytes: old.copy_bytes + cost.copy_bytes,
209            output_bytes: old.output_bytes + cost.output_bytes,
210            occurrences: old.occurrences + cost.occurrences,
211            live_bytes: old.live_bytes + cost.live_bytes,
212            peak_live_bytes: old.peak_live_bytes.max(old.live_bytes + cost.live_bytes),
213        };
214        Ok(Reservation {
215            account: self.clone(),
216            bytes: cost.live_bytes,
217            #[cfg(feature = "retained-runtime")]
218            allowance,
219        })
220    }
221}
222/// Unique live-storage ownership. Dropping refunds live bytes only; cumulative
223/// work/copy/output/occurrences are never refunded, including failed work.
224#[derive(Debug)]
225pub struct Reservation {
226    account: ExecutionAccount,
227    bytes: u64,
228    #[cfg(feature = "retained-runtime")]
229    allowance: Option<Box<Reservation>>,
230}
231impl Reservation {
232    pub(super) fn empty() -> Self {
233        Self {
234            account: ExecutionAccount::default(),
235            bytes: 0,
236            #[cfg(feature = "retained-runtime")]
237            allowance: None,
238        }
239    }
240    /// Transfer storage to the account's output/cache lifetime. The storage owner
241    /// MUST keep an account clone until that payload is destroyed.
242    pub fn retain(mut self) {
243        self.bytes = 0;
244        #[cfg(feature = "retained-runtime")]
245        if let Some(allowance) = self.allowance.take() { allowance.retain(); }
246    }
247}
248impl Drop for Reservation {
249    fn drop(&mut self) {
250        if let Some(inner) = &self.account.0 {
251            let mut state = inner.state.lock().unwrap_or_else(|e| e.into_inner());
252            state.usage.live_bytes = state.usage.live_bytes.saturating_sub(self.bytes);
253        }
254    }
255}