ipc-broker 1.1.4

A lightweight IPC broker for Rust that supports multiple transports (TCP, Unix sockets, Named Pipes) and provides an actor model with message passing and RPC capabilities.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
use async_trait::async_trait;
use serde_json::{Value, json};
use std::{
    sync::Arc,
    time::{Duration, SystemTime, UNIX_EPOCH},
};
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::windows::named_pipe::{ClientOptions, NamedPipeClient};
use tokio::{
    net::TcpStream,
    runtime::Runtime,
    sync::{Mutex, Notify},
    task,
    time::{sleep, timeout},
};
use uuid::Uuid;

use crate::{
    broker::{read_packet, run_broker, write_packet},
    client::IPCClient,
    logger,
    rpc::{CallId, RpcRequest, RpcResponse},
    worker::{SharedObject, WorkerBuilder},
};

// Stress test parameters (reduced slightly to avoid CI flakiness)
const CLIENTS: usize = 100; // lowered concurrency for stability
const OPS_PER_CLIENT: usize = 100; // fewer ops per client

// Simple RNG
struct SimpleRng(u64);
impl SimpleRng {
    fn new(seed: u64) -> Self {
        Self(seed)
    }
    fn next_u32(&mut self) -> u32 {
        let mut x = self.0;
        x ^= x << 13;
        x ^= x >> 7;
        x ^= x << 17;
        self.0 = x;
        (x & 0xFFFF_FFFF) as u32
    }
    fn choose<'a, T>(&mut self, items: &'a [T]) -> &'a T {
        let idx = (self.next_u32() as usize) % items.len();
        &items[idx]
    }
    fn gen_range(&mut self, min: u64, max: u64) -> u64 {
        min + (self.next_u32() as u64 % (max - min))
    }
}

// Start broker once using std::sync::Once
static START: std::sync::Once = std::sync::Once::new();
fn ensure_broker_running() {
    logger::setup_logger();
    START.call_once(|| {
        std::thread::spawn(|| {
            let rt = Runtime::new().unwrap();
            rt.block_on(async {
                let _ = run_broker().await;
            });
        });

        // poll for TCP port with retries but fail fast if not up
        let mut ok = false;
        for _ in 0..20 {
            if std::net::TcpStream::connect_timeout(
                &"127.0.0.1:5123".parse().unwrap(),
                Duration::from_millis(250),
            )
            .is_ok()
            {
                ok = true;
                break;
            }
            std::thread::sleep(Duration::from_millis(100));
        }
        if !ok {
            eprintln!("Broker did not start on TCP");
        }
    });
}

/// Abstraction for client connection type (TCP or Unix)
enum Conn {
    Tcp(TcpStream),
    #[cfg(unix)]
    Unix(UnixStream),
    #[cfg(windows)]
    Pipe(NamedPipeClient),
}

impl Conn {
    async fn connect_tcp() -> Self {
        // give a timeout to connect to avoid hanging tests
        let s = timeout(Duration::from_secs(3), TcpStream::connect("127.0.0.1:5123"))
            .await
            .expect("connect timeout")
            .expect("connect failed");
        Conn::Tcp(s)
    }
    #[cfg(unix)]
    async fn connect_unix() -> Self {
        use crate::rpc::UNIX_PATH;

        Conn::Unix(UnixStream::connect(UNIX_PATH).await.unwrap())
    }
    #[cfg(windows)]
    async fn connect_pipe() -> Self {
        use crate::rpc::PIPE_PATH;
        loop {
            match ClientOptions::new().open(PIPE_PATH) {
                Ok(pipe) => return Conn::Pipe(pipe),
                Err(e) if e.raw_os_error() == Some(231) => {
                    // All pipe instances are busy, wait and retry
                    log::error!("Pipe busy, retrying...");
                    sleep(Duration::from_millis(100)).await;
                }
                Err(e) => {
                    panic!("Failed to open Windows named pipe: {e:?}");
                }
            }
        }
    }

    async fn write_all(&mut self, buf: &[u8]) {
        match self {
            Conn::Tcp(s) => {
                write_packet(s, buf).await.unwrap();
            }
            #[cfg(unix)]
            Conn::Unix(s) => {
                write_packet(s, buf).await.unwrap();
            }
            #[cfg(windows)]
            Conn::Pipe(s) => {
                write_packet(s, buf).await.unwrap();
            }
        }
    }
    async fn read_some(&mut self, buf: &mut Vec<u8>) -> std::io::Result<usize> {
        match self {
            Conn::Tcp(s) => {
                let res = read_packet(s).await?;
                let len = res.len();
                *buf = res;
                Ok(len)
            }
            #[cfg(unix)]
            Conn::Unix(s) => {
                let res = read_packet(s).await?;
                let len = res.len();
                *buf = res;
                Ok(len)
            }
            #[cfg(windows)]
            Conn::Pipe(s) => {
                let res = read_packet(s).await?;
                let len = res.len();
                *buf = res;
                Ok(len)
            }
        }
    }
}

// (Stress tests reduced and made more conservative)
#[tokio::test]
async fn tcp_stress_broker() {
    ensure_broker_running();
    let mut handles = Vec::new();
    for i in 0..CLIENTS {
        handles.push(task::spawn(async move {
            let mut conn = Conn::connect_tcp().await;

            let seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos() as u64
                ^ (i as u64);
            let mut rng = SimpleRng::new(seed);

            let my_object = format!("obj_{i}");
            let reg = RpcRequest::RegisterObject {
                object_name: my_object.clone(),
            };
            conn.write_all(&serde_json::to_vec(&reg).unwrap()).await;

            let mut ops_done = 0usize;
            let mut read_buf = Vec::new();

            while ops_done < OPS_PER_CLIENT {
                let op_type = *rng.choose(&["call", "subscribe", "publish"]);
                match op_type {
                    "call" => {
                        let req = RpcRequest::Call {
                            call_id: CallId::from(Uuid::new_v4()),
                            object_name: my_object.clone(),
                            method: "echo".into(),
                            args: json!({"msg": format!("hello from client {i}")}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "subscribe" => {
                        let req = RpcRequest::Subscribe {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "publish" => {
                        let req = RpcRequest::Publish {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                            args: json!({"val": rng.next_u32()}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    _ => {}
                }

                // non-blocking read
                if let Ok(Ok(n)) =
                    timeout(Duration::from_millis(50), conn.read_some(&mut read_buf)).await
                    && n > 0
                    && let Ok(val) = serde_json::from_slice::<RpcResponse>(&read_buf[..n])
                {
                    log::debug!("Client {i} got response: {val:?}");
                }

                ops_done += 1;
                sleep(Duration::from_millis(rng.gen_range(5, 20))).await;
            }
        }));
    }
    for h in handles {
        let _ = h.await;
    }
}

#[cfg(unix)]
#[tokio::test]
async fn unix_stress_broker() {
    ensure_broker_running();
    let mut handles = Vec::new();
    for i in 0..CLIENTS {
        handles.push(task::spawn(async move {
            let mut conn = Conn::connect_unix().await;

            let seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos() as u64
                ^ (i as u64);
            let mut rng = SimpleRng::new(seed);

            let my_object = format!("obj_{i}");
            let reg = RpcRequest::RegisterObject {
                object_name: my_object.clone(),
            };
            conn.write_all(&serde_json::to_vec(&reg).unwrap()).await;

            let mut ops_done = 0usize;
            let mut read_buf = Vec::new();

            while ops_done < OPS_PER_CLIENT {
                let op_type = *rng.choose(&["call", "subscribe", "publish"]);
                match op_type {
                    "call" => {
                        let req = RpcRequest::Call {
                            call_id: CallId::from(Uuid::new_v4()),
                            object_name: my_object.clone(),
                            method: "echo".into(),
                            args: json!({"msg": format!("hello from client {i}")}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "subscribe" => {
                        let req = RpcRequest::Subscribe {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "publish" => {
                        let req = RpcRequest::Publish {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                            args: json!({"val": rng.next_u32()}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    _ => {}
                }

                // non-blocking read
                if let Ok(Ok(n)) =
                    timeout(Duration::from_millis(50), conn.read_some(&mut read_buf)).await
                    && n > 0
                    && let Ok(val) = serde_json::from_slice::<RpcResponse>(&read_buf[..n])
                {
                    log::debug!("Client {i} got response: {val:?}");
                }

                ops_done += 1;
                sleep(Duration::from_millis(rng.gen_range(5, 20))).await;
            }
        }));
    }
    for h in handles {
        let _ = h.await;
    }
}

#[cfg(windows)]
#[tokio::test]
async fn pipe_stress_broker() {
    ensure_broker_running();
    let mut handles = Vec::new();
    for i in 0..CLIENTS {
        handles.push(task::spawn(async move {
            let mut conn = Conn::connect_pipe().await;

            let seed = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .unwrap()
                .as_nanos() as u64
                ^ (i as u64);
            let mut rng = SimpleRng::new(seed);

            let my_object = format!("obj_{i}");
            let reg = RpcRequest::RegisterObject {
                object_name: my_object.clone(),
            };
            conn.write_all(&serde_json::to_vec(&reg).unwrap()).await;

            let mut ops_done = 0usize;
            let mut read_buf = Vec::new();

            while ops_done < OPS_PER_CLIENT {
                let op_type = *rng.choose(&["call", "subscribe", "publish"]);
                match op_type {
                    "call" => {
                        let req = RpcRequest::Call {
                            call_id: CallId::from(Uuid::new_v4()),
                            object_name: my_object.clone(),
                            method: "echo".into(),
                            args: json!({"msg": format!("hello from client {i}")}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "subscribe" => {
                        let req = RpcRequest::Subscribe {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    "publish" => {
                        let req = RpcRequest::Publish {
                            object_name: my_object.clone(),
                            topic: format!("topic_{}", i % 10),
                            args: json!({"val": rng.next_u32()}),
                        };
                        let _ = timeout(
                            Duration::from_secs(1),
                            conn.write_all(&serde_json::to_vec(&req).unwrap()),
                        )
                        .await;
                    }
                    _ => {}
                }

                // non-blocking read
                if let Ok(Ok(n)) =
                    timeout(Duration::from_millis(50), conn.read_some(&mut read_buf)).await
                    && n > 0
                    && let Ok(val) = serde_json::from_slice::<RpcResponse>(&read_buf[..n])
                {
                    log::debug!("Client {i} got response: {val:?}");
                }

                ops_done += 1;
                sleep(Duration::from_millis(rng.gen_range(5, 20))).await;
            }
        }));
    }
    for h in handles {
        let _ = h.await;
    }
}

#[tokio::test]
async fn client_worker() {
    ensure_broker_running();

    struct Calculator;

    #[async_trait]
    impl SharedObject for Calculator {
        async fn call(&self, method: &str, args: &Value) -> Value {
            match method {
                "add" => {
                    let a = args.get(0).and_then(Value::as_i64).unwrap_or(0);
                    let b = args.get(1).and_then(Value::as_i64).unwrap_or(0);
                    (a + b).into()
                }
                "mul" => {
                    let a = args.get(0).and_then(Value::as_i64).unwrap_or(0);
                    let b = args.get(1).and_then(Value::as_i64).unwrap_or(0);
                    (a * b).into()
                }
                _ => Value::String("Unknown method".into()),
            }
        }
    }

    struct Logger;
    #[async_trait]
    impl SharedObject for Logger {
        async fn call(&self, method: &str, args: &Value) -> Value {
            log::debug!("LOG: {method} -> {args}");
            Value::Null
        }
    }

    tokio::spawn(async move {
        // IMPORTANT: ensure run_worker signals readiness
        let calc = Calculator;
        let logger = Logger;
        if let Err(e) = WorkerBuilder::new()
            .add("Calculator", calc)
            .add("Logger", logger)
            .spawn()
            .await
        {
            log::error!("worker exited early: {e:?}");
        }
    });

    let proxy = IPCClient::connect().await.unwrap();

    proxy
        .wait_for_object("Calculator")
        .await
        .expect("wait_for_object failed");

    let response = proxy
        .remote_call::<Value, i32>("Calculator", "add", json!([5, 7]))
        .await
        .unwrap();
    log::debug!("Client got response: {response}");
    assert_eq!(response, 12);

    let response = proxy
        .remote_call::<Value, i32>("Calculator", "mul", json!([5, 7]))
        .await
        .unwrap();
    log::debug!("Client got response: {response}");
    assert_eq!(response, 35);

    let response = proxy
        .remote_call::<Value, Value>("Logger", "method", Value::Null)
        .await
        .unwrap();
    log::debug!("Client got response: {response}");
    assert_eq!(response, Value::Null);
}

#[tokio::test(flavor = "multi_thread", worker_threads = 8)]
async fn publish_subscribe() {
    ensure_broker_running();

    // Shared states for each subscription
    let news_val: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
    let news1_val: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));

    // signal channel
    let news_val_for_task = Arc::clone(&news_val);
    let news1_val_for_task = Arc::clone(&news1_val);
    let notify = Arc::new(Notify::new());
    let notify_clone = notify.clone();
    tokio::spawn(async move {
        let client = IPCClient::connect().await.unwrap();

        let inner_news_val = Arc::clone(&news_val_for_task);
        client
            .subscribe_async("news_obj", "news", move |value| {
                let inner_news_val = Arc::clone(&inner_news_val);
                tokio::spawn(async move {
                    let mut val = inner_news_val.lock().await;
                    *val = Some(value);
                });
            })
            .await;

        let inner_news1_val = Arc::clone(&news1_val_for_task);
        client
            .subscribe_async("news_obj", "news1", move |value| {
                let inner_news1_val = Arc::clone(&inner_news1_val);
                tokio::spawn(async move {
                    let mut val = inner_news1_val.lock().await;
                    *val = Some(value);
                });
            })
            .await;

        // small sleep to allow registration (bounded)
        tokio::time::sleep(Duration::from_millis(200)).await;
        notify_clone.notify_one(); // signal that subscriber is ready
    });

    // wait for subscriber ready but bound it
    timeout(Duration::from_secs(3), notify.notified())
        .await
        .expect("subscriber did not register in time");
    let proxy = IPCClient::connect().await.unwrap();

    proxy
        .publish(
            "news_obj",
            "news",
            &json!({"headline": "Rust broker eventing works!"}),
        )
        .await
        .unwrap();
    proxy
        .publish("news_obj", "news1", &json!({"headline": "Another news!"}))
        .await
        .unwrap();

    log::debug!("[Publisher] done broadcasting");

    // Wait a bit for callbacks to fire (bounded)
    async fn wait_for_update(val: Arc<Mutex<Option<Value>>>) -> Value {
        timeout(Duration::from_secs(5), async {
            loop {
                if let Some(v) = val.lock().await.clone() {
                    return v;
                }
                tokio::task::yield_now().await;
            }
        })
        .await
        .expect("Timed out waiting for subscriber update")
    }

    let n1 = wait_for_update(news_val.clone()).await;
    let n2 = wait_for_update(news1_val.clone()).await;

    assert_eq!(n1["headline"], "Rust broker eventing works!");
    assert_eq!(n2["headline"], "Another news!");
}

// --- Additional edge-case and fuzz tests ---

#[tokio::test]
async fn oversized_payload_echo() {
    ensure_broker_running();

    // Echo object that returns the args so we can verify large payload roundtrip
    struct Echo;
    #[async_trait]
    impl SharedObject for Echo {
        async fn call(&self, _method: &str, args: &Value) -> Value {
            args.clone()
        }
    }

    tokio::spawn(async move {
        if let Err(e) = WorkerBuilder::new().add("Echo", Echo).spawn().await {
            log::error!("worker exited early: {e:?}");
        }
    });

    tokio::time::sleep(Duration::from_millis(200)).await;

    let proxy = IPCClient::connect().await.unwrap();
    proxy.wait_for_object("Echo").await.unwrap();

    // create a ~16KB string payload (safer for CI environments)
    let big = "x".repeat(16 * 1024);
    let arg = json!([big.clone()]);

    let got = proxy
        .remote_call::<Value, Value>("Echo", "any", arg.clone())
        .await
        .unwrap();

    assert_eq!(got, arg);
}

#[tokio::test]
async fn random_fuzz_echo_roundtrips() {
    ensure_broker_running();

    // re-use Echo object
    struct Echo2;
    #[async_trait]
    impl SharedObject for Echo2 {
        async fn call(&self, _method: &str, args: &Value) -> Value {
            args.clone()
        }
    }

    tokio::spawn(async move {
        if let Err(e) = WorkerBuilder::new().add("Echo2", Echo2).spawn().await {
            log::error!("worker exited early: {e:?}");
        }
    });

    tokio::time::sleep(Duration::from_millis(200)).await;

    let proxy = IPCClient::connect().await.unwrap();
    proxy.wait_for_object("Echo2").await.unwrap();

    // Seed RNG and perform many small randomized round-trips including edge cases
    let mut rng = SimpleRng::new(
        SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_nanos() as u64,
    );

    for _ in 0..120 {
        let choice = rng.next_u32() % 7;
        let val = match choice {
            0 => json!(null),
            1 => json!(true),
            2 => json!(""),
            3 => json!(rng.next_u32()),
            4 => json!(rng.gen_range(0, 1000)),
            5 => json!([rng.next_u32(), rng.next_u32(), rng.next_u32()]),
            _ => json!({"k": rng.next_u32(), "s": format!("fuzz-{}", rng.next_u32())}),
        };

        let sent = json!([val.clone()]);
        let got = timeout(
            Duration::from_secs(2),
            proxy.remote_call::<Value, Value>("Echo2", "any", sent.clone()),
        )
        .await
        .expect("timeout")
        .unwrap();

        assert_eq!(got, sent);
    }
}

#[tokio::test]
async fn oversized_remote_call_error() {
    ensure_broker_running();

    // Spawn a dedicated Echo object for this test
    struct EchoHuge;
    #[async_trait]
    impl SharedObject for EchoHuge {
        async fn call(&self, _method: &str, args: &Value) -> Value {
            args.clone()
        }
    }

    tokio::spawn(async move {
        if let Err(e) = WorkerBuilder::new().add("EchoHuge", EchoHuge).spawn().await {
            log::error!("worker exited early: {e:?}");
        }
    });

    tokio::time::sleep(Duration::from_millis(200)).await;

    let proxy = IPCClient::connect().await.unwrap();
    proxy.wait_for_object("EchoHuge").await.unwrap();

    // create payload larger than the allowed BUF_SIZE to trigger write_packet error
    let big = "x".repeat(crate::rpc::BUF_SIZE + 10);
    let arg = json!([big]);

    let res = proxy
        .remote_call::<Value, Value>("EchoHuge", "any", arg)
        .await;

    assert!(res.is_err(), "expected error for oversized payload");
    let e = res.unwrap_err();
    assert_eq!(e.kind(), std::io::ErrorKind::InvalidData);
    assert!(
        e.to_string().contains("exceeds"),
        "error message should mention 'exceeds'"
    );
}