Skip to main content

byteflow/scheduler/
handle.rs

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