Skip to main content

kardia_core/
effect.rs

1use std::future::Future;
2use std::panic::{AssertUnwindSafe, catch_unwind};
3use std::pin::Pin;
4use std::sync::{Arc, Weak};
5use std::task::{Context as TaskContext, Poll};
6
7use futures::FutureExt;
8use futures::future::{BoxFuture, Shared};
9use parking_lot::Mutex;
10use tokio::task::JoinHandle;
11
12use crate::context::Context;
13use crate::error::{Error, Interrupted, Result};
14use crate::key::FiberId;
15use crate::root::RootInner;
16
17pub(crate) enum DisposeResult {
18    Done(Result<()>),
19    Pending(BoxFuture<'static, Result<()>>),
20}
21
22/// The inverse of an effect. Runs at most once (it is consumed).
23///
24/// The closure passed to the constructors runs synchronously when disposal
25/// starts; an asynchronous disposer may return a future that finishes the
26/// work. Panics are caught and reported as errors.
27pub struct Disposer(Box<dyn FnOnce() -> DisposeResult + Send>);
28
29impl Disposer {
30    pub fn new(f: impl FnOnce() + Send + 'static) -> Self {
31        Self(Box::new(move || {
32            f();
33            DisposeResult::Done(Ok(()))
34        }))
35    }
36
37    pub fn fallible(f: impl FnOnce() -> Result<()> + Send + 'static) -> Self {
38        Self(Box::new(move || DisposeResult::Done(f())))
39    }
40
41    pub fn future<F, Fut>(f: F) -> Self
42    where
43        F: FnOnce() -> Fut + Send + 'static,
44        Fut: Future<Output = ()> + Send + 'static,
45    {
46        Self(Box::new(move || DisposeResult::Pending(f().map(Ok).boxed())))
47    }
48
49    pub fn try_future<F, Fut>(f: F) -> Self
50    where
51        F: FnOnce() -> Fut + Send + 'static,
52        Fut: Future<Output = Result<()>> + Send + 'static,
53    {
54        Self(Box::new(move || DisposeResult::Pending(f().boxed())))
55    }
56
57    pub(crate) fn from_handle(handle: EffectHandle) -> Self {
58        Self(Box::new(move || handle.dispose().into_result()))
59    }
60
61    pub(crate) fn call(self) -> DisposeResult {
62        match catch_unwind(AssertUnwindSafe(self.0)) {
63            Ok(DisposeResult::Pending(future)) => DisposeResult::Pending(
64                AssertUnwindSafe(future)
65                    .catch_unwind()
66                    .map(|result| result.unwrap_or_else(|panic| Err(Error::from_panic(panic))))
67                    .boxed(),
68            ),
69            Ok(done) => done,
70            Err(panic) => DisposeResult::Done(Err(Error::from_panic(panic))),
71        }
72    }
73}
74
75/// The completion of a disposal. Disposal makes progress without being
76/// polled: the synchronous part has already run, and any asynchronous rest
77/// runs as a spawned task, so dropping a `Disposal` does not cancel it.
78#[must_use = "a disposal completes on its own; await it to observe the result"]
79#[derive(Clone)]
80pub struct Disposal(DisposalInner);
81
82#[derive(Clone)]
83enum DisposalInner {
84    Ready(Option<Result<()>>),
85    Task(Shared<BoxFuture<'static, Result<()>>>),
86}
87
88impl Disposal {
89    pub(crate) fn ready(result: Result<()>) -> Self {
90        Self(DisposalInner::Ready(Some(result)))
91    }
92
93    pub(crate) fn spawn(future: impl Future<Output = Result<()>> + Send + 'static) -> Self {
94        Self(DisposalInner::Task(join(tokio::spawn(future)).boxed().shared()))
95    }
96
97    pub(crate) fn into_result(self) -> DisposeResult {
98        match self.0 {
99            DisposalInner::Ready(result) => DisposeResult::Done(result.unwrap_or(Ok(()))),
100            DisposalInner::Task(task) => DisposeResult::Pending(task.boxed()),
101        }
102    }
103
104    /// Whether everything finished synchronously.
105    pub fn is_ready(&self) -> bool {
106        matches!(self.0, DisposalInner::Ready(_))
107    }
108}
109
110impl Future for Disposal {
111    type Output = Result<()>;
112
113    fn poll(mut self: Pin<&mut Self>, cx: &mut TaskContext<'_>) -> Poll<Result<()>> {
114        match &mut self.0 {
115            DisposalInner::Ready(result) => Poll::Ready(result.take().unwrap_or(Ok(()))),
116            DisposalInner::Task(task) => task.poll_unpin(cx),
117        }
118    }
119}
120
121async fn join(task: JoinHandle<Result<()>>) -> Result<()> {
122    join_result(task.await)
123}
124
125fn join_result(result: std::result::Result<Result<()>, tokio::task::JoinError>) -> Result<()> {
126    match result {
127        Ok(result) => result,
128        Err(error) if error.is_panic() => Err(Error::from_panic(error.into_panic())),
129        Err(error) => Err(Error::new(error)),
130    }
131}
132
133/// Runs disposers newest first, one after another. Synchronous disposers run
134/// immediately; from the first asynchronous one on, the rest is spawned.
135/// Every disposer runs even if an earlier one fails; the first error wins.
136pub(crate) fn run_sequence(disposers: Vec<Disposer>) -> Disposal {
137    let mut rest = disposers;
138    let mut first_error = None;
139    while let Some(disposer) = rest.pop() {
140        match disposer.call() {
141            DisposeResult::Done(result) => record(&mut first_error, result),
142            DisposeResult::Pending(future) => {
143                return Disposal::spawn(async move {
144                    record(&mut first_error, future.await);
145                    while let Some(disposer) = rest.pop() {
146                        let result = match disposer.call() {
147                            DisposeResult::Done(result) => result,
148                            DisposeResult::Pending(future) => future.await,
149                        };
150                        record(&mut first_error, result);
151                    }
152                    first_error.map_or(Ok(()), Err)
153                });
154            }
155        }
156    }
157    Disposal::ready(first_error.map_or(Ok(()), Err))
158}
159
160fn record(first_error: &mut Option<Error>, result: Result<()>) {
161    if let Err(error) = result {
162        first_error.get_or_insert(error);
163    }
164}
165
166type SetupFuture = Shared<BoxFuture<'static, Result<()>>>;
167
168/// One effect: its collected inverses, nested effects and (for asynchronous
169/// effects) the in-flight setup.
170pub(crate) struct EffectCell {
171    pub(crate) label: String,
172    pub(crate) fiber: FiberId,
173    inner: Mutex<CellInner>,
174}
175
176struct CellInner {
177    active: bool,
178    /// Disposers were taken for the final run; late ones run immediately.
179    closed: bool,
180    /// Slot in the owning fiber's accumulator, while registered there.
181    entry: Option<u64>,
182    disposers: Vec<Disposer>,
183    children: Vec<Arc<EffectCell>>,
184    setup: Option<SetupFuture>,
185    disposal: Option<Disposal>,
186}
187
188impl EffectCell {
189    pub(crate) fn new(label: impl Into<String>, fiber: FiberId) -> Arc<Self> {
190        Arc::new(Self {
191            label: label.into(),
192            fiber,
193            inner: Mutex::new(CellInner {
194                active: true,
195                closed: false,
196                entry: None,
197                disposers: Vec::new(),
198                children: Vec::new(),
199                setup: None,
200                disposal: None,
201            }),
202        })
203    }
204
205    pub(crate) fn set_entry(&self, entry: Option<u64>) {
206        self.inner.lock().entry = entry;
207    }
208
209    pub(crate) fn take_entry(&self) -> Option<u64> {
210        self.inner.lock().entry.take()
211    }
212
213    pub(crate) fn is_active(&self) -> bool {
214        self.inner.lock().active
215    }
216
217    pub(crate) fn push_disposer(&self, disposer: Disposer) {
218        let mut inner = self.inner.lock();
219        if inner.closed {
220            drop(inner);
221            drop(run_sequence(vec![disposer]));
222        } else {
223            inner.disposers.push(disposer);
224        }
225    }
226
227    fn take_disposers(&self, close: bool) -> Vec<Disposer> {
228        let mut inner = self.inner.lock();
229        inner.closed |= close;
230        std::mem::take(&mut inner.disposers)
231    }
232
233    pub(crate) fn meta(&self) -> EffectMeta {
234        let children = self.inner.lock().children.clone();
235        EffectMeta { label: self.label.clone(), children: children.iter().map(|child| child.meta()).collect() }
236    }
237
238    /// Starts disposal at most once; waits for an in-flight setup first.
239    pub(crate) fn dispose(self: &Arc<Self>, root: Option<&Arc<RootInner>>) -> Disposal {
240        let (entry, setup, complete) = {
241            let mut inner = self.inner.lock();
242            if let Some(disposal) = &inner.disposal {
243                return disposal.clone();
244            }
245            // Publish completion before invoking callbacks outside the lock.
246            let (complete, completion) = tokio::sync::oneshot::channel::<Result<()>>();
247            inner.disposal = Some(Disposal(DisposalInner::Task(
248                async move { completion.await.map_err(Error::new)? }.boxed().shared(),
249            )));
250            inner.active = false;
251            (inner.entry.take(), inner.setup.clone(), complete)
252        };
253        if let (Some(entry), Some(root)) = (entry, root) {
254            let fiber = self.fiber;
255            let removed = root.run(|st| st.detach_effect(fiber, entry));
256            drop(removed);
257        }
258        let cleanup = match setup {
259            Some(setup) => {
260                let cell = self.clone();
261                Disposal::spawn(async move {
262                    let _ = setup.await;
263                    run_sequence(cell.take_disposers(true)).await
264                })
265            }
266            None => run_sequence(self.take_disposers(true)),
267        };
268        let disposal = match cleanup.into_result() {
269            DisposeResult::Done(result) => {
270                let _ = complete.send(result.clone());
271                Disposal::ready(result)
272            }
273            DisposeResult::Pending(future) => Disposal::spawn(async move {
274                let result = future.await;
275                let _ = complete.send(result.clone());
276                result
277            }),
278        };
279        self.inner.lock().disposal = Some(disposal.clone());
280        disposal
281    }
282}
283
284/// Introspection of an effect: its label and the effects it adopted.
285#[derive(Debug, Clone, PartialEq, Eq)]
286pub struct EffectMeta {
287    pub label: String,
288    pub children: Vec<EffectMeta>,
289}
290
291impl EffectMeta {
292    pub fn new(label: impl Into<String>, children: Vec<EffectMeta>) -> Self {
293        Self { label: label.into(), children }
294    }
295}
296
297/// A non-owning handle to an effect. Dropping it does not dispose the effect:
298/// its lifetime is governed by the fiber it was registered on.
299#[derive(Clone)]
300pub struct EffectHandle {
301    root: Weak<RootInner>,
302    cell: Arc<EffectCell>,
303}
304
305impl std::fmt::Debug for EffectHandle {
306    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
307        write!(f, "EffectHandle({:?})", self.cell.label)
308    }
309}
310
311impl EffectHandle {
312    pub(crate) fn new(root: &Arc<RootInner>, cell: Arc<EffectCell>) -> Self {
313        Self { root: Arc::downgrade(root), cell }
314    }
315
316    pub fn label(&self) -> &str {
317        &self.cell.label
318    }
319
320    pub fn is_active(&self) -> bool {
321        self.cell.is_active()
322    }
323
324    /// Reverts the effect (at most once). Inverses run newest first.
325    pub fn dispose(&self) -> Disposal {
326        self.cell.dispose(self.root.upgrade().as_ref())
327    }
328
329    /// Resolves when the setup has finished (immediately for synchronous
330    /// effects), with the setup's failure if it failed.
331    pub fn ready(&self) -> impl Future<Output = Result<()>> + Send + 'static {
332        let setup = self.cell.inner.lock().setup.clone();
333        async move {
334            match setup {
335                Some(setup) => setup.await,
336                None => Ok(()),
337            }
338        }
339    }
340
341    pub fn meta(&self) -> EffectMeta {
342        self.cell.meta()
343    }
344}
345
346/// The collector handed to an effect body.
347///
348/// Inverses collected here are disposed together, newest first. Iteration
349/// boundaries ([`EffectScope::checkpoint`], [`EffectScope::yield_`]) report
350/// [`Interrupted`] once the effect has been disposed; propagating it with `?`
351/// ends the body without failure.
352#[derive(Clone)]
353pub struct EffectScope {
354    root: Weak<RootInner>,
355    cell: Arc<EffectCell>,
356}
357
358impl EffectScope {
359    /// Collects an inverse without an iteration boundary.
360    pub fn defer(&self, disposer: Disposer) {
361        self.cell.push_disposer(disposer);
362    }
363
364    /// Shorthand for deferring a synchronous inverse.
365    pub fn defer_fn(&self, f: impl FnOnce() + Send + 'static) {
366        self.defer(Disposer::new(f));
367    }
368
369    /// Moves a nested effect under this one: it is no longer disposed by its
370    /// fiber directly, but together with this effect.
371    pub fn adopt(&self, handle: impl Into<EffectHandle>) {
372        let handle = handle.into();
373        if let (Some(root), Some(entry)) = (self.root.upgrade(), handle.cell.take_entry()) {
374            let fiber = handle.cell.fiber;
375            let removed = root.run(|st| st.detach_effect(fiber, entry));
376            drop(removed);
377        }
378        self.cell.inner.lock().children.push(handle.cell.clone());
379        self.cell.push_disposer(Disposer::from_handle(handle));
380    }
381
382    pub fn checkpoint(&self) -> Result<(), Interrupted> {
383        if self.cell.is_active() { Ok(()) } else { Err(Interrupted) }
384    }
385
386    /// Collects an inverse and marks an iteration boundary.
387    pub fn yield_(&self, disposer: Disposer) -> Result<(), Interrupted> {
388        self.defer(disposer);
389        self.checkpoint()
390    }
391}
392
393impl Context {
394    /// Runs a synchronous effect body. If it fails, whatever it collected is
395    /// disposed and the error is returned.
396    pub fn effect_sync<F>(&self, label: impl Into<String>, body: F) -> Result<EffectHandle>
397    where
398        F: FnOnce(&EffectScope) -> Result<()>,
399    {
400        self.root.run(|st| st.assert_active(self.fiber))?;
401        let cell = EffectCell::new(label, self.fiber);
402        let scope = self.effect_scope(&cell);
403        let result =
404            catch_unwind(AssertUnwindSafe(|| body(&scope))).unwrap_or_else(|panic| Err(Error::from_panic(panic)));
405        if let Err(error) = result {
406            drop(run_sequence(cell.take_disposers(true)));
407            return Err(error);
408        }
409        Ok(self.attach(cell))
410    }
411
412    /// Starts an asynchronous effect. The body is spawned and never dropped
413    /// half-way; disposal waits for it to reach its end or an iteration
414    /// boundary. A failure disposes what it collected, is logged, and is
415    /// reported by [`EffectHandle::ready`].
416    pub fn effect<F, Fut>(&self, label: impl Into<String>, body: F) -> Result<EffectHandle>
417    where
418        F: FnOnce(EffectScope) -> Fut,
419        Fut: Future<Output = Result<()>> + Send + 'static,
420    {
421        self.root.run(|st| st.assert_active(self.fiber))?;
422        let cell = EffectCell::new(label, self.fiber);
423        let future = body(self.effect_scope(&cell));
424        let task_cell = cell.clone();
425        let logger = self.clone();
426        let task = tokio::spawn(async move {
427            let result =
428                AssertUnwindSafe(future).catch_unwind().await.unwrap_or_else(|panic| Err(Error::from_panic(panic)));
429            match result {
430                Err(error) if !error.is_interrupted() => {
431                    if let Err(cleanup) = run_sequence(task_cell.take_disposers(false)).await {
432                        logger.logger().log_error(&cleanup);
433                    }
434                    logger.logger().log_error(&error);
435                    Err(error)
436                }
437                _ => Ok(()),
438            }
439        });
440        cell.inner.lock().setup = Some(join(task).boxed().shared());
441        Ok(self.attach(cell))
442    }
443
444    /// Registers a plain inverse on the current fiber.
445    pub fn on_dispose(&self, f: impl FnOnce() + Send + 'static) -> Result<EffectHandle> {
446        self.effect_sync("ctx.on_dispose()", |scope| {
447            scope.defer_fn(f);
448            Ok(())
449        })
450    }
451
452    /// Registers an arbitrary inverse on the current fiber.
453    pub fn defer(&self, label: impl Into<String>, disposer: Disposer) -> Result<EffectHandle> {
454        self.effect_sync(label, |scope| {
455            scope.defer(disposer);
456            Ok(())
457        })
458    }
459
460    fn effect_scope(&self, cell: &Arc<EffectCell>) -> EffectScope {
461        EffectScope { root: Arc::downgrade(&self.root), cell: cell.clone() }
462    }
463
464    fn attach(&self, cell: Arc<EffectCell>) -> EffectHandle {
465        self.root.run(|st| st.attach_effect(self.fiber, &cell));
466        EffectHandle::new(&self.root, cell)
467    }
468}