Skip to main content

byteflow/scheduler/
process.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::sync::atomic::{AtomicBool, AtomicU64, Ordering};
6use std::sync::Arc;
7use std::time::Duration;
8
9use crate::bytecode::{Cap, CapRights, CapTarget, RestartPolicy, RevocationCell};
10use crate::vm::Vm;
11
12use super::mailbox::Mailbox;
13use super::oneshot;
14
15/// Identifier of a **flow** — Byteflow's unit of concurrent work.
16///
17/// Host APIs and the directory key on this type. Inside messages it appears
18/// as [`crate::Value::Pid`] (`Message.sender` / `msg_sender`) for **identity**.
19/// Bytecode addressing uses [`crate::Value::Cap`] (FlowCap) — a Pid is not a
20/// Send/Ask authority token.
21///
22/// Backed by a single global, wait-free `AtomicU64` counter rather than
23/// anything derived from memory addresses: ids must stay unique for the
24/// lifetime of the runtime and must **never** be reused, or a stale id in
25/// someone's registers could address a *different* later flow (ABA) via the
26/// host/`Directory` path.
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
28pub struct FlowId(pub(crate) u64);
29
30impl FlowId {
31    /// Embedder origin for host `Runtime::send`. Never spawned, never finalized.
32    pub const HOST: FlowId = FlowId(0);
33
34    pub fn as_u64(self) -> u64 {
35        self.0
36    }
37
38    #[inline]
39    pub fn is_host(self) -> bool {
40        self.0 == 0
41    }
42}
43
44impl std::fmt::Display for FlowId {
45    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
46        write!(f, "flow#{}", self.0)
47    }
48}
49
50static NEXT_FLOW_ID: AtomicU64 = AtomicU64::new(1);
51static FLOW_IDS_EXHAUSTED: AtomicBool = AtomicBool::new(false);
52
53/// Allocate the next id. Tests and host helpers; spawn uses
54/// `try_next_flow_id` so wrap-around cannot mint [`FlowId::HOST`].
55pub fn next_flow_id() -> FlowId {
56    match try_next_flow_id() {
57        Ok(id) => id,
58        Err(_) => FlowId(u64::MAX),
59    }
60}
61
62/// Fail closed if the counter wrapped onto [`FlowId::HOST`] (`0`).
63/// After the first wrap the allocator stays exhausted so later ids cannot
64/// collide with live flows (ABA).
65pub(crate) fn try_next_flow_id() -> Result<FlowId, super::error::RuntimeError> {
66    if FLOW_IDS_EXHAUSTED.load(Ordering::Relaxed) {
67        return Err(super::error::RuntimeError::FlowIdExhausted);
68    }
69    let id = NEXT_FLOW_ID.fetch_add(1, Ordering::Relaxed);
70    if id == 0 {
71        FLOW_IDS_EXHAUSTED.store(true, Ordering::Relaxed);
72        return Err(super::error::RuntimeError::FlowIdExhausted);
73    }
74    Ok(FlowId(id))
75}
76
77/// Live counters for one flow (updated only by the worker currently
78/// running it).
79#[derive(Debug, Default)]
80pub struct FlowMetrics {
81    pub instructions: AtomicU64,
82    /// Atomic hops sent (`Send` of [`crate::Value::Message`]).
83    pub messages_sent: AtomicU64,
84    pub messages_received: AtomicU64,
85    pub reschedules: AtomicU64,
86}
87
88/// A single **flow**: VM state, mailbox, and bookkeeping.
89///
90/// This is the unit of work moved by the scheduler — pushed onto worker
91/// deques, stolen, parked inside a [`Mailbox`] on `Receive`, or held by
92/// the timer wheel while sleeping. Flows talk only via **Atomic Hops**
93/// ([`crate::Value::Message`] on `Send`).
94pub struct Flow {
95    pub id: FlowId,
96    pub vm: Vm,
97    pub mailbox: Arc<Mailbox>,
98    pub metrics: Arc<FlowMetrics>,
99    pub restart_policy: RestartPolicy,
100    /// Completion channel consumed by [`super::handle::FlowHandle::join`].
101    pub(crate) completion: oneshot::Sender<FlowOutcome>,
102    /// Set by [`Mailbox::park`] when a hop wins the park race.
103    pub pending_message: Option<crate::bytecode::Value>,
104    /// Destination register of the most recent `Receive` /
105    /// `ReceiveTimeout` / selective receive (`ReceiveMatch*`).
106    pub last_receive_dest: Option<u8>,
107    /// Continuation after a `WAITING_SEND` park is admitted.
108    pub(crate) pending_send: Option<PendingSend>,
109    /// Bytes held on [`Self::quota`] while a hop is parked in `WAITING_SEND`.
110    /// Freed once, on admit or finalize — never forwarded to [`crate::MemoryBudget`].
111    pub(crate) hop_charge: usize,
112    pub(crate) supervisor: Option<super::supervisor::SupervisorLink>,
113    /// Supervisor this flow started with `StartSupervisor`. Preferred by
114    /// `StartChild` over [`Self::supervisor`].
115    pub(crate) local_supervisor: Option<super::supervisor::SupervisorLink>,
116    /// Self-authority (rights + native mask). Derived only via [`Cap::attenuate`].
117    pub(crate) authority: Cap,
118    pub(crate) cell: Arc<RevocationCell>,
119    pub(crate) quota: Arc<super::quota::FlowQuota>,
120}
121
122/// What the worker should do after a parked sender's hop is admitted.
123#[derive(Debug, Clone, Copy)]
124pub(crate) enum PendingSend {
125    FireAndForget,
126    Ask {
127        dest_reg: u8,
128        expect_request_id: u64,
129        expect_sender: u64,
130        timeout: Option<Duration>,
131    },
132}
133
134/// Terminal outcome of a flow, delivered to whoever holds its
135/// [`super::handle::FlowHandle`].
136#[derive(Clone, Debug, PartialEq)]
137pub enum FlowOutcome {
138    Completed(crate::bytecode::Value),
139    Failed(String),
140}
141
142impl Flow {
143    pub fn new(
144        id: FlowId,
145        vm: Vm,
146        mailbox: Arc<Mailbox>,
147        restart_policy: RestartPolicy,
148        completion: oneshot::Sender<FlowOutcome>,
149    ) -> Self {
150        let cell = Arc::new(RevocationCell::new());
151        let authority = Cap::root(
152            CapTarget::Flow(id.as_u64()),
153            CapRights::NONE,
154            None,
155            cell.as_ref(),
156        );
157        Self {
158            id,
159            vm,
160            mailbox,
161            metrics: Arc::new(FlowMetrics::default()),
162            restart_policy,
163            completion,
164            pending_message: None,
165            last_receive_dest: None,
166            pending_send: None,
167            hop_charge: 0,
168            supervisor: None,
169            local_supervisor: None,
170            authority,
171            cell,
172            quota: Arc::new(super::quota::FlowQuota::from_config(
173                super::quota::QuotaConfig::default(),
174            )),
175        }
176    }
177
178    pub(crate) fn complete(self, outcome: FlowOutcome) {
179        self.completion.send(outcome);
180    }
181
182    /// Take the parked-hop quota charge so it is freed exactly once.
183    pub(crate) fn take_hop_charge(&mut self) -> usize {
184        let bytes = self.hop_charge;
185        self.hop_charge = 0;
186        bytes
187    }
188}