Skip to main content

byteflow/
lib.rs

1//! Byteflow — embeddable **flow** runtime (package **`byteflow-actors`**).
2//!
3//! Not a language, not Tokio, not a JVM. You assemble register bytecode in
4//! host Rust ([`Program`] / [`Fn`]), spawn many lightweight **flows** on an M:N
5//! scheduler, and they talk through mailboxes with a strict hop protocol.
6//!
7//! Dependents write `use byteflow::...` (crate name) while crates.io lists
8//! the package as [`byteflow-actors`](https://crates.io/crates/byteflow-actors).
9//!
10//! # What you get
11//!
12//! | Piece | Role |
13//! |-------|------|
14//! | [`Program`] / [`Fn`] / [`Opcode`] | Assemble `.bf` programs in Rust (no source language) |
15//! | [`verify`] | Static gate for untrusted chunks — mandatory, not advisory |
16//! | [`Vm`] / [`VmResult`] | Per-flow register interpreter; effects hand off to the scheduler |
17//! | [`Runtime`] | Worker pool + timer; spawn / join / host [`Runtime::send`] |
18//! | [`FlowHandle`] | Collect an outcome: blocking [`FlowHandle::join`] or a bounded form |
19//! | [`Value::Message`] | **Atomic Hop** envelope — the only value allowed on `Send` / `Ask` |
20//! | [`Value::Cap`] | **FlowCap** address for bytecode delivery (`Send` / `Ask` targets) |
21//! | [`Cap`] / [`CapRights`] / [`NativeMask`] | Holder + rights; [`Cap::attenuate`] is the only grant path |
22//! | [`QuotaConfig`] / [`FlowQuota`] | Per-flow CPU / heap / spawn-send budgets |
23//! | [`Supervisor`] | OTP strategies (`OneForOne` / `OneForAll` / `RestForOne`) |
24//! | [`std_native_table`] | `print`, `now_ms`, `make_msg` (3-arg), `msg_*`, `msg_reply_cap` |
25//!
26//! # Atomic Hop (messaging contract)
27//!
28//! Every bytecode `Send` / `Ask` carries exactly one [`Message`]:
29//!
30//! ```text
31//! Message { sender, reply_cap, request_id, tag, payload }
32//! ```
33//!
34//! - Bare `Int` / `Pid` / `Str` on `Send` → trap / [`SendError::NotAHop`]
35//! - Scheduler **stamps** `sender` (authenticated origin) and attaches
36//!   `reply_cap` (stable SEND-only Cap back to the caller, reused per pair)
37//! - Reply with [`std_native_table`]'s `msg_reply_cap` — **not** `msg_sender`
38//!   (`Pid` is identity, not an address)
39//!
40//! Also: selective receive (`ReceiveMatch` / `ReceiveMatchCorr`),
41//! `Ask` / `AskTimeout` for correlated RPC, [`Fn::fresh_request_id`].
42//!
43//! # FlowCap (addressing)
44//!
45//! | Value | Use |
46//! |-------|-----|
47//! | [`Value::Cap`] | Target of `Send` / `Ask`; from `SelfPid`, `Spawn`, or `reply_cap` |
48//! | [`Value::Pid`] | Identity inside a delivered hop (`msg_sender`) |
49//!
50//! Host [`Runtime::send`] still takes [`FlowId`] (trusted embedder path)
51//! and is stamped `sender = 0` / `reply_cap = NONE`.
52//!
53//! Named discovery: [`Fn::register_name`] / [`Fn::whereis`] — `whereis`
54//! returns a SEND Cap for the caller, never a raw FlowId.
55//!
56//! Caps resolve only for the **holder** with sufficient rights. Derive a
57//! weaker grant with [`Fn::delegate`] / [`Cap::attenuate`] — never by
58//! copying a `CapId`. Host spawn is `ROOT`; bytecode [`Fn::spawn_confined`]
59//! starts at `NONE`.
60//!
61//! # Values (ABI v5)
62//!
63//! `Unit | Bool | Int | Float | Pid | Message | Cap | Str | Bytes`
64//!
65//! `CapId` is a 128-bit CSPRNG token. `Message.payload` is a nested
66//! [`Value`]. `Str` / `Bytes` are `Arc`-backed for cheap register/mailbox
67//! clones. They are **not** Atomic Hops by themselves.
68//!
69//! # Quick start — scalar
70//!
71//! ```
72//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
73//! use byteflow::{Program, FlowOutcome, Runtime, Value};
74//!
75//! let mut program = Program::new("demo");
76//! program.function("main", 0, |f| {
77//!     let a = f.load_i32(41);
78//!     let b = f.load_i32(1);
79//!     let sum = f.add(a, b);
80//!     f.return_(sum);
81//! });
82//!
83//! let rt = Runtime::new(program.build())?;
84//! let outcome = rt.spawn(0, &[])?.join();
85//! rt.shutdown();
86//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(42))));
87//! # Ok(())
88//! # }
89//! ```
90//!
91//! # Quick start — Atomic Hop (ping-pong)
92//!
93//! Assemble with [`Program`] / [`Fn`], then run on [`Runtime`]:
94//!
95//! ```
96//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
97//! use byteflow::{FlowOutcome, Program, Runtime, Value, std_native_table};
98//!
99//! const TAG_PING: i32 = 10;
100//! const TAG_PONG: i32 = 11;
101//!
102//! let mut program = Program::new("ping-pong");
103//! let pong = program.function("pong", 0, |f| {
104//!     let msg = f.receive();
105//!     let payload = f.hop_payload(msg);
106//!     f.add_imm(payload, 1);
107//!     f.send_reply(msg, TAG_PONG, payload);
108//!     f.exit(payload);
109//! });
110//! program.function("main", 0, |f| {
111//!     let child = f.spawn(pong, 0);
112//!     let payload = f.load_i32(1);
113//!     let req = f.hop_fresh(TAG_PING, payload);
114//!     let rid = f.hop_request_id(req);
115//!     f.send(child, req);
116//!     let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
117//!     let out = f.hop_payload(reply);
118//!     f.return_(out);
119//! });
120//!
121//! let rt = Runtime::with_natives(program.build(), std_native_table())?;
122//! let Some(main) = rt.function_index("main") else {
123//!     return Err("missing main".into());
124//! };
125//! let outcome = rt.spawn(main, &[])?.join();
126//! rt.shutdown();
127//! assert!(matches!(outcome, FlowOutcome::Completed(Value::Int(2))));
128//! # Ok(())
129//! # }
130//! ```
131//!
132//! Built-in helpers for tests: [`samples::ping_pong`], [`samples::ask_reply`],
133//! [`samples::selective_receive`], forged-sender security regressions.
134//!
135//! # Collecting a result
136//!
137//! [`FlowHandle::join`] blocks, which suits a `main` with nothing else to
138//! do. Anything holding a deadline picks its own bound instead:
139//!
140//! | Call | Waits | While the flow is still running |
141//! |------|-------|---------------------------------|
142//! | [`FlowHandle::try_join`] | never | `None` |
143//! | [`FlowHandle::join_timeout`] / [`FlowHandle::join_deadline`] | up to the bound | `None` |
144//! | [`FlowHandle::join`] | unbounded | (blocks) |
145//!
146//! ```
147//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
148//! use byteflow::{Program, FlowOutcome, Runtime, Value};
149//! use std::time::Duration;
150//!
151//! let mut program = Program::new("slow");
152//! program.function("main", 0, |f| {
153//!     let ms = f.load_i32(300);
154//!     f.sleep(ms);
155//!     let out = f.load_i32(7);
156//!     f.return_(out);
157//! });
158//!
159//! let rt = Runtime::new(program.build())?;
160//! let handle = rt.spawn(0, &[])?;
161//!
162//! // Neither of these consumes the handle or the outcome.
163//! assert!(handle.try_join().is_none());
164//! assert!(handle.join_timeout(Duration::from_millis(10)).is_none());
165//!
166//! let outcome = handle.join_timeout(Duration::from_secs(10));
167//! rt.shutdown();
168//! assert!(matches!(outcome, Some(FlowOutcome::Completed(Value::Int(7)))));
169//! # Ok(())
170//! # }
171//! ```
172//!
173//! A flow destroyed before it produced an outcome — [`Runtime::shutdown`]
174//! does not drain suspended flows — wakes its joiner with a failure instead
175//! of leaving it parked forever. See [`docs::error_model`].
176//!
177//! # Design guides (rendered on docs.rs)
178//!
179//! - [`docs::atomic_hop`] — hop protocol, Cap addressing, natives table
180//! - [`docs::beam_mapping`] — BEAM / OTP mental model → Byteflow equivalents
181//! - [`docs::lifecycle`] — monitors, links, registry, `WAITING_SEND`
182//! - [`docs::mailbox`] — bounded inbox, overflow, lost-wakeup
183//! - [`docs::security`] — threat model, invariants S1–S7, Phase 3 (0.9.2+)
184//! - [`docs::error_model`] — fail-closed errors (no `unwrap`), bounded joins
185//! - [`docs::vm_safety`] — trust boundary: `verify` vs per-step `Fault`
186//!
187//! # What this is *not*
188//!
189//! - Not a replacement for Tokio / async Rust (no `.await` IO loop)
190//! - Not a distributed cluster runtime (single process, in-memory mailboxes)
191//! - Not a full object-capability OS (no distributed revocation / Cap persistence)
192//!
193//! Host owns I/O and policy. Byteflow owns cheap concurrency and hop delivery.
194#![deny(unsafe_code)]
195#![cfg_attr(docsrs, feature(doc_cfg))]
196
197pub mod bytecode;
198pub mod log;
199pub mod natives;
200pub mod output;
201pub mod samples;
202pub mod scheduler;
203pub mod vm;
204
205#[cfg(feature = "jit")]
206#[cfg_attr(docsrs, doc(cfg(feature = "jit")))]
207pub mod jit;
208
209/// Long-form design notes shipped inside the crate (also under `docs/` on GitHub).
210///
211/// These modules exist so [docs.rs](https://docs.rs/byteflow-actors) shows the
212/// same guides as the repository, not only API rustdoc.
213pub mod docs {
214    /// Atomic Hop: Message-only Send, FlowCap addressing, Ask, selective receive.
215    #[doc = include_str!("../docs/atomic-hop.md")]
216    pub mod atomic_hop {}
217
218    /// BEAM / OTP concepts mapped to Byteflow flows, Caps, and Atomic Hop.
219    #[doc = include_str!("../docs/beam-mapping.md")]
220    pub mod beam_mapping {}
221
222    /// Flow lifecycle: monitors, links, registry, WAITING_SEND.
223    #[doc = include_str!("../docs/lifecycle.md")]
224    pub mod lifecycle {}
225
226    /// Security model: authenticated sender, FlowCap, invariants S1–S7.
227    #[doc = include_str!("../docs/security.md")]
228    pub mod security {}
229
230    /// Fail-closed error taxonomy and mutex policy.
231    #[doc = include_str!("../docs/error-model.md")]
232    pub mod error_model {}
233
234    /// Trust boundary: what `verify` settles statically vs what the `Vm`
235    /// checks per step, and why a fault never becomes a panic.
236    #[doc = include_str!("../docs/vm-safety.md")]
237    pub mod vm_safety {}
238
239    /// Bounded mailbox: capacity contract, overflow, anti lost-wakeup.
240    #[doc = include_str!("../docs/mailbox.md")]
241    pub mod mailbox {}
242}
243
244pub use bytecode::{
245    asm_macros, decode, decode_with, disassemble, encode, verify, verify_with, Cap, CapId,
246    CapIdError, CapRights, CapTarget, Chunk, Fn, ConstantKind, FormatError, FuncId, FunctionDef,
247    Instruction, Label, Message, NativeIdx, NativeMask, Opcode, Program, Reg, RegWindow,
248    RevocationCell, TrustLevel, Value, VerifyConfig, VerifyError, ABI_VERSION, MAGIC,
249    TAG_SYS_DOWN, TAG_SYS_EXIT,
250};
251pub use output::{NullSink, OutputSink, StdoutSink};
252pub use natives::{std_native, std_native_map, std_native_table, std_native_table_with, std_natives};
253pub use scheduler::{
254    fault_count, next_flow_id, flow_id_from_u64, report_fault, CapError, Capability,
255    ChildSpec, Delivery, DownEvent, FlowExitReason, FlowQuota, LifecycleError, LinkId, Mailbox, MailboxBytes,
256    MailboxCapacity, MailboxConfig, MailboxFull, MailboxFullReason, MailboxStats,
257    MonitorRef, OverflowPolicy, QuotaConfig, QuotaError, RegistryName, WaitEpoch, Flow, FlowHandle, FlowId,
258    FlowMetrics, FlowOutcome, RestartPolicy, RestartStrategy, Runtime, RuntimeConfig,
259    RuntimeError, RuntimeMetrics, RuntimeMetricsSnapshot, RuntimeSpawner, SendError,
260    SpawnError, Supervisor, SupervisorConfig, DEFAULT_QUANTUM, check_admin, check_link,
261    check_monitor, exec_delegate, AdminError, DelegateError, LinkError,
262};
263#[cfg(feature = "jit")]
264pub use scheduler::JitConfig;
265pub use vm::{
266    expect_arg, expect_bool, expect_int, expect_message, expect_u64, check_native_call,
267    check_native_gate,
268    Fault, NativeCallError, NativeFn, NativeGate, NativeResult, NativeTable, NativeTableBuilder,
269    NativeTableError, Vm, VmResult, MAX_CALL_DEPTH,
270};
271
272#[cfg(feature = "jit")]
273pub use jit::{
274    apply_exit_to_vm, force_compile, hot_threshold, run_compiled_trace, run_compiled_trace_ref,
275    run_vm_with_jit, run_vm_with_jit_runtime, sync_slots_from_vm, try_run_hot, try_run_hot_runtime,
276    CompileError, CompiledTrace, ExitReason, HotCounter, JitContext, JitEntry, JitFrame, JitReturn,
277    JitRuntime, SyncSlotsResult, TraceCache, TraceCompiler, TraceKey, TraceSpan, HOT_THRESHOLD,
278    MAX_TRACE_LENGTH, JIT_BUDGET, JIT_CONTINUE, JIT_DEOPT, JIT_EFFECT, JIT_RETURN, JIT_TRAP,
279};
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284
285    #[test]
286    fn std_native_map_has_stable_indices() {
287        let map = std_native_map();
288        assert_eq!(map.get("print"), Some(&0));
289        assert_eq!(map.get("now_ms"), Some(&1));
290        assert_eq!(map.get("make_msg"), Some(&2));
291        assert_eq!(map.get("msg_payload"), Some(&6));
292        assert_eq!(map.get("msg_reply_cap"), Some(&7));
293    }
294
295    #[test]
296    fn std_native_chunk_runs() -> Result<(), Box<dyn std::error::Error>> {
297        let mut program = Program::new("std-natives-demo");
298        program.function("main", 0, |f| {
299            let n = f.load_i32(42);
300            f.native1_on(n, 0);
301            let ms = f.call_native0(1);
302            f.return_(ms);
303        });
304
305        let chunk = program.build();
306        verify(&chunk)?;
307
308        let rt = Runtime::with_natives(chunk, std_native_table())?;
309        let outcome = rt.spawn(0, &[])?.join();
310        rt.shutdown();
311
312        match outcome {
313            FlowOutcome::Completed(Value::Int(ms)) => {
314                assert!(ms >= 0);
315                Ok(())
316            }
317            other => Err(format!("expected Completed(Value::Int(_)), got {other:?}").into()),
318        }
319    }
320}