Skip to main content

hyprstream_rpc/transport/
in_memory.rs

1//! In-process RPC transport for co-located services.
2//!
3//! Dials a service running in the *same process* without a network socket.
4//! This is the in-memory dial target the [`crate::dial`] factory selects for
5//! `inproc://` endpoints — the replacement for ZMQ's `inproc://` transport.
6//!
7//! # No second security model
8//!
9//! [`InMemoryTransport::send`] forwards the canonical request bytes to an
10//! [`IrohRequestProcessor`] (in production a
11//! [`LocalServiceBridge`](crate::transport::iroh_rpc::LocalServiceBridge),
12//! which isolates `!Send` `tch`-holding services on a dedicated `LocalSet`
13//! thread and exposes only a `Send` `Bytes`-in/`Bytes`-out surface) and returns
14//! the signed response bytes. The envelope is signed and verified by the exact
15//! same `process_request` path a networked transport uses — co-located calls
16//! skip *serialization to a socket*, never authentication or Casbin authz. This
17//! is behaviourally identical to ZMQ's `inproc://` (serialize once, no socket),
18//! so there is no distinct trust path to review.
19//!
20//! Per the A1 addressing spike, every in-process call goes through the bridge
21//! (one channel hop — the same cost as inproc-ZMQ today). A zero-hop tier that
22//! calls `process_request` directly is inexpressible while `RequestService` is
23//! unconditionally `?Send`; it is a deliberate later follow-up, not part of this
24//! change.
25//!
26//! # RPC plane only
27//!
28//! Like [`SessionRpcTransport`](crate::transport::rpc_session::SessionRpcTransport),
29//! this transport is request-response only; `subscribe`/`publish` bail. The
30//! streaming plane (moq-net) carries SUB/PUB, and in-process streaming is
31//! deferred with the streaming substrate (#134).
32
33use std::sync::Arc;
34use std::time::Duration;
35
36use anyhow::{anyhow, bail, Result};
37use async_trait::async_trait;
38use bytes::Bytes;
39
40use crate::transport::rpc_session::{IrohRequestProcessor, RpcPendingStream, RpcPublishStub};
41use crate::transport_traits::Transport;
42
43/// Default ceiling on a single in-process request, mirroring the networked
44/// RPC transport. A wedged co-located handler should surface as a timeout
45/// rather than hanging the caller indefinitely.
46///
47/// Note this deadline also covers *enqueue* latency: `LocalServiceBridge`
48/// forwards over a bounded mpsc, so a saturated bridge can make `send()` block
49/// on the channel and eventually trip this timeout. The error therefore
50/// conflates "handler wedged" with "bridge backpressure" — acceptable for the
51/// transport surface, but not a substitute for a real backpressure signal.
52const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
53
54/// In-process RPC transport over an [`IrohRequestProcessor`].
55///
56/// Cheaply cloneable: holds an `Arc` to the shared processor.
57#[derive(Clone)]
58pub struct InMemoryTransport {
59    processor: Arc<dyn IrohRequestProcessor>,
60}
61
62impl InMemoryTransport {
63    /// Dial a co-located service by its already-resolved request processor.
64    pub fn new(processor: Arc<dyn IrohRequestProcessor>) -> Self {
65        Self { processor }
66    }
67}
68
69#[async_trait]
70impl Transport for InMemoryTransport {
71    type Sub = RpcPendingStream;
72    type Pub = RpcPublishStub;
73
74    /// Same-process, zero-copy carrier: never leaves the address space, so
75    /// cleartext envelopes are permitted (explicit opt-out of the fail-closed
76    /// default).
77    fn forbids_cleartext_envelope(&self) -> bool {
78        false
79    }
80
81    async fn send(&self, payload: Vec<u8>, timeout_ms: Option<i32>) -> Result<Vec<u8>> {
82        let timeout = timeout_ms
83            .map(|ms| Duration::from_millis(ms.max(0) as u64))
84            .unwrap_or(DEFAULT_TIMEOUT);
85        let processor = Arc::clone(&self.processor);
86        // INV-2 (#1042): the request never leaves this address space — the
87        // one carrier class that is inproc by construction.
88        let fut = async move {
89            processor
90                .process(
91                    Bytes::from(payload),
92                    crate::transport::carrier::CarrierContext::inproc(),
93                )
94                .await
95        };
96        let resp = tokio::time::timeout(timeout, fut)
97            .await
98            .map_err(|_| anyhow!("in-process RPC timeout after {timeout:?}"))??;
99        Ok(resp.to_vec())
100    }
101
102    async fn subscribe(&self, _topic: &[u8]) -> Result<Self::Sub> {
103        bail!("in-process RPC transport does not support SUB — streaming moves to moq-net (#134)")
104    }
105
106    async fn publish(&self, _topic: &[u8]) -> Result<Self::Pub> {
107        bail!("in-process RPC transport does not support PUB — streaming moves to moq-net (#134)")
108    }
109}
110
111#[cfg(test)]
112#[allow(clippy::unwrap_used, clippy::expect_used)]
113mod tests {
114    use super::*;
115    use crate::transport::rpc_session::from_fn;
116
117    fn echo_processor() -> Arc<dyn IrohRequestProcessor> {
118        Arc::new(from_fn(|req: Bytes| async move { Ok(req) }))
119    }
120
121    #[tokio::test]
122    async fn send_roundtrips_through_processor() {
123        let t = InMemoryTransport::new(echo_processor());
124        let resp = t.send(b"ping".to_vec(), None).await.unwrap();
125        assert_eq!(resp, b"ping");
126    }
127
128    #[tokio::test]
129    async fn subscribe_and_publish_bail() {
130        let t = InMemoryTransport::new(echo_processor());
131        assert!(t.subscribe(b"topic").await.is_err());
132        assert!(t.publish(b"topic").await.is_err());
133    }
134
135    #[tokio::test]
136    async fn slow_processor_times_out() {
137        let slow = Arc::new(from_fn(|req: Bytes| async move {
138            tokio::time::sleep(Duration::from_millis(200)).await;
139            Ok(req)
140        }));
141        let t = InMemoryTransport::new(slow);
142        let err = t.send(b"x".to_vec(), Some(20)).await;
143        assert!(
144            err.is_err(),
145            "a handler exceeding the deadline must time out"
146        );
147    }
148
149    #[tokio::test]
150    async fn processor_error_propagates() {
151        let failing = Arc::new(from_fn(|_req: Bytes| async move {
152            Err(anyhow!("handler boom"))
153        }));
154        let t = InMemoryTransport::new(failing);
155        let err = t.send(b"x".to_vec(), None).await;
156        assert!(err.is_err());
157    }
158}