use async_trait::async_trait;
use std::sync::{Arc, Mutex};
mod callback;
#[cfg(feature = "mqtt")]
mod mqtt;
#[cfg(feature = "webhook")]
mod webhook;
pub use callback::{CallbackPolicy, CallbackRejected, is_private};
#[cfg(feature = "mqtt")]
#[cfg_attr(docsrs, doc(cfg(feature = "mqtt")))]
pub use mqtt::{MqttConfig, MqttError, MqttNotifier};
#[cfg(feature = "webhook")]
#[cfg_attr(docsrs, doc(cfg(feature = "webhook")))]
pub use webhook::{WebhookConfig, WebhookError, WebhookNotifier};
use crate::core::{Access, Role};
use crate::model::{
ClientId, ObjectId, ObjectType, Operation, Subscription, Target,
notification::{AnyObject, Notification},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Channel {
Webhook,
Mqtt,
}
impl core::fmt::Display for Channel {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(match self {
Channel::Webhook => "webhook",
Channel::Mqtt => "mqtt",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Route {
Webhook {
callback_url: String,
bearer_token: Option<String>,
},
Topic {
topic: String,
},
}
impl Route {
pub fn channel(&self) -> Channel {
match self {
Route::Webhook { .. } => Channel::Webhook,
Route::Topic { .. } => Channel::Mqtt,
}
}
pub fn callback_url(&self) -> Option<&str> {
match self {
Route::Webhook { callback_url, .. } => Some(callback_url),
Route::Topic { .. } => None,
}
}
pub fn bearer_token(&self) -> Option<&str> {
match self {
Route::Webhook { bearer_token, .. } => bearer_token.as_deref(),
Route::Topic { .. } => None,
}
}
pub fn topic(&self) -> Option<&str> {
match self {
Route::Topic { topic } => Some(topic),
Route::Webhook { .. } => None,
}
}
}
#[derive(Debug, Clone, PartialEq)]
pub struct Delivery {
pub subscription_id: Option<ObjectId>,
pub route: Route,
pub notification: Notification,
}
impl Delivery {
pub fn channel(&self) -> Channel {
self.route.channel()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DeliveryFailure {
pub message: String,
pub retriable: bool,
}
impl DeliveryFailure {
pub fn retriable(message: impl Into<String>) -> Self {
Self {
message: message.into(),
retriable: true,
}
}
pub fn permanent(message: impl Into<String>) -> Self {
Self {
message: message.into(),
retriable: false,
}
}
}
impl core::fmt::Display for DeliveryFailure {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for DeliveryFailure {}
#[async_trait]
pub trait Notifier: Send + Sync + 'static {
fn handles(&self, channel: Channel) -> bool;
async fn deliver(&self, delivery: &Delivery, attempt: u32) -> Result<(), DeliveryFailure>;
async fn verify_callback(&self, _callback_url: &str) -> Result<(), DeliveryFailure> {
Ok(())
}
fn name(&self) -> &'static str;
}
#[derive(Debug, Clone, Copy, Default)]
pub struct NullNotifier;
#[async_trait]
impl Notifier for NullNotifier {
fn handles(&self, _channel: Channel) -> bool {
true
}
async fn deliver(&self, _delivery: &Delivery, _attempt: u32) -> Result<(), DeliveryFailure> {
Ok(())
}
fn name(&self) -> &'static str {
"null"
}
}
#[derive(Debug, Default)]
pub struct RecordingNotifier {
delivered: Mutex<Vec<Delivery>>,
}
impl RecordingNotifier {
pub fn new() -> Self {
Self::default()
}
pub fn shared() -> Arc<Self> {
Arc::new(Self::new())
}
pub fn delivered(&self) -> Vec<Delivery> {
self.delivered
.lock()
.unwrap_or_else(|e| e.into_inner())
.clone()
}
pub fn clear(&self) {
self.delivered
.lock()
.unwrap_or_else(|e| e.into_inner())
.clear();
}
}
#[async_trait]
impl Notifier for RecordingNotifier {
fn handles(&self, _channel: Channel) -> bool {
true
}
async fn deliver(&self, delivery: &Delivery, _attempt: u32) -> Result<(), DeliveryFailure> {
tracing::debug!(
object = %delivery.notification.object.object_type(),
operation = %delivery.notification.operation,
"notification recorded"
);
self.delivered
.lock()
.unwrap_or_else(|e| e.into_inner())
.push(delivery.clone());
Ok(())
}
fn name(&self) -> &'static str {
"recording"
}
}
#[derive(Default)]
pub struct Notifiers {
transports: Vec<Arc<dyn Notifier>>,
}
impl std::fmt::Debug for Notifiers {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Notifiers")
.field(
"transports",
&self.transports.iter().map(|t| t.name()).collect::<Vec<_>>(),
)
.finish()
}
}
impl Notifiers {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, notifier: Arc<dyn Notifier>) -> Self {
self.transports.push(notifier);
self
}
pub fn shared(self) -> Arc<Self> {
Arc::new(self)
}
pub fn is_empty(&self) -> bool {
self.transports.is_empty()
}
fn transport_for(&self, channel: Channel) -> Option<&Arc<dyn Notifier>> {
self.transports.iter().find(|t| t.handles(channel))
}
}
#[async_trait]
impl Notifier for Notifiers {
fn handles(&self, channel: Channel) -> bool {
self.transport_for(channel).is_some()
}
async fn deliver(&self, delivery: &Delivery, attempt: u32) -> Result<(), DeliveryFailure> {
let channel = delivery.channel();
match self.transport_for(channel) {
Some(transport) => transport.deliver(delivery, attempt).await,
None => Err(DeliveryFailure::permanent(format!(
"no transport is configured for {channel} notifications"
))),
}
}
async fn verify_callback(&self, callback_url: &str) -> Result<(), DeliveryFailure> {
match self.transport_for(Channel::Webhook) {
Some(transport) => transport.verify_callback(callback_url).await,
None => Ok(()),
}
}
fn name(&self) -> &'static str {
"notifiers"
}
}
#[derive(Debug, Clone)]
pub struct Fanout {
subscribers: Vec<(Subscription, Role)>,
grants: Vec<(ObjectId, ClientId, crate::core::Grant)>,
topics: Option<Topics>,
now: crate::model::Timestamp,
}
impl Fanout {
pub fn new(
subscribers: Vec<(Subscription, Role)>,
grants: Vec<(ObjectId, ClientId, crate::core::Grant)>,
topics: Option<Topics>,
now: crate::model::Timestamp,
) -> Self {
Self {
subscribers,
grants,
topics,
now,
}
}
pub fn none() -> Self {
Self {
subscribers: Vec::new(),
grants: Vec::new(),
topics: None,
now: crate::model::Timestamp::UNIX_EPOCH,
}
}
pub fn now(&self) -> crate::model::Timestamp {
self.now
}
pub fn is_empty(&self) -> bool {
self.subscribers.is_empty() && self.topics.is_none()
}
pub fn deliveries(&self, object: &AnyObject, operation: Operation) -> Vec<Delivery> {
if self.is_empty() {
return Vec::new();
}
let owner = self.owner_of(object);
let mut out = deliveries_for(object, operation, owner, &self.subscribers);
if let Some(topics) = &self.topics {
out.extend(mqtt_deliveries(
object,
operation,
owner,
topics,
&self.grants,
));
}
out
}
fn owner_of<'a>(&'a self, object: &'a AnyObject) -> Option<&'a ClientId> {
match object {
AnyObject::Ven(v) => Some(&v.client_id),
AnyObject::Report(r) => r.client_id.as_ref(),
AnyObject::Subscription(s) => Some(&s.client_id),
AnyObject::Resource(r) => self
.grants
.iter()
.find(|(ven_id, _, _)| *ven_id == r.ven_id)
.map(|(_, client_id, _)| client_id),
_ => None,
}
}
}
pub fn deliveries_for(
object: &AnyObject,
operation: Operation,
owner: Option<&ClientId>,
subscriptions: &[(Subscription, Role)],
) -> Vec<Delivery> {
let object_type = object.object_type();
let mut out = Vec::new();
for (subscription, role) in subscriptions {
if let Some(wanted) = &subscription.content.program_id
&& object.program_id() != Some(wanted)
{
continue;
}
let access = Access::push(role.clone(), subscription.content.targets.clone());
let visible = if is_owned_type(object_type) {
if !access.owns(owner) {
continue;
}
object.targets().to_vec()
} else {
match access.visible_targets(object.targets()) {
Some(visible) => visible,
None => continue,
}
};
for op in &subscription.content.object_operations {
if !op.matches(object_type, operation) {
continue;
}
out.push(Delivery {
subscription_id: Some(subscription.id.clone()),
route: Route::Webhook {
callback_url: op.callback_url.clone(),
bearer_token: op.bearer_token.clone(),
},
notification: Notification::new(operation, object.clone())
.with_targets(visible.clone()),
});
}
}
out
}
fn is_owned_type(object_type: ObjectType) -> bool {
matches!(
object_type,
ObjectType::Ven | ObjectType::Resource | ObjectType::Report | ObjectType::Subscription
)
}
#[derive(Debug, Clone)]
pub struct Topics {
prefix: String,
}
impl Topics {
pub fn new(prefix: impl Into<String>) -> Self {
let mut prefix = prefix.into();
if !prefix.is_empty() && !prefix.ends_with('/') {
prefix.push('/');
}
Self { prefix }
}
fn join(&self, rest: &str) -> String {
format!("{}{rest}", self.prefix)
}
pub fn collection(&self, object_type: ObjectType) -> String {
self.join(object_type.collection())
}
pub fn object(&self, object_type: ObjectType, id: &ObjectId) -> String {
self.join(&format!("{}/{id}", object_type.collection()))
}
pub fn program_events(&self, program_id: &ObjectId) -> String {
self.join(&format!("events/programs/{program_id}"))
}
pub fn ven_scoped(&self, object_type: ObjectType, ven_id: &ObjectId) -> String {
if object_type == ObjectType::Ven {
return self.object(ObjectType::Ven, ven_id);
}
self.join(&format!("{}/vens/{ven_id}", object_type.collection()))
}
pub fn operation(&self, root: &str, operation: Operation) -> String {
format!("{root}/{}", operation.topic_segment())
}
}
pub fn mqtt_deliveries(
object: &AnyObject,
operation: Operation,
owner: Option<&ClientId>,
topics: &Topics,
grants: &[(ObjectId, ClientId, crate::core::Grant)],
) -> Vec<Delivery> {
let object_type = object.object_type();
let object_targets: Vec<Target> = object.targets().to_vec();
let publish = |topic: String, targets: Vec<Target>| Delivery {
subscription_id: None,
route: Route::Topic { topic },
notification: Notification::new(operation, object.clone()).with_targets(targets),
};
let mut out = vec![publish(
topics.operation(&topics.collection(object_type), operation),
object_targets.clone(),
)];
if object_type == ObjectType::Event
&& let Some(program_id) = object.program_id()
{
out.push(publish(
topics.operation(&topics.program_events(program_id), operation),
object_targets.clone(),
));
}
for (ven_id, client_id, grant) in grants {
let topic = topics.operation(&topics.ven_scoped(object_type, ven_id), operation);
if is_owned_type(object_type) {
if owner.is_some() && owner == Some(client_id) {
out.push(publish(topic, object_targets.clone()));
}
continue;
}
let access = Access::push(
Role::Ven {
client_id: client_id.clone(),
grant: grant.clone(),
},
Vec::new(),
);
if let Some(visible) = access.visible_targets(&object_targets) {
out.push(publish(topic, visible));
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Grant;
use crate::model::{
ClientName, Event, EventRequest, ObjectOperation, Program, ProgramName, ProgramRequest,
SubscriptionRequest, Timestamp,
};
use crate::std_shim::Vec;
fn now() -> Timestamp {
"2026-01-01T00:00:00Z".parse().unwrap()
}
fn event(targets: &[&str]) -> AnyObject {
let mut content = EventRequest::new("prg-1".parse().unwrap());
content.targets = targets.iter().map(|t| Target::new(*t).unwrap()).collect();
AnyObject::Event(Event {
id: "evt-1".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Event,
content,
})
}
fn subscription(client: &str, targets: &[&str], objects: &[ObjectType]) -> Subscription {
Subscription {
id: format!("sub-{client}").parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Subscription,
client_id: ClientId::new(client).unwrap(),
content: SubscriptionRequest {
client_name: ClientName::new(client).unwrap(),
program_id: None,
object_operations: vec![ObjectOperation {
objects: objects.to_vec(),
operations: vec![Operation::Create, Operation::Update],
callback_url: format!("https://{client}.example.com/hook"),
bearer_token: Some("tok".into()),
}],
targets: targets.iter().map(|t| Target::new(*t).unwrap()).collect(),
},
}
}
fn ven_role(client: &str, grants: &[&str]) -> Role {
Role::Ven {
client_id: ClientId::new(client).unwrap(),
grant: Grant::from_targets(grants.iter().map(|t| Target::new(*t).unwrap())),
}
}
#[derive(Debug)]
struct Claiming {
channel: Channel,
seen: Mutex<Vec<String>>,
}
impl Claiming {
fn new(channel: Channel) -> Arc<Self> {
Arc::new(Self {
channel,
seen: Mutex::new(Vec::new()),
})
}
fn seen(&self) -> Vec<String> {
self.seen.lock().unwrap().clone()
}
}
#[async_trait]
impl Notifier for Claiming {
fn handles(&self, channel: Channel) -> bool {
channel == self.channel
}
async fn deliver(&self, delivery: &Delivery, _attempt: u32) -> Result<(), DeliveryFailure> {
self.seen
.lock()
.unwrap()
.push(format!("{:?}", delivery.route));
Ok(())
}
fn name(&self) -> &'static str {
"claiming"
}
}
fn program_object() -> AnyObject {
AnyObject::Program(Program {
id: "prg-1".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Program,
content: ProgramRequest::new(ProgramName::new("tou").unwrap()),
})
}
fn webhook_delivery() -> Delivery {
Delivery {
subscription_id: None,
route: Route::Webhook {
callback_url: "https://ven.example.com/hook".into(),
bearer_token: None,
},
notification: Notification::new(Operation::Create, program_object()),
}
}
fn topic_delivery() -> Delivery {
Delivery {
subscription_id: None,
route: Route::Topic {
topic: "programs/create".into(),
},
notification: Notification::new(Operation::Create, program_object()),
}
}
#[tokio::test]
async fn each_transport_gets_only_the_channel_it_claims() {
let webhook = Claiming::new(Channel::Webhook);
let broker = Claiming::new(Channel::Mqtt);
let notifiers = Notifiers::new().with(webhook.clone()).with(broker.clone());
notifiers.deliver(&webhook_delivery(), 1).await.unwrap();
notifiers.deliver(&topic_delivery(), 1).await.unwrap();
assert_eq!(webhook.seen().len(), 1);
assert_eq!(broker.seen().len(), 1);
assert!(webhook.seen()[0].contains("Webhook"));
assert!(broker.seen()[0].contains("Topic"));
}
#[tokio::test]
async fn a_delivery_no_transport_claims_is_refused_rather_than_completed() {
let notifiers = Notifiers::new().with(Claiming::new(Channel::Webhook));
assert!(!notifiers.handles(Channel::Mqtt));
let failure = notifiers
.deliver(&topic_delivery(), 1)
.await
.expect_err("an unroutable delivery must not be reported as delivered");
assert!(
!failure.retriable,
"no number of attempts configures a transport"
);
assert!(failure.message.contains("mqtt"), "{failure}");
}
#[test]
fn a_targeted_event_reaches_only_entitled_subscribers() {
let subs = vec![
(
subscription("ven-a", &[], &[ObjectType::Event]),
ven_role("ven-a", &["group1"]),
),
(
subscription("ven-b", &[], &[ObjectType::Event]),
ven_role("ven-b", &["group2"]),
),
];
let out = deliveries_for(&event(&["group1"]), Operation::Create, None, &subs);
assert_eq!(out.len(), 1);
assert!(out[0].route.callback_url().unwrap().contains("ven-a"));
}
#[test]
fn notifications_carry_only_the_subscribers_own_targets() {
let subs = vec![(
subscription("ven-a", &[], &[ObjectType::Event]),
ven_role("ven-a", &["group1"]),
)];
let out = deliveries_for(
&event(&["group1", "group2"]),
Operation::Update,
None,
&subs,
);
assert_eq!(
out[0].notification.targets,
vec![Target::new("group1").unwrap()],
"group2 must not be revealed"
);
}
#[test]
fn a_subscription_for_another_object_type_is_not_woken() {
let subs = vec![(
subscription("ven-a", &[], &[ObjectType::Report]),
ven_role("ven-a", &["group1"]),
)];
assert!(deliveries_for(&event(&["group1"]), Operation::Create, None, &subs).is_empty());
}
#[test]
fn an_operation_the_subscription_did_not_ask_for_is_not_delivered() {
let subs = vec![(
subscription("ven-a", &[], &[ObjectType::Event]),
ven_role("ven-a", &["group1"]),
)];
assert!(deliveries_for(&event(&["group1"]), Operation::Delete, None, &subs).is_empty());
}
#[test]
fn programme_scoping_is_honoured() {
let mut sub = subscription("ven-a", &[], &[ObjectType::Event]);
sub.content.program_id = Some("other-program".parse().unwrap());
let subs = vec![(sub, ven_role("ven-a", &["group1"]))];
assert!(deliveries_for(&event(&["group1"]), Operation::Create, None, &subs).is_empty());
}
#[test]
fn business_logic_receives_everything() {
let subs = vec![(
subscription("bl", &[], &[ObjectType::Event]),
Role::BusinessLogic,
)];
assert_eq!(
deliveries_for(&event(&["group1"]), Operation::Create, None, &subs).len(),
1
);
}
#[test]
fn untargeted_objects_reach_every_subscriber() {
let program = AnyObject::Program(Program {
id: "prg-1".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Program,
content: ProgramRequest::new(ProgramName::new("public-tariff").unwrap()),
});
let subs = vec![
(
subscription("ven-a", &[], &[ObjectType::Program]),
ven_role("ven-a", &[]),
),
(
subscription("ven-b", &[], &[ObjectType::Program]),
ven_role("ven-b", &["group2"]),
),
];
assert_eq!(
deliveries_for(&program, Operation::Update, None, &subs).len(),
2
);
}
fn report(client: &str) -> AnyObject {
use crate::model::{Report, ReportRequest};
AnyObject::Report(Report {
id: "rpt-1".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Report,
client_id: Some(ClientId::new(client).unwrap()),
content: ReportRequest::new(
"evt-1".parse().unwrap(),
ClientName::new(client).unwrap(),
Vec::new(),
),
})
}
fn resource(ven_id: &str) -> AnyObject {
AnyObject::Resource(crate::model::Resource {
id: "res-1".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Resource,
resource_name: "meter".parse().unwrap(),
ven_id: ven_id.parse().unwrap(),
targets: Vec::new(),
attributes: None,
})
}
fn two_vens() -> Vec<(ObjectId, ClientId, Grant)> {
vec![
(
ObjectId::new("ven-a").unwrap(),
ClientId::new("client-a").unwrap(),
Grant::from_targets([Target::new("group1").unwrap()]),
),
(
ObjectId::new("ven-b").unwrap(),
ClientId::new("client-b").unwrap(),
Grant::from_targets([Target::new("group2").unwrap()]),
),
]
}
#[test]
fn an_owned_object_reaches_only_its_owners_private_topic() {
let fanout = Fanout::new(Vec::new(), two_vens(), Some(Topics::new("openadr3")), now());
let published: Vec<String> = fanout
.deliveries(&report("client-a"), Operation::Create)
.into_iter()
.filter_map(|d| d.route.topic().map(str::to_string))
.collect();
assert!(published.contains(&"openadr3/reports/vens/ven-a/create".to_string()));
assert!(
!published.contains(&"openadr3/reports/vens/ven-b/create".to_string()),
"client-b must not receive client-a's report: {published:?}"
);
}
#[test]
fn an_owned_object_with_no_resolvable_owner_reaches_no_private_topic() {
use crate::model::{Report, ReportRequest};
let orphan = AnyObject::Report(Report {
id: "rpt-2".parse().unwrap(),
created_date_time: now(),
modification_date_time: now(),
object_type: ObjectType::Report,
client_id: None,
content: ReportRequest::new(
"evt-1".parse().unwrap(),
ClientName::new("who").unwrap(),
Vec::new(),
),
});
let fanout = Fanout::new(Vec::new(), two_vens(), Some(Topics::new("openadr3")), now());
let published: Vec<String> = fanout
.deliveries(&orphan, Operation::Create)
.into_iter()
.filter_map(|d| d.route.topic().map(str::to_string))
.collect();
assert_eq!(published, vec!["openadr3/reports/create".to_string()]);
}
#[test]
fn a_ven_is_told_about_its_own_resource() {
let subs = vec![
(
subscription("client-a", &[], &[ObjectType::Resource]),
ven_role("client-a", &[]),
),
(
subscription("client-b", &[], &[ObjectType::Resource]),
ven_role("client-b", &[]),
),
];
let fanout = Fanout::new(subs, two_vens(), None, now());
let out = fanout.deliveries(&resource("ven-a"), Operation::Update);
assert_eq!(out.len(), 1);
assert!(out[0].route.callback_url().unwrap().contains("client-a"));
}
#[test]
fn mqtt_fan_out_gives_each_ven_a_private_topic() {
let topics = Topics::new("openadr3/3.1.0");
let grants = vec![
(
ObjectId::new("ven-a").unwrap(),
ClientId::new("client-a").unwrap(),
Grant::from_targets([Target::new("group1").unwrap()]),
),
(
ObjectId::new("ven-b").unwrap(),
ClientId::new("client-b").unwrap(),
Grant::from_targets([Target::new("group2").unwrap()]),
),
];
let out = mqtt_deliveries(
&event(&["group1"]),
Operation::Create,
None,
&topics,
&grants,
);
let published: Vec<&str> = out.iter().filter_map(|d| d.route.topic()).collect();
assert!(published.contains(&"openadr3/3.1.0/events/create"));
assert!(published.contains(&"openadr3/3.1.0/events/programs/prg-1/create"));
assert!(published.contains(&"openadr3/3.1.0/events/vens/ven-a/create"));
assert!(
!published.contains(&"openadr3/3.1.0/events/vens/ven-b/create"),
"ven-b is not in group1 and must not receive a copy"
);
}
}