1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
//! Lifecycle-owned effects and single-shot asynchronous disposers.
use crate::fiber::{Fiber, FiberInner};
use crate::utils::{BoxFuture, block_on, lock};
use crate::{CordisError, ErrorCode, Result};
use std::fmt::{self, Debug, Formatter};
use std::future::Future;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, Weak};
/// A boxed, single-shot asynchronous cleanup operation.
pub struct AsyncDisposer {
callback: Option<Box<dyn FnOnce() -> BoxFuture<Result<()>> + Send + 'static>>,
}
impl AsyncDisposer {
/// Wrap a synchronous cleanup callback.
pub fn from_sync<F>(callback: F) -> Self
where
F: FnOnce() -> Result<()> + Send + 'static,
{
Self {
callback: Some(Box::new(move || Box::pin(async move { callback() }))),
}
}
/// Wrap an infallible synchronous cleanup callback.
pub fn infallible<F>(callback: F) -> Self
where
F: FnOnce() + Send + 'static,
{
Self::from_sync(move || {
callback();
Ok(())
})
}
/// Wrap an asynchronous cleanup callback.
pub fn from_async<F, Fut>(callback: F) -> Self
where
F: FnOnce() -> Fut + Send + 'static,
Fut: Future<Output = Result<()>> + Send + 'static,
{
Self {
callback: Some(Box::new(move || Box::pin(callback()))),
}
}
/// Run this disposer. Calling `run` consumes it, enforcing single-shot use.
pub async fn run(mut self) -> Result<()> {
match self.callback.take() {
Some(callback) => callback().await,
None => Ok(()),
}
}
}
impl Debug for AsyncDisposer {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("AsyncDisposer")
.field("pending", &self.callback.is_some())
.finish()
}
}
/// Diagnostic tree describing a live effect and nested effects it owns.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EffectMeta {
/// Human-readable effect label.
pub label: String,
/// Nested effect metadata.
pub children: Vec<EffectMeta>,
}
impl EffectMeta {
/// Construct a leaf effect metadata node.
pub fn new(label: impl Into<String>) -> Self {
Self {
label: label.into(),
children: Vec::new(),
}
}
}
pub(crate) struct EffectCell {
pub(crate) id: u64,
owner: Weak<FiberInner>,
disposed: AtomicBool,
disposer: Mutex<Option<AsyncDisposer>>,
children: Mutex<Vec<Arc<EffectCell>>>,
meta: Mutex<EffectMeta>,
}
impl EffectCell {
pub(crate) fn new(
id: u64,
owner: Weak<FiberInner>,
label: impl Into<String>,
disposer: AsyncDisposer,
) -> Arc<Self> {
Arc::new(Self {
id,
owner,
disposed: AtomicBool::new(false),
disposer: Mutex::new(Some(disposer)),
children: Mutex::new(Vec::new()),
meta: Mutex::new(EffectMeta::new(label)),
})
}
async fn dispose(self: &Arc<Self>) -> Result<()> {
if self.disposed.swap(true, Ordering::AcqRel) {
return Ok(());
}
if let Some(owner) = self.owner.upgrade() {
owner.remove_effect(self.id);
}
let children = {
let mut children = lock(&self.children);
std::mem::take(&mut *children)
};
let mut first_error = None;
for child in children.into_iter().rev() {
if let Err(error) = Box::pin(child.dispose()).await {
if first_error.is_none() {
first_error = Some(error);
}
}
}
let disposer = lock(&self.disposer).take();
if let Some(disposer) = disposer {
if let Err(error) = disposer.run().await {
if first_error.is_none() {
first_error = Some(error);
}
}
}
match first_error {
Some(error) => Err(error),
None => Ok(()),
}
}
pub(crate) fn cancel(&self) {
if self.disposed.swap(true, Ordering::AcqRel) {
return;
}
if let Some(owner) = self.owner.upgrade() {
owner.remove_effect(self.id);
}
// Adopted children were detached from their owning fiber's effect
// list at adopt() time, so nobody else will ever dispose them; drop
// them through the normal disposal path or their cleanup callbacks
// leak. Only this effect's own disposer is skipped — that is what
// "cancel" means.
let children = {
let mut children = lock(&self.children);
std::mem::take(&mut *children)
};
for child in children.into_iter().rev() {
if let Err(error) = crate::utils::block_on(child.dispose()) {
// Surface the failure on the fiber's log like dispose does;
// cancellation itself must stay infallible.
if let Some(owner) = child.owner.upgrade() {
if let Some(ctx) = Fiber::from_inner(owner).context() {
ctx.log_error(&error);
}
}
}
}
lock(&self.disposer).take();
}
fn adopt(self: &Arc<Self>, child: Arc<EffectCell>) -> Result<()> {
// Serialize against dispose()/cancel(): they swap `disposed` before
// draining `children`, so re-checking `disposed` while holding the
// children lock guarantees that a child pushed after a passing check
// is always seen by a concurrent disposal. Without this, a child
// adopted mid-disposal is detached from its fiber's list but never
// cleaned up — a silent leak.
let mut children = lock(&self.children);
if self.disposed.load(Ordering::Acquire) {
return Err(CordisError::new(ErrorCode::InactiveEffect));
}
if child.disposed.load(Ordering::Acquire) {
return Ok(());
}
if let Some(owner) = child.owner.upgrade() {
owner.remove_effect(child.id);
}
lock(&self.meta).children.push(lock(&child.meta).clone());
children.push(child);
Ok(())
}
}
/// A cloneable handle to one registered effect.
///
/// Dropping a handle does not dispose the effect: ownership belongs to the
/// fiber. Call [`EffectHandle::dispose`] for early cleanup, or dispose the
/// owning fiber.
#[derive(Clone)]
pub struct EffectHandle {
pub(crate) cell: Arc<EffectCell>,
}
impl EffectHandle {
pub(crate) fn new(cell: Arc<EffectCell>) -> Self {
Self { cell }
}
/// Dispose this effect synchronously, waiting for asynchronous cleanup.
pub fn dispose(&self) -> Result<()> {
block_on(self.dispose_async())
}
/// Dispose this effect asynchronously.
pub async fn dispose_async(&self) -> Result<()> {
self.cell.dispose().await
}
/// Stop owning this effect without running *its own* cleanup callback.
///
/// Adopted children are unaffected by the cancellation of their parent:
/// they were detached from their owning fiber at [`adopt`](Self::adopt)
/// time, so cancelling runs each child's disposer exactly as
/// [`dispose`](Self::dispose) would — otherwise those children would be
/// orphaned with cleanup that never runs.
///
/// This is intended for framework structural effects. Application code
/// normally wants [`dispose`](Self::dispose).
pub fn cancel(&self) {
self.cell.cancel();
}
/// Move `child` under this effect's diagnostic and disposal tree.
pub fn adopt(&self, child: EffectHandle) -> Result<()> {
self.cell.adopt(child.cell)
}
/// Return a snapshot of diagnostic metadata.
pub fn meta(&self) -> EffectMeta {
lock(&self.cell.meta).clone()
}
/// Whether cleanup has already started.
pub fn is_disposed(&self) -> bool {
self.cell.disposed.load(Ordering::Acquire)
}
/// Return the owning fiber while it remains alive.
pub fn owner(&self) -> Option<Fiber> {
self.cell.owner.upgrade().map(Fiber::from_inner)
}
}
impl Debug for EffectHandle {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
f.debug_struct("EffectHandle")
.field("id", &self.cell.id)
.field("meta", &self.meta())
.field("disposed", &self.is_disposed())
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::thread;
use std::time::Duration;
/// Disposing a parent recurses into adopted children (reverse adoption
/// order) — this exercises the boxed recursive dispose path at runtime.
#[test]
fn dispose_runs_adopted_children_in_reverse_order() {
let runs = Arc::new(Mutex::new(Vec::new()));
let parent = EffectCell::new(
1,
Weak::new(),
"parent",
AsyncDisposer::from_sync(|| Ok(())),
);
for id in [2_u64, 3] {
let runs = runs.clone();
let child = EffectCell::new(
id,
Weak::new(),
"child",
AsyncDisposer::from_sync(move || {
lock(&runs).push(id);
Ok(())
}),
);
parent.adopt(child).unwrap();
}
block_on(parent.dispose()).unwrap();
assert_eq!(*lock(&runs), vec![3, 2]);
}
/// Regression: adopt checked `disposed` outside the children lock, so a
/// child adopted while the parent was mid-disposal ended up detached from
/// its owner but never cleaned up. The children lock is the gate: the
/// adopting thread must observe the disposal and back off.
#[test]
fn adopt_racing_parent_disposal_is_rejected() {
let parent = EffectCell::new(
1,
Weak::new(),
"parent",
AsyncDisposer::from_sync(|| Ok(())),
);
let child_ran = Arc::new(AtomicBool::new(false));
let child_ran_in_disposer = child_ran.clone();
let child = EffectCell::new(
2,
Weak::new(),
"child",
AsyncDisposer::from_sync(move || {
child_ran_in_disposer.store(true, Ordering::SeqCst);
Ok(())
}),
);
// Hold the adoption gate so the ordering is deterministic.
let gate = lock(&parent.children);
let adopting_parent = parent.clone();
let adopt_handle = thread::spawn(move || adopting_parent.adopt(child));
thread::sleep(Duration::from_millis(50));
let disposing_parent = parent.clone();
let dispose_handle = thread::spawn(move || block_on(disposing_parent.dispose()));
thread::sleep(Duration::from_millis(50));
drop(gate);
assert!(adopt_handle.join().unwrap().is_err());
dispose_handle.join().unwrap().unwrap();
assert!(!child_ran.load(Ordering::SeqCst));
}
/// Regression: cancel() used to clear the children list without
/// disposing them; since adopt() already detached those children from
/// their owning fiber, their disposers were lost forever. Cancelling a
/// parent must run adopted children's disposers, exactly once, while
/// still skipping the parent's own.
#[test]
fn cancel_disposes_adopted_children_but_not_the_parent() {
let runs = Arc::new(Mutex::new(Vec::new()));
let parent_ran = Arc::new(AtomicBool::new(false));
let parent_ran_in_disposer = parent_ran.clone();
let parent = EffectCell::new(
1,
Weak::new(),
"parent",
AsyncDisposer::from_sync(move || {
parent_ran_in_disposer.store(true, Ordering::SeqCst);
Ok(())
}),
);
for id in [2_u64, 3] {
let runs = runs.clone();
let child = EffectCell::new(
id,
Weak::new(),
"child",
AsyncDisposer::from_sync(move || {
lock(&runs).push(id);
Ok(())
}),
);
parent.adopt(child).unwrap();
}
parent.cancel();
assert_eq!(*lock(&runs), vec![3, 2], "children disposed, reverse order");
assert!(!parent_ran.load(Ordering::SeqCst), "own disposer skipped");
// Second cancel (or a later dispose) must not double-run anything.
parent.cancel();
let _ = block_on(parent.dispose());
assert_eq!(*lock(&runs), vec![3, 2]);
assert!(!parent_ran.load(Ordering::SeqCst));
}
}