Skip to main content

ping_pong/
ping_pong.rs

1//! Two flows, one Atomic Hop round-trip (`Value::Message`).
2//!
3//! Assembles the program with [`byteflow::Program`] / [`byteflow::Fn`] and
4//! runs it on [`byteflow::Runtime`] — the public host API only.
5//!
6//! ```text
7//! cargo run -p byteflow-actors --example ping_pong
8//! ```
9
10use byteflow::{
11    Chunk, FlowOutcome, MailboxConfig, Program, Runtime, RuntimeConfig, Value, DEFAULT_QUANTUM,
12    std_native_table,
13};
14
15const TAG_PING: i32 = 10;
16const TAG_PONG: i32 = 11;
17
18fn ping_pong_chunk() -> Chunk {
19    let mut program = Program::new("ping-pong");
20    let pong = program.function("pong", 0, |f| {
21        let msg = f.receive();
22        let payload = f.hop_payload(msg);
23        f.add_imm(payload, 1);
24        f.send_reply(msg, TAG_PONG, payload);
25        f.exit(payload);
26    });
27    program.function("main", 0, |f| {
28        let child = f.spawn(pong, 0);
29        let payload = f.load_i32(1);
30        let req = f.hop_fresh(TAG_PING, payload);
31        let rid = f.hop_request_id(req);
32        f.send(child, req);
33        let reply = f.receive_match_corr_imm(TAG_PONG as u16, rid);
34        let out = f.hop_payload(reply);
35        f.return_(out);
36    });
37    program.build()
38}
39
40fn main() {
41    let rt = match Runtime::with_natives_and_config(
42        ping_pong_chunk(),
43        std_native_table(),
44        RuntimeConfig {
45            workers: 1,
46            quantum: DEFAULT_QUANTUM,
47            mailbox: MailboxConfig::DEFAULT,
48            ..Default::default()
49        },
50    ) {
51        Ok(rt) => rt,
52        Err(e) => {
53            eprintln!("runtime: {e}");
54            std::process::exit(1);
55        }
56    };
57    let Some(main_fn) = rt.function_index("main") else {
58        eprintln!("missing main");
59        std::process::exit(1);
60    };
61    let handle = match rt.spawn(main_fn, &[]) {
62        Ok(h) => h,
63        Err(e) => {
64            eprintln!("spawn: {e}");
65            std::process::exit(1);
66        }
67    };
68    let outcome = handle.join();
69    let metrics = rt.metrics();
70    rt.shutdown();
71
72    match outcome {
73        FlowOutcome::Completed(Value::Int(2)) => {
74            println!("pong replied 2 (Atomic Hop)");
75            println!("{metrics}");
76        }
77        other => {
78            eprintln!("unexpected {other:?}");
79            std::process::exit(1);
80        }
81    }
82}