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 — most commonly
53    /// `Runtime::shutdown` while the flow was suspended, since shutdown does
54    /// not drain flows out of the timer or the worker deques. The message
55    /// comes from [`super::error::RuntimeError::Abandoned`], so it is
56    /// distinguishable from a flow that genuinely faulted.
57    pub fn join(self) -> FlowOutcome {
58        if is_on_worker() {
59            return FlowOutcome::Failed(JoinError::CalledFromWorker.to_string());
60        }
61        match self.receiver.join() {
62            Ok(outcome) => outcome,
63            Err(e) => FlowOutcome::Failed(e.to_string()),
64        }
65    }
66
67    /// Same as [`Self::join`], but surfaces [`JoinError`] instead of folding
68    /// it into [`FlowOutcome::Failed`].
69    pub fn join_checked(self) -> Result<FlowOutcome, JoinError> {
70        if is_on_worker() {
71            return Err(JoinError::CalledFromWorker);
72        }
73        Ok(match self.receiver.join() {
74            Ok(outcome) => outcome,
75            Err(e) => FlowOutcome::Failed(e.to_string()),
76        })
77    }
78
79    /// The outcome if the flow has already terminated, `None` if it is still
80    /// running. Never waits.
81    ///
82    /// For embedders that drive their own loop and cannot surrender a thread
83    /// to [`FlowHandle::join`]. Takes `&self`, so it can be polled until it
84    /// answers; note that the outcome is handed out exactly once, and a
85    /// further poll after that reports
86    /// [`super::error::RuntimeError::AlreadyCollected`] as
87    /// [`FlowOutcome::Failed`] rather than repeating it.
88    pub fn try_join(&self) -> Option<FlowOutcome> {
89        if is_on_worker() {
90            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
91        }
92        Self::settle(self.receiver.try_join())
93    }
94
95    /// Wait up to `timeout` for the flow to terminate; `None` if it is still
96    /// running when the bound elapses.
97    ///
98    /// This is the variant to reach for in anything with a deadline — a
99    /// control loop, a watchdog, a test harness — since it is the only join
100    /// whose worst-case duration the caller chooses.
101    pub fn join_timeout(&self, timeout: Duration) -> Option<FlowOutcome> {
102        if is_on_worker() {
103            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
104        }
105        Self::settle(self.receiver.join_timeout(timeout))
106    }
107
108    /// [`FlowHandle::join_timeout`] against an absolute deadline, for callers
109    /// that already track one and must not have it drift across repeated
110    /// waits.
111    pub fn join_deadline(&self, deadline: Instant) -> Option<FlowOutcome> {
112        if is_on_worker() {
113            return Some(FlowOutcome::Failed(JoinError::CalledFromWorker.to_string()));
114        }
115        Self::settle(self.receiver.join_deadline(deadline))
116    }
117
118    /// Collapse a bounded-wait result into the handle's public vocabulary:
119    /// `None` for "still running", `Some(Failed)` for an infrastructure
120    /// error, since an embedder polling a handle has no separate error
121    /// channel to report one on.
122    fn settle(state: Result<JoinState<FlowOutcome>, super::error::RuntimeError>) -> Option<FlowOutcome> {
123        match state {
124            Ok(JoinState::Ready(outcome)) => Some(outcome),
125            Ok(JoinState::Pending) => None,
126            Err(e) => Some(FlowOutcome::Failed(e.to_string())),
127        }
128    }
129}
130
131#[cfg(test)]
132mod tests {
133    use super::*;
134    use super::super::worker::WorkerGuard;
135
136    #[test]
137    fn join_from_worker_is_rejected() {
138        let _guard = WorkerGuard::enter();
139        // Synthetic handle: receiver will never complete; we must not block.
140        let (_tx, rx) = oneshot::channel::<FlowOutcome>();
141        let handle = FlowHandle {
142            id: FlowId(1),
143            receiver: rx,
144        };
145        match handle.join_checked() {
146            Err(JoinError::CalledFromWorker) => {}
147            other => panic!("expected CalledFromWorker, got {other:?}"),
148        }
149    }
150}