Skip to main content

byteflow/scheduler/
distribution.rs

1//! Outbound hops for another node.
2//!
3//! Byteflow does not open sockets and does not speak a cluster protocol.
4//! The host owns I/O. Bytecode [`crate::Opcode::SendRemote`] stamps the
5//! sender here and queues the hop on [`DistributionBridge`]; the embedder
6//! drains that queue and delivers it however it wants.
7//!
8//! Payload `Cap` tokens are not re-granted to the remote node. They stay
9//! opaque bytes the host must not treat as local authority on another
10//! process. `reply_cap` is [`crate::CapId::NONE`] — there is no local flow
11//! to mint a reply address for.
12
13use std::collections::VecDeque;
14use std::sync::{Arc, Condvar, Mutex};
15
16use crate::bytecode::{CapId, Message, Value};
17
18use super::error::RuntimeError;
19use super::process::FlowId;
20use super::sync_lock;
21
22/// How many outbound hops a bridge holds before `SendRemote` fails the flow.
23const MAX_OUTBOUND: usize = 1024;
24
25/// One authenticated hop waiting for the host to deliver it off-node.
26#[derive(Clone, Debug)]
27pub struct OutboundHop {
28    pub sender: FlowId,
29    /// Host-defined node number. `0` is not special.
30    pub node: u64,
31    pub name: Arc<str>,
32    pub message: Message,
33}
34
35/// Queue the host drains. Share one [`Arc`] via [`crate::RuntimeConfig::distribution`].
36#[derive(Debug)]
37pub struct DistributionBridge {
38    queue: Mutex<VecDeque<OutboundHop>>,
39    ready: Condvar,
40}
41
42impl DistributionBridge {
43    pub fn new() -> Arc<Self> {
44        Arc::new(Self {
45            queue: Mutex::new(VecDeque::new()),
46            ready: Condvar::new(),
47        })
48    }
49
50    pub(crate) fn push(&self, hop: OutboundHop) -> Result<(), String> {
51        let mut queue =
52            sync_lock::lock(&self.queue, "DistributionBridge::push").map_err(|e| e.to_string())?;
53        if queue.len() >= MAX_OUTBOUND {
54            return Err("distribution bridge full".into());
55        }
56        queue.push_back(hop);
57        self.ready.notify_one();
58        Ok(())
59    }
60
61    /// Next hop, if the host has not fallen behind.
62    pub fn try_recv(&self) -> Result<Option<OutboundHop>, RuntimeError> {
63        let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::try_recv")?;
64        Ok(queue.pop_front())
65    }
66
67    /// Block until a hop arrives or `timeout` elapses.
68    pub fn recv_timeout(
69        &self,
70        timeout: std::time::Duration,
71    ) -> Result<Option<OutboundHop>, RuntimeError> {
72        let mut queue = sync_lock::lock(&self.queue, "DistributionBridge::recv_timeout")?;
73        let start = std::time::Instant::now();
74        loop {
75            if let Some(hop) = queue.pop_front() {
76                return Ok(Some(hop));
77            }
78            let left = match timeout.checked_sub(start.elapsed()) {
79                Some(left) => left,
80                None => return Ok(None),
81            };
82            let (guard, status) =
83                sync_lock::wait_timeout(&self.ready, queue, left, "DistributionBridge::wait")?;
84            queue = guard;
85            if status.timed_out() && queue.is_empty() {
86                return Ok(None);
87            }
88        }
89    }
90}
91
92/// Stamp `sender` and clear `reply_cap`. Does not mint a local reply Cap.
93pub(crate) fn stamp(message: Message, sender: FlowId) -> Message {
94    message.authenticate(sender.as_u64(), CapId::NONE)
95}
96
97/// `SendRemote` effect. `message` must already be a hop.
98pub(crate) fn deliver(
99    shared: &super::runtime::Shared,
100    flow: &mut super::process::Flow,
101    node: u64,
102    name: Arc<str>,
103    message: Value,
104) -> Result<(), String> {
105    if !flow.authority.rights().contains(crate::CapRights::SEND) {
106        return Err("send_remote denied: flow lacks SEND right".into());
107    }
108    let Some(bridge) = shared.distribution.as_ref() else {
109        return Err("send_remote: no distribution bridge".into());
110    };
111    let Some(mut msg) = message.as_message().cloned() else {
112        return Err("send_remote: value is not a hop".into());
113    };
114    if let Err(e) = flow.quota.check_send() {
115        return Err(e.to_string());
116    }
117    if msg.request_id == 0 {
118        msg.request_id = flow.vm.fresh_request_id();
119    }
120    let stamped = stamp(msg, flow.id);
121    bridge.push(OutboundHop {
122        sender: flow.id,
123        node,
124        name,
125        message: stamped,
126    })
127}
128
129#[cfg(test)]
130mod tests {
131    use std::time::Duration;
132
133    use crate::{FlowOutcome, Program, Runtime, RuntimeConfig, Value};
134
135    use super::*;
136
137    #[test]
138    fn host_drains_a_remote_hop() -> Result<(), Box<dyn std::error::Error>> {
139        let bridge = DistributionBridge::new();
140        let mut program = Program::new("remote");
141        program.function("main", 0, |f| {
142            let node = f.load_i32(7);
143            let name = f.load_str("svc");
144            let payload = f.load_i32(41);
145            let msg = f.hop_fresh(3, payload);
146            f.send_remote(node, name, msg);
147            f.return_(payload);
148        });
149        let rt = Runtime::with_natives_and_config(
150            program.build(),
151            crate::std_native_table(),
152            RuntimeConfig {
153                distribution: Some(Arc::clone(&bridge)),
154                workers: 1,
155                ..RuntimeConfig::default()
156            },
157        )?;
158        let outcome = rt.spawn(0, &[])?.join();
159        rt.shutdown();
160        match outcome {
161            FlowOutcome::Completed(Value::Int(41)) => {}
162            other => return Err(format!("remote send failed: {other:?}").into()),
163        }
164        let hop = match bridge.recv_timeout(Duration::from_secs(1))? {
165            Some(hop) => hop,
166            None => return Err("bridge empty".into()),
167        };
168        if hop.node != 7 || hop.name.as_ref() != "svc" {
169            return Err(format!("unexpected route {hop:?}").into());
170        }
171        if hop.message.reply_cap != CapId::NONE {
172            return Err("remote hop minted a local reply cap".into());
173        }
174        if !matches!(hop.message.payload.as_ref(), Value::Int(41)) {
175            return Err(format!("payload {:?}", hop.message.payload).into());
176        }
177        Ok(())
178    }
179}