mod backoff;
mod queue;
#[cfg(feature = "std")]
mod store_file;
mod time;
use alloc::boxed::Box;
use alloc::collections::{BTreeSet, VecDeque};
use alloc::format;
use alloc::string::{String, ToString};
use alloc::vec::Vec;
use core::fmt;
use core::time::Duration;
use serde::Deserialize;
use serde_json::value::RawValue;
use crate::actions;
use crate::message::{MessageKind, Origin};
use crate::rpc::{CallError, CallErrorRef, ErrorCode, Frame, FrameError, FrameReply};
use crate::types::{DateTime, IdGenerator, MessageId};
use crate::version::Version;
pub use backoff::{Backoff, Jitter};
pub use queue::{MemStore, MessageStore, QueuedCall, RetryPolicy, Seq, StoreError};
#[cfg(feature = "std")]
pub use store_file::FileStore;
pub use time::{Instant, Timer};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Role {
ChargingStation,
Csms,
}
impl Role {
const fn sends(self) -> Origin {
match self {
Role::ChargingStation => Origin::ChargingStation,
Role::Csms => Origin::Csms,
}
}
const fn receives(self) -> Origin {
match self {
Role::ChargingStation => Origin::Csms,
Role::Csms => Origin::ChargingStation,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum InboundConcurrency {
#[default]
Serve,
Reject,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum HeartbeatPolicy {
#[default]
Automatic,
Manual,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct OfflinePolicy {
pub queue_all_messages: bool,
pub max_queued: usize,
}
impl Default for OfflinePolicy {
fn default() -> Self {
Self {
queue_all_messages: false,
max_queued: 1024,
}
}
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct EngineConfig {
pub role: Role,
pub version: Version,
pub call_timeout: Duration,
pub inbound_concurrency: InboundConcurrency,
pub heartbeat: HeartbeatPolicy,
pub retry: RetryPolicy,
pub offline: OfflinePolicy,
pub backoff: Backoff,
pub enforce_boot_gate: bool,
pub boot_retry_fallback: Duration,
pub max_peer_requests: usize,
}
impl EngineConfig {
#[must_use]
pub fn new(role: Role, version: Version) -> Self {
Self {
role,
version,
call_timeout: Duration::from_secs(30),
inbound_concurrency: InboundConcurrency::Serve,
heartbeat: HeartbeatPolicy::Automatic,
retry: RetryPolicy::default(),
offline: OfflinePolicy::default(),
backoff: Backoff::default(),
enforce_boot_gate: true,
boot_retry_fallback: Duration::from_secs(30),
max_peer_requests: 64,
}
}
#[must_use]
pub const fn with_call_timeout(mut self, timeout: Duration) -> Self {
self.call_timeout = timeout;
self
}
#[must_use]
pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
self.retry = retry;
self
}
#[must_use]
pub const fn with_offline(mut self, offline: OfflinePolicy) -> Self {
self.offline = offline;
self
}
#[must_use]
pub const fn with_heartbeat(mut self, heartbeat: HeartbeatPolicy) -> Self {
self.heartbeat = heartbeat;
self
}
#[must_use]
pub const fn with_inbound_concurrency(mut self, mode: InboundConcurrency) -> Self {
self.inbound_concurrency = mode;
self
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
pub enum BootState {
#[default]
Idle,
Pending,
Accepted,
Rejected,
}
impl BootState {
#[must_use]
pub const fn allows_traffic(self) -> bool {
matches!(self, BootState::Accepted)
}
#[must_use]
pub const fn blocks_unsolicited_traffic(self) -> bool {
matches!(self, BootState::Pending | BootState::Rejected)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct CallToken(u64);
impl fmt::Display for CallToken {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "call#{}", self.0)
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct CallOptions {
pub triggered: bool,
pub persist: Option<bool>,
pub queue_when_offline: Option<bool>,
}
impl CallOptions {
#[must_use]
pub const fn triggered() -> Self {
Self {
triggered: true,
persist: None,
queue_when_offline: None,
}
}
#[must_use]
pub const fn persist(mut self, persist: bool) -> Self {
self.persist = Some(persist);
self
}
#[must_use]
pub const fn queue_when_offline(mut self, queue: bool) -> Self {
self.queue_when_offline = Some(queue);
self
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum ProtocolViolation {
UnexpectedResponse {
id: MessageId,
},
UnknownMessageType {
number: String,
},
ConcurrentCall {
id: MessageId,
},
WrongMessageKind {
action: String,
received: MessageKind,
},
WrongDirection {
action: String,
},
NonConformingMessageId {
id: MessageId,
},
DuplicateMessageId {
id: MessageId,
},
TooManyPeerRequests {
id: MessageId,
},
MalformedFrame {
error: FrameError,
},
StoreFailure {
error: StoreError,
},
UnserializableFrame {
reason: String,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum CloseReason {
Drained,
DrainTimedOut,
Requested,
}
#[derive(Clone, Debug)]
pub struct IncomingRequest {
pub id: MessageId,
pub action: String,
pub payload: Box<RawValue>,
pub kind: MessageKind,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum CallFailure {
Rejected(CallError),
Timeout,
Disconnected,
RetriesExhausted,
QueueFull,
Cancelled,
ShuttingDown,
}
impl fmt::Display for CallFailure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
CallFailure::Rejected(error) => write!(f, "peer answered {error}"),
CallFailure::Timeout => f.write_str("no answer before the message timeout"),
CallFailure::Disconnected => f.write_str("connection lost"),
CallFailure::RetriesExhausted => f.write_str("transaction message attempts exhausted"),
CallFailure::QueueFull => f.write_str("offline queue is full"),
CallFailure::Cancelled => f.write_str("cancelled before transmission"),
CallFailure::ShuttingDown => f.write_str("engine is draining"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for CallFailure {}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Answer {
Result(Box<RawValue>),
Sent,
}
impl Answer {
#[must_use]
pub fn payload(&self) -> Option<&RawValue> {
match self {
Answer::Result(payload) => Some(payload),
Answer::Sent => None,
}
}
#[must_use]
pub fn into_payload(self) -> Option<Box<RawValue>> {
match self {
Answer::Result(payload) => Some(payload),
Answer::Sent => None,
}
}
}
#[derive(Clone, Debug)]
pub struct CallOutcome {
pub token: CallToken,
pub id: Option<MessageId>,
pub action: String,
pub result: Result<Answer, CallFailure>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ClockSample {
pub csms_time: DateTime,
pub at: Instant,
}
#[derive(Clone, Debug)]
#[non_exhaustive]
pub enum Output {
Transmit(String),
Request(IncomingRequest),
Outcome(CallOutcome),
ResultRejected {
id: MessageId,
error: CallError,
},
SetTimer {
timer: Timer,
at: Instant,
},
ClearTimer(Timer),
BootState(BootState),
ClockSample(ClockSample),
Violation(ProtocolViolation),
Close(CloseReason),
}
#[derive(Clone, Copy, Debug)]
#[non_exhaustive]
pub enum Input<'a> {
Connected {
version: Version,
},
Received(&'a str),
Disconnected,
Timeout,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum EngineError {
UnknownAction(String),
WrongDirection(String),
SendNotSupported(String),
WrongMessageKind(String),
NoSuchRequest(MessageId),
CallResultErrorNotSupported,
ShuttingDown,
}
impl fmt::Display for EngineError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
EngineError::UnknownAction(action) => write!(f, "unknown action {action:?}"),
EngineError::WrongDirection(action) => {
write!(f, "this peer may not originate {action:?}")
}
EngineError::SendNotSupported(action) => {
write!(f, "{action:?} is a SEND, which needs OCPP 2.1")
}
EngineError::WrongMessageKind(action) => {
write!(f, "{action:?} was submitted with the wrong message kind")
}
EngineError::NoSuchRequest(id) => write!(f, "no outstanding request with id {id}"),
EngineError::CallResultErrorNotSupported => {
f.write_str("CALLRESULTERROR needs OCPP 2.1")
}
EngineError::ShuttingDown => f.write_str("engine is draining"),
}
}
}
#[cfg(feature = "std")]
impl std::error::Error for EngineError {}
#[derive(Debug)]
struct Pending {
token: CallToken,
action: String,
payload: Box<RawValue>,
kind: MessageKind,
transactional: bool,
attempts: u32,
seq: Option<Seq>,
not_before: Option<Instant>,
triggered: bool,
queue_when_offline: bool,
}
#[derive(Debug)]
struct InFlight {
id: MessageId,
token: CallToken,
action: String,
transactional: bool,
attempts: u32,
seq: Option<Seq>,
payload: Box<RawValue>,
triggered: bool,
queue_when_offline: bool,
deadline: Instant,
}
#[derive(Deserialize)]
struct BootAnswer<'a> {
status: &'a str,
#[serde(default)]
interval: Option<u64>,
#[serde(default)]
#[serde(rename = "currentTime")]
current_time: Option<DateTime>,
}
#[derive(Deserialize)]
struct HeartbeatAnswer {
#[serde(rename = "currentTime")]
current_time: DateTime,
}
#[derive(Deserialize)]
struct TriggerRequest<'a> {
#[serde(default)]
#[serde(rename = "requestedMessage")]
requested_message: Option<&'a str>,
}
pub struct Engine<S: MessageStore = MemStore> {
config: EngineConfig,
store: S,
ids: Box<dyn IdGenerator + Send>,
outputs: VecDeque<Output>,
queue: VecDeque<Pending>,
inflight: Option<InFlight>,
peer_inflight: BTreeSet<MessageId>,
connected: bool,
version: Version,
now: Instant,
next_token: u64,
boot: BootState,
heartbeat_interval: Option<Duration>,
solicited: BTreeSet<String>,
draining: Option<Instant>,
boot_retry_at: Option<Instant>,
heartbeat_at: Option<Instant>,
}
impl Engine<MemStore> {
#[must_use]
pub fn new(config: EngineConfig) -> Self {
Self::with_store(config, MemStore::new()).expect("MemStore never fails")
}
}
impl<S: MessageStore> Engine<S> {
pub fn with_store(config: EngineConfig, store: S) -> Result<Self, StoreError> {
let version = config.version;
let mut engine = Self {
config,
store,
ids: default_ids(),
outputs: VecDeque::new(),
queue: VecDeque::new(),
inflight: None,
peer_inflight: BTreeSet::new(),
connected: false,
version,
now: Instant::ZERO,
next_token: 0,
boot: BootState::Idle,
heartbeat_interval: None,
solicited: BTreeSet::new(),
draining: None,
boot_retry_at: None,
heartbeat_at: None,
};
for (seq, entry) in engine.store.pending()? {
let pending = engine.stored(seq, entry);
engine.queue.push_back(pending);
}
Ok(engine)
}
pub fn require_boot(&mut self, now: Instant) {
self.advance(now);
if self.config.role != Role::ChargingStation || self.boot == BootState::Idle {
return;
}
self.boot = BootState::Idle;
self.boot_retry_at = None;
self.outputs.push_back(Output::BootState(BootState::Idle));
}
pub fn adopt_pending(&mut self, now: Instant) -> Result<usize, StoreError> {
self.advance(now);
if self.draining.is_some() {
return Ok(0);
}
let held: BTreeSet<Seq> = self
.queue
.iter()
.filter_map(|entry| entry.seq)
.chain(self.inflight.as_ref().and_then(|inflight| inflight.seq))
.collect();
let mut room = self
.config
.offline
.max_queued
.saturating_sub(self.queue.len());
let mut adopted = 0;
for (seq, entry) in self.store.pending()? {
if held.contains(&seq) {
continue;
}
if room == 0 {
break;
}
let pending = self.stored(seq, entry);
let at = self
.queue
.iter()
.position(|queued| queued.seq.is_some_and(|queued| queued > seq))
.unwrap_or(self.queue.len());
self.queue.insert(at, pending);
room -= 1;
adopted += 1;
}
if adopted > 0 {
self.pump();
}
Ok(adopted)
}
fn stored(&mut self, seq: Seq, entry: QueuedCall) -> Pending {
Pending {
token: self.mint_token(),
action: entry.action,
payload: entry.payload,
kind: entry.kind,
transactional: entry.transactional,
attempts: entry.attempts,
seq: Some(seq),
not_before: None,
triggered: false,
queue_when_offline: true,
}
}
pub fn set_call_timeout(&mut self, timeout: Duration) {
self.config.call_timeout = timeout;
}
pub fn set_id_generator(&mut self, ids: Box<dyn IdGenerator + Send>) {
self.ids = ids;
}
#[must_use]
pub fn config(&self) -> &EngineConfig {
&self.config
}
#[must_use]
pub fn version(&self) -> Version {
self.version
}
#[must_use]
pub fn is_connected(&self) -> bool {
self.connected
}
#[must_use]
pub fn boot_state(&self) -> BootState {
self.boot
}
#[must_use]
pub fn heartbeat_interval(&self) -> Option<Duration> {
self.heartbeat_interval
}
#[must_use]
pub fn queued(&self) -> usize {
self.queue.len()
}
pub fn store(&self) -> &S {
&self.store
}
#[must_use]
pub fn has_outstanding_call(&self) -> bool {
self.inflight.is_some()
}
#[must_use]
pub fn awaiting_response(&self) -> usize {
self.peer_inflight.len()
}
pub fn handle(&mut self, now: Instant, input: Input<'_>) {
self.advance(now);
match input {
Input::Connected { version } => self.on_connected(version),
Input::Received(text) => self.on_received(text),
Input::Disconnected => self.on_disconnected(),
Input::Timeout => self.on_timeout(),
}
}
fn advance(&mut self, now: Instant) {
if now > self.now {
self.now = now;
}
}
#[must_use]
pub fn now(&self) -> Instant {
self.now
}
pub fn poll_output(&mut self) -> Option<Output> {
self.outputs.pop_front()
}
pub fn drain(&mut self) -> Vec<Output> {
self.outputs.drain(..).collect()
}
pub fn call(
&mut self,
now: Instant,
action: &str,
payload: Box<RawValue>,
) -> Result<CallToken, EngineError> {
self.call_with(now, action, payload, CallOptions::default())
}
pub fn call_with(
&mut self,
now: Instant,
action: &str,
payload: Box<RawValue>,
options: CallOptions,
) -> Result<CallToken, EngineError> {
self.advance(now);
if self.draining.is_some() {
return Err(EngineError::ShuttingDown);
}
let Some(kind) = actions::kind(self.version, action) else {
return Err(EngineError::UnknownAction(action.to_string()));
};
let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
if !allows(origin, self.config.role.sends()) {
return Err(EngineError::WrongDirection(action.to_string()));
}
if kind == MessageKind::Send && !self.version.has_extended_message_types() {
return Err(EngineError::SendNotSupported(action.to_string()));
}
let transactional = actions::is_transaction_related(self.version, action);
let persist = options.persist.unwrap_or(transactional);
let queue_when_offline = options
.queue_when_offline
.unwrap_or(transactional || self.config.offline.queue_all_messages);
let token = self.mint_token();
if !self.connected && !queue_when_offline {
self.fail(token, None, action, CallFailure::Disconnected);
return Ok(token);
}
if self.queue.len() >= self.config.offline.max_queued {
self.fail(token, None, action, CallFailure::QueueFull);
return Ok(token);
}
let mut seq = None;
if persist {
let entry = QueuedCall {
action: action.to_string(),
payload: payload.clone(),
kind,
attempts: 0,
transactional,
};
match self.store.push(&entry) {
Ok(value) => seq = Some(value),
Err(error) => {
self.outputs
.push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
self.fail(token, None, action, CallFailure::QueueFull);
return Ok(token);
}
}
}
if self.config.role == Role::Csms {
self.remember_solicited(action, &payload);
}
self.queue.push_back(Pending {
token,
action: action.to_string(),
payload,
kind,
transactional,
attempts: 0,
seq,
not_before: None,
triggered: options.triggered,
queue_when_offline,
});
self.pump();
Ok(token)
}
pub fn respond(
&mut self,
now: Instant,
id: &MessageId,
payload: &RawValue,
) -> Result<(), EngineError> {
self.advance(now);
self.take_peer_request(id)?;
if self.config.role == Role::Csms {
self.observe_boot_answer(payload, true);
}
let frame = Frame::CallResult {
id: id.clone(),
payload: alloc::borrow::Cow::Borrowed(payload),
};
self.transmit(&frame);
Ok(())
}
pub fn respond_error(
&mut self,
now: Instant,
id: &MessageId,
error: CallError,
) -> Result<(), EngineError> {
self.advance(now);
self.take_peer_request(id)?;
let frame = Frame::CallError {
id: id.clone(),
error: error.into(),
};
self.transmit(&frame);
Ok(())
}
pub fn reject_result(
&mut self,
now: Instant,
id: &MessageId,
error: CallError,
) -> Result<(), EngineError> {
self.advance(now);
if !self.version.has_extended_message_types() {
return Err(EngineError::CallResultErrorNotSupported);
}
let frame = Frame::CallResultError {
id: id.clone(),
error: error.into(),
};
self.transmit(&frame);
Ok(())
}
pub fn cancel(&mut self, token: CallToken) -> bool {
let Some(index) = self.queue.iter().position(|entry| entry.token == token) else {
return false;
};
let entry = self.queue.remove(index).expect("index from position");
self.ack_store(entry.seq);
self.outputs.push_back(Output::Outcome(CallOutcome {
token,
id: None,
action: entry.action,
result: Err(CallFailure::Cancelled),
}));
true
}
pub fn shutdown(&mut self, now: Instant, deadline: Instant) {
self.advance(now);
if self.draining.is_some() {
return;
}
self.draining = Some(deadline);
self.outputs.push_back(Output::SetTimer {
timer: Timer::DrainDeadline,
at: deadline,
});
self.check_drain();
}
fn on_connected(&mut self, version: Version) {
self.version = version;
self.connected = true;
self.peer_inflight.clear();
self.arm_heartbeat();
self.pump();
}
fn on_disconnected(&mut self) {
self.connected = false;
self.peer_inflight.clear();
self.outputs
.push_back(Output::ClearTimer(Timer::CallTimeout));
self.outputs.push_back(Output::ClearTimer(Timer::Heartbeat));
self.heartbeat_at = None;
if let Some(inflight) = self.inflight.take() {
self.requeue_or_fail(inflight, CallFailure::Disconnected);
}
let mut kept = VecDeque::with_capacity(self.queue.len());
while let Some(entry) = self.queue.pop_front() {
if entry.queue_when_offline {
kept.push_back(entry);
} else {
self.ack_store(entry.seq);
self.outputs.push_back(Output::Outcome(CallOutcome {
token: entry.token,
id: None,
action: entry.action,
result: Err(CallFailure::Disconnected),
}));
}
}
self.queue = kept;
self.check_drain();
}
fn on_timeout(&mut self) {
let now = self.now;
if let Some(deadline) = self.inflight.as_ref().map(|f| f.deadline) {
if now >= deadline {
let inflight = self.inflight.take().expect("checked");
self.outputs
.push_back(Output::ClearTimer(Timer::CallTimeout));
self.requeue_or_fail(inflight, CallFailure::Timeout);
}
}
if let Some(at) = self.heartbeat_at {
if now >= at {
self.heartbeat_at = None;
if self.connected && self.boot.allows_traffic() {
self.send_heartbeat();
}
self.arm_heartbeat();
}
}
if let Some(at) = self.boot_retry_at {
if now >= at {
self.boot_retry_at = None;
self.boot = BootState::Idle;
self.outputs.push_back(Output::BootState(BootState::Idle));
}
}
if let Some(deadline) = self.draining {
if now >= deadline && !self.drain_complete() {
self.outputs
.push_back(Output::Close(CloseReason::DrainTimedOut));
self.draining = None;
return;
}
}
self.pump();
self.check_drain();
}
fn on_received(&mut self, text: &str) {
self.arm_heartbeat();
let frame = match Frame::parse(text, self.version) {
Ok(frame) => frame,
Err(error) => {
let reply = error.reply(self.version);
let reply_id = error.reply_id();
let code = error.error_code();
self.outputs.push_back(Output::Violation(match &error {
FrameError::UnknownMessageType { number } => {
ProtocolViolation::UnknownMessageType {
number: number.clone(),
}
}
_ => ProtocolViolation::MalformedFrame { error },
}));
let answer = match reply {
FrameReply::Ignore => return,
FrameReply::CallError => Frame::CallError {
id: reply_id,
error: CallError::new(code, "frame could not be processed").into(),
},
FrameReply::CallResultError => Frame::CallResultError {
id: reply_id,
error: CallError::new(code, "result could not be processed").into(),
},
};
self.transmit(&answer);
return;
}
};
if !frame.id().is_conforming() {
self.outputs.push_back(Output::Violation(
ProtocolViolation::NonConformingMessageId {
id: frame.id().clone(),
},
));
}
match frame {
Frame::Call {
id,
action,
payload,
} => {
self.on_call(id, &action, payload.into_owned(), MessageKind::Call);
}
Frame::Send {
id,
action,
payload,
} => {
self.on_call(id, &action, payload.into_owned(), MessageKind::Send);
}
Frame::CallResult { id, payload } => self.on_call_result(&id, payload.into_owned()),
Frame::CallError { id, error } => self.on_call_error(&id, &error),
Frame::CallResultError { id, error } => {
self.outputs.push_back(Output::ResultRejected {
id,
error: error.to_call_error(),
});
}
}
}
fn on_call(
&mut self,
id: MessageId,
action: &str,
payload: Box<RawValue>,
received: MessageKind,
) {
let Some(expected) = actions::kind(self.version, action) else {
self.reject(&id, received, CallError::not_implemented(action));
return;
};
if expected != received {
self.outputs
.push_back(Output::Violation(ProtocolViolation::WrongMessageKind {
action: action.to_string(),
received,
}));
self.reject(
&id,
received,
CallError::new(
ErrorCode::ProtocolError,
format!("{action} is a {expected:?} message, not a {received:?} message"),
),
);
return;
}
let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
if !allows(origin, self.config.role.receives()) {
self.outputs
.push_back(Output::Violation(ProtocolViolation::WrongDirection {
action: action.to_string(),
}));
self.reject(&id, received, CallError::not_supported(action));
return;
}
if received == MessageKind::Call {
if self.peer_inflight.contains(&id) {
self.outputs
.push_back(Output::Violation(ProtocolViolation::DuplicateMessageId {
id: id.clone(),
}));
self.reject(
&id,
received,
CallError::new(
ErrorCode::RpcFrameworkError,
"a CALL with this MessageId is already being handled (Part 4 §4.2.3)",
),
);
return;
}
if !self.peer_inflight.is_empty() {
self.outputs
.push_back(Output::Violation(ProtocolViolation::ConcurrentCall {
id: id.clone(),
}));
let over_limit = self.peer_inflight.len() >= self.config.max_peer_requests;
if over_limit {
self.outputs.push_back(Output::Violation(
ProtocolViolation::TooManyPeerRequests { id: id.clone() },
));
}
if over_limit || self.config.inbound_concurrency == InboundConcurrency::Reject {
self.reject(
&id,
received,
CallError::new(
ErrorCode::ProtocolError,
"a CALL is already outstanding in this direction (Part 4 §4.1.1)",
),
);
return;
}
}
}
if self.config.role == Role::Csms
&& self.config.enforce_boot_gate
&& self.boot.blocks_unsolicited_traffic()
&& action != "BootNotification"
&& !self.solicited.contains(action)
{
self.reject(
&id,
received,
CallError::security(format!(
"{action} is not allowed while the charging station is {:?} (B02.FR.09)",
self.boot
)),
);
return;
}
if self.config.role == Role::Csms && action == "BootNotification" {
self.boot = BootState::Idle;
}
if received == MessageKind::Call {
self.peer_inflight.insert(id.clone());
}
self.outputs.push_back(Output::Request(IncomingRequest {
id,
action: action.to_string(),
payload,
kind: received,
}));
}
fn on_call_result(&mut self, id: &MessageId, payload: Box<RawValue>) {
let Some(inflight) = self.take_inflight(id) else {
self.outputs
.push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
id: id.clone(),
}));
return;
};
self.ack_store(inflight.seq);
self.outputs
.push_back(Output::ClearTimer(Timer::CallTimeout));
match inflight.action.as_str() {
"BootNotification" if self.config.role == Role::ChargingStation => {
self.observe_boot_answer(&payload, false);
}
"Heartbeat" => {
if let Ok(answer) = serde_json::from_str::<HeartbeatAnswer>(payload.get()) {
self.outputs.push_back(Output::ClockSample(ClockSample {
csms_time: answer.current_time,
at: self.now,
}));
}
}
_ => {}
}
self.outputs.push_back(Output::Outcome(CallOutcome {
token: inflight.token,
id: Some(inflight.id),
action: inflight.action,
result: Ok(Answer::Result(payload)),
}));
self.pump();
self.check_drain();
}
fn on_call_error(&mut self, id: &MessageId, error: &CallErrorRef<'_>) {
let Some(inflight) = self.take_inflight(id) else {
self.outputs
.push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
id: id.clone(),
}));
return;
};
self.ack_store(inflight.seq);
self.outputs
.push_back(Output::ClearTimer(Timer::CallTimeout));
self.outputs.push_back(Output::Outcome(CallOutcome {
token: inflight.token,
id: Some(inflight.id),
action: inflight.action,
result: Err(CallFailure::Rejected(error.to_call_error())),
}));
self.pump();
self.check_drain();
}
fn mint_token(&mut self) -> CallToken {
let token = CallToken(self.next_token);
self.next_token += 1;
token
}
fn take_inflight(&mut self, id: &MessageId) -> Option<InFlight> {
match self.inflight.as_ref() {
Some(inflight) if &inflight.id == id => self.inflight.take(),
_ => None,
}
}
fn take_peer_request(&mut self, id: &MessageId) -> Result<(), EngineError> {
if self.peer_inflight.remove(id) {
return Ok(());
}
Err(EngineError::NoSuchRequest(id.clone()))
}
fn reject(&mut self, id: &MessageId, kind: MessageKind, error: CallError) {
if kind == MessageKind::Send {
return;
}
let frame = Frame::CallError {
id: id.clone(),
error: error.into(),
};
self.transmit(&frame);
}
fn transmit(&mut self, frame: &Frame<'_>) {
match frame.to_json(self.version) {
Ok(text) => {
self.outputs.push_back(Output::Transmit(text));
self.arm_heartbeat();
}
Err(error) => {
self.outputs
.push_back(Output::Violation(ProtocolViolation::StoreFailure {
error: StoreError::new(format!("frame could not be serialized: {error}")),
}));
}
}
}
fn ack_store(&mut self, seq: Option<Seq>) {
if let Some(seq) = seq {
if let Err(error) = self.store.ack(seq) {
self.outputs
.push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
}
}
}
fn fail(&mut self, token: CallToken, id: Option<MessageId>, action: &str, why: CallFailure) {
self.outputs.push_back(Output::Outcome(CallOutcome {
token,
id,
action: action.to_string(),
result: Err(why),
}));
}
fn requeue_or_fail(&mut self, inflight: InFlight, why: CallFailure) {
let attempts = inflight.attempts;
if inflight.transactional && self.config.retry.may_retry(attempts) {
let delay = self.config.retry.delay_after(attempts);
let not_before = self.now.saturating_add(delay);
if let Some(seq) = inflight.seq {
if let Err(error) = self.store.set_attempts(seq, attempts) {
self.outputs
.push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
}
}
self.queue.push_front(Pending {
token: inflight.token,
action: inflight.action,
payload: inflight.payload,
kind: MessageKind::Call,
transactional: true,
attempts,
seq: inflight.seq,
not_before: Some(not_before),
triggered: inflight.triggered,
queue_when_offline: inflight.queue_when_offline,
});
self.outputs.push_back(Output::SetTimer {
timer: Timer::TransactionRetry,
at: not_before,
});
return;
}
let why = if inflight.transactional {
CallFailure::RetriesExhausted
} else {
why
};
self.ack_store(inflight.seq);
self.outputs.push_back(Output::Outcome(CallOutcome {
token: inflight.token,
id: Some(inflight.id),
action: inflight.action,
result: Err(why),
}));
}
fn eligible(&self, index: usize) -> bool {
let entry = &self.queue[index];
if entry.not_before.is_some_and(|at| self.now < at) {
return false;
}
if entry.transactional {
let oldest = self
.queue
.iter()
.position(|other| other.transactional)
.expect("this entry is transactional");
if oldest != index {
return false;
}
}
if !self.config.enforce_boot_gate || self.config.role != Role::ChargingStation {
return true;
}
self.boot.allows_traffic() || entry.action == "BootNotification" || entry.triggered
}
fn pump(&mut self) {
if !self.connected {
return;
}
while let Some(index) = (0..self.queue.len())
.find(|index| self.queue[*index].kind == MessageKind::Send && self.eligible(*index))
{
let entry = self.queue.remove(index).expect("index from position");
let id = self.ids.next_id();
let frame = Frame::Send {
id: id.clone(),
action: (&entry.action).into(),
payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
};
self.transmit(&frame);
self.ack_store(entry.seq);
self.outputs.push_back(Output::Outcome(CallOutcome {
token: entry.token,
id: Some(id),
action: entry.action,
result: Ok(Answer::Sent),
}));
}
while self.inflight.is_none() {
let Some(index) = (0..self.queue.len()).find(|index| {
self.queue[*index].kind == MessageKind::Call && self.eligible(*index)
}) else {
break;
};
let entry = self.queue.remove(index).expect("index from position");
let id = self.ids.next_id();
let frame = Frame::Call {
id: id.clone(),
action: (&entry.action).into(),
payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
};
self.transmit(&frame);
let deadline = self.now.saturating_add(self.config.call_timeout);
self.outputs.push_back(Output::SetTimer {
timer: Timer::CallTimeout,
at: deadline,
});
self.inflight = Some(InFlight {
id,
token: entry.token,
action: entry.action,
transactional: entry.transactional,
attempts: entry.attempts + 1,
seq: entry.seq,
payload: entry.payload,
triggered: entry.triggered,
queue_when_offline: entry.queue_when_offline,
deadline,
});
}
}
fn send_heartbeat(&mut self) {
let now = self.now;
let _ = self.call_with(
now,
"Heartbeat",
empty_payload(),
CallOptions::default().queue_when_offline(false),
);
}
fn arm_heartbeat(&mut self) {
if self.config.heartbeat != HeartbeatPolicy::Automatic
|| self.config.role != Role::ChargingStation
{
return;
}
let Some(interval) = self.heartbeat_interval.filter(|d| !d.is_zero()) else {
return;
};
let at = self.now.saturating_add(interval);
if self.heartbeat_at == Some(at) {
return;
}
self.heartbeat_at = Some(at);
self.outputs.push_back(Output::SetTimer {
timer: Timer::Heartbeat,
at,
});
}
fn observe_boot_answer(&mut self, payload: &RawValue, outgoing: bool) {
let Ok(answer) = serde_json::from_str::<BootAnswer<'_>>(payload.get()) else {
return;
};
let state = match answer.status {
"Accepted" => BootState::Accepted,
"Pending" => BootState::Pending,
"Rejected" => BootState::Rejected,
_ => return,
};
self.boot = state;
self.outputs.push_back(Output::BootState(state));
if let Some(time) = answer.current_time {
if !outgoing {
self.outputs.push_back(Output::ClockSample(ClockSample {
csms_time: time,
at: self.now,
}));
}
}
let interval = answer.interval.map(Duration::from_secs);
match state {
BootState::Accepted => {
self.heartbeat_interval = interval.filter(|d| !d.is_zero());
if !outgoing {
self.arm_heartbeat();
self.pump();
}
}
BootState::Pending | BootState::Rejected if !outgoing => {
let wait = interval
.filter(|d| !d.is_zero())
.unwrap_or(self.config.boot_retry_fallback);
let at = self.now.saturating_add(wait);
self.boot_retry_at = Some(at);
self.outputs.push_back(Output::SetTimer {
timer: Timer::BootRetry,
at,
});
}
_ => {}
}
}
fn remember_solicited(&mut self, action: &str, payload: &RawValue) {
if action == "TriggerMessage" || action == "ExtendedTriggerMessage" {
if let Ok(trigger) = serde_json::from_str::<TriggerRequest<'_>>(payload.get()) {
if let Some(requested) = trigger.requested_message {
self.solicited.insert(requested.to_string());
if requested == "SignChargePointCertificate" {
self.solicited.insert("SignCertificate".to_string());
}
}
}
}
for follow_up in actions::solicited_by(self.version, action) {
self.solicited.insert((*follow_up).to_string());
}
}
fn drain_complete(&self) -> bool {
self.inflight.is_none() && self.queue.is_empty()
}
fn check_drain(&mut self) {
if self.draining.is_some() && self.drain_complete() {
self.draining = None;
self.outputs
.push_back(Output::ClearTimer(Timer::DrainDeadline));
self.outputs.push_back(Output::Close(CloseReason::Drained));
}
}
}
fn default_ids() -> Box<dyn IdGenerator + Send> {
#[cfg(feature = "getrandom")]
{
Box::new(crate::types::RandomIds::new())
}
#[cfg(not(feature = "getrandom"))]
{
Box::new(crate::types::CounterIds::default())
}
}
fn allows(origin: Origin, side: Origin) -> bool {
match side {
Origin::ChargingStation => origin.from_charging_station(),
Origin::Csms => origin.from_csms(),
Origin::Both => true,
}
}
fn empty_payload() -> Box<RawValue> {
RawValue::from_string("{}".to_string()).expect("`{}` is valid JSON")
}