1use 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
28pub const HANDSHAKE_TIMEOUT: Duration = Duration::from_secs(5);
34
35pub(crate) trait ByteStream: AsyncRead + AsyncWrite + Unpin + Send {}
38
39impl<T: AsyncRead + AsyncWrite + Unpin + Send> ByteStream for T {}
40
41pub(crate) type Frames = Framed<Box<dyn ByteStream>, LengthDelimitedCodec>;
49
50#[derive(Debug)]
54#[non_exhaustive]
55pub enum ConnectError {
56 Connect {
59 path: PathBuf,
61 source: std::io::Error,
63 },
64 Io(std::io::Error),
66 Wire(WireError),
68 HandshakeClosed,
70 HandshakeTimeout {
74 after: Duration,
76 },
77 ProtocolMismatch {
81 client: u32,
83 daemon_version: Option<String>,
88 message: String,
90 },
91 Destination(DestinationError),
97 Ssh {
99 destination: String,
101 cause: SshCause,
103 },
104}
105
106impl ConnectError {
107 #[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 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 Self::Ssh { cause, .. } => core::error::Error::source(cause),
175 Self::HandshakeClosed
176 | Self::HandshakeTimeout { .. }
177 | Self::ProtocolMismatch { .. } => None,
178 }
179 }
180}
181
182pub(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 pub(crate) async fn open(
211 socket: &Path,
212 timeout: Duration,
213 dog_name: Option<&str>,
214 ) -> Result<Self, ConnectError> {
215 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 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 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 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 #[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 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 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 #[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 #[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 #[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 #[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 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 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 });
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 #[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 #[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 #[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}