#![cfg(unix)]
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use shep_client::ConnectError;
use shep_client::spawn::{SpawnError, SpawnOutcome, connect_or_spawn, connect_or_spawn_with};
use shep_client::testing::{
child_exiting_with, fake_daemon, fast_opts, sample_ack, start_fake_daemon_answering_on,
};
use shep_core::protocol::{RpcError, RpcErrorCode};
#[derive(Debug, Default)]
struct Reaper(Arc<Mutex<Vec<i32>>>);
impl Reaper {
fn spawn_long_lived(
&self,
) -> impl FnOnce() -> std::io::Result<std::process::Child> + Send + 'static {
let pids = Arc::clone(&self.0);
move || {
let child = std::process::Command::new("cat")
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()?;
pids.lock()
.unwrap()
.push(i32::try_from(child.id()).unwrap());
Ok(child)
}
}
}
impl Drop for Reaper {
fn drop(&mut self) {
for pid in self.0.lock().unwrap().drain(..) {
let _ = nix::sys::wait::waitpid(nix::unistd::Pid::from_raw(pid), None);
}
}
}
#[tokio::test]
async fn an_existing_daemon_is_used_without_launching_anything() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let _served = fake_daemon(&path, Ok(sample_ack())).await;
let outcome = connect_or_spawn_with(
&path,
|| unreachable!("a live daemon must never be re-spawned"),
fast_opts(),
)
.await
.unwrap();
assert!(matches!(outcome, SpawnOutcome::Connected(_)));
}
#[tokio::test]
async fn a_socket_that_accepts_but_never_handshakes_is_not_mistaken_for_ready() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let reaper = Reaper::default();
let held: Arc<Mutex<Option<std::os::unix::net::UnixListener>>> = Arc::default();
let err = {
let slot = Arc::clone(&held);
let bind_at = path.clone();
let long_lived = reaper.spawn_long_lived();
connect_or_spawn_with(
&path,
move || {
*slot.lock().unwrap() = Some(std::os::unix::net::UnixListener::bind(&bind_at)?);
long_lived()
},
fast_opts(),
)
.await
.unwrap_err()
};
let SpawnError::DeadlineExpired {
last: Some(ConnectError::HandshakeTimeout { .. }),
after,
} = err
else {
panic!("a backlogged connect must read as an unfinished handshake, got {err:?}");
};
assert_eq!(after, fast_opts().deadline);
assert!(
held.lock().unwrap().is_some(),
"the fixture must actually have bound the socket"
);
}
#[tokio::test]
async fn a_child_that_dies_fails_fast_instead_of_waiting_out_the_deadline() {
let dir = tempfile::tempdir().unwrap();
let absent_path = shep_client::testing::control_address(dir.path());
let started = Instant::now();
let err = connect_or_spawn(&absent_path, || child_exiting_with(3))
.await
.unwrap_err();
let SpawnError::DaemonExited { status } = err else {
panic!("a dead child's status must reach the caller, got {err:?}");
};
assert_eq!(status.code(), Some(3));
assert!(
started.elapsed() < Duration::from_secs(5),
"must not wait out SPAWN_DEADLINE on a dead child"
);
}
#[tokio::test]
async fn a_child_exiting_with_the_already_running_code_keeps_probing() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let answer_on = path.clone();
let outcome = connect_or_spawn_with(
&path,
move || {
start_fake_daemon_answering_on(&answer_on);
let child = std::process::Command::new("sh")
.args(["-c", "exit 10"])
.spawn()?;
std::thread::sleep(Duration::from_millis(50));
Ok(child)
},
fast_opts(),
)
.await
.unwrap();
assert!(
matches!(outcome, SpawnOutcome::Spawned(_)),
"another process winning the race is not this process's failure"
);
}
#[tokio::test]
async fn a_protocol_mismatch_propagates_instead_of_spawning_a_second_daemon() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let _served = fake_daemon(
&path,
Err(RpcError {
code: RpcErrorCode::ProtocolMismatch,
message: "daemon speaks protocol 2, client speaks 1".into(),
daemon_version: None,
}),
)
.await;
let err = connect_or_spawn_with(
&path,
|| unreachable!("a refusing daemon is still a daemon"),
fast_opts(),
)
.await
.unwrap_err();
assert!(matches!(
err,
SpawnError::Connect(ConnectError::ProtocolMismatch { .. })
));
}
#[tokio::test]
async fn a_protocol_mismatch_on_a_loop_probe_propagates_instead_of_looping_to_the_deadline() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let reaper = Reaper::default();
let answer_on = path.clone();
let started = Instant::now();
let err = {
let long_lived = reaper.spawn_long_lived();
connect_or_spawn_with(
&path,
move || {
tokio::runtime::Handle::current().block_on(fake_daemon(
&answer_on,
Err(RpcError {
code: RpcErrorCode::ProtocolMismatch,
message: "daemon speaks protocol 2, client speaks 1".into(),
daemon_version: None,
}),
));
long_lived()
},
fast_opts(),
)
.await
.unwrap_err()
};
assert!(
matches!(
err,
SpawnError::Connect(ConnectError::ProtocolMismatch { .. })
),
"a mismatch on a loop probe must propagate immediately, got {err:?}"
);
assert!(
started.elapsed() < fast_opts().deadline,
"must not burn the rest of the deadline after a definitive answer"
);
}
#[tokio::test]
async fn a_bound_but_silent_socket_is_probed_not_respawned() {
let dir = tempfile::tempdir().unwrap();
let path = shep_client::testing::control_address(dir.path());
let _listener = std::os::unix::net::UnixListener::bind(&path).unwrap();
let err = connect_or_spawn_with(
&path,
|| unreachable!("something is already bound here"),
fast_opts(),
)
.await
.unwrap_err();
assert!(matches!(err, SpawnError::DeadlineExpired { .. }));
}