Skip to main content

astrs_node_api/session/
connect.rs

1//! Dialling the daemon (blueprint §4.2, §7.2).
2//!
3//! > Local node listener on **TCP 7408** (loopback) and a Unix domain socket
4//! > (`$XDG_RUNTIME_DIR/astrs/daemon.sock`) — UDS preferred, TCP fallback.
5//!
6//! The node tries every endpoint its configuration names, in order, and keeps
7//! every failure: "connection refused on the Unix socket" and "no route to
8//! host on the TCP fallback" are two different diagnoses, and an error that
9//! reports only the last one sends an operator to the wrong place.
10//!
11//! # What this module produces
12//!
13//! A [`NodeLink`]: a framed duplex whose halves are **boxed trait objects**,
14//! so a Unix socket, a TCP socket and the testing harness's
15//! `tokio::io::duplex` pair are all the same type from here on. That is what
16//! lets [`crate::Node`] be one concrete type instead of being generic over
17//! its transport, and it is what makes the in-process mock daemon speak the
18//! *real* protocol rather than a stub of it.
19
20use std::sync::Arc;
21use std::time::Duration;
22
23use astrs_transport::{
24    ConnectionCounters, FramedDuplex, FramedReader, FramedWriter, HandshakeParams, LocalIdentity,
25    TransportAddr, TransportConfig, initiate,
26};
27use astrs_wire::{AuthToken, FrameLimits, NegotiatedLimits, NegotiatedSession, Role};
28use tokio::io::{AsyncRead, AsyncWrite};
29
30use crate::env::DEFAULT_DAEMON_PORT;
31use crate::error::{NodeError, Result};
32
33/// The read half of a node's daemon link, type-erased.
34pub type LinkReader = FramedReader<Box<dyn AsyncRead + Send + Unpin>>;
35
36/// The write half of a node's daemon link, type-erased.
37pub type LinkWriter = FramedWriter<Box<dyn AsyncWrite + Send + Unpin>>;
38
39/// A framed duplex over a type-erased transport.
40pub type LinkDuplex =
41    FramedDuplex<Box<dyn AsyncRead + Send + Unpin>, Box<dyn AsyncWrite + Send + Unpin>>;
42
43/// The read-buffer capacity a node's link starts with.
44///
45/// Larger than the transport default because the daemon path carries whole
46/// payloads until a route is upgraded (§6.3): 64 KiB absorbs a typical
47/// pre-upgrade burst without a second read syscall per frame.
48pub const LINK_BUFFER_CAPACITY: usize = 64 * 1024;
49
50/// A live, greeted connection to the daemon.
51pub struct NodeLink {
52    /// The framed duplex.
53    pub duplex: LinkDuplex,
54    /// What the greeting agreed to (§7.2).
55    pub session: NegotiatedSession,
56    /// The endpoint that answered.
57    pub endpoint: String,
58}
59
60impl NodeLink {
61    /// Splits the link into the halves the reader and writer tasks own.
62    #[must_use]
63    pub fn into_halves(self) -> (LinkReader, LinkWriter, NegotiatedSession) {
64        let (reader, writer) = self.duplex.into_halves();
65        (reader, writer, self.session)
66    }
67}
68
69impl core::fmt::Debug for NodeLink {
70    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
71        f.debug_struct("NodeLink")
72            .field("endpoint", &self.endpoint)
73            .field("session", &self.session.session_id)
74            .field("protocol", &self.session.protocol)
75            .finish_non_exhaustive()
76    }
77}
78
79/// Wraps an already-open byte stream in the node link's frame codec.
80///
81/// The seam the testing harness uses: hand it one end of a
82/// `tokio::io::duplex` pair and the node cannot tell it from a socket.
83#[must_use]
84pub fn wrap_stream<S>(stream: S, limits: FrameLimits) -> LinkDuplex
85where
86    S: AsyncRead + AsyncWrite + Send + Unpin + 'static,
87{
88    let (read, write) = tokio::io::split(stream);
89    let read: Box<dyn AsyncRead + Send + Unpin> = Box::new(read);
90    let write: Box<dyn AsyncWrite + Send + Unpin> = Box::new(write);
91    FramedDuplex::from_halves(
92        read,
93        write,
94        limits,
95        LINK_BUFFER_CAPACITY,
96        ConnectionCounters::shared(),
97    )
98}
99
100/// The handshake parameters a node presents (§7.2).
101#[must_use]
102pub fn node_handshake_params(auth: AuthToken, label: Option<String>) -> HandshakeParams {
103    let identity = match label {
104        Some(label) => LocalIdentity::new(Role::Node).with_label(label),
105        None => LocalIdentity::new(Role::Node),
106    };
107    HandshakeParams::new(identity, auth).with_limits(NegotiatedLimits::uds())
108}
109
110/// Dials the first endpoint that answers, then greets it.
111///
112/// # Errors
113///
114/// [`NodeError::Connect`] listing every attempt when none answered, and
115/// [`NodeError::Handshake`] when one answered but refused the greeting.
116pub async fn dial(
117    endpoints: &[String],
118    auth: &AuthToken,
119    label: Option<String>,
120    timeout: Duration,
121) -> Result<NodeLink> {
122    if endpoints.is_empty() {
123        return Err(NodeError::Connect {
124            attempts: Vec::new(),
125        });
126    }
127    let mut attempts = Vec::with_capacity(endpoints.len());
128    for endpoint in endpoints {
129        match dial_one(endpoint, auth, label.clone(), timeout).await {
130            Ok(link) => return Ok(link),
131            Err(NodeError::Handshake(reason)) => {
132                // A refused greeting is not "try the next address": the token
133                // or the protocol is wrong, and every other endpoint of the
134                // same daemon will refuse identically.
135                return Err(NodeError::Handshake(reason));
136            }
137            Err(error) => attempts.push((endpoint.clone(), error.to_string())),
138        }
139    }
140    Err(NodeError::Connect { attempts })
141}
142
143/// Dials exactly one endpoint.
144///
145/// # Errors
146///
147/// [`NodeError::Transport`] when the address is unusable or the connect
148/// fails, and [`NodeError::Handshake`] when the greeting is refused.
149pub async fn dial_one(
150    endpoint: &str,
151    auth: &AuthToken,
152    label: Option<String>,
153    timeout: Duration,
154) -> Result<NodeLink> {
155    let addr =
156        TransportAddr::parse_with_default_port(endpoint, DEFAULT_DAEMON_PORT).map_err(|error| {
157            NodeError::BadEnv {
158                name: "endpoint",
159                value: endpoint.to_owned(),
160                reason: error.to_string(),
161            }
162        })?;
163    let config = TransportConfig::uds();
164    let limits = FrameLimits::uds();
165
166    let mut duplex = match &addr {
167        TransportAddr::Uds(path) => {
168            let stream = tokio::time::timeout(timeout, tokio::net::UnixStream::connect(path))
169                .await
170                .map_err(|_| NodeError::Timeout {
171                    operation: "daemon connect",
172                    millis: as_millis(timeout),
173                })?
174                .map_err(|error| NodeError::Transport(error.into()))?;
175            wrap_stream(stream, limits)
176        }
177        TransportAddr::Tcp(socket) => {
178            let stream = astrs_transport::backend::tcp::dial(*socket, &config).await?;
179            wrap_stream(stream, FrameLimits::network())
180        }
181        other => {
182            return Err(NodeError::BadEnv {
183                name: "endpoint",
184                value: endpoint.to_owned(),
185                reason: format!("a node cannot dial a {} endpoint", other.scheme()),
186            });
187        }
188    };
189
190    let params = node_handshake_params(auth.clone(), label);
191    let greeting = initiate(&mut duplex, &params, timeout)
192        .await
193        .map_err(|error| NodeError::Handshake(error.to_string()))?;
194    Ok(NodeLink {
195        duplex,
196        session: greeting.session,
197        endpoint: endpoint.to_owned(),
198    })
199}
200
201/// Milliseconds, saturating rather than wrapping.
202fn as_millis(duration: Duration) -> u64 {
203    u64::try_from(duration.as_millis()).unwrap_or(u64::MAX)
204}
205
206/// The counters a freshly wrapped link starts with, exposed so a caller can
207/// share one set across a reconnect.
208#[must_use]
209pub fn fresh_counters() -> Arc<ConnectionCounters> {
210    ConnectionCounters::shared()
211}
212
213#[cfg(test)]
214mod tests {
215    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
216
217    use super::*;
218    use astrs_wire::{Acceptor, RoleSet, SessionAssignment, SessionId};
219
220    #[test]
221    fn an_empty_endpoint_list_is_reported_as_such() {
222        let runtime = crate::runtime::NodeRuntime::owned().unwrap();
223        let error = runtime
224            .block_on("dial", "dial", async {
225                dial(&[], &AuthToken::ZERO, None, Duration::from_millis(50)).await
226            })
227            .unwrap()
228            .unwrap_err();
229        let NodeError::Connect { attempts } = error else {
230            panic!("expected a connect error");
231        };
232        assert!(attempts.is_empty());
233    }
234
235    #[test]
236    fn an_unreachable_endpoint_is_reported_with_its_reason() {
237        let runtime = crate::runtime::NodeRuntime::owned().unwrap();
238        let missing = std::env::temp_dir().join("astrs-node-api-no-such.sock");
239        let endpoint = format!("uds://{}", missing.display());
240        let error = runtime
241            .block_on("dial", "dial", async {
242                dial(
243                    std::slice::from_ref(&endpoint),
244                    &AuthToken::ZERO,
245                    None,
246                    Duration::from_millis(200),
247                )
248                .await
249            })
250            .unwrap()
251            .unwrap_err();
252        let NodeError::Connect { attempts } = error else {
253            panic!("expected a connect error");
254        };
255        assert_eq!(attempts.len(), 1);
256        assert_eq!(attempts[0].0, endpoint);
257        assert!(!attempts[0].1.is_empty());
258    }
259
260    #[test]
261    fn a_malformed_endpoint_is_named() {
262        let runtime = crate::runtime::NodeRuntime::owned().unwrap();
263        let error = runtime
264            .block_on("dial", "dial", async {
265                dial_one(
266                    "nonsense://x",
267                    &AuthToken::ZERO,
268                    None,
269                    Duration::from_millis(50),
270                )
271                .await
272            })
273            .unwrap()
274            .unwrap_err();
275        assert!(matches!(error, NodeError::BadEnv { .. }), "{error}");
276    }
277
278    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
279    async fn a_wrapped_duplex_completes_the_real_greeting() {
280        let token = AuthToken::from_bytes([3; 32]);
281        let (client_io, server_io) = tokio::io::duplex(64 * 1024);
282        let mut client = wrap_stream(client_io, FrameLimits::uds());
283        let mut server = wrap_stream(server_io, FrameLimits::uds());
284
285        let acceptor = Acceptor::new(token.clone()).with_accepted_roles(RoleSet::NODES);
286        let server_task = tokio::spawn(async move {
287            astrs_transport::accept(
288                &mut server,
289                &acceptor,
290                SessionAssignment::Fresh(SessionId::from_u128(9)),
291                Duration::from_secs(5),
292            )
293            .await
294            .map(|accepted| accepted.session.session_id)
295        });
296
297        let params = node_handshake_params(token, Some("camera".to_owned()));
298        let greeting = initiate(&mut client, &params, Duration::from_secs(5))
299            .await
300            .unwrap();
301        assert_eq!(greeting.session.role, Role::Node);
302        assert_eq!(
303            server_task.await.unwrap().unwrap(),
304            greeting.session.session_id
305        );
306    }
307
308    #[test]
309    fn the_link_buffer_is_sized_for_the_pre_upgrade_path() {
310        assert_eq!(LINK_BUFFER_CAPACITY, 64 * 1024);
311        assert_eq!(fresh_counters().snapshot().frames_sent, 0);
312    }
313}