use crate::std_shim::{String, Vec};
use core::{cmp::Ordering, fmt, str::FromStr};
use serde::{Deserialize, Serialize};
use super::{
ids::{ClientId, ClientName, ObjectId, ProgramName, ResourceName, Target, VenName},
time::{Duration, StartTime, Timestamp},
values::{PayloadType, ReadingType, Unit, ValuesMap},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ObjectType {
Program,
Event,
Report,
Subscription,
Ven,
Resource,
}
impl ObjectType {
pub const fn as_str(self) -> &'static str {
match self {
ObjectType::Program => "PROGRAM",
ObjectType::Event => "EVENT",
ObjectType::Report => "REPORT",
ObjectType::Subscription => "SUBSCRIPTION",
ObjectType::Ven => "VEN",
ObjectType::Resource => "RESOURCE",
}
}
pub const fn collection(self) -> &'static str {
match self {
ObjectType::Program => "programs",
ObjectType::Event => "events",
ObjectType::Report => "reports",
ObjectType::Subscription => "subscriptions",
ObjectType::Ven => "vens",
ObjectType::Resource => "resources",
}
}
pub const ALL: [ObjectType; 6] = [
ObjectType::Program,
ObjectType::Event,
ObjectType::Report,
ObjectType::Subscription,
ObjectType::Ven,
ObjectType::Resource,
];
pub const fn announces(self) -> &'static [ObjectType] {
match self {
ObjectType::Program => &[
ObjectType::Program,
ObjectType::Event,
ObjectType::Report,
ObjectType::Subscription,
],
ObjectType::Event => &[ObjectType::Event, ObjectType::Report],
ObjectType::Ven => &[ObjectType::Ven, ObjectType::Resource],
ObjectType::Report => &[ObjectType::Report],
ObjectType::Subscription => &[ObjectType::Subscription],
ObjectType::Resource => &[ObjectType::Resource],
}
}
}
impl fmt::Display for ObjectType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for ObjectType {
type Err = UnknownObjectType;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s {
"PROGRAM" => Ok(ObjectType::Program),
"EVENT" => Ok(ObjectType::Event),
"REPORT" => Ok(ObjectType::Report),
"SUBSCRIPTION" => Ok(ObjectType::Subscription),
"VEN" => Ok(ObjectType::Ven),
"RESOURCE" => Ok(ObjectType::Resource),
_ => Err(UnknownObjectType),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("unknown object type")]
pub struct UnknownObjectType;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectMetadata {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
pub object_type: ObjectType,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct IntervalPeriod {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub start: Option<StartTime>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration: Option<Duration>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub randomize_start: Option<Duration>,
}
impl IntervalPeriod {
pub fn new(start: StartTime, duration: Duration) -> Self {
Self {
start: Some(start),
duration: Some(duration),
randomize_start: None,
}
}
pub fn with_randomize_start(mut self, d: Duration) -> Self {
self.randomize_start = Some(d);
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Interval {
pub id: i32,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_period: Option<IntervalPeriod>,
pub payloads: Vec<ValuesMap>,
}
impl Interval {
pub fn new(id: i32, payloads: Vec<ValuesMap>) -> Self {
Self {
id,
interval_period: None,
payloads,
}
}
pub fn with_period(mut self, period: IntervalPeriod) -> Self {
self.interval_period = Some(period);
self
}
pub fn payload(&self, payload_type: impl AsRef<str>) -> Option<&ValuesMap> {
find_payload(&self.payloads, payload_type.as_ref())
}
}
pub(crate) fn find_payload<'a>(payloads: &'a [ValuesMap], wanted: &str) -> Option<&'a ValuesMap> {
payloads.iter().find(|p| p.value_type.as_str() == wanted)
}
fn find_descriptor<'a, T: 'a>(
descriptors: impl IntoIterator<Item = &'a T>,
wanted: &str,
payload_type: impl Fn(&T) -> &PayloadType,
) -> Option<&'a T> {
descriptors
.into_iter()
.find(|d| payload_type(d).as_str() == wanted)
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventPayloadDescriptor {
#[serde(default = "event_payload_descriptor_tag")]
pub object_type: String,
pub payload_type: PayloadType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub units: Option<Unit>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub currency: Option<String>,
}
fn event_payload_descriptor_tag() -> String {
"EVENT_PAYLOAD_DESCRIPTOR".into()
}
impl EventPayloadDescriptor {
pub fn new(payload_type: PayloadType) -> Self {
Self {
object_type: event_payload_descriptor_tag(),
payload_type,
units: None,
currency: None,
}
}
pub fn with_units(mut self, units: Unit) -> Self {
self.units = Some(units);
self
}
pub fn with_currency(mut self, currency: impl Into<String>) -> Self {
self.currency = Some(currency.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportPayloadDescriptor {
#[serde(default = "report_payload_descriptor_tag")]
pub object_type: String,
pub payload_type: PayloadType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reading_type: Option<ReadingType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub units: Option<Unit>,
#[serde(
default,
with = "super::values::decimal_as_number::option",
skip_serializing_if = "Option::is_none"
)]
pub accuracy: Option<rust_decimal::Decimal>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub confidence: Option<u8>,
}
fn report_payload_descriptor_tag() -> String {
"REPORT_PAYLOAD_DESCRIPTOR".into()
}
impl ReportPayloadDescriptor {
pub fn new(payload_type: PayloadType) -> Self {
Self {
object_type: report_payload_descriptor_tag(),
payload_type,
reading_type: None,
units: None,
accuracy: None,
confidence: None,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum PayloadDescriptor {
#[serde(rename = "EVENT_PAYLOAD_DESCRIPTOR")]
Event(EventPayloadDescriptor),
#[serde(rename = "REPORT_PAYLOAD_DESCRIPTOR")]
Report(ReportPayloadDescriptor),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReportIntervals {
#[default]
Intervals,
SubIntervals,
OpenIntervals,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportDescriptor {
pub payload_type: PayloadType,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub reading_type: Option<ReadingType>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub units: Option<Unit>,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default)]
pub aggregate: bool,
#[serde(default = "minus_one")]
pub start_interval: i32,
#[serde(default = "minus_one")]
pub num_intervals: i32,
#[serde(default = "bool_true")]
pub historical: bool,
#[serde(default = "minus_one")]
pub frequency: i32,
#[serde(default = "one")]
pub repeat: i32,
#[serde(default)]
pub report_intervals: ReportIntervals,
}
const fn minus_one() -> i32 {
-1
}
const fn one() -> i32 {
1
}
const fn bool_true() -> bool {
true
}
impl ReportDescriptor {
pub fn new(payload_type: PayloadType) -> Self {
Self {
payload_type,
reading_type: None,
units: None,
targets: Vec::new(),
aggregate: false,
start_interval: -1,
num_intervals: -1,
historical: true,
frequency: -1,
repeat: 1,
report_intervals: ReportIntervals::default(),
}
}
pub fn is_ad_hoc(&self) -> bool {
self.frequency == 0
}
pub fn repeats_forever(&self) -> bool {
self.repeat < 0
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ProgramDescription {
#[serde(rename = "URL")]
pub url: String,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProgramRequest {
pub program_name: ProgramName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_period: Option<IntervalPeriod>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub program_descriptions: Option<Vec<ProgramDescription>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload_descriptors: Option<Vec<PayloadDescriptor>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
}
impl ProgramRequest {
pub fn new(program_name: ProgramName) -> Self {
Self {
program_name,
interval_period: None,
program_descriptions: None,
payload_descriptors: None,
attributes: None,
targets: Vec::new(),
}
}
pub fn event_payload_descriptor(
&self,
payload_type: impl AsRef<str>,
) -> Option<&EventPayloadDescriptor> {
let events = self.descriptors().filter_map(|d| match d {
PayloadDescriptor::Event(d) => Some(d),
PayloadDescriptor::Report(_) => None,
});
find_descriptor(events, payload_type.as_ref(), |d| &d.payload_type)
}
pub fn report_payload_descriptor(
&self,
payload_type: impl AsRef<str>,
) -> Option<&ReportPayloadDescriptor> {
let reports = self.descriptors().filter_map(|d| match d {
PayloadDescriptor::Report(d) => Some(d),
PayloadDescriptor::Event(_) => None,
});
find_descriptor(reports, payload_type.as_ref(), |d| &d.payload_type)
}
fn descriptors(&self) -> impl Iterator<Item = &PayloadDescriptor> {
self.payload_descriptors.iter().flatten()
}
pub fn with_targets(mut self, targets: Vec<Target>) -> Self {
self.targets = targets;
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Program {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "program_type")]
pub object_type: ObjectType,
#[serde(flatten)]
pub content: ProgramRequest,
}
fn program_type() -> ObjectType {
ObjectType::Program
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Priority(pub Option<u32>);
impl Priority {
pub const MAX: Priority = Priority(Some(0));
pub const UNSPECIFIED: Priority = Priority(None);
pub const fn new(value: u32) -> Self {
Priority(Some(value))
}
pub const fn value(self) -> Option<u32> {
self.0
}
}
impl Ord for Priority {
fn cmp(&self, other: &Self) -> Ordering {
match (self.0, other.0) {
(Some(a), Some(b)) => a.cmp(&b),
(Some(_), None) => Ordering::Less,
(None, Some(_)) => Ordering::Greater,
(None, None) => Ordering::Equal,
}
}
}
impl PartialOrd for Priority {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct EventRequest {
#[serde(rename = "programID")]
pub program_id: ObjectId,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub event_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub duration: Option<Duration>,
#[serde(default, skip_serializing_if = "Priority::is_unspecified")]
pub priority: Priority,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub report_descriptors: Option<Vec<ReportDescriptor>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload_descriptors: Option<Vec<EventPayloadDescriptor>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_period: Option<IntervalPeriod>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub intervals: Option<Vec<Interval>>,
}
impl Priority {
fn is_unspecified(&self) -> bool {
self.0.is_none()
}
}
impl EventRequest {
pub fn new(program_id: ObjectId) -> Self {
Self {
program_id,
event_name: None,
duration: None,
priority: Priority::UNSPECIFIED,
targets: Vec::new(),
report_descriptors: None,
payload_descriptors: None,
interval_period: None,
intervals: None,
}
}
pub fn with_intervals(mut self, intervals: Vec<Interval>) -> Self {
self.intervals = Some(intervals);
self
}
pub fn with_interval_period(mut self, period: IntervalPeriod) -> Self {
self.interval_period = Some(period);
self
}
pub fn with_targets(mut self, targets: Vec<Target>) -> Self {
self.targets = targets;
self
}
pub fn with_priority(mut self, priority: Priority) -> Self {
self.priority = priority;
self
}
pub fn payload_descriptor(
&self,
payload_type: impl AsRef<str>,
) -> Option<&EventPayloadDescriptor> {
find_descriptor(
self.payload_descriptors.iter().flatten(),
payload_type.as_ref(),
|d| &d.payload_type,
)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Event {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "event_type")]
pub object_type: ObjectType,
#[serde(flatten)]
pub content: EventRequest,
}
fn event_type() -> ObjectType {
ObjectType::Event
}
impl Event {
pub fn payload_descriptor_in<'a>(
&'a self,
program: &'a Program,
payload_type: impl AsRef<str>,
) -> Option<&'a EventPayloadDescriptor> {
let wanted = payload_type.as_ref();
self.content.payload_descriptor(wanted).or_else(|| {
(program.id == self.content.program_id)
.then(|| program.content.event_payload_descriptor(wanted))
.flatten()
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportResource {
pub resource_name: ResourceName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub interval_period: Option<IntervalPeriod>,
pub intervals: Vec<Interval>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ReportRequest {
#[serde(rename = "eventID")]
pub event_id: ObjectId,
pub client_name: ClientName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub report_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payload_descriptors: Option<Vec<ReportPayloadDescriptor>>,
pub resources: Vec<ReportResource>,
}
impl ReportRequest {
pub fn new(
event_id: ObjectId,
client_name: ClientName,
resources: Vec<ReportResource>,
) -> Self {
Self {
event_id,
client_name,
report_name: None,
payload_descriptors: None,
resources,
}
}
pub fn payload_descriptor(
&self,
payload_type: impl AsRef<str>,
) -> Option<&ReportPayloadDescriptor> {
find_descriptor(
self.payload_descriptors.iter().flatten(),
payload_type.as_ref(),
|d| &d.payload_type,
)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Report {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "report_type")]
pub object_type: ObjectType,
#[serde(rename = "clientID", default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<ClientId>,
#[serde(flatten)]
pub content: ReportRequest,
}
fn report_type() -> ObjectType {
ObjectType::Report
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Operation {
Read,
Create,
Update,
Delete,
}
impl Operation {
pub const fn topic_segment(self) -> &'static str {
match self {
Operation::Read => "read",
Operation::Create => "create",
Operation::Update => "update",
Operation::Delete => "delete",
}
}
}
impl fmt::Display for Operation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match self {
Operation::Read => "READ",
Operation::Create => "CREATE",
Operation::Update => "UPDATE",
Operation::Delete => "DELETE",
})
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ObjectOperation {
pub objects: Vec<ObjectType>,
pub operations: Vec<Operation>,
pub callback_url: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bearer_token: Option<String>,
}
impl ObjectOperation {
pub fn matches(&self, object: ObjectType, operation: Operation) -> bool {
self.objects.contains(&object) && self.operations.contains(&operation)
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SubscriptionRequest {
pub client_name: ClientName,
#[serde(rename = "programID", default, skip_serializing_if = "Option::is_none")]
pub program_id: Option<ObjectId>,
pub object_operations: Vec<ObjectOperation>,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Subscription {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "subscription_type")]
pub object_type: ObjectType,
#[serde(rename = "clientID")]
pub client_id: ClientId,
#[serde(flatten)]
pub content: SubscriptionRequest,
}
fn subscription_type() -> ObjectType {
ObjectType::Subscription
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlVenRequest {
#[serde(rename = "clientID")]
pub client_id: ClientId,
pub ven_name: VenName,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenVenRequest {
pub ven_name: VenName,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum VenRequest {
#[serde(rename = "BL_VEN_REQUEST")]
Bl(BlVenRequest),
#[serde(rename = "VEN_VEN_REQUEST")]
Ven(VenVenRequest),
}
impl VenRequest {
pub fn ven_name(&self) -> &VenName {
match self {
VenRequest::Bl(r) => &r.ven_name,
VenRequest::Ven(r) => &r.ven_name,
}
}
pub fn attributes(&self) -> Option<&Vec<ValuesMap>> {
match self {
VenRequest::Bl(r) => r.attributes.as_ref(),
VenRequest::Ven(r) => r.attributes.as_ref(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Ven {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "ven_type")]
pub object_type: ObjectType,
#[serde(rename = "clientID")]
pub client_id: ClientId,
pub ven_name: VenName,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
fn ven_type() -> ObjectType {
ObjectType::Ven
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BlResourceRequest {
pub resource_name: ResourceName,
#[serde(rename = "venID")]
pub ven_id: ObjectId,
#[serde(rename = "clientID", default, skip_serializing_if = "Option::is_none")]
pub client_id: Option<ClientId>,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct VenResourceRequest {
pub resource_name: ResourceName,
#[serde(rename = "venID", default, skip_serializing_if = "Option::is_none")]
pub ven_id: Option<ObjectId>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "objectType")]
pub enum ResourceRequest {
#[serde(rename = "BL_RESOURCE_REQUEST")]
Bl(BlResourceRequest),
#[serde(rename = "VEN_RESOURCE_REQUEST")]
Ven(VenResourceRequest),
}
impl ResourceRequest {
pub fn resource_name(&self) -> &ResourceName {
match self {
ResourceRequest::Bl(r) => &r.resource_name,
ResourceRequest::Ven(r) => &r.resource_name,
}
}
pub fn attributes(&self) -> Option<&Vec<ValuesMap>> {
match self {
ResourceRequest::Bl(r) => r.attributes.as_ref(),
ResourceRequest::Ven(r) => r.attributes.as_ref(),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Resource {
pub id: ObjectId,
pub created_date_time: Timestamp,
pub modification_date_time: Timestamp,
#[serde(default = "resource_type")]
pub object_type: ObjectType,
pub resource_name: ResourceName,
#[serde(rename = "venID")]
pub ven_id: ObjectId,
#[serde(
default,
skip_serializing_if = "Vec::is_empty",
deserialize_with = "super::null_as_default"
)]
pub targets: Vec<Target>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub attributes: Option<Vec<ValuesMap>>,
}
fn resource_type() -> ObjectType {
ObjectType::Resource
}
#[cfg(test)]
mod tests {
use super::*;
use crate::std_shim::vec;
#[test]
fn every_object_type_announces_itself() {
for t in ObjectType::ALL {
assert!(t.announces().contains(&t), "{t} does not announce itself");
}
}
#[test]
fn a_cascade_is_announced_by_the_type_that_causes_it() {
assert!(ObjectType::Program.announces().contains(&ObjectType::Event));
assert!(
ObjectType::Program
.announces()
.contains(&ObjectType::Report)
);
assert!(
ObjectType::Program
.announces()
.contains(&ObjectType::Subscription)
);
assert!(ObjectType::Event.announces().contains(&ObjectType::Report));
assert!(ObjectType::Ven.announces().contains(&ObjectType::Resource));
}
#[test]
fn priority_orders_most_important_first() {
let mut ps = vec![Priority::UNSPECIFIED, Priority::new(10), Priority::new(0)];
ps.sort();
assert_eq!(
ps,
vec![Priority::new(0), Priority::new(10), Priority::UNSPECIFIED]
);
}
#[test]
fn ven_request_discriminator_gates_target_assignment() {
let ven_written =
r#"{"objectType":"VEN_VEN_REQUEST","venName":"ven-1","targets":["gold"]}"#;
let parsed: VenRequest = serde_json::from_str(ven_written).unwrap();
match parsed {
VenRequest::Ven(v) => assert_eq!(v.ven_name.as_str(), "ven-1"),
VenRequest::Bl(_) => panic!("wrong variant"),
}
let bl_written = r#"{"objectType":"BL_VEN_REQUEST","clientID":"c1","venName":"ven-1","targets":["gold"]}"#;
match serde_json::from_str::<VenRequest>(bl_written).unwrap() {
VenRequest::Bl(v) => assert_eq!(v.targets.len(), 1),
VenRequest::Ven(_) => panic!("wrong variant"),
}
}
#[test]
fn missing_discriminator_is_an_error() {
assert!(serde_json::from_str::<VenRequest>(r#"{"venName":"ven-1"}"#).is_err());
}
#[test]
fn null_targets_deserialize_as_empty() {
let e: EventRequest = serde_json::from_str(r#"{"programID":"p1","targets":null}"#).unwrap();
assert!(e.targets.is_empty());
assert_eq!(serde_json::to_string(&e).unwrap(), r#"{"programID":"p1"}"#);
}
#[test]
fn report_descriptor_defaults_match_the_schema() {
let rd: ReportDescriptor = serde_json::from_str(r#"{"payloadType":"USAGE"}"#).unwrap();
assert_eq!(rd.start_interval, -1);
assert_eq!(rd.num_intervals, -1);
assert!(rd.historical);
assert_eq!(rd.frequency, -1);
assert_eq!(rd.repeat, 1);
assert!(!rd.aggregate);
assert_eq!(rd.report_intervals, ReportIntervals::Intervals);
}
#[test]
fn event_round_trips_with_metadata_flattened() {
let json = r#"{
"id":"e1",
"createdDateTime":"2026-02-10T16:00:00Z",
"modificationDateTime":"2026-02-10T16:00:00Z",
"objectType":"EVENT",
"programID":"p1",
"eventName":"test",
"intervals":[{"id":0,"payloads":[{"type":"PRICE","values":[0.17]}]}]
}"#;
let e: Event = serde_json::from_str(json).unwrap();
assert_eq!(e.object_type, ObjectType::Event);
assert_eq!(e.content.program_id.as_str(), "p1");
let back: Event = serde_json::from_str(&serde_json::to_string(&e).unwrap()).unwrap();
assert_eq!(e, back);
}
}
#[cfg(test)]
mod converter_tests {
use super::*;
use crate::model::Value;
use crate::std_shim::vec;
use rust_decimal::Decimal;
fn descriptor(json: &str) -> Result<ReportPayloadDescriptor, serde_json::Error> {
serde_json::from_str(&format!(r#"{{"payloadType":"USAGE","accuracy":{json}}}"#))
}
#[test]
fn accuracy_is_an_exact_decimal_on_the_wire_and_in_memory() {
let d = descriptor("0.1").unwrap();
assert_eq!(d.accuracy, Some(Decimal::new(1, 1)));
let json = serde_json::to_string(&d).unwrap();
assert!(json.contains(r#""accuracy":0.1"#), "{json}");
assert_eq!(descriptor("1").unwrap().accuracy, Some(Decimal::ONE));
assert_eq!(
descriptor(r#""0.25""#).unwrap().accuracy,
Some(Decimal::new(25, 2))
);
assert_eq!(descriptor("null").unwrap().accuracy, None);
let absent: ReportPayloadDescriptor =
serde_json::from_str(r#"{"payloadType":"USAGE"}"#).unwrap();
assert_eq!(absent.accuracy, None);
assert!(!serde_json::to_string(&absent).unwrap().contains("accuracy"));
}
#[test]
fn accuracy_out_of_range_or_not_a_number_is_refused() {
assert!(descriptor("1e100").is_err());
assert!(descriptor(r#""abc""#).is_err());
}
fn program_and_event(program_id: &str, event_descriptors: &str) -> (Program, Event) {
let program: Program = serde_json::from_str(&format!(
r#"{{"id": "{program_id}", "createdDateTime": "2026-03-13T12:00:00Z",
"modificationDateTime": "2026-03-13T12:00:00Z", "programName": "caps",
"payloadDescriptors": [
{{"objectType": "REPORT_PAYLOAD_DESCRIPTOR", "payloadType": "IMPORT_CAPACITY_LIMIT", "units": "KWH"}},
{{"objectType": "EVENT_PAYLOAD_DESCRIPTOR", "payloadType": "IMPORT_CAPACITY_LIMIT", "units": "KW"}},
{{"objectType": "REPORT_PAYLOAD_DESCRIPTOR", "payloadType": "USAGE", "units": "KWH"}}]}}"#
))
.unwrap();
let event: Event = serde_json::from_str(&format!(
r#"{{"id": "e1", "programID": "p1", "createdDateTime": "2026-03-13T12:00:00Z",
"modificationDateTime": "2026-03-13T12:00:00Z"{event_descriptors}}}"#
))
.unwrap();
(program, event)
}
#[test]
fn the_program_supplies_default_descriptors_ug_7_6() {
let (program, event) = program_and_event("p1", "");
let limit = event
.payload_descriptor_in(&program, "IMPORT_CAPACITY_LIMIT")
.unwrap();
assert_eq!(
limit.units,
Some(Unit::Kw),
"the event flavour, not the report one before it"
);
assert!(
event.payload_descriptor_in(&program, "USAGE").is_none(),
"a report default never answers an event"
);
assert_eq!(
program
.content
.report_payload_descriptor("USAGE")
.unwrap()
.units,
Some(Unit::Kwh)
);
assert!(program.content.event_payload_descriptor("PRICE").is_none());
}
#[test]
fn a_program_the_event_does_not_belong_to_contributes_nothing() {
let (other, event) = program_and_event("p2", "");
assert!(
event
.payload_descriptor_in(&other, "IMPORT_CAPACITY_LIMIT")
.is_none()
);
}
#[test]
fn the_events_own_descriptor_wins_whole() {
let (program, event) = program_and_event(
"p1",
r#", "payloadDescriptors": [{"payloadType": "IMPORT_CAPACITY_LIMIT"}]"#,
);
let limit = event
.payload_descriptor_in(&program, "IMPORT_CAPACITY_LIMIT")
.unwrap();
assert_eq!(
limit.units, None,
"fields are not merged from the programme"
);
}
#[test]
fn payloads_and_descriptors_are_found_by_type() {
let limit = PayloadType::new("IMPORT_CAPACITY_LIMIT").unwrap();
let interval = Interval::new(0, vec![ValuesMap::single(limit.clone(), 7)]);
assert_eq!(
interval.payload("IMPORT_CAPACITY_LIMIT").unwrap().values,
[Value::Integer(7)]
);
assert_eq!(interval.payload(&limit), interval.payload(limit.as_str()));
assert!(interval.payload("EXPORT_CAPACITY_LIMIT").is_none());
let mut event = EventRequest::new(ObjectId::new("p").unwrap());
assert!(event.payload_descriptor(&limit).is_none());
event.payload_descriptors = Some(vec![
EventPayloadDescriptor::new(limit.clone()).with_units(Unit::Kw),
]);
assert_eq!(
event.payload_descriptor(&limit).unwrap().units,
Some(Unit::Kw)
);
assert!(event.payload_descriptor("PRICE").is_none());
let mut report = ReportRequest::new(
ObjectId::new("e").unwrap(),
ClientName::new("c").unwrap(),
vec![],
);
report.payload_descriptors = Some(vec![descriptor("0.5").unwrap()]);
assert_eq!(
report.payload_descriptor("USAGE").unwrap().accuracy,
Some(Decimal::new(5, 1))
);
assert!(report.payload_descriptor("DEMAND").is_none());
}
}