Skip to main content

shep_client/
connection.rs

1//! The bounded connect-plus-handshake: [`Connection::open`], [`ConnectError`]
2//!
3//! A bound-but-not-accepting unix socket still completes `connect(2)` into
4//! the kernel backlog, so a bare connect is not a readiness probe. Only a
5//! completed version handshake (connect, send [`Hello`], receive a
6//! [`HelloAck`]) means the daemon is up. [`Connection::open`] bounds the
7//! whole attempt in one [`tokio::time::timeout`].
8//!
9//! The OS transport is [`shep_core::transport`]'s to pick: a Windows named
10//! pipe has the same readiness trap when every server instance is busy.
11
12use core::fmt;
13use std::path::{Path, PathBuf};
14use std::time::Duration;
15
16use futures_util::{SinkExt, StreamExt};
17use tokio::io::{AsyncRead, AsyncWrite};
18use tokio_util::codec::{Framed, LengthDelimitedCodec};
19
20use shep_core::destination::DestinationError;
21use shep_core::protocol::{
22    Hello, HelloAck, HelloReply, PROTOCOL_VERSION, WireError, codec, decode_frame, encode_frame,
23};
24use shep_core::transport;
25
26use crate::ssh::SshCause;
27
28/// Budget for one connect-plus-handshake attempt.
29///
30/// Mirrors the daemon's own `HANDSHAKE_TIMEOUT_MS = 5_000`
31/// (`shep-daemon/src/server.rs`) so neither side out-waits the other. The
32/// `spawn` module's own connect-and-wait budget reads from this constant too.
33pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
34
35/// Any byte stream a [`Connection`] can handshake and run over: the OS
36/// socket, or a pipe to an ssh child.
37pub(crate) trait ByteStream: AsyncRead + AsyncWrite + Unpin + Send {}
38
39impl<T: AsyncRead + AsyncWrite + Unpin + Send> ByteStream for T {}
40
41/// The framed transport a [`Connection`] wraps, named so callers past this
42/// module don't have to spell out the framed type themselves.
43///
44/// Boxed rather than generic: `Connection`, the actor and `Client` stay
45/// non-generic, so the actor compiles once, and one vtable call per read is
46/// noise beside JSON decoding. This alias also keeps `crate::actor` free of
47/// any platform gate.
48pub(crate) type Frames = Framed<Box<dyn ByteStream>, LengthDelimitedCodec>;
49
50/// Why `Connection::open` failed.
51///
52/// Non-exhaustive: expect more variants.
53#[derive(Debug)]
54#[non_exhaustive]
55pub enum ConnectError {
56    /// `connect(2)` itself failed: nothing is listening at `path` (no
57    /// socket file, permission denied, connection refused, ...).
58    Connect {
59        /// The socket path that was dialed.
60        path: PathBuf,
61        /// The OS error `connect` returned.
62        source: std::io::Error,
63    },
64    /// A framed read or write failed after the connection was established.
65    Io(std::io::Error),
66    /// The `Hello` failed to encode, or the reply frame failed to decode.
67    Wire(WireError),
68    /// The peer closed the connection before a [`HelloReply`] arrived.
69    HandshakeClosed,
70    /// Connect succeeded but no [`HelloReply`] (and no close) arrived within
71    /// the timeout. Distinct from [`Self::Connect`]: a refusal means nothing
72    /// is listening, a timeout means something is bound but not answering.
73    HandshakeTimeout {
74        /// The timeout that was exceeded.
75        after: Duration,
76    },
77    /// The daemon refused the handshake on protocol-version skew. `client`
78    /// is this client's own [`PROTOCOL_VERSION`]; `message` is the
79    /// daemon's own sentence, not meant for parsing.
80    ProtocolMismatch {
81        /// This client's own protocol version.
82        client: u32,
83        /// The daemon's own crate version, when it named one.
84        ///
85        /// `None` from a daemon built before this field existed. Read it
86        /// as unknown rather than assuming either side is the older build.
87        daemon_version: Option<String>,
88        /// The daemon's refusal message, verbatim.
89        message: String,
90    },
91    /// The destination handed to [`Client::connect_ssh_with`] is not one
92    /// [`Destination::parse`] accepts. Nothing was spawned.
93    ///
94    /// [`Client::connect_ssh_with`]: crate::Client::connect_ssh_with
95    /// [`Destination::parse`]: shep_core::destination::Destination::parse
96    Destination(DestinationError),
97    /// Dialling `destination` through ssh failed; `cause` says how.
98    Ssh {
99        /// The destination that was dialled.
100        destination: String,
101        /// What went wrong, on this side or the far one.
102        cause: SshCause,
103    },
104}
105
106impl ConnectError {
107    /// The [`shep_core::exit`] code a process stopping on this error uses:
108    /// a refusal is a protocol mismatch, a destination ssh would misread is a
109    /// usage error, and every other stage is nothing usable answering.
110    #[must_use]
111    pub const fn exit_code(&self) -> u8 {
112        use shep_core::exit;
113        match self {
114            Self::ProtocolMismatch { .. } => exit::PROTOCOL_MISMATCH,
115            Self::Destination(_) => exit::USAGE,
116            Self::Connect { .. }
117            | Self::Ssh { .. }
118            | Self::Io(_)
119            | Self::Wire(_)
120            | Self::HandshakeClosed
121            | Self::HandshakeTimeout { .. } => exit::DAEMON_UNREACHABLE,
122        }
123    }
124}
125
126impl fmt::Display for ConnectError {
127    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128        match self {
129            Self::Connect { path, source } => {
130                write!(f, "could not connect to `{}`: {source}", path.display())
131            }
132            Self::Io(err) => write!(f, "connection I/O error: {err}"),
133            Self::Wire(err) => write!(f, "handshake frame error: {err}"),
134            Self::HandshakeClosed => {
135                f.write_str("the daemon closed the connection during the handshake")
136            }
137            Self::HandshakeTimeout { after } => {
138                write!(f, "the handshake did not complete within {after:?}")
139            }
140            Self::Destination(err) => write!(f, "invalid destination: {err}"),
141            Self::Ssh { destination, cause } => cause.write_for(f, destination),
142            // `message` states the daemon's side of the skew; this arm adds
143            // what it cannot: what to do, and which shep to do it against.
144            // Both directions of the remedy are named, since `client` and
145            // `message` don't say which build is the older one.
146            Self::ProtocolMismatch {
147                client,
148                daemon_version,
149                message,
150            } => {
151                let shep = daemon_version
152                    .as_deref()
153                    .map_or_else(|| "the running shep".to_string(), |v| format!("shep {v}"));
154                write!(
155                    f,
156                    "protocol mismatch (this client speaks {client}): {message}. \
157                     The older of the two has to be replaced: rebuild or reinstall this \
158                     program against {shep} and restart it, or upgrade shep itself and run \
159                     `shep daemon reload`"
160                )
161            }
162        }
163    }
164}
165
166impl core::error::Error for ConnectError {
167    fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
168        match self {
169            Self::Connect { source, .. } | Self::Io(source) => Some(source),
170            Self::Wire(err) => Some(err),
171            Self::Destination(err) => Some(err),
172            // the cause's own source, not the cause: `Display` already
173            // spelled the cause out, and a chain would print it twice
174            Self::Ssh { cause, .. } => core::error::Error::source(cause),
175            Self::HandshakeClosed
176            | Self::HandshakeTimeout { .. }
177            | Self::ProtocolMismatch { .. } => None,
178        }
179    }
180}
181
182/// One handshaken connection to the daemon: an established, version-checked
183/// framed transport plus the daemon's [`HelloAck`].
184pub(crate) struct Connection {
185    frames: Frames,
186    ack: HelloAck,
187}
188
189impl fmt::Debug for Connection {
190    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191        f.debug_struct("Connection")
192            .field("ack", &self.ack)
193            .finish_non_exhaustive()
194    }
195}
196
197impl Connection {
198    /// Connects to `socket` and performs the version handshake (connect,
199    /// send [`Hello`], read the reply), bounded by `timeout`. `dog_name`
200    /// travels in the `Hello` so a refusing daemon knows which dog it refused.
201    ///
202    /// # Errors
203    ///
204    /// - [`ConnectError::Connect`]: the initial `connect(2)` call failed.
205    /// - [`ConnectError::Wire`]: `Hello` failed to encode, or the reply failed to decode.
206    /// - [`ConnectError::Io`]: a framed read or write failed after connect.
207    /// - [`ConnectError::HandshakeClosed`]: the peer closed before a `HelloReply`.
208    /// - [`ConnectError::HandshakeTimeout`]: no `HelloReply` arrived within `timeout`.
209    /// - [`ConnectError::ProtocolMismatch`]: the daemon refused on protocol-version skew.
210    pub(crate) async fn open(
211        socket: &Path,
212        timeout: Duration,
213        dog_name: Option<&str>,
214    ) -> Result<Self, ConnectError> {
215        // bounds connect(2) together with the handshake, not just the handshake.
216        tokio::time::timeout(timeout, Self::open_inner(socket, dog_name))
217            .await
218            .map_err(|_elapsed| ConnectError::HandshakeTimeout { after: timeout })?
219    }
220
221    async fn open_inner(socket: &Path, dog_name: Option<&str>) -> Result<Self, ConnectError> {
222        let stream = transport::connect(socket)
223            .await
224            .map_err(|source| ConnectError::Connect {
225                path: socket.to_path_buf(),
226                source,
227            })?;
228        Self::open_over(stream, dog_name).await
229    }
230
231    /// Performs the version handshake (send [`Hello`], read the reply) over
232    /// an already-established `stream`. `dog_name` travels in the `Hello`.
233    ///
234    /// Unbounded: the caller owns the timeout, as [`Self::open`] does.
235    ///
236    /// # Errors
237    ///
238    /// - [`ConnectError::Wire`]: `Hello` failed to encode, or the reply failed to decode.
239    /// - [`ConnectError::Io`]: a framed read or write failed.
240    /// - [`ConnectError::HandshakeClosed`]: the peer closed before a `HelloReply`.
241    /// - [`ConnectError::ProtocolMismatch`]: the daemon refused on protocol-version skew.
242    pub(crate) async fn open_over(
243        stream: impl ByteStream + 'static,
244        dog_name: Option<&str>,
245    ) -> Result<Self, ConnectError> {
246        let mut frames = Framed::new(Box::new(stream) as Box<dyn ByteStream>, codec());
247
248        let hello = Hello {
249            client_version: env!("CARGO_PKG_VERSION").to_string(),
250            protocol: PROTOCOL_VERSION,
251            dog_name: dog_name.map(str::to_owned),
252        };
253        let payload = encode_frame(&hello).map_err(ConnectError::Wire)?;
254        frames.send(payload).await.map_err(ConnectError::Io)?;
255
256        let frame = frames
257            .next()
258            .await
259            .ok_or(ConnectError::HandshakeClosed)?
260            .map_err(ConnectError::Io)?;
261        let reply: HelloReply = decode_frame(&frame).map_err(ConnectError::Wire)?;
262        // flattens every `RpcError` into `ProtocolMismatch`: `server.rs` is
263        // the only producer and always sends that code
264        let ack = reply.map_err(|err| ConnectError::ProtocolMismatch {
265            client: PROTOCOL_VERSION,
266            daemon_version: err.daemon_version,
267            message: err.message,
268        })?;
269
270        Ok(Self { frames, ack })
271    }
272
273    /// Splits the connection into its raw framed transport and the
274    /// handshake acknowledgement, for the actor task that takes ownership
275    /// of the transport and needs both.
276    pub(crate) fn into_parts(self) -> (Frames, HelloAck) {
277        (self.frames, self.ack)
278    }
279}
280
281#[cfg(test)]
282mod tests {
283    use super::*;
284    use crate::testing::fake_daemon;
285    use shep_core::protocol::{HelloAck, PROTOCOL_VERSION, RpcError, RpcErrorCode};
286    use shep_core::transport::Listener;
287
288    #[tokio::test]
289    async fn open_sends_hello_and_returns_the_ack() {
290        let dir = tempfile::tempdir().unwrap();
291        let path = crate::testing::control_address(dir.path());
292        let ack = HelloAck {
293            daemon_version: "9.9.9".into(),
294            protocol: PROTOCOL_VERSION,
295            pid: 4242,
296            min_supported: None,
297        };
298        let served = fake_daemon(&path, Ok(ack.clone())).await;
299
300        let conn = Connection::open(&path, HANDSHAKE_TIMEOUT, None)
301            .await
302            .unwrap();
303
304        let (_frames, actual_ack) = conn.into_parts();
305        assert_eq!(actual_ack, ack);
306        let hello = served.await.unwrap();
307        assert_eq!(
308            hello.protocol, PROTOCOL_VERSION,
309            "the client must announce the version it speaks"
310        );
311        assert_eq!(
312            hello.client_version,
313            env!("CARGO_PKG_VERSION"),
314            "the client must identify its own version"
315        );
316        assert_eq!(
317            hello.dog_name, None,
318            "a client that is not a dog must not claim to be one"
319        );
320    }
321
322    /// fails if a dog's name is dropped between [`Connection::open`]'s
323    /// argument and the frame that goes out, which is all the daemon has
324    /// to name the dog it refuses on a bad handshake.
325    #[tokio::test]
326    async fn a_dogs_hello_carries_the_name_it_was_registered_under() {
327        let dir = tempfile::tempdir().unwrap();
328        let path = crate::testing::control_address(dir.path());
329        let ack = HelloAck {
330            daemon_version: "9.9.9".into(),
331            protocol: PROTOCOL_VERSION,
332            pid: 4242,
333            min_supported: None,
334        };
335        let served = fake_daemon(&path, Ok(ack)).await;
336
337        let _conn = Connection::open(&path, HANDSHAKE_TIMEOUT, Some("metrics"))
338            .await
339            .unwrap();
340
341        let hello = served.await.unwrap();
342        assert_eq!(hello.dog_name.as_deref(), Some("metrics"));
343    }
344
345    #[tokio::test]
346    async fn a_protocol_refusal_becomes_its_own_error_variant() {
347        let dir = tempfile::tempdir().unwrap();
348        let path = crate::testing::control_address(dir.path());
349        let refusal = RpcError {
350            code: RpcErrorCode::ProtocolMismatch,
351            message: "daemon speaks protocol 2, client speaks 1".into(),
352            daemon_version: None,
353        };
354        let _served = fake_daemon(&path, Err(refusal)).await;
355
356        let err = Connection::open(&path, HANDSHAKE_TIMEOUT, None)
357            .await
358            .unwrap_err();
359
360        let ConnectError::ProtocolMismatch {
361            client, message, ..
362        } = err
363        else {
364            panic!("a protocol refusal must not be flattened into a generic error, got {err:?}");
365        };
366        assert_eq!(
367            client, PROTOCOL_VERSION,
368            "`client` is our own version, not the daemon's"
369        );
370        assert!(
371            message.contains("protocol 2"),
372            "the daemon's own message must survive: {message}"
373        );
374    }
375
376    #[tokio::test]
377    async fn a_refusal_carries_the_daemon_version_past_the_flattening() {
378        // only this side tests the RpcError -> ConnectError carry-through
379        let dir = tempfile::tempdir().unwrap();
380        let path = crate::testing::control_address(dir.path());
381        let refusal = RpcError {
382            code: RpcErrorCode::ProtocolMismatch,
383            message: "daemon speaks protocol 2, client speaks 1".into(),
384            daemon_version: Some("0.1.16".into()),
385        };
386        let _served = fake_daemon(&path, Err(refusal)).await;
387
388        let err = Connection::open(&path, HANDSHAKE_TIMEOUT, None)
389            .await
390            .unwrap_err();
391
392        let ConnectError::ProtocolMismatch { daemon_version, .. } = err else {
393            panic!("expected a protocol refusal, got {err:?}");
394        };
395        assert_eq!(daemon_version.as_deref(), Some("0.1.16"));
396    }
397
398    #[tokio::test]
399    async fn an_old_daemons_refusal_still_connects_and_reports_no_version() {
400        // `skip_serializing_if` means a daemon predating this field puts no
401        // `daemon_version` on the wire at all; this must decode as `None`.
402        // the byte-for-byte omission itself is pinned in shep-core; this
403        // crate has no serde_json to assert it with.
404        let dir = tempfile::tempdir().unwrap();
405        let path = crate::testing::control_address(dir.path());
406        let refusal = RpcError {
407            code: RpcErrorCode::ProtocolMismatch,
408            message: "daemon speaks protocol 2, client speaks 1".into(),
409            daemon_version: None,
410        };
411        let _served = fake_daemon(&path, Err(refusal)).await;
412
413        let err = Connection::open(&path, HANDSHAKE_TIMEOUT, None)
414            .await
415            .unwrap_err();
416
417        let ConnectError::ProtocolMismatch {
418            daemon_version,
419            message,
420            ..
421        } = err
422        else {
423            panic!("expected a protocol refusal, got {err:?}");
424        };
425        assert_eq!(daemon_version, None);
426        assert!(
427            message.contains("protocol 2"),
428            "the daemon's own message must still survive: {message}"
429        );
430    }
431
432    /// fails if the rendered refusal states the skew and stops without
433    /// saying what to do about it: this string is the whole of what a
434    /// refused dog's log gets.
435    #[test]
436    fn a_rendered_refusal_says_what_to_do_about_it() {
437        let rendered = ConnectError::ProtocolMismatch {
438            client: 1,
439            daemon_version: Some("0.1.27".into()),
440            message: "daemon speaks protocol 2, client sent 1".into(),
441        }
442        .to_string();
443
444        assert!(
445            rendered.contains("daemon speaks protocol 2, client sent 1"),
446            "the daemon's own sentence still leads: {rendered}"
447        );
448        assert!(
449            rendered.contains("shep 0.1.27"),
450            "the remedy has to name a version somebody can install: {rendered}"
451        );
452        assert!(
453            rendered.contains("rebuild or reinstall this program"),
454            "one direction of the remedy: {rendered}"
455        );
456        assert!(
457            rendered.contains("shep daemon reload"),
458            "the other direction, because this type cannot tell which build \
459             is the older one: {rendered}"
460        );
461        assert_eq!(rendered.lines().count(), 1, "one line: {rendered}");
462    }
463
464    /// fails if a daemon too old to name its version renders a remedy with a
465    /// hole in it: `rebuild against shep` with nothing after `shep`, or a
466    /// literal `None`.
467    #[test]
468    fn a_refusal_without_a_version_still_names_something_to_build_against() {
469        let rendered = ConnectError::ProtocolMismatch {
470            client: 2,
471            daemon_version: None,
472            message: "daemon speaks protocol 1, client sent 2".into(),
473        }
474        .to_string();
475
476        assert!(
477            rendered.contains("against the running shep and restart it"),
478            "the remedy must still point somewhere: {rendered}"
479        );
480        assert!(
481            !rendered.contains("None"),
482            "an absent version must never reach the reader: {rendered}"
483        );
484    }
485
486    /// fails if a daemon that accepts and immediately closes is read as
487    /// anything but unreachable, or as a silent success. Asserts the
488    /// outcome bucket, not one variant: macOS reports `HandshakeClosed`,
489    /// Linux reports `Io`, and downstream folds both the same way.
490    #[tokio::test]
491    async fn a_daemon_that_closes_without_answering_is_not_a_silent_success() {
492        let dir = tempfile::tempdir().unwrap();
493        let path = crate::testing::control_address(dir.path());
494        let mut listener = Listener::bind(&path).unwrap();
495        tokio::spawn(async move {
496            let stream = listener.accept().await.unwrap();
497            drop(stream);
498        });
499
500        let err = Connection::open(&path, HANDSHAKE_TIMEOUT, None)
501            .await
502            .expect_err("a peer that closed without a HelloReply is not a connection");
503
504        assert!(
505            matches!(err, ConnectError::HandshakeClosed | ConnectError::Io(_)),
506            "a peer that closed mid-handshake must report as unreachable, got {err:?}"
507        );
508    }
509
510    #[tokio::test]
511    async fn connecting_to_a_missing_socket_names_the_path() {
512        let dir = tempfile::tempdir().unwrap();
513        let path = crate::testing::control_address(dir.path());
514        let ConnectError::Connect { path: reported, .. } =
515            Connection::open(&path, HANDSHAKE_TIMEOUT, None)
516                .await
517                .unwrap_err()
518        else {
519            panic!("a missing socket must report which path failed");
520        };
521        assert_eq!(reported, path);
522    }
523
524    /// 150ms stands in for the real 5s [`HANDSHAKE_TIMEOUT`]; the mechanism is the same.
525    #[tokio::test]
526    async fn a_socket_bound_but_never_accepted_from_times_out_rather_than_hanging() {
527        let dir = tempfile::tempdir().unwrap();
528        let path = crate::testing::control_address(dir.path());
529        // unix completes connect() into the backlog; Windows completes it
530        // against an unaccepted pipe instance. Either way nothing answers.
531        let _listener = Listener::bind(&path).unwrap();
532
533        let err = Connection::open(&path, Duration::from_millis(150), None)
534            .await
535            .unwrap_err();
536
537        let ConnectError::HandshakeTimeout { after } = err else {
538            panic!("a backlogged connect must time out, not hang or read as success; got {err:?}");
539        };
540        assert_eq!(after, Duration::from_millis(150));
541    }
542
543    /// Spawns the far end of an in-memory stream that reads one [`Hello`]
544    /// and answers it with `reply`, then hands the [`Hello`] back.
545    fn serve_hello(
546        far: tokio::io::DuplexStream,
547        reply: HelloReply,
548    ) -> tokio::task::JoinHandle<Hello> {
549        tokio::spawn(async move {
550            let mut frames = Framed::new(far, codec());
551            let first = frames.next().await.unwrap().unwrap();
552            let hello: Hello = decode_frame(&first).unwrap();
553            frames.send(encode_frame(&reply).unwrap()).await.unwrap();
554            hello
555        })
556    }
557
558    #[tokio::test]
559    async fn open_over_completes_the_handshake_on_an_in_memory_stream() {
560        let (near, far) = tokio::io::duplex(1024);
561        let ack = HelloAck {
562            daemon_version: "9.9.9".into(),
563            protocol: PROTOCOL_VERSION,
564            pid: 4242,
565            min_supported: None,
566        };
567        let served = serve_hello(far, Ok(ack.clone()));
568
569        let conn = Connection::open_over(near, None).await.unwrap();
570
571        let (_frames, actual_ack) = conn.into_parts();
572        assert_eq!(actual_ack, ack);
573        let hello = served.await.unwrap();
574        assert_eq!(
575            hello.protocol, PROTOCOL_VERSION,
576            "the client must announce the version it speaks"
577        );
578        assert_eq!(
579            hello.client_version,
580            env!("CARGO_PKG_VERSION"),
581            "the client must identify its own version"
582        );
583        assert_eq!(
584            hello.dog_name, None,
585            "a client that is not a dog must not claim to be one"
586        );
587    }
588
589    #[tokio::test]
590    async fn open_over_carries_a_dogs_name_in_its_hello() {
591        let (near, far) = tokio::io::duplex(1024);
592        let ack = HelloAck {
593            daemon_version: "9.9.9".into(),
594            protocol: PROTOCOL_VERSION,
595            pid: 4242,
596            min_supported: None,
597        };
598        let served = serve_hello(far, Ok(ack));
599
600        let _conn = Connection::open_over(near, Some("metrics")).await.unwrap();
601
602        let hello = served.await.unwrap();
603        assert_eq!(hello.dog_name.as_deref(), Some("metrics"));
604    }
605
606    #[tokio::test]
607    async fn open_over_reports_a_stream_closed_before_the_ack_as_handshake_closed() {
608        let (near, far) = tokio::io::duplex(1024);
609        tokio::spawn(async move {
610            let mut frames = Framed::new(far, codec());
611            let _hello = frames.next().await;
612            // dropped after reading the Hello, so the near half sees a clean EOF
613        });
614
615        let err = Connection::open_over(near, None).await.unwrap_err();
616
617        assert!(
618            matches!(err, ConnectError::HandshakeClosed),
619            "an in-memory EOF carries no OS error to fold into `Io`, got {err:?}"
620        );
621    }
622
623    #[tokio::test]
624    async fn open_over_reports_a_protocol_refusal_as_protocol_mismatch() {
625        let (near, far) = tokio::io::duplex(1024);
626        let refusal = RpcError {
627            code: RpcErrorCode::ProtocolMismatch,
628            message: "daemon speaks protocol 2, client speaks 1".into(),
629            daemon_version: Some("0.1.16".into()),
630        };
631        let _served = serve_hello(far, Err(refusal));
632
633        let err = Connection::open_over(near, None).await.unwrap_err();
634
635        let ConnectError::ProtocolMismatch {
636            client,
637            daemon_version,
638            message,
639        } = err
640        else {
641            panic!("a protocol refusal must not be flattened into a generic error, got {err:?}");
642        };
643        assert_eq!(client, PROTOCOL_VERSION);
644        assert_eq!(daemon_version.as_deref(), Some("0.1.16"));
645        assert!(
646            message.contains("protocol 2"),
647            "the daemon's own message must survive: {message}"
648        );
649    }
650
651    /// A refusal is the one stage an upgrade fixes; every other stage is
652    /// nothing answering.
653    #[test]
654    fn a_refusal_exits_protocol_mismatch_and_every_other_stage_unreachable() {
655        let refused = ConnectError::ProtocolMismatch {
656            client: 1,
657            daemon_version: None,
658            message: "too old".to_owned(),
659        };
660        assert_eq!(refused.exit_code(), shep_core::exit::PROTOCOL_MISMATCH);
661        for unreachable in [
662            ConnectError::HandshakeClosed,
663            ConnectError::Io(std::io::Error::other("reset")),
664        ] {
665            assert_eq!(unreachable.exit_code(), shep_core::exit::DAEMON_UNREACHABLE);
666        }
667    }
668
669    /// Every ssh failure is nothing usable answering, whatever its cause; a
670    /// refusal through ssh is still the refusal, and keeps its own code.
671    #[test]
672    fn ssh_failures_exit_daemon_unreachable_and_a_refusal_keeps_protocol_mismatch() {
673        let causes = [
674            SshCause::Spawn {
675                program: PathBuf::from("ssh"),
676                source: std::io::Error::other("no such file"),
677            },
678            SshCause::Transport {
679                stderr: "Connection refused".to_owned(),
680            },
681            SshCause::CommandNotFound,
682            SshCause::NoShepherd,
683            SshCause::RemoteTooOld,
684            SshCause::LoginOutput(Box::new(ConnectError::HandshakeClosed)),
685        ];
686        for cause in causes {
687            let err = ConnectError::Ssh {
688                destination: "build-01".to_owned(),
689                cause,
690            };
691            assert_eq!(
692                err.exit_code(),
693                shep_core::exit::DAEMON_UNREACHABLE,
694                "{err}"
695            );
696        }
697
698        let refused = ConnectError::ProtocolMismatch {
699            client: 1,
700            daemon_version: None,
701            message: "too old".to_owned(),
702        };
703        assert_eq!(refused.exit_code(), shep_core::exit::PROTOCOL_MISMATCH);
704    }
705
706    /// `Display` names the host, and `source` reaches the cause underneath
707    /// without repeating the message `Display` already printed.
708    #[test]
709    fn an_ssh_failure_names_its_host_and_exposes_the_cause_beneath_it() {
710        let spawn = ConnectError::Ssh {
711            destination: "build-01".to_owned(),
712            cause: SshCause::Spawn {
713                program: PathBuf::from("/opt/ssh"),
714                source: std::io::Error::other("denied"),
715            },
716        };
717        assert!(spawn.to_string().contains("`/opt/ssh`"), "{spawn}");
718        assert_eq!(
719            core::error::Error::source(&spawn).unwrap().to_string(),
720            "denied"
721        );
722
723        let wrapped = ConnectError::Ssh {
724            destination: "build-01".to_owned(),
725            cause: SshCause::LoginOutput(Box::new(ConnectError::HandshakeClosed)),
726        };
727        assert!(wrapped.to_string().contains("`build-01`"), "{wrapped}");
728        assert_eq!(
729            core::error::Error::source(&wrapped).unwrap().to_string(),
730            ConnectError::HandshakeClosed.to_string()
731        );
732
733        let transport = ConnectError::Ssh {
734            destination: "build-01".to_owned(),
735            cause: SshCause::NoShepherd,
736        };
737        assert!(core::error::Error::source(&transport).is_none());
738    }
739
740    #[test]
741    fn a_refused_destination_is_a_usage_error() {
742        let err = ConnectError::Destination(DestinationError::Empty);
743        assert_eq!(err.exit_code(), shep_core::exit::USAGE);
744        assert!(core::error::Error::source(&err).is_some());
745    }
746}