1use std::{
5 fmt,
6 sync::{
7 atomic::{AtomicBool, AtomicU64, Ordering},
8 Arc, Mutex, OnceLock,
9 },
10};
11
12mod resource_context;
13pub use resource_context::{SourceResourceContext, SourceStopHandle};
14mod allocation_account;
15pub use allocation_account::{
16 AllocationAccount, AllocationClass, AllocationCost, AllocationObserver, StorageEvent,
17};
18use resource_context::ActiveSource;
19mod work;
20use work::WorkEpoch;
21pub use work::{ExecutionChildCapability, ExecutionSourceScope, ExecutionWork};
22
23static NEXT_ID: AtomicU64 = AtomicU64::new(1);
24fn next_id() -> u64 {
25 NEXT_ID
26 .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
27 value.checked_add(1)
28 })
29 .expect("execution identity space exhausted")
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
35pub struct ExecutionIdentity {
36 instance: u64,
37 generation: u64,
38}
39
40impl ExecutionIdentity {
41 pub fn same_instance(&self, other: &Self) -> bool {
45 self.instance == other.instance
46 }
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
51pub struct ExecutionLeaseId(u64);
52
53#[derive(Debug)]
54struct State {
55 generation: AtomicU64,
56 reserved: AtomicBool,
57 alive: AtomicBool,
58 active_source: Mutex<Vec<(u64, ActiveSource)>>,
60 cache_authority: Mutex<CacheAuthority>,
61}
62
63#[derive(Debug, Clone, Default)]
66struct CacheAuthority {
67 revision: u64,
68 source: std::sync::Weak<crate::SourceBundle>,
69}
70
71#[derive(Debug)]
74pub struct ExecutionOwner {
75 instance: u64,
76 generation: u64,
77 state: OnceLock<Arc<State>>,
78 cache_authority: CacheAuthority,
79}
80impl Default for ExecutionOwner {
81 fn default() -> Self {
82 Self {
84 instance: next_id(),
85 generation: 0,
86 state: OnceLock::new(),
87 cache_authority: CacheAuthority::default(),
88 }
89 }
90}
91impl ExecutionOwner {
92 pub fn identity(&self) -> ExecutionIdentity {
93 ExecutionIdentity {
94 instance: self.instance,
95 generation: self.generation,
96 }
97 }
98 pub fn changed(&mut self) {
100 self.generation = self
101 .generation
102 .checked_add(1)
103 .expect("execution generation space exhausted");
104 if let Some(state) = self.state.get() {
105 state.generation.store(self.generation, Ordering::Release);
106 }
107 }
108 pub(crate) fn cache_changed(&mut self) {
111 self.cache_authority.revision = self
112 .cache_authority
113 .revision
114 .checked_add(1)
115 .expect("execution cache revision space exhausted");
116 if let Some(state) = self.state.get() {
117 let previous = std::mem::replace(
118 &mut *state.cache_authority.lock().unwrap_or_else(|poisoned| poisoned.into_inner()),
119 self.cache_authority.clone(),
120 );
121 drop(previous); }
123 }
124 pub(crate) fn publish_cache_source(&mut self, source: Option<&Arc<crate::SourceBundle>>) {
125 self.cache_authority.source = source.map_or_else(Default::default, Arc::downgrade);
126 self.cache_changed();
127 }
128 pub fn try_lease(&self) -> Result<ExecutionLease, ExecutionLeaseError> {
129 let id = ExecutionLeaseId(next_id());
130 let state = self.state.get_or_init(|| {
131 Arc::new(State {
132 generation: AtomicU64::new(self.generation),
133 reserved: AtomicBool::new(false),
134 alive: AtomicBool::new(true),
135 active_source: Mutex::new(Vec::new()),
136 cache_authority: Mutex::new(self.cache_authority.clone()),
137 })
138 });
139 state
140 .reserved
141 .compare_exchange(false, true, Ordering::AcqRel, Ordering::Acquire)
142 .map_err(|_| ExecutionLeaseError::AlreadyLeased)?;
143 Ok(ExecutionLease {
144 identity: self.identity(),
145 id,
146 state: state.clone(),
147 parent: None,
148 source_borrow: false,
149 resources: None,
150 })
151 }
152 pub(crate) fn try_source_borrow_lease(
153 &mut self,
154 ) -> Result<Option<ExecutionLease>, ExecutionLeaseError> {
155 let Some(state) = self.state.get() else {
156 return Ok(None);
157 };
158 let source = state
159 .active_source
160 .lock()
161 .unwrap_or_else(|poisoned| poisoned.into_inner())
162 .last()
163 .map(|(_, source)| source.clone())
164 .unwrap_or_default();
165 let Some(epoch) = source.epoch.upgrade() else {
166 return Ok(None);
167 };
168 epoch.validate(true)?;
169 if !state.alive.load(Ordering::Acquire) {
170 return Err(ExecutionLeaseError::OwnerDropped);
171 }
172 if !state.reserved.load(Ordering::Acquire) {
173 return Err(ExecutionLeaseError::ExpiredWork);
174 }
175 Ok(Some(ExecutionLease {
176 identity: self.identity(),
177 id: ExecutionLeaseId(next_id()),
178 state: state.clone(),
179 parent: Some(epoch),
180 source_borrow: true,
181 resources: source.resources,
182 }))
183 }
184}
185impl Drop for ExecutionOwner {
186 fn drop(&mut self) {
187 if let Some(state) = self.state.get() {
188 state.alive.store(false, Ordering::Release);
189 }
190 }
191}
192
193#[derive(Debug)]
198pub struct ExecutionLease {
199 identity: ExecutionIdentity,
200 id: ExecutionLeaseId,
201 state: Arc<State>,
202 parent: Option<Arc<WorkEpoch>>,
203 source_borrow: bool,
204 resources: Option<SourceResourceContext>,
205}
206impl ExecutionLease {
207 fn validate_parent(&self) -> Result<(), ExecutionLeaseError> {
208 if let Some(parent) = &self.parent {
209 parent.validate(self.source_borrow)?;
210 }
211 Ok(())
212 }
213 pub fn source_resource_context(
216 &self,
217 ) -> Result<Option<SourceResourceContext>, ExecutionLeaseError> {
218 self.validate_parent()?;
219 Ok(self.resources.clone())
220 }
221 pub fn source_stop_handle(&self) -> Result<Option<SourceStopHandle>, ExecutionLeaseError> {
222 self.validate_parent()?;
223 Ok(self
224 .parent
225 .as_ref()
226 .map(|epoch| SourceStopHandle::new(Arc::clone(epoch))))
227 }
228 pub fn id(&self) -> ExecutionLeaseId {
229 self.id
230 }
231 pub fn identity(&self) -> ExecutionIdentity {
232 self.identity
233 }
234 pub fn begin_synchronous_work(
239 &mut self,
240 current: ExecutionIdentity,
241 ) -> Result<ExecutionWork<'_>, ExecutionLeaseError> {
242 self.validate(current)?;
243 Ok(ExecutionWork {
244 lease: self,
245 epoch: std::cell::OnceCell::new(),
246 _thread_bound: std::marker::PhantomData,
247 })
248 }
249 pub fn validate(&self, current: ExecutionIdentity) -> Result<(), ExecutionLeaseError> {
251 self.validate_parent()?;
252 if !self.state.alive.load(Ordering::Acquire) {
253 return Err(ExecutionLeaseError::OwnerDropped);
254 }
255 if current.instance != self.identity.instance {
256 return Err(ExecutionLeaseError::WrongOwner);
257 }
258 if current != self.identity
259 || self.state.generation.load(Ordering::Acquire) != self.identity.generation
260 {
261 return Err(ExecutionLeaseError::ConfigurationChanged);
262 }
263 Ok(())
264 }
265}
266impl Drop for ExecutionLease {
267 fn drop(&mut self) {
268 if self.parent.is_none() {
269 self.state.reserved.store(false, Ordering::Release);
270 }
271 }
272}
273
274#[derive(Debug, Clone, Copy, PartialEq, Eq)]
277pub enum ExecutionLeaseError {
278 AlreadyLeased,
279 WrongOwner,
280 ConfigurationChanged,
281 OwnerDropped,
282 ExpiredWork,
283}
284impl fmt::Display for ExecutionLeaseError {
285 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
286 formatter.write_str(match self {
287 Self::AlreadyLeased => "execution owner already has a product lease",
288 Self::WrongOwner => "execution lease belongs to a different owner",
289 Self::ConfigurationChanged => "execution configuration changed while work was pending",
290 Self::OwnerDropped => "execution owner was dropped",
291 Self::ExpiredWork => "synchronous ancestor work is no longer active on this thread",
292 })
293 }
294}
295impl std::error::Error for ExecutionLeaseError {}
296
297#[cfg(test)]
298#[path = "execution_owner/resource_context_tests.rs"]
299mod resource_context_tests;
300#[cfg(test)]
301#[path = "execution_owner_tests.rs"]
302mod tests;