Skip to main content

byteflow/scheduler/
process.rs

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