1use core::fmt;
4
5use crate::types::{OperatorId, ProviderId};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
9pub enum Role {
10 Cpo,
12 Emp,
14}
15
16impl Role {
17 #[must_use]
19 pub const fn as_str(self) -> &'static str {
20 match self {
21 Self::Cpo => "CPO",
22 Self::Emp => "EMP",
23 }
24 }
25
26 #[must_use]
28 pub const fn counterpart(self) -> Self {
29 match self {
30 Self::Cpo => Self::Emp,
31 Self::Emp => Self::Cpo,
32 }
33 }
34}
35
36impl fmt::Display for Role {
37 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
38 f.write_str(self.as_str())
39 }
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
55pub enum Involvement {
56 YouCall,
58 YouServe,
61}
62
63impl Involvement {
64 #[must_use]
66 pub const fn as_str(self) -> &'static str {
67 match self {
68 Self::YouCall => "you -> Hubject",
69 Self::YouServe => "Hubject -> you",
70 }
71 }
72}
73
74impl fmt::Display for Involvement {
75 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
76 f.write_str(self.as_str())
77 }
78}
79
80#[derive(Clone, Debug, PartialEq, Eq, Hash)]
86pub enum PathId {
87 Operator(OperatorId),
89 Provider(ProviderId),
91}
92
93impl PathId {
94 #[must_use]
96 pub fn as_str(&self) -> &str {
97 match self {
98 Self::Operator(id) => id.as_str(),
99 Self::Provider(id) => id.as_str(),
100 }
101 }
102}
103
104impl fmt::Display for PathId {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 f.write_str(self.as_str())
107 }
108}
109
110impl From<OperatorId> for PathId {
111 fn from(id: OperatorId) -> Self {
112 Self::Operator(id)
113 }
114}
115
116impl From<ProviderId> for PathId {
117 fn from(id: ProviderId) -> Self {
118 Self::Provider(id)
119 }
120}
121
122#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
134#[non_exhaustive]
135pub enum Operation {
136 AuthorizeStart,
138 AuthorizeStop,
140 AuthorizeRemoteStart,
142 AuthorizeRemoteStop,
144 ChargeDetailRecord,
146 GetChargeDetailRecords,
148 PushAuthenticationData,
150 AuthorizeRemoteReservationStart,
152 AuthorizeRemoteReservationStop,
154 PushEvseData,
156 PullEvseData,
158 PushEvseStatus,
160 PullEvseStatus,
162 PushPricingProductData,
164 PullPricingProductData,
166 PushEvsePricing,
168 PullEvsePricing,
170 ChargingNotifications,
172}
173
174#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176#[non_exhaustive]
177pub struct EndpointInfo {
178 pub service: &'static str,
180 pub version: &'static str,
182 pub path_template: &'static str,
184 pub cpo: Option<Involvement>,
186 pub emp: Option<Involvement>,
188 pub paginated: bool,
190}
191
192macro_rules! involvement {
194 (Calls) => {
195 Some(Involvement::YouCall)
196 };
197 (Serves) => {
198 Some(Involvement::YouServe)
199 };
200 (NoPart) => {
201 None
202 };
203}
204
205macro_rules! endpoint_table {
206 ($( $op:ident => $service:literal, $version:literal, $path:literal, $cpo:ident, $emp:ident, $paginated:literal );* $(;)?) => {
207 impl Operation {
208 pub const ALL: &'static [Self] = &[ $( Self::$op ),* ];
210
211 #[must_use]
213 pub const fn info(self) -> EndpointInfo {
214 match self {
215 $( Self::$op => EndpointInfo {
216 service: $service,
217 version: $version,
218 path_template: $path,
219 cpo: involvement!($cpo),
220 emp: involvement!($emp),
221 paginated: $paginated,
222 }, )*
223 }
224 }
225 }
226 };
227}
228
229endpoint_table! {
231 AuthorizeStart => "charging", "v21", "/charging/v21/operators/{operatorID}/authorize/start", Calls, Serves, false;
232 AuthorizeStop => "charging", "v21", "/charging/v21/operators/{operatorID}/authorize/stop", Calls, Serves, false;
233 AuthorizeRemoteStart => "charging", "v21", "/charging/v21/providers/{providerID}/authorize-remote/start", Serves, Calls, false;
234 AuthorizeRemoteStop => "charging", "v21", "/charging/v21/providers/{providerID}/authorize-remote/stop", Serves, Calls, false;
235 ChargeDetailRecord => "cdrmgmt", "v22", "/cdrmgmt/v22/operators/{operatorID}/charge-detail-record", Calls, Serves, false;
236 GetChargeDetailRecords => "cdrmgmt", "v22", "/cdrmgmt/v22/providers/{providerID}/get-charge-detail-records-request", NoPart, Calls, true;
237 PushAuthenticationData => "authdata", "v21", "/authdata/v21/providers/{providerID}/push-request", NoPart, Calls, false;
238 AuthorizeRemoteReservationStart => "reservation", "v11", "/reservation/v11/providers/{providerID}/reservation-start-request", Serves, Calls, false;
239 AuthorizeRemoteReservationStop => "reservation", "v11", "/reservation/v11/providers/{providerID}/reservation-stop-request", Serves, Calls, false;
240 PushEvseData => "evsepush", "v23", "/evsepush/v23/operators/{operatorID}/data-records", Calls, NoPart, false;
241 PullEvseData => "evsepull", "v23", "/evsepull/v23/providers/{providerID}/data-records", NoPart, Calls, true;
242 PushEvseStatus => "evsepush", "v21", "/evsepush/v21/operators/{operatorID}/status-records", Calls, NoPart, false;
243 PullEvseStatus => "evsepull", "v21", "/evsepull/v21/providers/{providerID}/status-records", NoPart, Calls, false;
244 PushPricingProductData => "dynamicpricing", "v10", "/dynamicpricing/v10/operators/{operatorID}/pricing-products", Calls, NoPart, false;
245 PullPricingProductData => "dynamicpricing", "v10", "/dynamicpricing/v10/providers/{providerID}/pricing-products", NoPart, Calls, false;
246 PushEvsePricing => "dynamicpricing", "v10", "/dynamicpricing/v10/operators/{operatorID}/evse-pricing", Calls, NoPart, false;
247 PullEvsePricing => "dynamicpricing", "v10", "/dynamicpricing/v10/providers/{providerID}/evse-pricing", NoPart, Calls, false;
248 ChargingNotifications => "notificationmgmt", "v11", "/notificationmgmt/v11/charging-notifications", Calls, Serves, false;
249}
250
251impl Operation {
252 #[must_use]
254 pub const fn service(self) -> &'static str {
255 self.info().service
256 }
257
258 #[must_use]
260 pub const fn version(self) -> &'static str {
261 self.info().version
262 }
263
264 #[must_use]
266 pub const fn path_template(self) -> &'static str {
267 self.info().path_template
268 }
269
270 #[must_use]
272 pub const fn is_paginated(self) -> bool {
273 self.info().paginated
274 }
275
276 #[must_use]
282 pub const fn is_served_by(self, role: Role) -> bool {
283 matches!(self.involvement(role), Some(Involvement::YouServe))
284 }
285
286 #[must_use]
288 pub fn takes_operator_id(self) -> bool {
289 self.info().path_template.contains("{operatorID}")
290 }
291
292 #[must_use]
297 pub const fn involvement(self, role: Role) -> Option<Involvement> {
298 match role {
299 Role::Cpo => self.info().cpo,
300 Role::Emp => self.info().emp,
301 }
302 }
303
304 #[must_use]
306 pub fn for_role(role: Role) -> Vec<Self> {
307 Self::ALL.iter().copied().filter(|op| op.involvement(role).is_some()).collect()
308 }
309
310 #[must_use]
314 pub fn caller_path_id(self, role: Role, id: &str) -> Option<PathId> {
315 if self.involvement(role) != Some(Involvement::YouCall) || !self.path_template().contains('{') {
316 return None;
317 }
318 Some(if self.takes_operator_id() {
319 PathId::Operator(OperatorId::new_unchecked(id))
320 } else {
321 PathId::Provider(ProviderId::new_unchecked(id))
322 })
323 }
324
325 pub fn path(self, id: &PathId) -> Result<String, EndpointError> {
335 let template = self.path_template();
336 match (id, self.takes_operator_id()) {
337 (PathId::Operator(_), true) => Ok(template.replace("{operatorID}", id.as_str())),
338 (PathId::Provider(_), false) if template.contains("{providerID}") => {
339 Ok(template.replace("{providerID}", id.as_str()))
340 }
341 (_, false) if !template.contains('{') => Ok(template.to_owned()),
343 (PathId::Operator(_), false) => {
344 Err(EndpointError::WrongIdKind { operation: self, expected: "providerID" })
345 }
346 (PathId::Provider(_), true) => {
347 Err(EndpointError::WrongIdKind { operation: self, expected: "operatorID" })
348 }
349 _ => Err(EndpointError::WrongIdKind { operation: self, expected: "no id" }),
350 }
351 }
352
353 pub fn url(self, base: &str, id: &PathId) -> Result<String, EndpointError> {
359 Ok(format!("{}{}", base.trim_end_matches('/'), self.path(id)?))
360 }
361
362 #[must_use]
364 pub fn from_path(path: &str) -> Option<Self> {
365 Self::ALL.iter().copied().find(|op| path_matches(op.path_template(), path))
366 }
367}
368
369fn path_matches(template: &str, path: &str) -> bool {
371 let mut t = template.split('/');
372 let mut p = path.trim_end_matches('/').split('/');
373 loop {
374 match (t.next(), p.next()) {
375 (None, None) => return true,
376 (Some(ts), Some(ps)) if ts.starts_with('{') && ts.ends_with('}') => {
377 if ps.is_empty() {
378 return false;
379 }
380 }
381 (Some(ts), Some(ps)) if ts == ps => {}
382 _ => return false,
383 }
384 }
385}
386
387#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
389pub enum EndpointError {
390 #[error("{operation:?} takes a {expected} in its path, but the other kind of identifier was given")]
392 WrongIdKind {
393 operation: Operation,
395 expected: &'static str,
397 },
398}
399
400#[derive(Clone, Debug, PartialEq, Eq)]
402pub enum HubjectEnv {
403 Prod,
405 Qa,
407 Custom(String),
409}
410
411impl HubjectEnv {
412 #[must_use]
414 pub fn base_url(&self) -> &str {
415 match self {
416 Self::Prod => "https://service.hubject.com/api/oicp",
417 Self::Qa => "https://service-qa.hubject.com/api/oicp",
418 Self::Custom(url) => url.trim_end_matches('/'),
419 }
420 }
421
422 #[must_use]
427 pub const fn is_production(&self) -> bool {
428 matches!(self, Self::Prod)
429 }
430}
431
432impl fmt::Display for HubjectEnv {
433 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
434 f.write_str(self.base_url())
435 }
436}
437
438#[cfg(test)]
439mod tests {
440 use super::*;
441
442 #[test]
443 fn the_table_covers_every_operation_exactly_once() {
444 assert_eq!(Operation::ALL.len(), 18);
445 let mut paths: Vec<_> = Operation::ALL.iter().map(|op| (op.path_template(), *op)).collect();
446 paths.sort_unstable();
447 let mut unique = paths.clone();
448 unique.dedup_by_key(|(p, _)| *p);
449 assert_eq!(paths.len(), unique.len(), "two operations share a path template");
450 }
451
452 #[test]
453 fn paths_carry_the_identifier_exactly_as_given() {
454 let op = Operation::PushEvseData;
455 let id = PathId::Operator("DE*ABC".parse().unwrap());
457 assert_eq!(op.path(&id).unwrap(), "/evsepush/v23/operators/DE*ABC/data-records");
458
459 let packed = PathId::Operator("DEABC".parse().unwrap());
460 assert_eq!(op.path(&packed).unwrap(), "/evsepush/v23/operators/DEABC/data-records");
461 }
462
463 #[test]
464 fn the_wrong_kind_of_identifier_is_caught_locally() {
465 let provider = PathId::Provider("DE-DCB".parse().unwrap());
466 let err = Operation::PushEvseData.path(&provider).unwrap_err();
468 assert!(matches!(err, EndpointError::WrongIdKind { expected: "operatorID", .. }));
469
470 let operator = PathId::Operator("DE*ABC".parse().unwrap());
471 assert!(Operation::PullEvseData.path(&operator).is_err());
472 }
473
474 #[test]
475 fn the_notification_endpoint_takes_no_identifier() {
476 let op = Operation::ChargingNotifications;
477 let id = PathId::Operator("DE*ABC".parse().unwrap());
478 assert_eq!(op.path(&id).unwrap(), "/notificationmgmt/v11/charging-notifications");
479 }
480
481 #[test]
482 fn routing_recovers_the_operation_from_a_concrete_path() {
483 assert_eq!(
484 Operation::from_path("/evsepush/v23/operators/DE*ABC/data-records"),
485 Some(Operation::PushEvseData)
486 );
487 assert_eq!(
488 Operation::from_path("/charging/v21/providers/DE-DCB/authorize-remote/start"),
489 Some(Operation::AuthorizeRemoteStart)
490 );
491 assert_eq!(Operation::from_path("/nope"), None);
492 assert_eq!(
494 Operation::from_path("/charging/v21/operators/DE*ABC/authorize/stop"),
495 Some(Operation::AuthorizeStop)
496 );
497 }
498
499 #[test]
500 fn what_a_partner_serves_depends_on_which_partner_they_are() {
501 assert_eq!(
505 Operation::ALL.iter().copied().filter(|op| op.is_served_by(Role::Cpo)).collect::<Vec<_>>(),
506 vec![
507 Operation::AuthorizeRemoteStart,
508 Operation::AuthorizeRemoteStop,
509 Operation::AuthorizeRemoteReservationStart,
510 Operation::AuthorizeRemoteReservationStop,
511 ]
512 );
513 assert_eq!(
514 Operation::ALL.iter().copied().filter(|op| op.is_served_by(Role::Emp)).collect::<Vec<_>>(),
515 vec![
516 Operation::AuthorizeStart,
517 Operation::AuthorizeStop,
518 Operation::ChargeDetailRecord,
519 Operation::ChargingNotifications,
520 ]
521 );
522 }
523
524 #[test]
525 fn the_role_that_calls_an_operation_is_the_role_whose_identifier_the_path_carries() {
526 for operation in Operation::ALL.iter().copied() {
530 if !operation.path_template().contains('{') {
531 continue;
532 }
533 let caller = if operation.involvement(Role::Cpo) == Some(Involvement::YouCall) {
534 Role::Cpo
535 } else {
536 Role::Emp
537 };
538 assert_eq!(
539 operation.involvement(caller),
540 Some(Involvement::YouCall),
541 "{operation:?} is called by neither role"
542 );
543 assert_eq!(
544 operation.takes_operator_id(),
545 caller == Role::Cpo,
546 "{operation:?} is called by {caller} but its path carries the other identifier"
547 );
548 }
549 }
550
551 #[test]
552 fn every_operation_involves_at_least_one_role() {
553 for operation in Operation::ALL.iter().copied() {
554 assert!(
555 operation.involvement(Role::Cpo).is_some() || operation.involvement(Role::Emp).is_some(),
556 "{operation:?} is in the table and belongs to nobody"
557 );
558 }
559 assert_eq!(Operation::for_role(Role::Cpo).len(), 12, "the CPO document's twelve endpoints");
560 assert_eq!(Operation::for_role(Role::Emp).len(), 14, "the EMP document's fourteen");
561 }
562
563 #[test]
564 fn only_the_two_big_pulls_are_paginated() {
565 let paginated: Vec<_> = Operation::ALL.iter().copied().filter(|op| op.is_paginated()).collect();
566 assert_eq!(paginated, vec![Operation::GetChargeDetailRecords, Operation::PullEvseData]);
567 }
568
569 #[test]
570 fn the_environments_have_the_urls_the_spec_gives() {
571 assert_eq!(HubjectEnv::Prod.base_url(), "https://service.hubject.com/api/oicp");
572 assert_eq!(HubjectEnv::Qa.base_url(), "https://service-qa.hubject.com/api/oicp");
573 assert!(HubjectEnv::Prod.is_production());
574 assert!(!HubjectEnv::Qa.is_production());
575 assert_eq!(HubjectEnv::Custom("http://localhost:8080/".into()).base_url(), "http://localhost:8080");
576 }
577
578 #[test]
579 fn urls_join_base_and_path_without_doubling_the_slash() {
580 let url = Operation::PullEvseData
581 .url(HubjectEnv::Qa.base_url(), &PathId::Provider("DE-DCB".parse().unwrap()))
582 .unwrap();
583 assert_eq!(url, "https://service-qa.hubject.com/api/oicp/evsepull/v23/providers/DE-DCB/data-records");
584 }
585}