ifc_lite_core/execution_owner/
work.rs

1// SPDX-License-Identifier: MPL-2.0
2//! Synchronous work epochs, child capabilities and source-borrow scopes
3//! issued by an [`ExecutionLease`](super::ExecutionLease).
4use super::*;
5
6/// Short-lived trusted execution scope. It borrows its reservation and is
7/// thread-bound; no active scope may cross a yield. Dropping it, including on
8/// panic, never acknowledges changed configuration. Normal executor completion
9/// must explicitly commit against the same live owner's fresh identity.
10#[derive(Debug)]
11pub struct ExecutionWork<'a> {
12    pub(super) lease: &'a mut ExecutionLease,
13    pub(super) epoch: std::cell::OnceCell<Arc<WorkEpoch>>,
14    pub(super) _thread_bound: std::marker::PhantomData<*const ()>,
15}
16impl ExecutionWork<'_> {
17    /// Grant synchronous descendants access without releasing this reservation.
18    /// Allocation occurs only when a descendant capability is actually requested.
19    pub fn child_capability(&self) -> ExecutionChildCapability {
20        let epoch = self.epoch.get_or_init(|| {
21            Arc::new(WorkEpoch {
22                active: AtomicBool::new(true),
23                thread: std::thread::current().id(),
24                parent: self.lease.parent.clone(),
25                parent_source: self.lease.source_borrow,
26                resource_stop: Mutex::new(None),
27                stopped: AtomicBool::new(false),
28            })
29        });
30        ExecutionChildCapability {
31            epoch: epoch.clone(),
32            state: self.lease.state.clone(),
33            instance: self.lease.identity.instance,
34            _thread_bound: std::marker::PhantomData,
35        }
36    }
37    /// Publish decoder-only authority for the duration of a trusted source
38    /// borrow. The actual decoder's mutable borrow can cross a scoped thread;
39    /// generic owner capabilities and router admission remain thread-bound.
40    pub fn source_borrow_scope(&self) -> ExecutionSourceScope {
41        self.source_borrow_scope_with_resources(None)
42    }
43    /// Attach only the explicitly supplied resource account to this source
44    /// capability. No kernel, diagnostics, census or other TLS state is copied.
45    pub fn source_borrow_scope_with_resources(
46        &self,
47        resources: Option<SourceResourceContext>,
48    ) -> ExecutionSourceScope {
49        let capability = self.child_capability();
50        let scope_id = next_id();
51        self.lease
52            .state
53            .active_source
54            .lock()
55            .unwrap_or_else(|poisoned| poisoned.into_inner())
56            .push((
57                scope_id,
58                ActiveSource {
59                    epoch: Arc::downgrade(&capability.epoch),
60                    resources,
61                },
62            ));
63        ExecutionSourceScope {
64            state: self.lease.state.clone(),
65            scope_id,
66            epoch: capability.epoch,
67            _thread_bound: std::marker::PhantomData,
68        }
69    }
70    pub fn commit(self, current: ExecutionIdentity) -> Result<(), ExecutionLeaseError> {
71        self.lease.validate_parent()?;
72        if !self.lease.state.alive.load(Ordering::Acquire) {
73            return Err(ExecutionLeaseError::OwnerDropped);
74        }
75        if current.instance != self.lease.identity.instance {
76            return Err(ExecutionLeaseError::WrongOwner);
77        }
78        if current.generation != self.lease.state.generation.load(Ordering::Acquire) {
79            return Err(ExecutionLeaseError::ConfigurationChanged);
80        }
81        self.lease.identity = current;
82        Ok(())
83    }
84}
85
86impl Drop for ExecutionWork<'_> {
87    fn drop(&mut self) {
88        if let Some(epoch) = self.epoch.get() {
89            epoch.active.store(false, Ordering::Release);
90        }
91    }
92}
93
94#[derive(Debug)]
95pub(super) struct WorkEpoch {
96    pub(super) active: AtomicBool,
97    pub(super) thread: std::thread::ThreadId,
98    pub(super) parent: Option<Arc<WorkEpoch>>,
99    pub(super) parent_source: bool,
100    pub(super) resource_stop: Mutex<Option<crate::resource_stop::ProgramStop>>,
101    /// Set after `resource_stop` is first written, so an unstopped chain is
102    /// checked without taking a lock.
103    pub(super) stopped: AtomicBool,
104}
105impl WorkEpoch {
106    pub(super) fn validate(&self, mut source_borrow: bool) -> Result<(), ExecutionLeaseError> {
107        let mut cursor = Some(self);
108        while let Some(epoch) = cursor {
109            if !epoch.active.load(Ordering::Acquire)
110                || (!source_borrow && epoch.thread != std::thread::current().id())
111            {
112                return Err(ExecutionLeaseError::ExpiredWork);
113            }
114            source_borrow |= epoch.parent_source;
115            cursor = epoch.parent.as_deref();
116        }
117        Ok(())
118    }
119}
120
121/// Same-thread capability for a synchronous descendant of active trusted work.
122/// It expires at that work's normal completion or unwind. Child reservations
123/// cannot release the root owner's exclusive reservation.
124#[derive(Debug, Clone)]
125pub struct ExecutionChildCapability {
126    epoch: Arc<WorkEpoch>,
127    state: Arc<State>,
128    instance: u64,
129    _thread_bound: std::marker::PhantomData<*const ()>,
130}
131impl ExecutionChildCapability {
132    pub fn try_lease(
133        &self,
134        current: ExecutionIdentity,
135    ) -> Result<ExecutionLease, ExecutionLeaseError> {
136        self.epoch.validate(false)?;
137        if !self.state.alive.load(Ordering::Acquire) {
138            return Err(ExecutionLeaseError::OwnerDropped);
139        }
140        if current.instance != self.instance {
141            return Err(ExecutionLeaseError::WrongOwner);
142        }
143        if current.generation != self.state.generation.load(Ordering::Acquire) {
144            return Err(ExecutionLeaseError::ConfigurationChanged);
145        }
146        Ok(ExecutionLease {
147            identity: current,
148            id: ExecutionLeaseId(next_id()),
149            state: self.state.clone(),
150            parent: Some(self.epoch.clone()),
151            source_borrow: false,
152            resources: None,
153        })
154    }
155}
156
157/// Thread-bound publication of source-borrow authority. No lock is held while
158/// extension work runs. Nested decoder borrows restore the enclosing authority;
159/// out-of-order drops remove only their own entry.
160#[derive(Debug)]
161pub struct ExecutionSourceScope {
162    state: Arc<State>,
163    scope_id: u64,
164    epoch: Arc<WorkEpoch>,
165    _thread_bound: std::marker::PhantomData<*const ()>,
166}
167impl ExecutionSourceScope {
168    pub fn resource_stop_handle(&self) -> SourceStopHandle {
169        SourceStopHandle::new(Arc::clone(&self.epoch))
170    }
171}
172impl Drop for ExecutionSourceScope {
173    fn drop(&mut self) {
174        // Remove exactly this scope's entry so non-LIFO drops never revive
175        // or clobber another scope's authority. No allocation under the lock.
176        let displaced = {
177            let mut active = self.state.active_source.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
178            active
179                .iter()
180                .rposition(|(id, _)| *id == self.scope_id)
181                .map(|at| active.remove(at))
182        };
183        drop(displaced); // Final account/pool destruction must occur outside the lock.
184    }
185}