use core::fmt;
use crate::types::{OperatorId, ProviderId};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum Role {
Cpo,
Emp,
}
impl Role {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Cpo => "CPO",
Self::Emp => "EMP",
}
}
#[must_use]
pub const fn counterpart(self) -> Self {
match self {
Self::Cpo => Self::Emp,
Self::Emp => Self::Cpo,
}
}
}
impl fmt::Display for Role {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Involvement {
YouCall,
YouServe,
}
impl Involvement {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::YouCall => "you -> Hubject",
Self::YouServe => "Hubject -> you",
}
}
}
impl fmt::Display for Involvement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum PathId {
Operator(OperatorId),
Provider(ProviderId),
}
impl PathId {
#[must_use]
pub fn as_str(&self) -> &str {
match self {
Self::Operator(id) => id.as_str(),
Self::Provider(id) => id.as_str(),
}
}
}
impl fmt::Display for PathId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl From<OperatorId> for PathId {
fn from(id: OperatorId) -> Self {
Self::Operator(id)
}
}
impl From<ProviderId> for PathId {
fn from(id: ProviderId) -> Self {
Self::Provider(id)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum Operation {
AuthorizeStart,
AuthorizeStop,
AuthorizeRemoteStart,
AuthorizeRemoteStop,
ChargeDetailRecord,
GetChargeDetailRecords,
PushAuthenticationData,
AuthorizeRemoteReservationStart,
AuthorizeRemoteReservationStop,
PushEvseData,
PullEvseData,
PushEvseStatus,
PullEvseStatus,
PushPricingProductData,
PullPricingProductData,
PushEvsePricing,
PullEvsePricing,
ChargingNotifications,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct EndpointInfo {
pub service: &'static str,
pub version: &'static str,
pub path_template: &'static str,
pub cpo: Option<Involvement>,
pub emp: Option<Involvement>,
pub paginated: bool,
}
macro_rules! involvement {
(Calls) => {
Some(Involvement::YouCall)
};
(Serves) => {
Some(Involvement::YouServe)
};
(NoPart) => {
None
};
}
macro_rules! endpoint_table {
($( $op:ident => $service:literal, $version:literal, $path:literal, $cpo:ident, $emp:ident, $paginated:literal );* $(;)?) => {
impl Operation {
pub const ALL: &'static [Self] = &[ $( Self::$op ),* ];
#[must_use]
pub const fn info(self) -> EndpointInfo {
match self {
$( Self::$op => EndpointInfo {
service: $service,
version: $version,
path_template: $path,
cpo: involvement!($cpo),
emp: involvement!($emp),
paginated: $paginated,
}, )*
}
}
}
};
}
endpoint_table! {
AuthorizeStart => "charging", "v21", "/charging/v21/operators/{operatorID}/authorize/start", Calls, Serves, false;
AuthorizeStop => "charging", "v21", "/charging/v21/operators/{operatorID}/authorize/stop", Calls, Serves, false;
AuthorizeRemoteStart => "charging", "v21", "/charging/v21/providers/{providerID}/authorize-remote/start", Serves, Calls, false;
AuthorizeRemoteStop => "charging", "v21", "/charging/v21/providers/{providerID}/authorize-remote/stop", Serves, Calls, false;
ChargeDetailRecord => "cdrmgmt", "v22", "/cdrmgmt/v22/operators/{operatorID}/charge-detail-record", Calls, Serves, false;
GetChargeDetailRecords => "cdrmgmt", "v22", "/cdrmgmt/v22/providers/{providerID}/get-charge-detail-records-request", NoPart, Calls, true;
PushAuthenticationData => "authdata", "v21", "/authdata/v21/providers/{providerID}/push-request", NoPart, Calls, false;
AuthorizeRemoteReservationStart => "reservation", "v11", "/reservation/v11/providers/{providerID}/reservation-start-request", Serves, Calls, false;
AuthorizeRemoteReservationStop => "reservation", "v11", "/reservation/v11/providers/{providerID}/reservation-stop-request", Serves, Calls, false;
PushEvseData => "evsepush", "v23", "/evsepush/v23/operators/{operatorID}/data-records", Calls, NoPart, false;
PullEvseData => "evsepull", "v23", "/evsepull/v23/providers/{providerID}/data-records", NoPart, Calls, true;
PushEvseStatus => "evsepush", "v21", "/evsepush/v21/operators/{operatorID}/status-records", Calls, NoPart, false;
PullEvseStatus => "evsepull", "v21", "/evsepull/v21/providers/{providerID}/status-records", NoPart, Calls, false;
PushPricingProductData => "dynamicpricing", "v10", "/dynamicpricing/v10/operators/{operatorID}/pricing-products", Calls, NoPart, false;
PullPricingProductData => "dynamicpricing", "v10", "/dynamicpricing/v10/providers/{providerID}/pricing-products", NoPart, Calls, false;
PushEvsePricing => "dynamicpricing", "v10", "/dynamicpricing/v10/operators/{operatorID}/evse-pricing", Calls, NoPart, false;
PullEvsePricing => "dynamicpricing", "v10", "/dynamicpricing/v10/providers/{providerID}/evse-pricing", NoPart, Calls, false;
ChargingNotifications => "notificationmgmt", "v11", "/notificationmgmt/v11/charging-notifications", Calls, Serves, false;
}
impl Operation {
#[must_use]
pub const fn service(self) -> &'static str {
self.info().service
}
#[must_use]
pub const fn version(self) -> &'static str {
self.info().version
}
#[must_use]
pub const fn path_template(self) -> &'static str {
self.info().path_template
}
#[must_use]
pub const fn is_paginated(self) -> bool {
self.info().paginated
}
#[must_use]
pub const fn is_served_by(self, role: Role) -> bool {
matches!(self.involvement(role), Some(Involvement::YouServe))
}
#[must_use]
pub fn takes_operator_id(self) -> bool {
self.info().path_template.contains("{operatorID}")
}
#[must_use]
pub const fn involvement(self, role: Role) -> Option<Involvement> {
match role {
Role::Cpo => self.info().cpo,
Role::Emp => self.info().emp,
}
}
#[must_use]
pub fn for_role(role: Role) -> Vec<Self> {
Self::ALL.iter().copied().filter(|op| op.involvement(role).is_some()).collect()
}
#[must_use]
pub fn caller_path_id(self, role: Role, id: &str) -> Option<PathId> {
if self.involvement(role) != Some(Involvement::YouCall) || !self.path_template().contains('{') {
return None;
}
Some(if self.takes_operator_id() {
PathId::Operator(OperatorId::new_unchecked(id))
} else {
PathId::Provider(ProviderId::new_unchecked(id))
})
}
pub fn path(self, id: &PathId) -> Result<String, EndpointError> {
let template = self.path_template();
match (id, self.takes_operator_id()) {
(PathId::Operator(_), true) => Ok(template.replace("{operatorID}", id.as_str())),
(PathId::Provider(_), false) if template.contains("{providerID}") => {
Ok(template.replace("{providerID}", id.as_str()))
}
(_, false) if !template.contains('{') => Ok(template.to_owned()),
(PathId::Operator(_), false) => {
Err(EndpointError::WrongIdKind { operation: self, expected: "providerID" })
}
(PathId::Provider(_), true) => {
Err(EndpointError::WrongIdKind { operation: self, expected: "operatorID" })
}
_ => Err(EndpointError::WrongIdKind { operation: self, expected: "no id" }),
}
}
pub fn url(self, base: &str, id: &PathId) -> Result<String, EndpointError> {
Ok(format!("{}{}", base.trim_end_matches('/'), self.path(id)?))
}
#[must_use]
pub fn from_path(path: &str) -> Option<Self> {
Self::ALL.iter().copied().find(|op| path_matches(op.path_template(), path))
}
}
fn path_matches(template: &str, path: &str) -> bool {
let mut t = template.split('/');
let mut p = path.trim_end_matches('/').split('/');
loop {
match (t.next(), p.next()) {
(None, None) => return true,
(Some(ts), Some(ps)) if ts.starts_with('{') && ts.ends_with('}') => {
if ps.is_empty() {
return false;
}
}
(Some(ts), Some(ps)) if ts == ps => {}
_ => return false,
}
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
pub enum EndpointError {
#[error("{operation:?} takes a {expected} in its path, but the other kind of identifier was given")]
WrongIdKind {
operation: Operation,
expected: &'static str,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum HubjectEnv {
Prod,
Qa,
Custom(String),
}
impl HubjectEnv {
#[must_use]
pub fn base_url(&self) -> &str {
match self {
Self::Prod => "https://service.hubject.com/api/oicp",
Self::Qa => "https://service-qa.hubject.com/api/oicp",
Self::Custom(url) => url.trim_end_matches('/'),
}
}
#[must_use]
pub const fn is_production(&self) -> bool {
matches!(self, Self::Prod)
}
}
impl fmt::Display for HubjectEnv {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.base_url())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_table_covers_every_operation_exactly_once() {
assert_eq!(Operation::ALL.len(), 18);
let mut paths: Vec<_> = Operation::ALL.iter().map(|op| (op.path_template(), *op)).collect();
paths.sort_unstable();
let mut unique = paths.clone();
unique.dedup_by_key(|(p, _)| *p);
assert_eq!(paths.len(), unique.len(), "two operations share a path template");
}
#[test]
fn paths_carry_the_identifier_exactly_as_given() {
let op = Operation::PushEvseData;
let id = PathId::Operator("DE*ABC".parse().unwrap());
assert_eq!(op.path(&id).unwrap(), "/evsepush/v23/operators/DE*ABC/data-records");
let packed = PathId::Operator("DEABC".parse().unwrap());
assert_eq!(op.path(&packed).unwrap(), "/evsepush/v23/operators/DEABC/data-records");
}
#[test]
fn the_wrong_kind_of_identifier_is_caught_locally() {
let provider = PathId::Provider("DE-DCB".parse().unwrap());
let err = Operation::PushEvseData.path(&provider).unwrap_err();
assert!(matches!(err, EndpointError::WrongIdKind { expected: "operatorID", .. }));
let operator = PathId::Operator("DE*ABC".parse().unwrap());
assert!(Operation::PullEvseData.path(&operator).is_err());
}
#[test]
fn the_notification_endpoint_takes_no_identifier() {
let op = Operation::ChargingNotifications;
let id = PathId::Operator("DE*ABC".parse().unwrap());
assert_eq!(op.path(&id).unwrap(), "/notificationmgmt/v11/charging-notifications");
}
#[test]
fn routing_recovers_the_operation_from_a_concrete_path() {
assert_eq!(
Operation::from_path("/evsepush/v23/operators/DE*ABC/data-records"),
Some(Operation::PushEvseData)
);
assert_eq!(
Operation::from_path("/charging/v21/providers/DE-DCB/authorize-remote/start"),
Some(Operation::AuthorizeRemoteStart)
);
assert_eq!(Operation::from_path("/nope"), None);
assert_eq!(
Operation::from_path("/charging/v21/operators/DE*ABC/authorize/stop"),
Some(Operation::AuthorizeStop)
);
}
#[test]
fn what_a_partner_serves_depends_on_which_partner_they_are() {
assert_eq!(
Operation::ALL.iter().copied().filter(|op| op.is_served_by(Role::Cpo)).collect::<Vec<_>>(),
vec![
Operation::AuthorizeRemoteStart,
Operation::AuthorizeRemoteStop,
Operation::AuthorizeRemoteReservationStart,
Operation::AuthorizeRemoteReservationStop,
]
);
assert_eq!(
Operation::ALL.iter().copied().filter(|op| op.is_served_by(Role::Emp)).collect::<Vec<_>>(),
vec![
Operation::AuthorizeStart,
Operation::AuthorizeStop,
Operation::ChargeDetailRecord,
Operation::ChargingNotifications,
]
);
}
#[test]
fn the_role_that_calls_an_operation_is_the_role_whose_identifier_the_path_carries() {
for operation in Operation::ALL.iter().copied() {
if !operation.path_template().contains('{') {
continue;
}
let caller = if operation.involvement(Role::Cpo) == Some(Involvement::YouCall) {
Role::Cpo
} else {
Role::Emp
};
assert_eq!(
operation.involvement(caller),
Some(Involvement::YouCall),
"{operation:?} is called by neither role"
);
assert_eq!(
operation.takes_operator_id(),
caller == Role::Cpo,
"{operation:?} is called by {caller} but its path carries the other identifier"
);
}
}
#[test]
fn every_operation_involves_at_least_one_role() {
for operation in Operation::ALL.iter().copied() {
assert!(
operation.involvement(Role::Cpo).is_some() || operation.involvement(Role::Emp).is_some(),
"{operation:?} is in the table and belongs to nobody"
);
}
assert_eq!(Operation::for_role(Role::Cpo).len(), 12, "the CPO document's twelve endpoints");
assert_eq!(Operation::for_role(Role::Emp).len(), 14, "the EMP document's fourteen");
}
#[test]
fn only_the_two_big_pulls_are_paginated() {
let paginated: Vec<_> = Operation::ALL.iter().copied().filter(|op| op.is_paginated()).collect();
assert_eq!(paginated, vec![Operation::GetChargeDetailRecords, Operation::PullEvseData]);
}
#[test]
fn the_environments_have_the_urls_the_spec_gives() {
assert_eq!(HubjectEnv::Prod.base_url(), "https://service.hubject.com/api/oicp");
assert_eq!(HubjectEnv::Qa.base_url(), "https://service-qa.hubject.com/api/oicp");
assert!(HubjectEnv::Prod.is_production());
assert!(!HubjectEnv::Qa.is_production());
assert_eq!(HubjectEnv::Custom("http://localhost:8080/".into()).base_url(), "http://localhost:8080");
}
#[test]
fn urls_join_base_and_path_without_doubling_the_slash() {
let url = Operation::PullEvseData
.url(HubjectEnv::Qa.base_url(), &PathId::Provider("DE-DCB".parse().unwrap()))
.unwrap();
assert_eq!(url, "https://service-qa.hubject.com/api/oicp/evsepull/v23/providers/DE-DCB/data-records");
}
}