use std::time::Duration;
use serde::de::DeserializeOwned;
use shep_core::paths::ShepPaths;
use shep_core::protocol::DogSectionToml;
use super::long_action::{self, ActionDone, ActionId, LongActionError, Waits};
use super::{DogIdentity, SectionError, ShepherdError, link, parse_section};
use crate::ReconnectingClient;
#[derive(Debug)]
pub struct DogRuntime {
client: ReconnectingClient,
section: DogSectionToml,
paths: ShepPaths,
identity: DogIdentity,
waits: Waits,
}
impl DogRuntime {
pub async fn start(identity: DogIdentity, paths: ShepPaths) -> Result<Self, ShepherdError> {
let client = link::connect(&identity, &paths.socket).await?;
let section = client.dog_config(identity.section()).await?;
Ok(Self {
client,
section,
paths,
identity,
waits: Waits::default(),
})
}
pub fn config<T>(&self) -> Result<T, SectionError>
where
T: DeserializeOwned + Default,
{
parse_section(self.identity.section(), self.section.as_str())
}
pub async fn publish(
&self,
kind: &str,
payload: serde_json::Value,
) -> Result<(), ShepherdError> {
Ok(self.client.publish_event(kind, payload).await?)
}
pub async fn finish_action(
&self,
id: &ActionId,
outcome: Result<serde_json::Value, String>,
) -> Result<(), ShepherdError> {
self.publish(super::DONE_KIND, long_action::done_payload(id, outcome))
.await
}
pub async fn trigger_and_wait(
&self,
callee: &str,
action: &str,
params: Option<&str>,
timeout: Duration,
) -> Result<ActionDone, LongActionError> {
long_action::trigger_and_wait(&self.waits, &self.client, callee, action, params, timeout)
.await
}
#[must_use]
pub fn client(&self) -> &ReconnectingClient {
&self.client
}
#[must_use]
pub fn section(&self) -> &DogSectionToml {
&self.section
}
#[must_use]
pub fn paths(&self) -> &ShepPaths {
&self.paths
}
#[must_use]
pub fn identity(&self) -> &DogIdentity {
&self.identity
}
#[must_use]
pub fn into_client(self) -> ReconnectingClient {
self.client
}
}
#[cfg(test)]
mod tests {
use std::path::Path;
use std::time::Duration;
use shep_core::protocol::{Request, Response, SelectorSpec};
use super::*;
use crate::testing::{control_address, fake_daemon, sample_ack, serve_one_request};
fn paths_in(dir: &Path) -> ShepPaths {
let mut paths = ShepPaths::resolve(&|_| None, dir);
paths.socket = control_address(dir);
paths
}
async fn started(dir: &Path, section: &str) -> (DogRuntime, Request) {
let paths = paths_in(dir);
let served = serve_one_request(
&paths.socket,
sample_ack(),
Response::DogSection {
toml: section.to_owned().into(),
},
)
.await;
let runtime = tokio::time::timeout(
Duration::from_secs(5),
DogRuntime::start(DogIdentity::named("bark"), paths),
)
.await
.expect("DogRuntime::start hung instead of connecting")
.unwrap();
let asked = tokio::time::timeout(Duration::from_secs(5), served)
.await
.expect("the request reached the fake daemon")
.unwrap();
(runtime, asked.body)
}
#[tokio::test]
async fn a_dog_asks_for_its_own_section_by_name() {
let dir = tempfile::tempdir().unwrap();
let (runtime, asked) = started(dir.path(), "poll = \"1m\"\n").await;
assert_eq!(
asked,
Request::DogConfigResolved {
name: "bark".to_owned()
}
);
assert_eq!(runtime.section().as_str(), "poll = \"1m\"\n");
assert_eq!(runtime.identity().section(), "bark");
}
#[tokio::test]
async fn publish_sends_the_dogs_event_and_payload_to_the_shepherd() {
use crate::testing::{Handshake, fake_daemon_across_handovers};
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
let shepherd =
fake_daemon_across_handovers(&paths.socket, vec![Handshake::Accept(sample_ack())]);
let runtime = tokio::time::timeout(
Duration::from_secs(5),
DogRuntime::start(DogIdentity::named("bark"), paths),
)
.await
.expect("DogRuntime::start hung instead of connecting")
.unwrap();
let payload = serde_json::json!({ "sent": 3 });
runtime.publish("exported", payload.clone()).await.unwrap();
let sent: Vec<Request> = shepherd
.envelopes()
.into_iter()
.map(|(_, envelope)| envelope.body)
.collect();
assert!(
sent.contains(&Request::PublishEvent {
event: "exported".to_owned(),
payload
}),
"{sent:?}"
);
}
#[tokio::test]
async fn the_trigger_waits_as_long_as_any_other_trigger_does() {
use crate::testing::{Handshake, fake_daemon_across_handovers};
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
let shepherd =
fake_daemon_across_handovers(&paths.socket, vec![Handshake::Accept(sample_ack())]);
let runtime = tokio::time::timeout(
Duration::from_secs(5),
DogRuntime::start(DogIdentity::named("bark"), paths),
)
.await
.expect("DogRuntime::start hung instead of connecting")
.unwrap();
let _ = runtime
.trigger_and_wait("builder", "build", Some("p"), Duration::from_millis(50))
.await;
let trigger = shepherd
.envelopes()
.into_iter()
.map(|(_, envelope)| envelope)
.find(|envelope| matches!(envelope.body, Request::Trigger { .. }))
.expect("the shepherd was sent a Trigger");
assert_eq!(
trigger.body,
Request::Trigger {
selector: SelectorSpec::Name("builder".to_owned()),
action: "build".to_owned(),
params: Some("p".to_owned()),
}
);
assert_eq!(
trigger.deadline_ms,
Some(u64::try_from(crate::TRIGGER_DEADLINE.as_millis()).unwrap())
);
}
fn subscribes(shepherd: &crate::testing::Handovers) -> Vec<u32> {
shepherd
.envelopes()
.into_iter()
.filter(|(_, envelope)| matches!(envelope.body, Request::Subscribe { .. }))
.map(|(generation, _)| generation)
.collect()
}
#[tokio::test]
async fn a_wait_on_a_topic_the_connection_already_hears_sends_no_subscribe() {
use crate::testing::{Handshake, fake_daemon_across_handovers};
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
let shepherd =
fake_daemon_across_handovers(&paths.socket, vec![Handshake::Accept(sample_ack())]);
let runtime = DogRuntime::start(DogIdentity::named("bark"), paths)
.await
.unwrap();
let wait = || runtime.trigger_and_wait("builder", "build", None, Duration::from_millis(50));
let _ = tokio::join!(wait(), wait());
let _ = wait().await;
assert_eq!(subscribes(&shepherd), [1]);
}
#[tokio::test]
async fn a_wait_after_a_handover_subscribes_again() {
use crate::testing::{Handshake, fake_daemon_across_handovers};
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
let shepherd = fake_daemon_across_handovers(
&paths.socket,
vec![
Handshake::Accept(sample_ack()),
Handshake::Accept(sample_ack()),
],
);
let runtime = DogRuntime::start(DogIdentity::named("bark"), paths)
.await
.unwrap();
let wait = || runtime.trigger_and_wait("builder", "build", None, Duration::from_millis(50));
let _ = wait().await;
shepherd.cut().await;
tokio::time::timeout(Duration::from_secs(5), async {
while shepherd.accepted() < 2 {
tokio::time::sleep(Duration::from_millis(10)).await;
}
runtime
.client()
.connected_within(Duration::from_secs(5))
.await
})
.await
.expect("the client reconnects")
.unwrap();
let _ = wait().await;
assert_eq!(subscribes(&shepherd), [1, 2]);
}
#[tokio::test]
async fn an_unnamed_dog_reads_its_default_section_anonymously() {
let dir = tempfile::tempdir().unwrap();
let paths = paths_in(dir.path());
let hello = fake_daemon(&paths.socket, Ok(sample_ack())).await;
let identity = DogIdentity::from_env(&|_| None, "log-rotate");
let started =
tokio::time::timeout(Duration::from_secs(5), DogRuntime::start(identity, paths))
.await
.expect("DogRuntime::start hung instead of connecting");
assert!(matches!(started, Err(ShepherdError::Request(_))));
let hello = tokio::time::timeout(Duration::from_secs(5), hello)
.await
.expect("the fake daemon read the hello")
.unwrap();
assert_eq!(hello.dog_name, None);
}
#[tokio::test]
async fn a_section_that_does_not_fit_is_refused_rather_than_defaulted() {
#[derive(Debug, Default, serde::Deserialize, PartialEq)]
#[serde(deny_unknown_fields, default)]
struct Settings {
port: u16,
}
let dir = tempfile::tempdir().unwrap();
let (runtime, _) = started(dir.path(), "port = \"nine thousand\"\n").await;
let err = runtime.config::<Settings>().unwrap_err();
assert_eq!(err.section(), "bark");
assert_eq!(err.line(), Some(1));
}
#[tokio::test]
async fn no_shepherd_is_a_connect_error() {
let dir = tempfile::tempdir().unwrap();
let started = DogRuntime::start(DogIdentity::named("bark"), paths_in(dir.path())).await;
let err = started.unwrap_err();
assert!(matches!(err, ShepherdError::Connect(_)), "{err}");
assert_eq!(err.exit_code(), shep_core::exit::DAEMON_UNREACHABLE);
}
#[tokio::test]
async fn debug_never_prints_the_section() {
let secret = "https://hooks.example.com/services/T00/B00/super-secret-token";
let section = format!("webhook = \"{secret}\"\n");
let dir = tempfile::tempdir().unwrap();
let (runtime, _) = started(dir.path(), §ion).await;
let debug = format!("{runtime:?}");
assert!(!debug.contains(secret), "{debug}");
assert!(
debug.contains(&format!(
"section: DogSectionToml(<{} bytes>)",
section.len()
)),
"{debug}"
);
}
}