use super::conn_protocol::handle_conn;
use crate::rpc::RpcContext;
use core::time::Duration;
use futures_util::{SinkExt, StreamExt};
use serde::Serialize;
use shep_core::protocol::{Hello, HelloReply, MIN_SUPPORTED, codec, decode_frame, encode_frame};
use std::collections::BTreeMap;
use serde::de::DeserializeOwned;
use shep_core::protocol::{
DogSource, Envelope, PROTOCOL_VERSION, ProcessInfo, Request, Response, ServerFrame,
};
use tokio_util::codec::Framed;
const RECV_TIMEOUT: Duration = Duration::from_secs(5);
pub(super) struct Client {
pub(super) frames:
Framed<shep_core::transport::ClientStream, tokio_util::codec::LengthDelimitedCodec>,
}
impl Client {
pub(super) async fn send<T: Serialize>(&mut self, value: &T) {
self.frames
.send(encode_frame(value).unwrap())
.await
.unwrap();
}
pub(super) async fn recv<T: DeserializeOwned>(&mut self) -> T {
let frame = tokio::time::timeout(RECV_TIMEOUT, self.frames.next())
.await
.expect("timed out waiting for a frame")
.expect("connection closed early")
.unwrap();
decode_frame(&frame).unwrap()
}
pub(super) async fn handshake(&mut self) {
self.send(&Hello {
client_version: "0.1.0".to_string(),
protocol: PROTOCOL_VERSION,
dog_name: None,
})
.await;
let ack: HelloReply = self.recv().await;
ack.expect("the fixture handshakes on this daemon's own protocol");
}
pub(super) async fn subscribe(&mut self, topics: &[&str]) {
self.send(&Envelope {
id: 1,
deadline_ms: None,
body: Request::Subscribe {
topics: topics.iter().map(|t| t.to_string()).collect(),
},
})
.await;
let frame: ServerFrame = self.recv().await;
assert!(
matches!(&frame, ServerFrame::Reply(reply) if reply.result == Ok(Response::Subscribed)),
"a Subscribe must be answered with Subscribed: {frame:?}"
);
}
pub(super) async fn closed(&mut self) -> bool {
tokio::time::timeout(RECV_TIMEOUT, self.frames.next())
.await
.expect("timed out waiting for close")
.is_none()
}
}
pub(super) async fn connected(ctx: RpcContext) -> Client {
let (server, client) = shep_core::transport::connected_pair().await.unwrap();
tokio::spawn(async move {
let _ = handle_conn(server, ctx).await;
});
Client {
frames: Framed::new(client, codec()),
}
}
pub(super) async fn start_dog(ctx: &RpcContext, name: &str) -> ProcessInfo {
let spec = crate::dogs::DogSpec {
name: name.to_string(),
source: DogSource::BuiltIn { grants: None },
env: BTreeMap::new(),
};
let app = crate::dogs::dog_app(&spec, &ctx.paths).expect("the dog fixture must assemble");
ctx.supervisor
.start_dog(app, DogSource::BuiltIn { grants: None })
.await
.expect("the dog fixture must start")
}
pub(super) async fn refuse_as(ctx: &RpcContext, dog: Option<&str>) {
let mut client = connected(ctx.clone()).await;
client
.send(&Hello {
client_version: "0.1.14".to_string(),
protocol: MIN_SUPPORTED - 1,
dog_name: dog.map(str::to_owned),
})
.await;
let refusal: HelloReply = client.recv().await;
refusal.expect_err("a protocol below the floor must be refused");
assert!(
client.closed().await,
"the daemon must close after refusing"
);
}
pub(super) async fn dog_row(ctx: &RpcContext, name: &str) -> ProcessInfo {
ctx.supervisor
.list()
.await
.into_iter()
.find(|info| info.name == name)
.unwrap_or_else(|| panic!("no row named {name}"))
}
pub(super) async fn await_dog(ctx: &RpcContext, name: &str, pid: u32) -> Duration {
let began = tokio::time::Instant::now();
let seen = tokio::time::timeout(RECV_TIMEOUT, async {
loop {
if dog_row(ctx, name).await.pid == Some(pid) {
return;
}
tokio::task::yield_now().await;
}
})
.await;
assert!(
seen.is_ok(),
"{name} never reached pid {pid} within {RECV_TIMEOUT:?}: {:?}",
ctx.supervisor.list().await
);
began.elapsed()
}