use std::collections::BTreeMap;
use std::fmt;
use std::time::Duration;
use crate::types::Identity;
use crate::version::{Subprotocol, Version};
use super::TransportError;
use super::security::{BasicAuthPassword, SecurityProfile};
#[derive(Clone)]
pub struct NetworkProfile {
pub(crate) slot: i32,
pub(crate) url: String,
pub(crate) versions: Option<Subprotocol>,
pub(crate) security: SecurityProfile,
pub(crate) password: Option<BasicAuthPassword>,
pub(crate) identity: Option<Identity>,
#[cfg(feature = "rustls")]
pub(crate) tls: Option<super::tls::ClientTls>,
pub(crate) message_timeout: Option<Duration>,
}
impl NetworkProfile {
#[must_use]
pub fn new(slot: i32, url: impl Into<String>) -> Self {
Self {
slot,
url: url.into(),
versions: None,
security: SecurityProfile::BasicAuth,
password: None,
identity: None,
#[cfg(feature = "rustls")]
tls: None,
message_timeout: None,
}
}
#[must_use]
pub const fn slot(&self) -> i32 {
self.slot
}
#[must_use]
pub fn url(&self) -> &str {
&self.url
}
#[must_use]
pub const fn security_profile_number(&self) -> u8 {
self.security.number()
}
#[must_use]
pub fn versions(mut self, versions: impl IntoIterator<Item = Version>) -> Self {
self.versions = Some(Subprotocol::new(versions));
self
}
#[must_use]
pub fn security_profile(mut self, profile: SecurityProfile) -> Self {
self.security = profile;
self
}
#[must_use]
pub fn password(mut self, password: BasicAuthPassword) -> Self {
self.password = Some(password);
self
}
#[must_use]
pub fn identity(mut self, identity: Identity) -> Self {
self.identity = Some(identity);
self
}
#[cfg(feature = "rustls")]
#[must_use]
pub fn tls(mut self, tls: super::tls::ClientTls) -> Self {
self.tls = Some(tls);
self
}
#[must_use]
pub fn message_timeout(mut self, timeout: Duration) -> Self {
self.message_timeout = Some(timeout);
self
}
}
impl fmt::Debug for NetworkProfile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NetworkProfile")
.field("slot", &self.slot)
.field("url", &self.url)
.field("security", &self.security)
.field("message_timeout", &self.message_timeout)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub struct NetworkProfiles {
slots: BTreeMap<i32, NetworkProfile>,
priority: Vec<i32>,
attempts: u32,
}
impl NetworkProfiles {
#[must_use]
pub fn new(profiles: impl IntoIterator<Item = NetworkProfile>) -> Self {
let mut slots = BTreeMap::new();
let mut priority = Vec::new();
for profile in profiles {
if !priority.contains(&profile.slot) {
priority.push(profile.slot);
}
slots.insert(profile.slot, profile);
}
Self {
slots,
priority,
attempts: 3,
}
}
pub fn priority(
mut self,
order: impl IntoIterator<Item = i32>,
) -> Result<Self, TransportError> {
let order: Vec<i32> = order.into_iter().collect();
if order.is_empty() {
return Err(TransportError::Configuration(
"NetworkConfigurationPriority must name at least one slot".into(),
));
}
for slot in &order {
if !self.slots.contains_key(slot) {
return Err(TransportError::Configuration(format!(
"NetworkConfigurationPriority names configuration slot {slot}, which has no profile"
)));
}
}
self.priority = order;
Ok(self)
}
#[must_use]
pub fn connection_attempts(mut self, attempts: u32) -> Self {
self.attempts = attempts.max(1);
self
}
#[must_use]
pub fn priority_order(&self) -> &[i32] {
&self.priority
}
#[must_use]
pub const fn attempts_per_profile(&self) -> u32 {
self.attempts
}
#[must_use]
pub fn configured_slots(&self) -> Vec<i32> {
self.slots.keys().copied().collect()
}
#[must_use]
pub fn get(&self, slot: i32) -> Option<&NetworkProfile> {
self.slots.get(&slot)
}
pub(crate) fn default_password(&mut self, password: &BasicAuthPassword) {
for profile in self.slots.values_mut() {
if profile.password.is_none() {
profile.password = Some(password.clone());
}
}
}
#[must_use]
pub(crate) fn at(&self, index: usize) -> &NetworkProfile {
let slot = self.priority[index % self.priority.len()];
self.slots
.get(&slot)
.expect("priority is validated against the slots")
}
#[must_use]
pub(crate) fn len(&self) -> usize {
self.priority.len()
}
}
#[derive(Debug)]
pub(crate) struct ProfileCycler {
index: usize,
failures: u32,
limit: u32,
len: usize,
}
impl ProfileCycler {
pub(crate) fn new(profiles: &NetworkProfiles) -> Self {
Self {
index: 0,
failures: 0,
limit: profiles.attempts_per_profile(),
len: profiles.len(),
}
}
pub(crate) const fn index(&self) -> usize {
self.index
}
pub(crate) fn succeeded(&mut self) {
self.failures = 0;
}
pub(crate) fn failed(&mut self) -> bool {
self.failures += 1;
if self.failures >= self.limit && self.len > 1 {
self.failures = 0;
self.index = (self.index + 1) % self.len;
return true;
}
false
}
}
#[cfg(test)]
mod tests {
use super::*;
fn profiles() -> NetworkProfiles {
NetworkProfiles::new([
NetworkProfile::new(0, "ws://fallback/ocpp"),
NetworkProfile::new(1, "ws://primary/ocpp"),
])
}
#[test]
fn the_priority_list_decides_the_order_and_must_be_configured() {
let configured = profiles().priority([1, 0]).unwrap();
assert_eq!(configured.priority_order(), &[1, 0]);
assert_eq!(configured.at(0).url(), "ws://primary/ocpp");
assert_eq!(configured.at(1).url(), "ws://fallback/ocpp");
assert_eq!(configured.at(2).url(), "ws://primary/ocpp");
let error = profiles().priority([1, 7]).unwrap_err();
assert!(
error.to_string().contains("configuration slot 7"),
"{error}"
);
assert!(profiles().priority([]).is_err());
}
#[test]
fn a_profile_gets_its_share_of_attempts_before_the_station_moves_on() {
let configured = profiles().priority([1, 0]).unwrap().connection_attempts(3);
let mut cycler = ProfileCycler::new(&configured);
assert_eq!(configured.at(cycler.index()).slot(), 1);
assert!(!cycler.failed());
assert!(!cycler.failed());
assert!(cycler.failed());
assert_eq!(configured.at(cycler.index()).slot(), 0);
cycler.succeeded();
assert!(!cycler.failed());
assert!(!cycler.failed());
assert!(cycler.failed());
assert_eq!(configured.at(cycler.index()).slot(), 1, "the list wraps");
}
#[test]
fn a_single_profile_never_switches_away_from_itself() {
let single = NetworkProfiles::new([NetworkProfile::new(0, "ws://only/ocpp")]);
let mut cycler = ProfileCycler::new(&single);
for _ in 0..10 {
assert!(!cycler.failed());
}
assert_eq!(single.at(cycler.index()).slot(), 0);
}
#[test]
fn the_configured_slots_are_the_values_list_of_the_priority_variable() {
assert_eq!(profiles().configured_slots(), vec![0, 1]);
}
}