Skip to main content

byteflow/scheduler/
handle.rs

1// Docs ratchet: public items here predate `missing_docs`. Delete this
2// allow once they are documented; new files get the lint by default.
3#![allow(missing_docs)]
4
5use std::time::{Duration, Instant};
6
7use super::oneshot::{self, JoinState};
8use super::process::{FlowId, FlowOutcome};
9use super::worker::is_on_worker;
10
11/// Why a host-side join refused to wait.
12#[derive(Debug, Clone, Copy, PartialEq, Eq)]
13pub enum JoinError {
14    /// [`FlowHandle::join`] (or a bounded variant) was called on a worker
15    /// thread. That deadlocks the M:N pool if the target needs this worker.
16    CalledFromWorker,
17}
18
19impl std::fmt::Display for JoinError {
20    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21        match self {
22            Self::CalledFromWorker => {
23                f.write_str("FlowHandle::join called from a Byteflow worker thread")
24            }
25        }
26    }
27}
28
29impl std::error::Error for JoinError {}
30
31/// A reference to a spawned **flow**, returned by
32/// [`super::runtime::Runtime::spawn`].
33///
34/// Holding a `FlowHandle` does not keep the flow alive — it is a way to
35/// (a) read its [`FlowId`] for addressing with `Send`, and (b) block the
36/// *calling native thread* until it finishes via [`FlowHandle::join`].
37/// Dropping without joining is fine (fire-and-forget).
38pub struct FlowHandle {
39    pub(crate) id: FlowId,
40    pub(crate) receiver: oneshot::Receiver<FlowOutcome>,
41}
42
43impl FlowHandle {
44    pub fn id(&self) -> FlowId {
45        self.id
46    }
47
48    /// Block the current (native) thread until the flow terminates.
49    ///
50    /// **Never call from inside a worker / from a native invoked by bytecode.**
51    /// That case is machine-checked: this returns
52    /// [`FlowOutcome::Failed`] with [`JoinError::CalledFromWorker`] rather
53    /// than deadlocking the pool.
54    ///
55    /// Returns [`FlowOutcome::Failed`] rather than blocking forever if the
56    /// flow was destroyed without producing an outcome.
57    /// [`super::runtime::Runtime::shutdown`] finalizes remaining flows
58    /// (`runtime shutdown`); a dropped sender without finalize is
59    /// [`super::error::RuntimeError::Abandoned`].
60    pub fn join(self) -> FlowOutcome {
61        if is_on_worker() {
62            return FlowOutcome::Failed(JoinError::CalledFromWorker.to_string());
63        }
64        match self.receiver.join() {
65            Ok(outcome) => outcome,
66            Err(e) => FlowOutcome::Failed(e.to_string()),
67        }
68    }
69
70    /// Same as [`Self::join`], but surfaces [`JoinError`] instead of folding
71    /// it into [`FlowOutcome::Failed`].
72    pub fn join_checked(self) -> Result<FlowOutcome, JoinError> {
73        if is_on_worker() {
74            return Err(JoinError::CalledFromWorker);
75        }
76        Ok(match self.receiver.join() {
77            Ok(outcome) => outcome,
78            Err(e) => FlowOutcome::Failed(e.to_string()),
79        })
80    }
81
82    /// The outcome if the flow has already terminated, `None` if it is still
83    /// running. Never waits.
84    ///
85    /// For embedders that drive their own loop and cannot surrender a thread
86    /// to [`FlowHandle::join`]. Takes `&self`, so it can be polled until it
87    /// answers; note that the outcome is handed out exactly once, and a
88    /// further poll after that reports
89    /// [`super::error::RuntimeError::AlreadyCollected`] as
90    /// [`FlowOutcome::Failed`] rather than repeating it.
91    pub fn try_join(&self) -> Option<FlowOutcome> {
92        if is_on_worker() {
93            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
94        }
95        Self::settle(self.receiver.try_join())
96    }
97
98    /// Wait up to `timeout` for the flow to terminate; `None` if it is still
99    /// running when the bound elapses.
100    ///
101    /// This is the variant to reach for in anything with a deadline — a
102    /// control loop, a watchdog, a test harness — since it is the only join
103    /// whose worst-case duration the caller chooses.
104    pub fn join_timeout(&self, timeout: Duration) -> Option<FlowOutcome> {
105        if is_on_worker() {
106            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
107        }
108        Self::settle(self.receiver.join_timeout(timeout))
109    }
110
111    /// [`FlowHandle::join_timeout`] against an absolute deadline, for callers
112    /// that already track one and must not have it drift across repeated
113    /// waits.
114    pub fn join_deadline(&self, deadline: Instant) -> Option<FlowOutcome> {
115        if is_on_worker() {
116            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
117        }
118        Self::settle(self.receiver.join_deadline(deadline))
119    }
120
121    /// Collapse a bounded-wait result into the handle's public vocabulary:
122    /// `None` for "still running", `Some(Failed)` for an infrastructure
123    /// error, since an embedder polling a handle has no separate error
124    /// channel to report one on.
125    fn settle(
126        state: Result<JoinState<FlowOutcome>, super::error::RuntimeError>,
127    ) -> Option<FlowOutcome> {
128        match state {
129            Ok(JoinState::Ready(outcome)) => Some(outcome),
130            Ok(JoinState::Pending) => None,
131            Err(e) => Some(FlowOutcome::Failed(e.to_string())),
132        }
133    }
134}
135
136#[cfg(test)]
137mod tests {
138    use super::super::worker::WorkerGuard;
139    use super::*;
140
141    #[test]
142    fn join_from_worker_is_rejected() {
143        let _guard = WorkerGuard::enter();
144        // Synthetic handle: receiver will never complete; we must not block.
145        let (_tx, rx) = oneshot::channel::<FlowOutcome>();
146        let handle = FlowHandle {
147            id: FlowId(1),
148            receiver: rx,
149        };
150        match handle.join_checked() {
151            Err(JoinError::CalledFromWorker) => {}
152            other => panic!("expected CalledFromWorker, got {other:?}"),
153        }
154    }
155}