Skip to main content

hyprstream_rpc/transport/
lazy_uds.rs

1//! Lazy-connecting UDS RPC transport (same-host `ipc` plane).
2//!
3//! Mirrors [`LazyQuinnTransport`](super::lazy_quinn::LazyQuinnTransport) and
4//! [`LazyIrohTransport`](super::lazy_iroh::LazyIrohTransport): the
5//! [`dial`](crate::dial::dial) factory is synchronous, so this holds the socket
6//! path and connects on the **first `send()`**, caching the session — preserving
7//! sync, zero-I/O construction.
8//!
9//! The connection is a [`UdsSession`](super::uds_session::UdsSession) on the RPC
10//! plane (`PLANE_RPC`), wrapped as a [`SessionRpcTransport`] — the *same* generic
11//! client used by the quinn and iroh backends, so the ipc plane carries the
12//! identical Cap'n Proto bidi wire protocol with no transport-specific RPC code.
13//! This is the post-ZMQ `ipc` transport: same-host processes keep `ipc`,
14//! re-platformed off ZMQ framing onto SignedEnvelope-over-UDS.
15//!
16//! # Identity
17//!
18//! UDS has no transport-level peer identity; same-host trust + the app-layer
19//! `SignedEnvelope` (verified against the response key) are the authentication.
20//! Socket-file permissions + `SO_PEERCRED` are defense-in-depth owned by the
21//! daemon that binds the listener (see #207). A `None` `server_verifying_key`
22//! leaves the response identity unpinned (the envelope sig is still verified),
23//! matching the quinn arm.
24//!
25//! Re-dial/self-heal semantics match the other lazy transports: a per-request
26//! timeout keeps the session; a transport-fatal error drops it so the next call
27//! re-dials.
28
29use std::path::PathBuf;
30use std::time::Duration;
31
32use anyhow::{anyhow, bail, Result};
33use async_trait::async_trait;
34use tokio::sync::Mutex;
35
36use super::backoff::LazyState;
37use super::rpc_session::{RpcPendingStream, RpcPublishStub, SessionRpcTransport};
38use super::uds_session::{connect_uds, UdsSession, PLANE_RPC};
39use crate::transport_traits::Transport;
40
41/// Default per-request deadline when the caller passes `None`.
42const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
43
44/// Ceiling on the lazy connect (UDS connect + yamux/SETUP). The per-request
45/// deadline wraps only the request; without this a missing socket would hang the
46/// first `send()`.
47const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
48
49/// A UDS RPC transport that connects on first use and caches the session.
50pub struct LazyUdsTransport {
51    path: PathBuf,
52    /// Cached session + reconnect backoff (#156).
53    state: Mutex<LazyState<SessionRpcTransport<UdsSession>>>,
54}
55
56impl LazyUdsTransport {
57    /// Create a lazy transport for the UDS endpoint at `path`. No connection is
58    /// made until the first `send()`.
59    pub fn new(path: PathBuf) -> Self {
60        Self {
61            path,
62            state: Mutex::new(LazyState::default()),
63        }
64    }
65
66    /// Return the cached connected transport, connecting once (single-flight
67    /// under the lock) if not yet connected. Backs off after consecutive failures
68    /// so a removed/restarting socket is not tight-looped (#156).
69    async fn connected(&self) -> Result<SessionRpcTransport<UdsSession>> {
70        let mut guard = self.state.lock().await;
71        if let Some(transport) = guard.cached.as_ref() {
72            return Ok(transport.clone());
73        }
74        if let Some(remaining) = guard.backoff.cooldown_remaining() {
75            return Err(anyhow!(
76                "uds peer at {} is in reconnect backoff — retry in {remaining:.1?}",
77                self.path.display()
78            ));
79        }
80        match tokio::time::timeout(CONNECT_TIMEOUT, connect_uds(&self.path, PLANE_RPC)).await {
81            Err(_) => {
82                guard.backoff.record_failure();
83                Err(anyhow!(
84                    "uds connect to {} timed out after {CONNECT_TIMEOUT:?}",
85                    self.path.display()
86                ))
87            }
88            Ok(Err(e)) => {
89                guard.backoff.record_failure();
90                Err(anyhow!("uds connect to {}: {e}", self.path.display()))
91            }
92            Ok(Ok(session)) => {
93                guard.backoff.record_success();
94                let transport = SessionRpcTransport::new(session);
95                guard.cached = Some(transport.clone());
96                Ok(transport)
97            }
98        }
99    }
100
101    /// Drop the cached session and record a failure so the next `send()`
102    /// re-connects after the backoff cooldown (#156).
103    async fn invalidate(&self) {
104        let mut guard = self.state.lock().await;
105        guard.cached = None;
106        guard.backoff.record_failure();
107    }
108}
109
110#[async_trait]
111impl Transport for LazyUdsTransport {
112    type Sub = RpcPendingStream;
113    type Pub = RpcPublishStub;
114
115    /// Same-host Unix domain socket: peer-credential authenticated and never
116    /// leaves the host, so cleartext envelopes are permitted (explicit opt-out
117    /// of the fail-closed default; #207).
118    fn forbids_cleartext_envelope(&self) -> bool {
119        false
120    }
121
122    async fn send(&self, payload: Vec<u8>, timeout_ms: Option<i32>) -> Result<Vec<u8>> {
123        let transport = self.connected().await?;
124
125        // Our deadline is authoritative so a per-request timeout (busy peer —
126        // keep the session) is distinguishable from a transport-fatal error
127        // (re-connect), matching the other lazy transports.
128        let deadline = timeout_ms
129            .map(|ms| Duration::from_millis(ms.max(0) as u64))
130            .unwrap_or(DEFAULT_TIMEOUT);
131        let inner_ceiling_ms = deadline.as_millis().saturating_mul(2).min(i32::MAX as u128) as i32;
132
133        match tokio::time::timeout(deadline, transport.send(payload, Some(inner_ceiling_ms))).await
134        {
135            Err(_elapsed) => Err(anyhow!("uds RPC timeout after {deadline:?}")),
136            Ok(Ok(resp)) => Ok(resp),
137            Ok(Err(e)) => {
138                self.invalidate().await;
139                Err(e)
140            }
141        }
142    }
143
144    async fn subscribe(&self, _topic: &[u8]) -> Result<Self::Sub> {
145        bail!("lazy UDS RPC transport does not support SUB — streaming is on the moq plane")
146    }
147
148    async fn publish(&self, _topic: &[u8]) -> Result<Self::Pub> {
149        bail!("lazy UDS RPC transport does not support PUB — streaming is on the moq plane")
150    }
151}
152
153#[cfg(test)]
154#[allow(clippy::unwrap_used, clippy::expect_used)]
155mod tests {
156    use super::*;
157    use crate::transport::rpc_session::{
158        from_fn, serve_rpc_connection, DEFAULT_STREAM_LIMIT, REQUEST_READ_TIMEOUT,
159    };
160    use crate::transport::uds_session::accept_uds;
161    use bytes::Bytes;
162    use std::sync::Arc;
163    use tokio::sync::Semaphore;
164    use tokio_util::sync::CancellationToken;
165
166    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
167    async fn lazy_uds_connects_on_first_send_and_caches() {
168        let dir = std::env::temp_dir().join(format!("lazy-uds-{}", std::process::id()));
169        let _ = std::fs::create_dir_all(&dir);
170        let path = dir.join("rpc.sock");
171        let _ = std::fs::remove_file(&path);
172        let listener = tokio::net::UnixListener::bind(&path).unwrap();
173
174        // Echo RPC server over UDS.
175        let shutdown = CancellationToken::new();
176        let shutdown_srv = shutdown.clone();
177        let srv = tokio::spawn(async move {
178            let (sk, _vk) = crate::generate_signing_keypair();
179            let processor = Arc::new(from_fn(|req: Bytes| async move { Ok(req) }));
180            let limit = Arc::new(Semaphore::new(DEFAULT_STREAM_LIMIT));
181            loop {
182                tokio::select! {
183                    _ = shutdown_srv.cancelled() => break,
184                    accepted = listener.accept() => {
185                        let (stream, _) = accepted.unwrap();
186                        let (plane, session) = accept_uds(stream).await.unwrap();
187                        assert_eq!(plane, PLANE_RPC);
188                        let p = Arc::clone(&processor);
189                        let l = Arc::clone(&limit);
190                        let sk = sk.clone();
191                        let sd = shutdown_srv.clone();
192                        tokio::spawn(async move {
193                            let _ = serve_rpc_connection(
194                                session, p, sk, l, REQUEST_READ_TIMEOUT, sd,
195                                crate::transport::carrier::CarrierContext::trusted_uds(),
196                            )
197                            .await;
198                        });
199                    }
200                }
201            }
202        });
203
204        let t = LazyUdsTransport::new(path.clone());
205        assert!(
206            t.state.lock().await.cached.is_none(),
207            "no connection before first send"
208        );
209        let resp = t.send(b"ping".to_vec(), Some(4_000)).await.unwrap();
210        assert_eq!(resp, b"ping");
211        assert!(
212            t.state.lock().await.cached.is_some(),
213            "session cached after first send"
214        );
215        // Second call reuses the cached session (multiplexed stream).
216        let resp2 = t.send(b"pong".to_vec(), Some(4_000)).await.unwrap();
217        assert_eq!(resp2, b"pong");
218
219        shutdown.cancel();
220        let _ = srv.await;
221        let _ = std::fs::remove_file(&path);
222        let _ = std::fs::remove_dir(&dir);
223    }
224
225    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
226    async fn lazy_uds_missing_socket_errors_without_hang() {
227        let path =
228            std::env::temp_dir().join(format!("lazy-uds-absent-{}.sock", std::process::id()));
229        let _ = std::fs::remove_file(&path);
230        let t = LazyUdsTransport::new(path);
231        let res = tokio::time::timeout(Duration::from_secs(5), t.send(b"x".to_vec(), Some(2_000)))
232            .await
233            .expect("send must complete (with an error), not hang");
234        assert!(res.is_err(), "dialing an absent socket must fail");
235        assert!(
236            t.state.lock().await.cached.is_none(),
237            "a failed connect caches nothing"
238        );
239    }
240
241    #[tokio::test]
242    async fn subscribe_publish_bail() {
243        let t = LazyUdsTransport::new(PathBuf::from("/nonexistent.sock"));
244        assert!(t.subscribe(b"topic").await.is_err());
245        assert!(t.publish(b"topic").await.is_err());
246    }
247}