use shep_core::protocol::{BusEvent, Response, RpcError};
use super::context::RpcContext;
use super::error::forbidden;
use super::gate::Link;
pub(super) fn publish_dog_event(
link: Option<Link<'_>>,
kind: &str,
payload: serde_json::Value,
ctx: &RpcContext,
) -> Result<Response, RpcError> {
let Some(Link::Dog(dog)) = link else {
return Err(forbidden(
"only a dog's own connection publishes events: this connection is not one",
));
};
if dog.contains('.') {
return Err(forbidden(format!(
"dog `{dog}` has a dot in its name, so it may not publish events: its topics \
would read as another dog's"
)));
}
if !ctx.known_dogs.declares(dog, kind) {
return Err(forbidden(format!(
"dog `{dog}` did not declare the event kind `{kind}` in its manifest, so it may not publish it"
)));
}
let _ = ctx.events.send(
BusEvent::Dog {
dog: dog.to_owned(),
kind: kind.to_owned(),
payload,
}
.into(),
);
Ok(Response::EventPublished)
}