1mod backoff;
60mod queue;
61#[cfg(feature = "std")]
62mod store_file;
63mod time;
64
65use alloc::boxed::Box;
66use alloc::collections::{BTreeSet, VecDeque};
67use alloc::format;
68use alloc::string::{String, ToString};
69use alloc::vec::Vec;
70use core::fmt;
71use core::time::Duration;
72
73use serde::Deserialize;
74use serde_json::value::RawValue;
75
76use crate::actions;
77use crate::message::{MessageKind, Origin};
78use crate::rpc::{CallError, CallErrorRef, ErrorCode, Frame, FrameError, FrameReply};
79use crate::types::{DateTime, IdGenerator, MessageId};
80use crate::version::Version;
81
82pub use backoff::{Backoff, Jitter};
83pub use queue::{MemStore, MessageStore, QueuedCall, RetryPolicy, Seq, StoreError};
84#[cfg(feature = "std")]
85pub use store_file::FileStore;
86pub use time::{Instant, Timer};
87
88#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum Role {
91 ChargingStation,
93 Csms,
95}
96
97impl Role {
98 const fn sends(self) -> Origin {
100 match self {
101 Role::ChargingStation => Origin::ChargingStation,
102 Role::Csms => Origin::Csms,
103 }
104 }
105
106 const fn receives(self) -> Origin {
108 match self {
109 Role::ChargingStation => Origin::Csms,
110 Role::Csms => Origin::ChargingStation,
111 }
112 }
113}
114
115#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
120pub enum InboundConcurrency {
121 #[default]
123 Serve,
124 Reject,
126}
127
128#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
130pub enum HeartbeatPolicy {
131 #[default]
138 Automatic,
139 Manual,
141}
142
143#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct OfflinePolicy {
146 pub queue_all_messages: bool,
149 pub max_queued: usize,
152}
153
154impl Default for OfflinePolicy {
155 fn default() -> Self {
156 Self {
157 queue_all_messages: false,
158 max_queued: 1024,
159 }
160 }
161}
162
163#[derive(Clone, Debug)]
165#[non_exhaustive]
166pub struct EngineConfig {
167 pub role: Role,
169 pub version: Version,
171 pub call_timeout: Duration,
177 pub inbound_concurrency: InboundConcurrency,
179 pub heartbeat: HeartbeatPolicy,
181 pub retry: RetryPolicy,
183 pub offline: OfflinePolicy,
185 pub backoff: Backoff,
187 pub enforce_boot_gate: bool,
191 pub boot_retry_fallback: Duration,
194 pub max_peer_requests: usize,
202}
203
204impl EngineConfig {
205 #[must_use]
207 pub fn new(role: Role, version: Version) -> Self {
208 Self {
209 role,
210 version,
211 call_timeout: Duration::from_secs(30),
212 inbound_concurrency: InboundConcurrency::Serve,
213 heartbeat: HeartbeatPolicy::Automatic,
214 retry: RetryPolicy::default(),
215 offline: OfflinePolicy::default(),
216 backoff: Backoff::default(),
217 enforce_boot_gate: true,
218 boot_retry_fallback: Duration::from_secs(30),
219 max_peer_requests: 64,
220 }
221 }
222
223 #[must_use]
225 pub const fn with_call_timeout(mut self, timeout: Duration) -> Self {
226 self.call_timeout = timeout;
227 self
228 }
229
230 #[must_use]
232 pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
233 self.retry = retry;
234 self
235 }
236
237 #[must_use]
239 pub const fn with_offline(mut self, offline: OfflinePolicy) -> Self {
240 self.offline = offline;
241 self
242 }
243
244 #[must_use]
246 pub const fn with_heartbeat(mut self, heartbeat: HeartbeatPolicy) -> Self {
247 self.heartbeat = heartbeat;
248 self
249 }
250
251 #[must_use]
253 pub const fn with_inbound_concurrency(mut self, mode: InboundConcurrency) -> Self {
254 self.inbound_concurrency = mode;
255 self
256 }
257}
258
259#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
261pub enum BootState {
262 #[default]
265 Idle,
266 Pending,
269 Accepted,
271 Rejected,
274}
275
276impl BootState {
277 #[must_use]
282 pub const fn allows_traffic(self) -> bool {
283 matches!(self, BootState::Accepted)
284 }
285
286 #[must_use]
294 pub const fn blocks_unsolicited_traffic(self) -> bool {
295 matches!(self, BootState::Pending | BootState::Rejected)
296 }
297}
298
299#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
304pub struct CallToken(u64);
305
306impl fmt::Display for CallToken {
307 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
308 write!(f, "call#{}", self.0)
309 }
310}
311
312#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
314#[non_exhaustive]
315pub struct CallOptions {
316 pub triggered: bool,
319 pub persist: Option<bool>,
322 pub queue_when_offline: Option<bool>,
325}
326
327impl CallOptions {
328 #[must_use]
330 pub const fn triggered() -> Self {
331 Self {
332 triggered: true,
333 persist: None,
334 queue_when_offline: None,
335 }
336 }
337
338 #[must_use]
340 pub const fn persist(mut self, persist: bool) -> Self {
341 self.persist = Some(persist);
342 self
343 }
344
345 #[must_use]
347 pub const fn queue_when_offline(mut self, queue: bool) -> Self {
348 self.queue_when_offline = Some(queue);
349 self
350 }
351}
352
353#[derive(Clone, Debug, PartialEq, Eq)]
355#[non_exhaustive]
356pub enum ProtocolViolation {
357 UnexpectedResponse {
359 id: MessageId,
361 },
362 UnknownMessageType {
364 number: String,
366 },
367 ConcurrentCall {
369 id: MessageId,
371 },
372 WrongMessageKind {
375 action: String,
377 received: MessageKind,
379 },
380 WrongDirection {
382 action: String,
384 },
385 NonConformingMessageId {
387 id: MessageId,
389 },
390 DuplicateMessageId {
392 id: MessageId,
394 },
395 TooManyPeerRequests {
398 id: MessageId,
400 },
401 MalformedFrame {
403 error: FrameError,
405 },
406 StoreFailure {
408 error: StoreError,
410 },
411 UnserializableFrame {
416 reason: String,
418 },
419}
420
421#[derive(Clone, Debug, PartialEq, Eq)]
423#[non_exhaustive]
424pub enum CloseReason {
425 Drained,
427 DrainTimedOut,
429 Requested,
431}
432
433#[derive(Clone, Debug)]
435pub struct IncomingRequest {
436 pub id: MessageId,
438 pub action: String,
440 pub payload: Box<RawValue>,
442 pub kind: MessageKind,
444}
445
446#[derive(Clone, Debug, PartialEq)]
448#[non_exhaustive]
449pub enum CallFailure {
450 Rejected(CallError),
452 Timeout,
454 Disconnected,
456 RetriesExhausted,
458 QueueFull,
460 Cancelled,
462 ShuttingDown,
464}
465
466impl fmt::Display for CallFailure {
467 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468 match self {
469 CallFailure::Rejected(error) => write!(f, "peer answered {error}"),
470 CallFailure::Timeout => f.write_str("no answer before the message timeout"),
471 CallFailure::Disconnected => f.write_str("connection lost"),
472 CallFailure::RetriesExhausted => f.write_str("transaction message attempts exhausted"),
473 CallFailure::QueueFull => f.write_str("offline queue is full"),
474 CallFailure::Cancelled => f.write_str("cancelled before transmission"),
475 CallFailure::ShuttingDown => f.write_str("engine is draining"),
476 }
477 }
478}
479
480#[cfg(feature = "std")]
481impl std::error::Error for CallFailure {}
482
483#[derive(Clone, Debug)]
488#[non_exhaustive]
489pub enum Answer {
490 Result(Box<RawValue>),
492 Sent,
494}
495
496impl Answer {
497 #[must_use]
499 pub fn payload(&self) -> Option<&RawValue> {
500 match self {
501 Answer::Result(payload) => Some(payload),
502 Answer::Sent => None,
503 }
504 }
505
506 #[must_use]
508 pub fn into_payload(self) -> Option<Box<RawValue>> {
509 match self {
510 Answer::Result(payload) => Some(payload),
511 Answer::Sent => None,
512 }
513 }
514}
515
516#[derive(Clone, Debug)]
518pub struct CallOutcome {
519 pub token: CallToken,
521 pub id: Option<MessageId>,
523 pub action: String,
525 pub result: Result<Answer, CallFailure>,
527}
528
529#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536pub struct ClockSample {
537 pub csms_time: DateTime,
539 pub at: Instant,
541}
542
543#[derive(Clone, Debug)]
545#[non_exhaustive]
546pub enum Output {
547 Transmit(String),
549 Request(IncomingRequest),
552 Outcome(CallOutcome),
554 ResultRejected {
556 id: MessageId,
558 error: CallError,
560 },
561 SetTimer {
563 timer: Timer,
565 at: Instant,
567 },
568 ClearTimer(Timer),
570 BootState(BootState),
572 ClockSample(ClockSample),
574 Violation(ProtocolViolation),
576 Close(CloseReason),
578}
579
580#[derive(Clone, Copy, Debug)]
582#[non_exhaustive]
583pub enum Input<'a> {
584 Connected {
586 version: Version,
588 },
589 Received(&'a str),
591 Disconnected,
593 Timeout,
595}
596
597#[derive(Clone, Debug, PartialEq, Eq)]
599#[non_exhaustive]
600pub enum EngineError {
601 UnknownAction(String),
603 WrongDirection(String),
605 SendNotSupported(String),
607 WrongMessageKind(String),
609 NoSuchRequest(MessageId),
611 CallResultErrorNotSupported,
613 ShuttingDown,
615}
616
617impl fmt::Display for EngineError {
618 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
619 match self {
620 EngineError::UnknownAction(action) => write!(f, "unknown action {action:?}"),
621 EngineError::WrongDirection(action) => {
622 write!(f, "this peer may not originate {action:?}")
623 }
624 EngineError::SendNotSupported(action) => {
625 write!(f, "{action:?} is a SEND, which needs OCPP 2.1")
626 }
627 EngineError::WrongMessageKind(action) => {
628 write!(f, "{action:?} was submitted with the wrong message kind")
629 }
630 EngineError::NoSuchRequest(id) => write!(f, "no outstanding request with id {id}"),
631 EngineError::CallResultErrorNotSupported => {
632 f.write_str("CALLRESULTERROR needs OCPP 2.1")
633 }
634 EngineError::ShuttingDown => f.write_str("engine is draining"),
635 }
636 }
637}
638
639#[cfg(feature = "std")]
640impl std::error::Error for EngineError {}
641
642#[derive(Debug)]
647struct Pending {
648 token: CallToken,
649 action: String,
650 payload: Box<RawValue>,
651 kind: MessageKind,
652 transactional: bool,
653 attempts: u32,
654 seq: Option<Seq>,
656 not_before: Option<Instant>,
658 triggered: bool,
659 queue_when_offline: bool,
660}
661
662#[derive(Debug)]
663struct InFlight {
664 id: MessageId,
665 token: CallToken,
666 action: String,
667 transactional: bool,
668 attempts: u32,
669 seq: Option<Seq>,
670 payload: Box<RawValue>,
671 triggered: bool,
672 queue_when_offline: bool,
673 deadline: Instant,
674}
675
676#[derive(Deserialize)]
682struct BootAnswer<'a> {
683 status: &'a str,
684 #[serde(default)]
685 interval: Option<u64>,
686 #[serde(default)]
687 #[serde(rename = "currentTime")]
688 current_time: Option<DateTime>,
689}
690
691#[derive(Deserialize)]
692struct HeartbeatAnswer {
693 #[serde(rename = "currentTime")]
694 current_time: DateTime,
695}
696
697#[derive(Deserialize)]
698struct TriggerRequest<'a> {
699 #[serde(default)]
700 #[serde(rename = "requestedMessage")]
701 requested_message: Option<&'a str>,
702}
703
704pub struct Engine<S: MessageStore = MemStore> {
708 config: EngineConfig,
709 store: S,
710 ids: Box<dyn IdGenerator + Send>,
711 outputs: VecDeque<Output>,
712 queue: VecDeque<Pending>,
713 inflight: Option<InFlight>,
714 peer_inflight: BTreeSet<MessageId>,
720 connected: bool,
721 version: Version,
722 now: Instant,
723 next_token: u64,
724 boot: BootState,
725 heartbeat_interval: Option<Duration>,
726 solicited: BTreeSet<String>,
729 draining: Option<Instant>,
730 boot_retry_at: Option<Instant>,
731 heartbeat_at: Option<Instant>,
732}
733
734impl Engine<MemStore> {
735 #[must_use]
737 pub fn new(config: EngineConfig) -> Self {
738 Self::with_store(config, MemStore::new()).expect("MemStore never fails")
739 }
740}
741
742impl<S: MessageStore> Engine<S> {
743 pub fn with_store(config: EngineConfig, store: S) -> Result<Self, StoreError> {
748 let version = config.version;
749 let mut engine = Self {
750 config,
751 store,
752 ids: default_ids(),
753 outputs: VecDeque::new(),
754 queue: VecDeque::new(),
755 inflight: None,
756 peer_inflight: BTreeSet::new(),
757 connected: false,
758 version,
759 now: Instant::ZERO,
760 next_token: 0,
761 boot: BootState::Idle,
762 heartbeat_interval: None,
763 solicited: BTreeSet::new(),
764 draining: None,
765 boot_retry_at: None,
766 heartbeat_at: None,
767 };
768 for (seq, entry) in engine.store.pending()? {
769 let token = engine.mint_token();
770 engine.queue.push_back(Pending {
771 token,
772 action: entry.action,
773 payload: entry.payload,
774 kind: entry.kind,
775 transactional: entry.transactional,
776 attempts: entry.attempts,
777 seq: Some(seq),
778 not_before: None,
779 triggered: false,
780 queue_when_offline: true,
781 });
782 }
783 Ok(engine)
784 }
785
786 pub fn set_call_timeout(&mut self, timeout: Duration) {
793 self.config.call_timeout = timeout;
794 }
795
796 pub fn set_id_generator(&mut self, ids: Box<dyn IdGenerator + Send>) {
801 self.ids = ids;
802 }
803
804 #[must_use]
806 pub fn config(&self) -> &EngineConfig {
807 &self.config
808 }
809
810 #[must_use]
812 pub fn version(&self) -> Version {
813 self.version
814 }
815
816 #[must_use]
818 pub fn is_connected(&self) -> bool {
819 self.connected
820 }
821
822 #[must_use]
824 pub fn boot_state(&self) -> BootState {
825 self.boot
826 }
827
828 #[must_use]
830 pub fn heartbeat_interval(&self) -> Option<Duration> {
831 self.heartbeat_interval
832 }
833
834 #[must_use]
838 pub fn queued(&self) -> usize {
839 self.queue.len()
840 }
841
842 pub fn store(&self) -> &S {
844 &self.store
845 }
846
847 #[must_use]
849 pub fn has_outstanding_call(&self) -> bool {
850 self.inflight.is_some()
851 }
852
853 #[must_use]
858 pub fn awaiting_response(&self) -> usize {
859 self.peer_inflight.len()
860 }
861
862 pub fn handle(&mut self, now: Instant, input: Input<'_>) {
870 self.advance(now);
871 match input {
872 Input::Connected { version } => self.on_connected(version),
873 Input::Received(text) => self.on_received(text),
874 Input::Disconnected => self.on_disconnected(),
875 Input::Timeout => self.on_timeout(),
876 }
877 }
878
879 fn advance(&mut self, now: Instant) {
882 if now > self.now {
883 self.now = now;
884 }
885 }
886
887 #[must_use]
889 pub fn now(&self) -> Instant {
890 self.now
891 }
892
893 pub fn poll_output(&mut self) -> Option<Output> {
895 self.outputs.pop_front()
896 }
897
898 pub fn drain(&mut self) -> Vec<Output> {
900 self.outputs.drain(..).collect()
901 }
902
903 pub fn call(
911 &mut self,
912 now: Instant,
913 action: &str,
914 payload: Box<RawValue>,
915 ) -> Result<CallToken, EngineError> {
916 self.call_with(now, action, payload, CallOptions::default())
917 }
918
919 pub fn call_with(
921 &mut self,
922 now: Instant,
923 action: &str,
924 payload: Box<RawValue>,
925 options: CallOptions,
926 ) -> Result<CallToken, EngineError> {
927 self.advance(now);
928 if self.draining.is_some() {
929 return Err(EngineError::ShuttingDown);
930 }
931 let Some(kind) = actions::kind(self.version, action) else {
932 return Err(EngineError::UnknownAction(action.to_string()));
933 };
934 let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
935 if !allows(origin, self.config.role.sends()) {
936 return Err(EngineError::WrongDirection(action.to_string()));
937 }
938 if kind == MessageKind::Send && !self.version.has_extended_message_types() {
939 return Err(EngineError::SendNotSupported(action.to_string()));
940 }
941
942 let transactional = actions::is_transaction_related(self.version, action);
943 let persist = options.persist.unwrap_or(transactional);
944 let queue_when_offline = options
945 .queue_when_offline
946 .unwrap_or(transactional || self.config.offline.queue_all_messages);
947
948 let token = self.mint_token();
949 if !self.connected && !queue_when_offline {
950 self.fail(token, None, action, CallFailure::Disconnected);
954 return Ok(token);
955 }
956 if self.queue.len() >= self.config.offline.max_queued {
957 self.fail(token, None, action, CallFailure::QueueFull);
958 return Ok(token);
959 }
960
961 let mut seq = None;
962 if persist {
963 let entry = QueuedCall {
964 action: action.to_string(),
965 payload: payload.clone(),
966 kind,
967 attempts: 0,
968 transactional,
969 };
970 match self.store.push(&entry) {
971 Ok(value) => seq = Some(value),
972 Err(error) => {
973 self.outputs
974 .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
975 self.fail(token, None, action, CallFailure::QueueFull);
976 return Ok(token);
977 }
978 }
979 }
980
981 if self.config.role == Role::Csms {
984 self.remember_solicited(action, &payload);
985 }
986
987 self.queue.push_back(Pending {
988 token,
989 action: action.to_string(),
990 payload,
991 kind,
992 transactional,
993 attempts: 0,
994 seq,
995 not_before: None,
996 triggered: options.triggered,
997 queue_when_offline,
998 });
999 self.pump();
1000 Ok(token)
1001 }
1002
1003 pub fn respond(
1005 &mut self,
1006 now: Instant,
1007 id: &MessageId,
1008 payload: &RawValue,
1009 ) -> Result<(), EngineError> {
1010 self.advance(now);
1011 self.take_peer_request(id)?;
1012 if self.config.role == Role::Csms {
1014 self.observe_boot_answer(payload, true);
1015 }
1016 let frame = Frame::CallResult {
1017 id: id.clone(),
1018 payload: alloc::borrow::Cow::Borrowed(payload),
1019 };
1020 self.transmit(&frame);
1021 Ok(())
1022 }
1023
1024 pub fn respond_error(
1026 &mut self,
1027 now: Instant,
1028 id: &MessageId,
1029 error: CallError,
1030 ) -> Result<(), EngineError> {
1031 self.advance(now);
1032 self.take_peer_request(id)?;
1033 let frame = Frame::CallError {
1034 id: id.clone(),
1035 error: error.into(),
1036 };
1037 self.transmit(&frame);
1038 Ok(())
1039 }
1040
1041 pub fn reject_result(
1046 &mut self,
1047 now: Instant,
1048 id: &MessageId,
1049 error: CallError,
1050 ) -> Result<(), EngineError> {
1051 self.advance(now);
1052 if !self.version.has_extended_message_types() {
1053 return Err(EngineError::CallResultErrorNotSupported);
1054 }
1055 let frame = Frame::CallResultError {
1056 id: id.clone(),
1057 error: error.into(),
1058 };
1059 self.transmit(&frame);
1060 Ok(())
1061 }
1062
1063 pub fn cancel(&mut self, token: CallToken) -> bool {
1068 let Some(index) = self.queue.iter().position(|entry| entry.token == token) else {
1069 return false;
1070 };
1071 let entry = self.queue.remove(index).expect("index from position");
1072 self.ack_store(entry.seq);
1073 self.outputs.push_back(Output::Outcome(CallOutcome {
1074 token,
1075 id: None,
1076 action: entry.action,
1077 result: Err(CallFailure::Cancelled),
1078 }));
1079 true
1080 }
1081
1082 pub fn shutdown(&mut self, now: Instant, deadline: Instant) {
1088 self.advance(now);
1089 if self.draining.is_some() {
1090 return;
1091 }
1092 self.draining = Some(deadline);
1093 self.outputs.push_back(Output::SetTimer {
1094 timer: Timer::DrainDeadline,
1095 at: deadline,
1096 });
1097 self.check_drain();
1098 }
1099
1100 fn on_connected(&mut self, version: Version) {
1103 self.version = version;
1104 self.connected = true;
1105 self.peer_inflight.clear();
1106 self.arm_heartbeat();
1110 self.pump();
1111 }
1112
1113 fn on_disconnected(&mut self) {
1114 self.connected = false;
1115 self.peer_inflight.clear();
1116 self.outputs
1117 .push_back(Output::ClearTimer(Timer::CallTimeout));
1118 self.outputs.push_back(Output::ClearTimer(Timer::Heartbeat));
1119 self.heartbeat_at = None;
1120
1121 if let Some(inflight) = self.inflight.take() {
1122 self.requeue_or_fail(inflight, CallFailure::Disconnected);
1123 }
1124 let mut kept = VecDeque::with_capacity(self.queue.len());
1126 while let Some(entry) = self.queue.pop_front() {
1127 if entry.queue_when_offline {
1128 kept.push_back(entry);
1129 } else {
1130 self.ack_store(entry.seq);
1131 self.outputs.push_back(Output::Outcome(CallOutcome {
1132 token: entry.token,
1133 id: None,
1134 action: entry.action,
1135 result: Err(CallFailure::Disconnected),
1136 }));
1137 }
1138 }
1139 self.queue = kept;
1140 self.check_drain();
1141 }
1142
1143 fn on_timeout(&mut self) {
1144 let now = self.now;
1145
1146 if let Some(deadline) = self.inflight.as_ref().map(|f| f.deadline) {
1147 if now >= deadline {
1148 let inflight = self.inflight.take().expect("checked");
1149 self.outputs
1150 .push_back(Output::ClearTimer(Timer::CallTimeout));
1151 self.requeue_or_fail(inflight, CallFailure::Timeout);
1152 }
1153 }
1154
1155 if let Some(at) = self.heartbeat_at {
1156 if now >= at {
1157 self.heartbeat_at = None;
1158 if self.connected && self.boot.allows_traffic() {
1159 self.send_heartbeat();
1160 }
1161 self.arm_heartbeat();
1164 }
1165 }
1166
1167 if let Some(at) = self.boot_retry_at {
1168 if now >= at {
1169 self.boot_retry_at = None;
1170 self.boot = BootState::Idle;
1174 self.outputs.push_back(Output::BootState(BootState::Idle));
1175 }
1176 }
1177
1178 if let Some(deadline) = self.draining {
1179 if now >= deadline && !self.drain_complete() {
1180 self.outputs
1181 .push_back(Output::Close(CloseReason::DrainTimedOut));
1182 self.draining = None;
1183 return;
1184 }
1185 }
1186
1187 self.pump();
1188 self.check_drain();
1189 }
1190
1191 fn on_received(&mut self, text: &str) {
1192 self.arm_heartbeat();
1195 let frame = match Frame::parse(text, self.version) {
1196 Ok(frame) => frame,
1197 Err(error) => {
1198 let reply = error.reply(self.version);
1199 let reply_id = error.reply_id();
1200 let code = error.error_code();
1201 self.outputs.push_back(Output::Violation(match &error {
1204 FrameError::UnknownMessageType { number } => {
1205 ProtocolViolation::UnknownMessageType {
1206 number: number.clone(),
1207 }
1208 }
1209 _ => ProtocolViolation::MalformedFrame { error },
1210 }));
1211 let answer = match reply {
1214 FrameReply::Ignore => return,
1215 FrameReply::CallError => Frame::CallError {
1216 id: reply_id,
1217 error: CallError::new(code, "frame could not be processed").into(),
1218 },
1219 FrameReply::CallResultError => Frame::CallResultError {
1220 id: reply_id,
1221 error: CallError::new(code, "result could not be processed").into(),
1222 },
1223 };
1224 self.transmit(&answer);
1225 return;
1226 }
1227 };
1228
1229 if !frame.id().is_conforming() {
1230 self.outputs.push_back(Output::Violation(
1231 ProtocolViolation::NonConformingMessageId {
1232 id: frame.id().clone(),
1233 },
1234 ));
1235 }
1236
1237 match frame {
1238 Frame::Call {
1239 id,
1240 action,
1241 payload,
1242 } => {
1243 self.on_call(id, &action, payload.into_owned(), MessageKind::Call);
1244 }
1245 Frame::Send {
1246 id,
1247 action,
1248 payload,
1249 } => {
1250 self.on_call(id, &action, payload.into_owned(), MessageKind::Send);
1251 }
1252 Frame::CallResult { id, payload } => self.on_call_result(&id, payload.into_owned()),
1253 Frame::CallError { id, error } => self.on_call_error(&id, &error),
1254 Frame::CallResultError { id, error } => {
1255 self.outputs.push_back(Output::ResultRejected {
1256 id,
1257 error: error.to_call_error(),
1258 });
1259 }
1260 }
1261 }
1262
1263 fn on_call(
1264 &mut self,
1265 id: MessageId,
1266 action: &str,
1267 payload: Box<RawValue>,
1268 received: MessageKind,
1269 ) {
1270 let Some(expected) = actions::kind(self.version, action) else {
1271 self.reject(&id, received, CallError::not_implemented(action));
1272 return;
1273 };
1274 if expected != received {
1275 self.outputs
1278 .push_back(Output::Violation(ProtocolViolation::WrongMessageKind {
1279 action: action.to_string(),
1280 received,
1281 }));
1282 self.reject(
1283 &id,
1284 received,
1285 CallError::new(
1286 ErrorCode::ProtocolError,
1287 format!("{action} is a {expected:?} message, not a {received:?} message"),
1288 ),
1289 );
1290 return;
1291 }
1292
1293 let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
1294 if !allows(origin, self.config.role.receives()) {
1295 self.outputs
1296 .push_back(Output::Violation(ProtocolViolation::WrongDirection {
1297 action: action.to_string(),
1298 }));
1299 self.reject(&id, received, CallError::not_supported(action));
1300 return;
1301 }
1302
1303 if received == MessageKind::Call {
1304 if self.peer_inflight.contains(&id) {
1308 self.outputs
1309 .push_back(Output::Violation(ProtocolViolation::DuplicateMessageId {
1310 id: id.clone(),
1311 }));
1312 self.reject(
1313 &id,
1314 received,
1315 CallError::new(
1316 ErrorCode::RpcFrameworkError,
1317 "a CALL with this MessageId is already being handled (Part 4 §4.2.3)",
1318 ),
1319 );
1320 return;
1321 }
1322 if !self.peer_inflight.is_empty() {
1323 self.outputs
1324 .push_back(Output::Violation(ProtocolViolation::ConcurrentCall {
1325 id: id.clone(),
1326 }));
1327 let over_limit = self.peer_inflight.len() >= self.config.max_peer_requests;
1330 if over_limit {
1331 self.outputs.push_back(Output::Violation(
1332 ProtocolViolation::TooManyPeerRequests { id: id.clone() },
1333 ));
1334 }
1335 if over_limit || self.config.inbound_concurrency == InboundConcurrency::Reject {
1336 self.reject(
1337 &id,
1338 received,
1339 CallError::new(
1340 ErrorCode::ProtocolError,
1341 "a CALL is already outstanding in this direction (Part 4 §4.1.1)",
1342 ),
1343 );
1344 return;
1345 }
1346 }
1347 }
1348
1349 if self.config.role == Role::Csms
1356 && self.config.enforce_boot_gate
1357 && self.boot.blocks_unsolicited_traffic()
1358 && action != "BootNotification"
1359 && !self.solicited.contains(action)
1360 {
1361 self.reject(
1362 &id,
1363 received,
1364 CallError::security(format!(
1365 "{action} is not allowed while the charging station is {:?} (B02.FR.09)",
1366 self.boot
1367 )),
1368 );
1369 return;
1370 }
1371
1372 if self.config.role == Role::Csms && action == "BootNotification" {
1373 self.boot = BootState::Idle;
1374 }
1375
1376 if received == MessageKind::Call {
1377 self.peer_inflight.insert(id.clone());
1378 }
1379 self.outputs.push_back(Output::Request(IncomingRequest {
1380 id,
1381 action: action.to_string(),
1382 payload,
1383 kind: received,
1384 }));
1385 }
1386
1387 fn on_call_result(&mut self, id: &MessageId, payload: Box<RawValue>) {
1388 let Some(inflight) = self.take_inflight(id) else {
1389 self.outputs
1390 .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1391 id: id.clone(),
1392 }));
1393 return;
1394 };
1395 self.ack_store(inflight.seq);
1396 self.outputs
1397 .push_back(Output::ClearTimer(Timer::CallTimeout));
1398
1399 match inflight.action.as_str() {
1400 "BootNotification" if self.config.role == Role::ChargingStation => {
1401 self.observe_boot_answer(&payload, false);
1402 }
1403 "Heartbeat" => {
1404 if let Ok(answer) = serde_json::from_str::<HeartbeatAnswer>(payload.get()) {
1405 self.outputs.push_back(Output::ClockSample(ClockSample {
1406 csms_time: answer.current_time,
1407 at: self.now,
1408 }));
1409 }
1410 }
1411 _ => {}
1412 }
1413
1414 self.outputs.push_back(Output::Outcome(CallOutcome {
1415 token: inflight.token,
1416 id: Some(inflight.id),
1417 action: inflight.action,
1418 result: Ok(Answer::Result(payload)),
1419 }));
1420 self.pump();
1421 self.check_drain();
1422 }
1423
1424 fn on_call_error(&mut self, id: &MessageId, error: &CallErrorRef<'_>) {
1425 let Some(inflight) = self.take_inflight(id) else {
1426 self.outputs
1427 .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1428 id: id.clone(),
1429 }));
1430 return;
1431 };
1432 self.ack_store(inflight.seq);
1435 self.outputs
1436 .push_back(Output::ClearTimer(Timer::CallTimeout));
1437 self.outputs.push_back(Output::Outcome(CallOutcome {
1438 token: inflight.token,
1439 id: Some(inflight.id),
1440 action: inflight.action,
1441 result: Err(CallFailure::Rejected(error.to_call_error())),
1442 }));
1443 self.pump();
1444 self.check_drain();
1445 }
1446
1447 fn mint_token(&mut self) -> CallToken {
1450 let token = CallToken(self.next_token);
1451 self.next_token += 1;
1452 token
1453 }
1454
1455 fn take_inflight(&mut self, id: &MessageId) -> Option<InFlight> {
1456 match self.inflight.as_ref() {
1457 Some(inflight) if &inflight.id == id => self.inflight.take(),
1458 _ => None,
1459 }
1460 }
1461
1462 fn take_peer_request(&mut self, id: &MessageId) -> Result<(), EngineError> {
1463 if self.peer_inflight.remove(id) {
1464 return Ok(());
1465 }
1466 Err(EngineError::NoSuchRequest(id.clone()))
1467 }
1468
1469 fn reject(&mut self, id: &MessageId, kind: MessageKind, error: CallError) {
1470 if kind == MessageKind::Send {
1472 return;
1473 }
1474 let frame = Frame::CallError {
1475 id: id.clone(),
1476 error: error.into(),
1477 };
1478 self.transmit(&frame);
1479 }
1480
1481 fn transmit(&mut self, frame: &Frame<'_>) {
1482 match frame.to_json(self.version) {
1483 Ok(text) => {
1484 self.outputs.push_back(Output::Transmit(text));
1485 self.arm_heartbeat();
1486 }
1487 Err(error) => {
1488 self.outputs
1489 .push_back(Output::Violation(ProtocolViolation::StoreFailure {
1490 error: StoreError::new(format!("frame could not be serialized: {error}")),
1491 }));
1492 }
1493 }
1494 }
1495
1496 fn ack_store(&mut self, seq: Option<Seq>) {
1497 if let Some(seq) = seq {
1498 if let Err(error) = self.store.ack(seq) {
1499 self.outputs
1500 .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1501 }
1502 }
1503 }
1504
1505 fn fail(&mut self, token: CallToken, id: Option<MessageId>, action: &str, why: CallFailure) {
1506 self.outputs.push_back(Output::Outcome(CallOutcome {
1507 token,
1508 id,
1509 action: action.to_string(),
1510 result: Err(why),
1511 }));
1512 }
1513
1514 fn requeue_or_fail(&mut self, inflight: InFlight, why: CallFailure) {
1523 let attempts = inflight.attempts;
1524 if inflight.transactional && self.config.retry.may_retry(attempts) {
1525 let delay = self.config.retry.delay_after(attempts);
1526 let not_before = self.now.saturating_add(delay);
1527 if let Some(seq) = inflight.seq {
1528 if let Err(error) = self.store.set_attempts(seq, attempts) {
1529 self.outputs
1530 .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1531 }
1532 }
1533 self.queue.push_front(Pending {
1534 token: inflight.token,
1535 action: inflight.action,
1536 payload: inflight.payload,
1537 kind: MessageKind::Call,
1538 transactional: true,
1539 attempts,
1540 seq: inflight.seq,
1541 not_before: Some(not_before),
1542 triggered: inflight.triggered,
1543 queue_when_offline: inflight.queue_when_offline,
1544 });
1545 self.outputs.push_back(Output::SetTimer {
1546 timer: Timer::TransactionRetry,
1547 at: not_before,
1548 });
1549 return;
1550 }
1551 let why = if inflight.transactional {
1552 CallFailure::RetriesExhausted
1553 } else {
1554 why
1555 };
1556 self.ack_store(inflight.seq);
1557 self.outputs.push_back(Output::Outcome(CallOutcome {
1558 token: inflight.token,
1559 id: Some(inflight.id),
1560 action: inflight.action,
1561 result: Err(why),
1562 }));
1563 }
1564
1565 fn eligible(&self, index: usize) -> bool {
1575 let entry = &self.queue[index];
1576 if entry.not_before.is_some_and(|at| self.now < at) {
1577 return false;
1578 }
1579 if entry.transactional {
1580 let oldest = self
1581 .queue
1582 .iter()
1583 .position(|other| other.transactional)
1584 .expect("this entry is transactional");
1585 if oldest != index {
1586 return false;
1587 }
1588 }
1589 if !self.config.enforce_boot_gate || self.config.role != Role::ChargingStation {
1590 return true;
1591 }
1592 self.boot.allows_traffic() || entry.action == "BootNotification" || entry.triggered
1595 }
1596
1597 fn pump(&mut self) {
1598 if !self.connected {
1599 return;
1600 }
1601
1602 while let Some(index) = (0..self.queue.len())
1605 .find(|index| self.queue[*index].kind == MessageKind::Send && self.eligible(*index))
1606 {
1607 let entry = self.queue.remove(index).expect("index from position");
1608 let id = self.ids.next_id();
1609 let frame = Frame::Send {
1610 id: id.clone(),
1611 action: (&entry.action).into(),
1612 payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1613 };
1614 self.transmit(&frame);
1615 self.ack_store(entry.seq);
1616 self.outputs.push_back(Output::Outcome(CallOutcome {
1617 token: entry.token,
1618 id: Some(id),
1619 action: entry.action,
1620 result: Ok(Answer::Sent),
1621 }));
1622 }
1623
1624 while self.inflight.is_none() {
1625 let Some(index) = (0..self.queue.len()).find(|index| {
1626 self.queue[*index].kind == MessageKind::Call && self.eligible(*index)
1627 }) else {
1628 break;
1629 };
1630 let entry = self.queue.remove(index).expect("index from position");
1631 let id = self.ids.next_id();
1632 let frame = Frame::Call {
1633 id: id.clone(),
1634 action: (&entry.action).into(),
1635 payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1636 };
1637 self.transmit(&frame);
1638 let deadline = self.now.saturating_add(self.config.call_timeout);
1639 self.outputs.push_back(Output::SetTimer {
1640 timer: Timer::CallTimeout,
1641 at: deadline,
1642 });
1643 self.inflight = Some(InFlight {
1644 id,
1645 token: entry.token,
1646 action: entry.action,
1647 transactional: entry.transactional,
1648 attempts: entry.attempts + 1,
1649 seq: entry.seq,
1650 payload: entry.payload,
1651 triggered: entry.triggered,
1652 queue_when_offline: entry.queue_when_offline,
1653 deadline,
1654 });
1655 }
1656 }
1657
1658 fn send_heartbeat(&mut self) {
1659 let now = self.now;
1661 let _ = self.call_with(
1662 now,
1663 "Heartbeat",
1664 empty_payload(),
1665 CallOptions::default().queue_when_offline(false),
1666 );
1667 }
1668
1669 fn arm_heartbeat(&mut self) {
1677 if self.config.heartbeat != HeartbeatPolicy::Automatic
1678 || self.config.role != Role::ChargingStation
1679 {
1680 return;
1681 }
1682 let Some(interval) = self.heartbeat_interval.filter(|d| !d.is_zero()) else {
1683 return;
1684 };
1685 let at = self.now.saturating_add(interval);
1686 if self.heartbeat_at == Some(at) {
1687 return;
1688 }
1689 self.heartbeat_at = Some(at);
1690 self.outputs.push_back(Output::SetTimer {
1691 timer: Timer::Heartbeat,
1692 at,
1693 });
1694 }
1695
1696 fn observe_boot_answer(&mut self, payload: &RawValue, outgoing: bool) {
1698 let Ok(answer) = serde_json::from_str::<BootAnswer<'_>>(payload.get()) else {
1699 return;
1700 };
1701 let state = match answer.status {
1702 "Accepted" => BootState::Accepted,
1703 "Pending" => BootState::Pending,
1704 "Rejected" => BootState::Rejected,
1705 _ => return,
1706 };
1707 self.boot = state;
1708 self.outputs.push_back(Output::BootState(state));
1709
1710 if let Some(time) = answer.current_time {
1711 if !outgoing {
1712 self.outputs.push_back(Output::ClockSample(ClockSample {
1713 csms_time: time,
1714 at: self.now,
1715 }));
1716 }
1717 }
1718
1719 let interval = answer.interval.map(Duration::from_secs);
1720 match state {
1721 BootState::Accepted => {
1722 self.heartbeat_interval = interval.filter(|d| !d.is_zero());
1723 if !outgoing {
1724 self.arm_heartbeat();
1725 self.pump();
1726 }
1727 }
1728 BootState::Pending | BootState::Rejected if !outgoing => {
1729 let wait = interval
1732 .filter(|d| !d.is_zero())
1733 .unwrap_or(self.config.boot_retry_fallback);
1734 let at = self.now.saturating_add(wait);
1735 self.boot_retry_at = Some(at);
1736 self.outputs.push_back(Output::SetTimer {
1737 timer: Timer::BootRetry,
1738 at,
1739 });
1740 }
1741 _ => {}
1742 }
1743 }
1744
1745 fn remember_solicited(&mut self, action: &str, payload: &RawValue) {
1747 if action == "TriggerMessage" || action == "ExtendedTriggerMessage" {
1748 if let Ok(trigger) = serde_json::from_str::<TriggerRequest<'_>>(payload.get()) {
1749 if let Some(requested) = trigger.requested_message {
1750 self.solicited.insert(requested.to_string());
1751 if requested == "SignChargePointCertificate" {
1754 self.solicited.insert("SignCertificate".to_string());
1755 }
1756 }
1757 }
1758 }
1759 for follow_up in actions::solicited_by(self.version, action) {
1760 self.solicited.insert((*follow_up).to_string());
1761 }
1762 }
1763
1764 fn drain_complete(&self) -> bool {
1765 self.inflight.is_none() && self.queue.is_empty()
1766 }
1767
1768 fn check_drain(&mut self) {
1769 if self.draining.is_some() && self.drain_complete() {
1770 self.draining = None;
1771 self.outputs
1772 .push_back(Output::ClearTimer(Timer::DrainDeadline));
1773 self.outputs.push_back(Output::Close(CloseReason::Drained));
1774 }
1775 }
1776}
1777
1778fn default_ids() -> Box<dyn IdGenerator + Send> {
1785 #[cfg(feature = "getrandom")]
1786 {
1787 Box::new(crate::types::RandomIds::new())
1788 }
1789 #[cfg(not(feature = "getrandom"))]
1790 {
1791 Box::new(crate::types::CounterIds::default())
1792 }
1793}
1794
1795fn allows(origin: Origin, side: Origin) -> bool {
1796 match side {
1797 Origin::ChargingStation => origin.from_charging_station(),
1798 Origin::Csms => origin.from_csms(),
1799 Origin::Both => true,
1800 }
1801}
1802
1803fn empty_payload() -> Box<RawValue> {
1804 RawValue::from_string("{}".to_string()).expect("`{}` is valid JSON")
1805}