use core::fmt;
use core::sync::atomic::{AtomicU64, Ordering};
use std::collections::BTreeMap;
use std::sync::{Mutex, OnceLock, PoisonError};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use serde_json::{Value, json};
use shep_core::protocol::{ActionOutcome, BusEvent, Request, Response, RpcErrorCode, SelectorSpec};
use crate::reconnect::Covered;
use crate::{EventStream, Lagged, ReconnectingClient, RequestError, TRIGGER_DEADLINE};
#[cfg(doc)]
use super::DogRuntime;
pub const DONE_KIND: &str = "action.done";
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ActionId(String);
impl ActionId {
#[must_use]
pub fn accept() -> (Self, String) {
let id = Self::mint();
let body = json!({ "id": id.0 }).to_string();
(id, body)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
fn mint() -> Self {
static COUNTER: AtomicU64 = AtomicU64::new(0);
static START: OnceLock<u128> = OnceLock::new();
let start = START.get_or_init(|| {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.as_nanos())
});
let count = COUNTER.fetch_add(1, Ordering::Relaxed);
Self(format!("{start:x}-{:x}-{count}", std::process::id()))
}
#[must_use]
pub fn from_reply(body: &str) -> Option<Self> {
let value: Value = serde_json::from_str(body).ok()?;
let id = value.get("id")?.as_str().filter(|id| !id.is_empty())?;
Some(Self(id.to_owned()))
}
}
impl fmt::Display for ActionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct ActionDone {
pub id: ActionId,
pub result: Value,
}
impl ActionDone {
#[must_use]
pub fn read(payload: &Value) -> Option<(ActionId, Result<Value, String>)> {
let id = payload.get("id")?.as_str().filter(|id| !id.is_empty())?;
let outcome = match payload.get("error") {
Some(Value::String(error)) => Err(error.clone()),
Some(_) => return None,
None => Ok(payload.get("result")?.clone()),
};
Some((ActionId(id.to_owned()), outcome))
}
}
#[derive(Debug)]
#[non_exhaustive]
pub enum LongActionError {
NotGranted {
grant: String,
message: String,
},
Request(RequestError),
NotDelivered(String),
NoId {
body: String,
},
Failed {
id: ActionId,
error: String,
},
Malformed {
id: ActionId,
payload: String,
},
TimedOut {
id: ActionId,
after: Duration,
},
EventsLost(String),
}
impl fmt::Display for LongActionError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::NotGranted { grant, message } => {
write!(f, "the caller needs the grant `{grant}`: {message}")
}
Self::Request(error) => write!(f, "a request to the shepherd failed: {error}"),
Self::NotDelivered(why) => write!(f, "the action was not delivered: {why}"),
Self::NoId { body } => write!(f, "the callee did not answer with an action id: {body}"),
Self::Failed { id, error } => write!(f, "action {id} failed: {error}"),
Self::Malformed { id, payload } => {
write!(f, "action {id} ended with an unreadable event: {payload}")
}
Self::TimedOut { id, after } => {
write!(f, "action {id} sent no result within {after:?}")
}
Self::EventsLost(why) => write!(f, "the result may have been missed: {why}"),
}
}
}
impl core::error::Error for LongActionError {
fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
match self {
Self::Request(error) => Some(error),
_ => None,
}
}
}
pub(super) fn done_payload(id: &ActionId, outcome: Result<Value, String>) -> Value {
match outcome {
Ok(result) => json!({ "id": id.0, "result": result }),
Err(error) => json!({ "id": id.0, "error": error }),
}
}
#[derive(Debug, Default)]
pub(super) struct Waits {
covered: tokio::sync::Mutex<Covered>,
topics: Mutex<BTreeMap<String, usize>>,
}
struct Listening<'a> {
waits: &'a Waits,
topic: String,
}
impl Waits {
async fn listen<'a>(
&'a self,
client: &ReconnectingClient,
topic: String,
) -> Result<(EventStream, Listening<'a>), RequestError> {
let mut covered = self.covered.lock().await;
let listening = self.claim(topic);
let events = client
.subscribe_covered(self.topics(), &mut covered)
.await?;
Ok((events, listening))
}
fn claim(&self, topic: String) -> Listening<'_> {
*self.lock().entry(topic.clone()).or_insert(0) += 1;
Listening { waits: self, topic }
}
fn topics(&self) -> Vec<String> {
self.lock().keys().cloned().collect()
}
fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap<String, usize>> {
self.topics.lock().unwrap_or_else(PoisonError::into_inner)
}
}
impl Drop for Listening<'_> {
fn drop(&mut self) {
let mut topics = self.waits.lock();
if let Some(count) = topics.get_mut(&self.topic) {
*count -= 1;
if *count == 0 {
topics.remove(&self.topic);
}
}
}
}
pub(super) async fn trigger_and_wait(
waits: &Waits,
client: &ReconnectingClient,
callee: &str,
action: &str,
params: Option<&str>,
timeout: Duration,
) -> Result<ActionDone, LongActionError> {
let topic = format!("dog.{callee}.{DONE_KIND}");
let (mut events, _listening) = waits
.listen(client, topic)
.await
.map_err(|error| refused(error, format!("events:dog.{callee}")))?;
let id = trigger(client, callee, action, params).await?;
match tokio::time::timeout(timeout, result_for(&mut events, callee, &id)).await {
Ok(Ok(result)) => Ok(ActionDone { id, result }),
Ok(Err(error)) => Err(error),
Err(_elapsed) => Err(LongActionError::TimedOut { id, after: timeout }),
}
}
async fn trigger(
client: &ReconnectingClient,
callee: &str,
action: &str,
params: Option<&str>,
) -> Result<ActionId, LongActionError> {
let request = Request::Trigger {
selector: SelectorSpec::Name(callee.to_owned()),
action: action.to_owned(),
params: params.map(str::to_owned),
};
let reply = client
.request_with_deadline(request, Some(TRIGGER_DEADLINE))
.await
.map_err(|error| refused(error, format!("dogs.trigger:{callee}")))?;
let Response::Triggered(rows) = reply else {
return Err(LongActionError::Request(RequestError::UnexpectedReply {
asked: "Trigger",
answered: reply.name(),
}));
};
let Some(row) = rows.into_iter().find(|row| row.name == callee) else {
return Err(LongActionError::NotDelivered(format!(
"no dog named `{callee}`"
)));
};
match row.outcome {
ActionOutcome::Replied { body } => {
ActionId::from_reply(&body).ok_or(LongActionError::NoId { body })
}
other => Err(LongActionError::NotDelivered(format!("{other:?}"))),
}
}
async fn result_for(
events: &mut EventStream,
callee: &str,
id: &ActionId,
) -> Result<Value, LongActionError> {
loop {
match events.next().await {
None => return Err(LongActionError::EventsLost("the connection closed".into())),
Some(Err(Lagged { count })) => {
return Err(LongActionError::EventsLost(format!(
"{count} events dropped locally"
)));
}
Some(Ok(BusEvent::Dropped { .. })) => {
return Err(LongActionError::EventsLost(
"the shepherd dropped events".into(),
));
}
Some(Ok(BusEvent::Dog { dog, kind, payload }))
if dog == callee && kind == DONE_KIND =>
{
if payload.get("id").and_then(Value::as_str) != Some(id.as_str()) {
continue;
}
return outcome_of(id, &payload);
}
Some(Ok(_other)) => {}
}
}
}
fn outcome_of(id: &ActionId, payload: &Value) -> Result<Value, LongActionError> {
let malformed = || LongActionError::Malformed {
id: id.clone(),
payload: payload.to_string(),
};
match payload.get("error") {
Some(Value::String(error)) => Err(LongActionError::Failed {
id: id.clone(),
error: error.clone(),
}),
Some(_) => Err(malformed()),
None => payload.get("result").cloned().ok_or_else(malformed),
}
}
fn refused(error: RequestError, grant: String) -> LongActionError {
match error {
RequestError::Rpc(rpc) if rpc.code == RpcErrorCode::Forbidden => {
LongActionError::NotGranted {
grant,
message: rpc.message,
}
}
other => LongActionError::Request(other),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_accepted_action_gets_its_own_id_and_the_body_carries_it() {
let (first, body) = ActionId::accept();
let (second, _) = ActionId::accept();
assert_ne!(first, second);
assert_eq!(ActionId::from_reply(&body), Some(first));
}
#[test]
fn a_reply_that_is_not_an_id_is_not_taken_for_one() {
for body in ["swept", "{}", r#"{"id":7}"#, r#"{"id":""}"#, ""] {
assert_eq!(ActionId::from_reply(body), None, "{body:?}");
}
}
#[test]
fn from_reply_refuses_an_empty_id_a_non_object_and_a_body_with_no_id() {
let (id, body) = ActionId::accept();
assert_eq!(ActionId::from_reply(&body), Some(id));
for body in [r#"{"id":""}"#, "[]", r#""abc""#, r#"{"name":"abc"}"#] {
assert_eq!(ActionId::from_reply(body), None, "{body:?}");
}
}
#[test]
fn done_read_reads_both_payload_shapes_done_payload_writes() {
let id = ActionId("abc".to_owned());
for outcome in [
Ok(json!({ "built": 3 })),
Ok(Value::Null),
Err("disk full".to_owned()),
] {
let payload = done_payload(&id, outcome.clone());
assert_eq!(ActionDone::read(&payload), Some((id.clone(), outcome)));
}
}
#[test]
fn done_read_refuses_a_payload_with_neither_result_nor_error() {
for payload in [
json!({ "id": "abc" }),
json!({ "id": "abc", "error": 7 }),
json!({ "result": 1 }),
json!({ "id": "", "result": 1 }),
json!("abc"),
] {
assert_eq!(ActionDone::read(&payload), None, "{payload}");
}
}
#[test]
fn the_done_payload_carries_the_id_and_either_a_result_or_an_error() {
let id = ActionId("abc".to_owned());
assert_eq!(
done_payload(&id, Ok(json!({ "built": 3 }))),
json!({ "id": "abc", "result": { "built": 3 } })
);
assert_eq!(
done_payload(&id, Err("disk full".to_owned())),
json!({ "id": "abc", "error": "disk full" })
);
}
#[test]
fn an_event_that_is_neither_a_result_nor_an_error_is_not_a_success() {
let id = ActionId("abc".to_owned());
assert_eq!(
outcome_of(&id, &json!({ "id": "abc", "result": null })).unwrap(),
Value::Null
);
for payload in [
json!({ "id": "abc" }),
json!({ "id": "abc", "error": 7 }),
json!({ "id": "abc", "error": null, "result": 1 }),
] {
let error = outcome_of(&id, &payload).unwrap_err();
assert!(
matches!(error, LongActionError::Malformed { .. }),
"{payload}"
);
}
let error = outcome_of(&id, &json!({ "id": "abc", "error": "disk full" })).unwrap_err();
assert!(matches!(error, LongActionError::Failed { error, .. } if error == "disk full"));
}
#[test]
fn waits_on_two_topics_listen_to_both_until_each_ends() {
let waits = Waits::default();
let first = waits.claim("dog.a.action.done".to_owned());
let second = waits.claim("dog.b.action.done".to_owned());
let again = waits.claim("dog.a.action.done".to_owned());
assert_eq!(waits.topics(), ["dog.a.action.done", "dog.b.action.done"]);
drop(first);
assert_eq!(waits.topics(), ["dog.a.action.done", "dog.b.action.done"]);
drop(again);
drop(second);
assert!(waits.topics().is_empty());
}
}