use futures_util::{SinkExt, StreamExt};
use shep_core::protocol::{
BusEvent, DogSource, Envelope, ExitInfo, Hello, HelloAck, HelloReply, Lamb, PROTOCOL_VERSION,
ProcessEventKind, ProcessInfo, Reply, Response, RpcError, RpcErrorCode, decode_frame,
encode_frame,
};
use shep_core::status::ProcStatus;
use shep_core::transport::{Listener, ServerStream};
use std::path::{Path, PathBuf};
use tokio_util::codec::Framed;
#[must_use]
pub fn control_address(dir: &Path) -> PathBuf {
#[cfg(unix)]
{
dir.join("s.sock")
}
#[cfg(windows)]
{
let sanitized: String = dir
.to_string_lossy()
.chars()
.map(|c| if c.is_ascii_alphanumeric() { c } else { '-' })
.collect();
PathBuf::from(format!(
r"\\.\pipe\shep-test-{}-{}",
std::process::id(),
sanitized.trim_matches('-')
))
}
}
pub(super) fn bind(path: &Path) -> Listener {
Listener::bind(path).unwrap_or_else(|error| panic!("bind {}: {error}", path.display()))
}
pub(super) type Frames = Framed<ServerStream, tokio_util::codec::LengthDelimitedCodec>;
#[must_use]
pub fn sample_ack() -> HelloAck {
HelloAck {
daemon_version: "9.9.9".into(),
protocol: PROTOCOL_VERSION,
pid: 4242,
min_supported: None,
}
}
#[must_use]
pub fn sample_info() -> ProcessInfo {
ProcessInfo::builder(1, "web", ProcStatus::Online)
.pid(Some(4242))
.restarts(3)
.uptime_ms(60_000)
.fold(Some("backend".to_string()))
.out_file(Some("/home/ada/.shep/logs/web-0-out.log".to_string()))
.err_file(Some("/home/ada/.shep/logs/web-0-err.log".to_string()))
.cpu_percent(Some(12.5))
.memory_bytes(Some(48 * 1024 * 1024))
.dog(Some(DogSource::BuiltIn))
.lambs(Some(vec![Lamb::new(4243, "node")]))
.last_exit(Some(ExitInfo {
code: Some(1),
signal: None,
}))
.smit(Some("\u{25b2} main@a1b2c3".to_string()))
.build()
}
pub(super) async fn handshake(frames: &mut Frames, ack: HelloAck) -> Hello {
let first = frames.next().await.unwrap().unwrap();
let hello: Hello = decode_frame(&first).unwrap();
let reply: HelloReply = Ok(ack);
frames.send(encode_frame(&reply).unwrap()).await.unwrap();
hello
}
pub(super) async fn read_envelope(frames: &mut Frames) -> Envelope {
let frame = frames.next().await.unwrap().unwrap();
decode_frame(&frame).unwrap()
}
pub(super) async fn write_reply(frames: &mut Frames, id: u64, response: Response) {
let reply = Reply {
id,
result: Ok(response),
};
frames.send(encode_frame(&reply).unwrap()).await.unwrap();
}
pub(super) async fn write_err(frames: &mut Frames, id: u64, code: RpcErrorCode, message: String) {
let reply = Reply {
id,
result: Err(RpcError {
code,
message,
daemon_version: None,
}),
};
frames.send(encode_frame(&reply).unwrap()).await.unwrap();
}
pub(super) async fn write_event(frames: &mut Frames, event: BusEvent) {
frames.send(encode_frame(&event).unwrap()).await.unwrap();
}
pub(super) async fn send_sample_event(frames: &mut Frames) {
write_event(
frames,
BusEvent::Process {
event: ProcessEventKind::Online,
info: sample_info(),
manually: false,
at_ms: 0,
},
)
.await;
}