ipc-broker 1.1.5

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
use std::sync::Arc;

use serde::{Serialize, de::DeserializeOwned};
use serde_json::Value;
#[cfg(unix)]
use tokio::net::UnixStream;
#[cfg(windows)]
use tokio::net::windows::named_pipe::ClientOptions;
use tokio::{
    io::{AsyncRead, AsyncWrite},
    net::TcpStream,
    sync::{mpsc, oneshot},
};
use uuid::Uuid;

use crate::{
    broker::{read_packet, write_packet},
    rpc::{CallId, RpcRequest, RpcResponse},
};

/// A trait alias for any asynchronous stream type
/// that implements both [`AsyncRead`] and [`AsyncWrite`].
pub trait AsyncStream: AsyncRead + AsyncWrite {}
impl<T: AsyncRead + AsyncWrite + Unpin> AsyncStream for T {}

/// Internal message sent to the client actor.
///
/// This is used to decouple the `IPCClient` (public API)
/// from the background task that drives I/O with the server.
enum ClientMsg {
    /// Request a remote procedure call, expecting a response.
    Request {
        req: RpcRequest,
        resp_tx: oneshot::Sender<std::io::Result<RpcResponse>>,
    },
    /// Subscribe to a publish/subscribe topic on a remote object.
    Subscribe {
        object_name: String,
        topic: String,
        updates: mpsc::Sender<serde_json::Value>,
    },
}

/// A handle to a client connection.
///
/// This is the main entrypoint for making RPC calls,
/// publishing events, or subscribing to topics.
/// Internally it communicates with a background task (the “client actor”)
/// that manages the network connection.
#[derive(Clone)]
pub struct IPCClient {
    tx: mpsc::Sender<ClientMsg>,
}

impl IPCClient {
    /// Connect to the broker and spawn the client actor.
    ///
    /// - If `BROKER_ADDR` environment variable is set, it connects via TCP.
    /// - Otherwise it attempts local IPC:
    ///   - On Unix: connects to a Unix socket at `rpc::UNIX_PATH`.
    ///   - On Windows: connects to a named pipe at `rpc::PIPE_PATH`.
    ///
    /// Returns a [`IPCClient`] that can be used to issue requests.
    pub async fn connect() -> std::io::Result<Self> {
        // Pick transport
        let stream: Box<dyn AsyncStream + Send + Unpin> =
            if let Ok(ip) = std::env::var("BROKER_ADDR") {
                let tcp = TcpStream::connect(ip.as_str()).await?;
                log::info!("Connected into TCP: {ip}");
                Box::new(tcp)
            } else {
                // Local IPC depending on OS
                #[cfg(unix)]
                {
                    use crate::rpc::UNIX_PATH;

                    let unix = UnixStream::connect(UNIX_PATH).await?;
                    log::info!("Connected into Unix: {UNIX_PATH}");
                    Box::new(unix)
                }

                #[cfg(windows)]
                {
                    use crate::rpc::PIPE_PATH;
                    loop {
                        let res = match ClientOptions::new().open(PIPE_PATH) {
                            Ok(pipe) => {
                                log::info!("Connected into NamedPipe: {PIPE_PATH}");
                                Box::new(pipe)
                            }
                            Err(e) if e.raw_os_error() == Some(231) => {
                                // All pipe instances busy → wait and retry

                                use std::time::Duration;

                                log::error!("All pipe instances busy, retrying...");
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                continue;
                            }
                            Err(e) => {
                                use std::time::Duration;
                                log::error!("Failed to connect to pipe: {}", e);
                                tokio::time::sleep(Duration::from_millis(100)).await;
                                continue;
                            }
                        };
                        break res;
                    }
                }
            };

        // channel for handles -> actor (bounded to provide backpressure)
        let (tx, mut rx) = mpsc::channel::<ClientMsg>(64);

        // Spawn the client actor task
        tokio::spawn(async move {
            let mut stream = stream;
            let mut subs: std::collections::HashMap<
                (String, String),
                Vec<mpsc::Sender<serde_json::Value>>,
            > = std::collections::HashMap::new();

            loop {
                tokio::select! {
                    Some(msg) = rx.recv() => {
                        match msg {
                            ClientMsg::Request { req, resp_tx } => {
                                // Serialize and send
                                let data = match serde_json::to_vec(&req) {
                                    Ok(d) => d,
                                    Err(e) => {
                                        let _ = resp_tx.send(Err(std::io::Error::new(std::io::ErrorKind::InvalidData, e)));
                                        continue;
                                    }
                                };

                                if let Err(e) = write_packet(&mut stream, &data).await {
                                    let _ = resp_tx.send(Err(e));
                                    continue;
                                }

                                // Wait for one response
                                match req {
                                    RpcRequest::Call { .. } | RpcRequest::RegisterObject { .. }
                                    | RpcRequest::HasObject { .. }
                                    | RpcRequest::RegisterService { .. } => {
                                        // Only these expect a response
                                        match read_packet(&mut stream).await {
                                            Ok(data) => {
                                                let resp: Result<RpcResponse, _> = serde_json::from_slice(&data);
                                                match resp {
                                                    Ok(r) => { let _ = resp_tx.send(Ok(r)); }
                                                    Err(e) => {
                                                        let _ = resp_tx.send(Err(std::io::Error::new(
                                                            std::io::ErrorKind::InvalidData,
                                                            e,
                                                        )));
                                                    }
                                                }
                                            }
                                            Err(e) => {
                                                let _ = resp_tx.send(Err(e));
                                            }
                                         }
                                    }
                                    RpcRequest::Publish { .. } | RpcRequest::Subscribe { .. } => {
                                        log::trace!("Fire-and-forget: do not await a response");
                                        let _ = resp_tx.send(Ok(RpcResponse::Event {
                                            object_name: "".into(),
                                            topic: "".into(),
                                            args: serde_json::Value::Null,
                                        }));
                                    }
                                }
                            }
                            ClientMsg::Subscribe { object_name, topic, updates } => {
                                log::debug!("Client subscribing to {object_name}/{topic}");
                                subs.entry((object_name.clone(), topic.clone()))
                                    .or_default()
                                    .push(updates);

                                let data = match serde_json::to_vec(&RpcRequest::Subscribe {
                                    object_name: object_name.clone(),
                                    topic: topic.clone(),
                                }) {
                                    Ok(d) => d,
                                    Err(e) => {
                                        log::error!("Failed to serialize Subscribe request: {e}");
                                        continue;
                                    }
                                };

                                let _ = write_packet(&mut stream, &data).await;
                            }

                        }
                    }
                    Ok(data) = read_packet(&mut stream) => {
                        if data.is_empty() {
                            break;
                        }
                        log::debug!("Data {}", String::from_utf8_lossy(&data));
                        match serde_json::from_slice::<RpcResponse>(&data) {
                            Ok(resp) => {
                                // Handle Publish notifications
                                if let RpcResponse::Event { object_name, topic, args } = resp {
                                    if let Some(subscribers) = subs.get_mut(&(object_name.clone(), topic.clone())) {
                                        // Iterate and prune closed or slow subscribers
                                        subscribers.retain(|tx| {
                                            match tx.try_send(args.clone()) {
                                                Ok(()) => true,
                                                Err(e) => {
                                                    use tokio::sync::mpsc::error::TrySendError;
                                                    match e {
                                                        TrySendError::Closed(_) => {
                                                            // Subscriber dropped, remove
                                                            log::debug!("Pruning closed subscriber for {object_name}/{topic}");
                                                            false
                                                        }
                                                        TrySendError::Full(_) => {
                                                            // Subscriber is slow; drop to avoid unbounded buffering
                                                            log::warn!("Dropping slow subscriber for {object_name}/{topic}");
                                                            false
                                                        }
                                                    }
                                                }
                                            }
                                        });
                                    }
                                } else{
                                    log::trace!("Other responses are ignored here; handled elsewhere");
                                }
                                continue;
                            }
                            Err(_) => {
                                log::trace!("Partial JSON, fallthrough to buffer handling");
                            }
                        }
                    }
                    else => {
                        // This should never trigger now, but prevents future panics
                        log::warn!("All select branches disabled — exiting loop defensively");
                        break;
                    }
                }
            }
        });

        Ok(Self { tx })
    }

    /// Call a method on a remote object.
    ///
    /// - `object`: name of the remote object.
    /// - `method`: method name.
    /// - `args`: JSON arguments.
    ///
    /// Returns the deserialized [`RpcResponse`] or an error if
    /// the call failed or connection was lost.
    pub async fn remote_call<U, T>(&self, object: &str, method: &str, args: U) -> std::io::Result<T>
    where
        T: DeserializeOwned,
        U: Serialize + std::any::Any + 'static,
    {
        let args = if let Some(val) = (&args as &dyn std::any::Any).downcast_ref::<Value>() {
            val.clone()
        } else {
            serde_json::to_value(args)?
        };
        let call_id = CallId::from(Uuid::new_v4());

        let req = RpcRequest::Call {
            call_id,
            object_name: object.into(),
            method: method.into(),
            args,
        };

        let (resp_tx, resp_rx) = oneshot::channel();
        let msg = ClientMsg::Request { req, resp_tx };

        // Send request to actor
        self.tx
            .send(msg)
            .await
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "Actor dropped"))?;

        // Wait for reply. If the oneshot channel is closed, log the underlying
        // error and return a `ConnectionAborted` I/O error rather than silently
        // hiding the cause.
        let resp = match resp_rx.await {
            Ok(res) => res,
            Err(e) => {
                log::error!("Actor response channel closed: {e}");
                return Err(std::io::Error::new(
                    std::io::ErrorKind::ConnectionAborted,
                    format!("Actor task ended: {e}"),
                ));
            }
        }?;

        // Match the RpcResponse
        match resp {
            RpcResponse::Result { value, .. } => serde_json::from_value(value).map_err(|e| {
                std::io::Error::new(
                    std::io::ErrorKind::InvalidData,
                    format!("Deserialize error: {e}"),
                )
            }),
            RpcResponse::Error { message, .. } => {
                Err(std::io::Error::other(format!("Remote error: {message}")))
            }
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Unexpected response type",
            )),
        }
    }

    /// Publish an event to a remote object/topic.
    ///
    /// Unlike [`remote_call`], this is fire-and-forget: no response is awaited.
    pub async fn publish(
        &self,
        object: &str,
        topic: &str,
        args: &serde_json::Value,
    ) -> std::io::Result<()> {
        let (resp_tx, _resp_rx) = oneshot::channel();
        let msg = ClientMsg::Request {
            req: RpcRequest::Publish {
                object_name: object.into(),
                topic: topic.into(),
                args: args.clone(),
            },
            resp_tx,
        };

        self.tx
            .send(msg)
            .await
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "Actor dropped"))
    }

    /// Subscribe to events from a remote object/topic.
    ///
    /// Returns an [`mpsc::UnboundedReceiver`] where updates
    /// will be delivered as `serde_json::Value`.
    pub async fn subscribe(&self, object: &str, topic: &str) -> mpsc::Receiver<serde_json::Value> {
        // Use a bounded channel to provide backpressure and avoid unbounded memory growth
        let (tx_updates, rx_updates) = mpsc::channel(16);
        let _ = self
            .tx
            .send(ClientMsg::Subscribe {
                object_name: object.into(),
                topic: topic.into(),
                updates: tx_updates,
            })
            .await;
        rx_updates
    }

    /// Subscribe asynchronously with a callback.
    ///
    /// Spawns a background task that invokes `callback` whenever
    /// a new event is received on the subscription.
    pub async fn subscribe_async<F>(&self, object: &str, topic: &str, callback: F)
    where
        F: Fn(Value) + Send + Sync + 'static,
    {
        let (tx, mut rx) = mpsc::channel::<Value>(16);
        let callback = Arc::new(callback);

        // Tell the actor to subscribe
        let _ = self
            .tx
            .send(ClientMsg::Subscribe {
                object_name: object.into(),
                topic: topic.into(),
                updates: tx,
            })
            .await;

        // Spawn a task to handle messages and call the callback synchronously
        tokio::spawn(async move {
            while let Some(msg) = rx.recv().await {
                let cb = callback.clone();
                // Call synchronously
                cb(msg);
            }
        });
    }

    /// Wait until a given object exists on the server.
    ///
    /// This polls periodically using [`has_object`] until success.
    pub async fn wait_for_object(&self, object: &str) -> std::io::Result<()> {
        loop {
            if self.has_object(object).await? {
                return Ok(());
            }
            tokio::time::sleep(std::time::Duration::from_millis(100)).await;
        }
    }

    /// Check whether a remote object exists.
    ///
    /// Returns `Ok(true)` if the object is present, `Ok(false)` otherwise.
    async fn has_object(&self, object: &str) -> std::io::Result<bool> {
        let req = RpcRequest::HasObject {
            object_name: object.into(),
        };

        let (resp_tx, resp_rx) = oneshot::channel();
        let msg = ClientMsg::Request { req, resp_tx };

        // Send request to actor
        self.tx
            .send(msg)
            .await
            .map_err(|_| std::io::Error::new(std::io::ErrorKind::BrokenPipe, "Actor dropped"))?;

        // Wait for reply. If the oneshot channel is closed, log the underlying
        // error and return a `ConnectionAborted` I/O error rather than silently
        // hiding the cause.
        match match resp_rx.await {
            Ok(res) => res,
            Err(e) => {
                log::error!("Actor response channel closed: {e}");
                return Err(std::io::Error::new(
                    std::io::ErrorKind::ConnectionAborted,
                    format!("Actor task ended: {e}"),
                ));
            }
        }? {
            RpcResponse::HasObjectResult { exists, .. } => Ok(exists),
            _ => Err(std::io::Error::new(
                std::io::ErrorKind::InvalidData,
                "Unexpected response type",
            )),
        }
    }
}