use core::future::Future;
use shep_core::config::DogTable;
use shep_core::protocol::{
DogSectionToml, HostUsage, LogStream, LogTail, ProcessInfo, Request, Response, RpcError,
RpcErrorCode, SelectorSpec,
};
use shep_core::secrets::references_in;
use crate::ReconnectingClient;
use crate::client::{Client, LOG_PLANE_DEADLINE, RequestError};
impl Client {
pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
resolved_dog_section(name, |body| self.request(body)).await
}
pub async fn sheep_dog_table(
&self,
name: &str,
dog: &str,
) -> Result<Option<DogTable>, RequestError> {
resolved_sheep_dog_table(name, dog, |body| self.request(body)).await
}
pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
flock(self.request(Request::ListFlock).await?)
}
pub async fn reopen(&self, selector: SelectorSpec) -> Result<Vec<ProcessInfo>, RequestError> {
let body = Request::Reopen { selector };
reopened(
self.request_with_deadline(body, Some(LOG_PLANE_DEADLINE))
.await?,
)
}
pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
host(self.request(Request::HostUsage).await?)
}
pub async fn publish_event(
&self,
event: &str,
payload: serde_json::Value,
) -> Result<(), RequestError> {
published(
self.request(Request::PublishEvent {
event: event.to_owned(),
payload,
})
.await?,
)
}
pub async fn tail_log(
&self,
id: u32,
stream: LogStream,
lines: u32,
) -> Result<LogTail, RequestError> {
log_tail(self.request(Request::TailLog { id, stream, lines }).await?)
}
}
impl ReconnectingClient {
pub async fn publish_event(
&self,
event: &str,
payload: serde_json::Value,
) -> Result<(), RequestError> {
published(
self.request(Request::PublishEvent {
event: event.to_owned(),
payload,
})
.await?,
)
}
pub async fn dog_config(&self, name: &str) -> Result<DogSectionToml, RequestError> {
resolved_dog_section(name, |body| self.request(body)).await
}
pub async fn sheep_dog_table(
&self,
name: &str,
dog: &str,
) -> Result<Option<DogTable>, RequestError> {
resolved_sheep_dog_table(name, dog, |body| self.request(body)).await
}
pub async fn list_flock(&self) -> Result<Vec<ProcessInfo>, RequestError> {
flock(self.request(Request::ListFlock).await?)
}
pub async fn reopen(&self, selector: SelectorSpec) -> Result<Vec<ProcessInfo>, RequestError> {
let body = Request::Reopen { selector };
reopened(
self.request_with_deadline(body, Some(LOG_PLANE_DEADLINE))
.await?,
)
}
pub async fn host_usage(&self) -> Result<Option<HostUsage>, RequestError> {
host(self.request(Request::HostUsage).await?)
}
pub async fn tail_log(
&self,
id: u32,
stream: LogStream,
lines: u32,
) -> Result<LogTail, RequestError> {
log_tail(self.request(Request::TailLog { id, stream, lines }).await?)
}
}
fn dog_config_request(name: &str) -> Request {
Request::DogConfigResolved {
name: name.to_owned(),
}
}
async fn resolved_dog_section<F, Fut>(name: &str, ask: F) -> Result<DogSectionToml, RequestError>
where
F: Fn(Request) -> Fut,
Fut: Future<Output = Result<Response, RequestError>>,
{
match ask(dog_config_request(name)).await {
Err(RequestError::Rpc(refusal)) if is_unknown_request(&refusal) => {
let plain = Request::DogConfig {
name: name.to_owned(),
};
let section = dog_section(ask(plain).await?)?;
if !references_in(section.as_str()).is_empty() {
return Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::Unsupported,
message: format!(
"the shepherd is too old to resolve secret references in the \
`{name}` dog's section"
),
daemon_version: refusal.daemon_version,
}));
}
Ok(section)
}
answer => dog_section(answer?),
}
}
fn is_unknown_request(refusal: &RpcError) -> bool {
matches!(
refusal.code,
RpcErrorCode::Unsupported | RpcErrorCode::Unrecognized
)
}
async fn resolved_sheep_dog_table<F, Fut>(
name: &str,
dog: &str,
ask: F,
) -> Result<Option<DogTable>, RequestError>
where
F: Fn(Request) -> Fut,
Fut: Future<Output = Result<Response, RequestError>>,
{
let resolved = Request::SheepDogSettingsResolved {
name: name.to_owned(),
dog: dog.to_owned(),
};
match ask(resolved).await {
Err(RequestError::Rpc(refusal)) if is_unknown_request(&refusal) => {
let plain = Request::DogSheepSettings {
dog: dog.to_owned(),
};
let table = match ask(plain).await? {
Response::DogSheepSettings { mut tables } => tables.remove(name),
other => return Err(unexpected("DogSheepSettings", &other)),
};
if table.is_none() {
ensure_a_sheep(name, &ask).await?;
}
if table
.as_ref()
.is_some_and(|table| !table.references().is_empty())
{
return Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::Unsupported,
message: format!(
"the shepherd is too old to resolve secret references in the \
`{name}` sheep's `{dog}` table"
),
daemon_version: refusal.daemon_version,
}));
}
Ok(table)
}
answer => match answer? {
Response::SheepDogTable { table } => Ok(table),
other => Err(unexpected("SheepDogSettingsResolved", &other)),
},
}
}
async fn ensure_a_sheep<F, Fut>(name: &str, ask: &F) -> Result<(), RequestError>
where
F: Fn(Request) -> Fut,
Fut: Future<Output = Result<Response, RequestError>>,
{
let sheep = flock(ask(Request::ListFlock).await?)?;
if sheep
.iter()
.any(|entry| entry.name == name && entry.dog.is_none())
{
return Ok(());
}
Err(RequestError::Rpc(RpcError {
code: RpcErrorCode::NotFound,
message: format!("no sheep named {name}"),
daemon_version: None,
}))
}
fn dog_section(answer: Response) -> Result<DogSectionToml, RequestError> {
match answer {
Response::DogSection { toml } => Ok(toml),
other => Err(unexpected("DogConfigResolved", &other)),
}
}
fn flock(answer: Response) -> Result<Vec<ProcessInfo>, RequestError> {
match answer {
Response::Flock(flock) => Ok(flock),
other => Err(unexpected("ListFlock", &other)),
}
}
fn reopened(answer: Response) -> Result<Vec<ProcessInfo>, RequestError> {
match answer {
Response::Reopened(sheep) => Ok(sheep),
other => Err(unexpected("Reopen", &other)),
}
}
fn host(answer: Response) -> Result<Option<HostUsage>, RequestError> {
match answer {
Response::HostUsage(usage) => Ok(usage),
other => Err(unexpected("HostUsage", &other)),
}
}
fn published(answer: Response) -> Result<(), RequestError> {
match answer {
Response::EventPublished => Ok(()),
other => Err(unexpected("PublishEvent", &other)),
}
}
fn log_tail(answer: Response) -> Result<LogTail, RequestError> {
match answer {
Response::LogTail(tail) => Ok(tail),
other => Err(unexpected("TailLog", &other)),
}
}
fn unexpected(asked: &'static str, answer: &Response) -> RequestError {
RequestError::UnexpectedReply {
asked,
answered: answer.name(),
}
}
#[cfg(test)]
mod tests;