Skip to main content

ocpp_kit/engine/
mod.rs

1//! Layer 2 — the sans-I/O protocol engine.
2//!
3//! [`Engine`] is a pure state machine. It owns no socket, reads no clock and spawns no task:
4//! the driver feeds it [`Input`]s and drains [`Output`]s. That is what makes every timing
5//! rule in OCPP — message timeouts, the linear transaction-retry schedule, boot back-off —
6//! testable in microseconds, and what lets the same code run on Tokio, inside an `embassy`
7//! firmware loop, or in a browser.
8//!
9//! Every entry point takes the driver's current [`Instant`]: the engine has no clock of its
10//! own, and a deadline armed against a stale one fires the moment it is armed.
11//!
12//! ```
13//! use ocpp_kit::Version;
14//! use ocpp_kit::engine::{Engine, EngineConfig, Input, Instant, Output, Role};
15//! use serde_json::value::RawValue;
16//!
17//! let now = Instant::ZERO;
18//! let mut engine = Engine::new(EngineConfig::new(Role::ChargingStation, Version::V2_1));
19//! engine.handle(now, Input::Connected { version: Version::V2_1 });
20//!
21//! let payload = RawValue::from_string(
22//!     r#"{"reason":"PowerUp","chargingStation":{"model":"M1","vendorName":"ACME"}}"#.into(),
23//! )
24//! .unwrap();
25//! engine.call(now, "BootNotification", payload).unwrap();
26//!
27//! let frame = engine
28//!     .drain()
29//!     .into_iter()
30//!     .find_map(|output| match output {
31//!         Output::Transmit(text) => Some(text),
32//!         _ => None,
33//!     })
34//!     .unwrap();
35//! assert!(frame.starts_with(r#"[2,"#));
36//! ```
37//!
38//! In a test, [`Sim`](crate::testkit::Sim) owns the clock for you and the same session reads
39//! as a transcript.
40//!
41//! # Rules this layer enforces
42//!
43//! * **One outstanding `CALL` per direction** (2.x Part 4 §4.1.1 `SHALL NOT`; 1.6J §4.1.1
44//!   `SHOULD NOT` — hence [`InboundConcurrency`]). Our own extra calls are queued, never
45//!   rejected.
46//! * **`SEND` is exempt** and is never answered (Part 4 §4.2.4, FR.07).
47//! * **Unknown message type numbers** are ignored on every version (1.6J §4.1.3, 2.x
48//!   Part 4 §4.1).
49//! * **Message timeout**, freeing the slot and starting the next queued call.
50//! * **Transaction-message retries only**, on the linear schedule of 1.6 §3.7.1 and the 2.x
51//!   `MessageAttempts[TransactionEvent]` variables, in chronological order, skipping a
52//!   message once its attempts are exhausted.
53//! * **Durable offline queueing** of transaction messages (E04/E08/E12) via
54//!   [`MessageStore`] — [`MemStore`] in memory, [`FileStore`] on disk, or your own.
55//! * **The boot state machine** (B01–B04) on *both* sides, including the CSMS's
56//!   `SecurityError` answer to an unsolicited call from a `Pending` station (B02.FR.09).
57//! * **Graceful drain**: finish the in-flight call, flush the queue, then close.
58
59mod 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/// Which side of the connection this engine is.
89#[derive(Clone, Copy, Debug, PartialEq, Eq)]
90pub enum Role {
91    /// A Charging Station: it dials out, and it boots.
92    ChargingStation,
93    /// A CSMS: it accepts connections and decides whether a station may proceed.
94    Csms,
95}
96
97impl Role {
98    /// The origin this engine is allowed to send.
99    const fn sends(self) -> Origin {
100        match self {
101            Role::ChargingStation => Origin::ChargingStation,
102            Role::Csms => Origin::Csms,
103        }
104    }
105
106    /// The origin this engine expects to receive.
107    const fn receives(self) -> Origin {
108        match self {
109            Role::ChargingStation => Origin::Csms,
110            Role::Csms => Origin::ChargingStation,
111        }
112    }
113}
114
115/// What to do when the peer breaks the one-outstanding-`CALL` rule.
116///
117/// 1.6J §4.1.1 words it as `SHOULD NOT`, 2.x Part 4 §4.1.1 as `SHALL NOT`. Field stations
118/// break it either way, and dropping their calls is usually worse than serving them.
119#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
120pub enum InboundConcurrency {
121    /// Answer the extra call normally. The default, and the only workable choice on 1.6.
122    #[default]
123    Serve,
124    /// Answer the extra call with `CALLERROR: ProtocolError`.
125    Reject,
126}
127
128/// Whether the engine sends `Heartbeat` on its own.
129#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
130pub enum HeartbeatPolicy {
131    /// The engine schedules and sends `Heartbeat` itself.
132    ///
133    /// `OCPPCommCtrlr.HeartbeatInterval` is defined as the *interval of inactivity* — "no
134    /// OCPP exchanges" — after which a station sends `Heartbeat`, so the timer is an idle
135    /// timer that every frame in either direction resets, not a fixed period. The payload is
136    /// an empty object in every version, so no application code is needed.
137    #[default]
138    Automatic,
139    /// The application sends `Heartbeat` itself; the engine only reports the interval.
140    Manual,
141}
142
143/// What happens to outgoing calls while the connection is down.
144#[derive(Clone, Copy, Debug, PartialEq, Eq)]
145pub struct OfflinePolicy {
146    /// Queue every message, not just transaction-related ones — the 1.6
147    /// `QueueAllMessages` behaviour.
148    pub queue_all_messages: bool,
149    /// Upper bound on the in-memory queue. Reached, further calls fail with
150    /// [`CallFailure::QueueFull`] instead of growing without limit.
151    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/// Engine configuration.
164#[derive(Clone, Debug)]
165#[non_exhaustive]
166pub struct EngineConfig {
167    /// Which side this is.
168    pub role: Role,
169    /// The negotiated protocol version.
170    pub version: Version,
171    /// How long to wait for a `CALLRESULT` / `CALLERROR`.
172    ///
173    /// The specification deliberately leaves this implementation-defined (Part 4 §4.1.1);
174    /// 2.x sources it from `NetworkConnectionProfile.messageTimeout`, falling back to
175    /// `OCPPCommCtrlr.MessageTimeout[Default]`. 30 s is the widely used default.
176    pub call_timeout: Duration,
177    /// What to do about a peer that keeps two calls in flight.
178    pub inbound_concurrency: InboundConcurrency,
179    /// Whether the engine sends `Heartbeat` itself.
180    pub heartbeat: HeartbeatPolicy,
181    /// Retry schedule for transaction-related messages.
182    pub retry: RetryPolicy,
183    /// Offline queueing behaviour.
184    pub offline: OfflinePolicy,
185    /// Reconnect back-off parameters, for the driver to use (Part 4 §5.4).
186    pub backoff: Backoff,
187    /// Whether the boot state machine gates outgoing calls (B02.FR.02).
188    ///
189    /// Always on for a Charging Station; a CSMS uses it to enforce B02.FR.09.
190    pub enforce_boot_gate: bool,
191    /// How long to wait before re-sending `BootNotification` when the CSMS answered
192    /// `Pending` or `Rejected` with `interval = 0` (B02.FR.07).
193    pub boot_retry_fallback: Duration,
194    /// Upper bound on the peer's simultaneously unanswered `CALL`s.
195    ///
196    /// The specification allows exactly one (Part 4 §4.1.1), and
197    /// [`InboundConcurrency::Serve`] deliberately tolerates more — but "more" must still be
198    /// finite, or a peer that never stops asking can make the receiver hold requests, and
199    /// handler tasks, without limit. Beyond this many the extra call is answered
200    /// `ProtocolError` regardless of [`InboundConcurrency`].
201    pub max_peer_requests: usize,
202}
203
204impl EngineConfig {
205    /// A configuration with the specification's defaults.
206    #[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    /// Sets the message timeout.
224    #[must_use]
225    pub const fn with_call_timeout(mut self, timeout: Duration) -> Self {
226        self.call_timeout = timeout;
227        self
228    }
229
230    /// Sets the transaction retry schedule.
231    #[must_use]
232    pub const fn with_retry(mut self, retry: RetryPolicy) -> Self {
233        self.retry = retry;
234        self
235    }
236
237    /// Sets the offline queueing policy.
238    #[must_use]
239    pub const fn with_offline(mut self, offline: OfflinePolicy) -> Self {
240        self.offline = offline;
241        self
242    }
243
244    /// Sets the heartbeat policy.
245    #[must_use]
246    pub const fn with_heartbeat(mut self, heartbeat: HeartbeatPolicy) -> Self {
247        self.heartbeat = heartbeat;
248        self
249    }
250
251    /// Sets what happens when the peer keeps two calls in flight.
252    #[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/// The boot state machine (OCPP 2.x block B; 1.6 §4.2).
260#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
261pub enum BootState {
262    /// No `BootNotification` has been answered yet. Only `BootNotification` and messages the
263    /// CSMS explicitly asked for may be sent (B02.FR.02).
264    #[default]
265    Idle,
266    /// The CSMS answered `Pending`: it is still configuring the station. The connection
267    /// stays open (B02.FR.06) and the station may only answer what it is asked.
268    Pending,
269    /// The CSMS answered `Accepted`. Normal operation.
270    Accepted,
271    /// The CSMS answered `Rejected`. The station must wait for the interval before trying
272    /// again (B02.FR.08).
273    Rejected,
274}
275
276impl BootState {
277    /// Whether ordinary, unsolicited calls may be sent.
278    ///
279    /// Only `Accepted` does: B01.FR.08 keeps a freshly powered station quiet until the CSMS
280    /// answers, and B02.FR.02 keeps it quiet while the answer is `Pending`.
281    #[must_use]
282    pub const fn allows_traffic(self) -> bool {
283        matches!(self, BootState::Accepted)
284    }
285
286    /// Whether a *CSMS* must answer an unsolicited call with `SecurityError`.
287    ///
288    /// B01.FR.10 and B02.FR.09 both have the same precondition: *the Charging Station has
289    /// received a `BootNotificationResponse` whose status is not `Accepted`*. A station that
290    /// has not been answered at all — the normal state of a reconnected station, which
291    /// Part 4 §5.4 tells not to repeat its `BootNotification` — is therefore not covered,
292    /// and blocking it would break every reconnect.
293    #[must_use]
294    pub const fn blocks_unsolicited_traffic(self) -> bool {
295        matches!(self, BootState::Pending | BootState::Rejected)
296    }
297}
298
299/// A handle to a call the application asked for.
300///
301/// Issued when the call is accepted — which may be long before it reaches the wire, since it
302/// can sit in the offline queue — and reported back in [`CallOutcome`].
303#[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/// Per-call overrides.
313#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
314#[non_exhaustive]
315pub struct CallOptions {
316    /// The CSMS asked for this message (`TriggerMessage`, `GetBaseReport`, …), so the boot
317    /// gate does not apply to it (B02.FR.02).
318    pub triggered: bool,
319    /// Override whether the message is queued durably. Defaults to "yes for
320    /// transaction-related messages".
321    pub persist: Option<bool>,
322    /// Override whether the message survives a disconnection. Defaults to the
323    /// [`OfflinePolicy`].
324    pub queue_when_offline: Option<bool>,
325}
326
327impl CallOptions {
328    /// Marks the call as one the peer explicitly requested.
329    #[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    /// Overrides whether the call is written to the durable [`MessageStore`].
339    #[must_use]
340    pub const fn persist(mut self, persist: bool) -> Self {
341        self.persist = Some(persist);
342        self
343    }
344
345    /// Overrides whether the call waits out a disconnection instead of failing.
346    #[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/// Something the peer did that the specification forbids, but which is not fatal.
354#[derive(Clone, Debug, PartialEq, Eq)]
355#[non_exhaustive]
356pub enum ProtocolViolation {
357    /// A `CALLRESULT` / `CALLERROR` arrived for an id that is not outstanding.
358    UnexpectedResponse {
359        /// The id that was answered.
360        id: MessageId,
361    },
362    /// A message type number outside 2–6 (Part 4 §4.4).
363    UnknownMessageType {
364        /// The raw JSON of the type element.
365        number: String,
366    },
367    /// The peer started a second `CALL` while one was still outstanding.
368    ConcurrentCall {
369        /// The id of the extra call.
370        id: MessageId,
371    },
372    /// The peer sent an action defined as a `SEND` as a `CALL`, or the other way round
373    /// (N15.FR.01).
374    WrongMessageKind {
375        /// The action name.
376        action: String,
377        /// The kind it arrived as.
378        received: MessageKind,
379    },
380    /// The peer sent an action it is not allowed to originate.
381    WrongDirection {
382        /// The action name.
383        action: String,
384    },
385    /// The peer used a `MessageId` longer than 36 characters.
386    NonConformingMessageId {
387        /// The id, kept verbatim so responses still correlate.
388        id: MessageId,
389    },
390    /// The peer reused a `MessageId` that is still unanswered (Part 4 §4.1.4, §4.2.3).
391    DuplicateMessageId {
392        /// The id that was reused.
393        id: MessageId,
394    },
395    /// The peer has more unanswered `CALL`s than
396    /// [`EngineConfig::max_peer_requests`] allows.
397    TooManyPeerRequests {
398        /// The id of the call that went over the limit.
399        id: MessageId,
400    },
401    /// The frame could not be parsed at all.
402    MalformedFrame {
403        /// The parse failure.
404        error: FrameError,
405    },
406    /// The durable store failed.
407    StoreFailure {
408        /// The store's complaint.
409        error: StoreError,
410    },
411    /// A frame this peer wanted to send could not be serialized.
412    ///
413    /// Only reachable from a payload the application supplied, since everything else the
414    /// engine builds is known-good JSON.
415    UnserializableFrame {
416        /// What `serde_json` said.
417        reason: String,
418    },
419}
420
421/// Why the engine wants the connection closed.
422#[derive(Clone, Debug, PartialEq, Eq)]
423#[non_exhaustive]
424pub enum CloseReason {
425    /// A graceful drain finished.
426    Drained,
427    /// The drain deadline passed with work still queued.
428    DrainTimedOut,
429    /// The application asked for it.
430    Requested,
431}
432
433/// A request the peer sent that the application must handle.
434#[derive(Clone, Debug)]
435pub struct IncomingRequest {
436    /// Correlation id. Pass it back to [`Engine::respond`].
437    pub id: MessageId,
438    /// The action name, already checked against the version and the direction.
439    pub action: String,
440    /// The still-unparsed payload.
441    pub payload: Box<RawValue>,
442    /// `Call` (answer it) or `Send` (do not).
443    pub kind: MessageKind,
444}
445
446/// Why a call did not succeed.
447#[derive(Clone, Debug, PartialEq)]
448#[non_exhaustive]
449pub enum CallFailure {
450    /// The peer answered `CALLERROR`.
451    Rejected(CallError),
452    /// No answer arrived before [`EngineConfig::call_timeout`].
453    Timeout,
454    /// The connection went away and the message was not queued.
455    Disconnected,
456    /// A transaction message used up its attempts and was skipped (1.6 §3.7.1).
457    RetriesExhausted,
458    /// The offline queue is full.
459    QueueFull,
460    /// The application withdrew the call before it was transmitted.
461    Cancelled,
462    /// The engine is draining and refused a new call.
463    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/// How a message the application started ended, when it ended well.
484///
485/// A `CALL` succeeds when the peer answers; a `SEND` when it is written, because Part 4
486/// §4.2.4 forbids the peer from ever answering one.
487#[derive(Clone, Debug)]
488#[non_exhaustive]
489pub enum Answer {
490    /// The peer's `CALLRESULT` payload.
491    Result(Box<RawValue>),
492    /// A `SEND` reached the wire. There is nothing further to wait for.
493    Sent,
494}
495
496impl Answer {
497    /// The peer's payload, or `None` for a `SEND`.
498    #[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    /// Unwraps the peer's payload, or `None` for a `SEND`.
507    #[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/// The final result of a call the application started.
517#[derive(Clone, Debug)]
518pub struct CallOutcome {
519    /// The handle returned by [`Engine::call`].
520    pub token: CallToken,
521    /// The `MessageId` it was sent with, if it ever reached the wire.
522    pub id: Option<MessageId>,
523    /// The action.
524    pub action: String,
525    /// How it ended.
526    pub result: Result<Answer, CallFailure>,
527}
528
529/// An authoritative timestamp observed in a `BootNotificationResponse` or
530/// `HeartbeatResponse`.
531///
532/// A station whose `ClockCtrlr.TimeSource` is `Heartbeat` uses this to discipline its clock;
533/// `at` is the monotonic instant the answer arrived, so the application can subtract the
534/// round-trip.
535#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536pub struct ClockSample {
537    /// The CSMS's `currentTime`.
538    pub csms_time: DateTime,
539    /// When the answer was processed, on the driver's monotonic clock.
540    pub at: Instant,
541}
542
543/// What the driver must do next.
544#[derive(Clone, Debug)]
545#[non_exhaustive]
546pub enum Output {
547    /// Write this UTF-8 text frame to the WebSocket.
548    Transmit(String),
549    /// The peer sent a request. Answer a `Call` with [`Engine::respond`]; a `Send` needs no
550    /// answer and must not get one.
551    Request(IncomingRequest),
552    /// One of our calls finished.
553    Outcome(CallOutcome),
554    /// The peer rejected a `CALLRESULT` we sent, with `CALLRESULTERROR` (OCPP 2.1).
555    ResultRejected {
556        /// The id of the result the peer could not use.
557        id: MessageId,
558        /// Why.
559        error: CallError,
560    },
561    /// Arm a timer. Re-arming an already-armed timer replaces it.
562    SetTimer {
563        /// Which timer.
564        timer: Timer,
565        /// When it should fire, on the driver's monotonic clock.
566        at: Instant,
567    },
568    /// Disarm a timer.
569    ClearTimer(Timer),
570    /// The boot state changed (Charging Station side), or was decided (CSMS side).
571    BootState(BootState),
572    /// A `currentTime` was observed.
573    ClockSample(ClockSample),
574    /// The peer misbehaved. Never fatal by itself; log it and carry on.
575    Violation(ProtocolViolation),
576    /// Close the connection.
577    Close(CloseReason),
578}
579
580/// Events the driver feeds into the engine, via [`Engine::handle`].
581#[derive(Clone, Copy, Debug)]
582#[non_exhaustive]
583pub enum Input<'a> {
584    /// The WebSocket handshake completed with this negotiated version.
585    Connected {
586        /// The subprotocol the peer selected.
587        version: Version,
588    },
589    /// One complete text frame arrived.
590    Received(&'a str),
591    /// The connection went away.
592    Disconnected,
593    /// Nothing happened but time. Every timer whose deadline has passed fires.
594    Timeout,
595}
596
597/// Why a command was refused.
598#[derive(Clone, Debug, PartialEq, Eq)]
599#[non_exhaustive]
600pub enum EngineError {
601    /// This version does not define the action.
602    UnknownAction(String),
603    /// This peer is not allowed to originate the action.
604    WrongDirection(String),
605    /// A `SEND` was requested on a version that has no `SEND` (before 2.1).
606    SendNotSupported(String),
607    /// The action is a `SEND` but was submitted as a call, or the other way round.
608    WrongMessageKind(String),
609    /// No outstanding request has that id.
610    NoSuchRequest(MessageId),
611    /// `CALLRESULTERROR` needs OCPP 2.1.
612    CallResultErrorNotSupported,
613    /// The engine is draining.
614    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// ---------------------------------------------------------------------------
643// Internal state
644// ---------------------------------------------------------------------------
645
646#[derive(Debug)]
647struct Pending {
648    token: CallToken,
649    action: String,
650    payload: Box<RawValue>,
651    kind: MessageKind,
652    transactional: bool,
653    attempts: u32,
654    /// Sequence number in the durable store, when persisted.
655    seq: Option<Seq>,
656    /// Not eligible for transmission before this instant (retry back-off).
657    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/// Minimal view of a `BootNotificationResponse`, the one payload the engine looks inside.
677///
678/// The three members it needs have the same names and meanings in 1.6 and 2.x, so one shape
679/// covers every version. Nothing else is parsed, and a payload that does not match is
680/// ignored rather than treated as an error — the application still sees it in full.
681#[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
704/// The sans-I/O OCPP protocol engine.
705///
706/// See the [module documentation](self) for the rules it enforces.
707pub 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    /// The ids of the `CALL`s the peer is waiting on.
715    ///
716    /// Normally at most one — that is the rule — but [`InboundConcurrency::Serve`] means a
717    /// peer that breaks it is answered anyway, and every one of its calls still has to be
718    /// matched to its answer.
719    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    /// Actions the CSMS asked this station for, which therefore survive the boot gate
727    /// (B02.FR.09).
728    solicited: BTreeSet<String>,
729    draining: Option<Instant>,
730    boot_retry_at: Option<Instant>,
731    heartbeat_at: Option<Instant>,
732}
733
734impl Engine<MemStore> {
735    /// An engine with an in-memory queue.
736    #[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    /// An engine backed by a durable [`MessageStore`].
744    ///
745    /// Anything the store still holds is loaded into the queue, so a Charging Station
746    /// replays the transaction messages a power cut interrupted.
747    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 pending = engine.stored(seq, entry);
770            engine.queue.push_back(pending);
771        }
772        Ok(engine)
773    }
774
775    /// Re-opens the boot gate, so the station registers again before ordinary traffic.
776    ///
777    /// The engine keeps its boot state across reconnects (Part 4 §5.4). The exception is
778    /// B10.FR.10 (2.0.1 edition 4, 2.1 edition 2): a station that "successfully connected after
779    /// having switched to a different `NetworkConnectionProfile`" SHALL send a
780    /// `BootNotificationRequest` "even if it has not rebooted". This returns the engine to
781    /// [`BootState::Idle`] and reports it as [`Output::BootState`], the same signal a
782    /// `Pending`/`Rejected` retry gives; the application then sends the `BootNotification`.
783    /// The Tokio station calls it when it connects on a different configuration slot.
784    pub fn require_boot(&mut self, now: Instant) {
785        self.advance(now);
786        if self.config.role != Role::ChargingStation || self.boot == BootState::Idle {
787            return;
788        }
789        self.boot = BootState::Idle;
790        self.boot_retry_at = None;
791        self.outputs.push_back(Output::BootState(BootState::Idle));
792    }
793
794    /// Queues what another process added to the store since this engine was built.
795    ///
796    /// The engine reads its store when it is built ([`with_store`](Self::with_store)) and
797    /// otherwise only writes it. With a store shared between processes — a station and a
798    /// metering daemon on one SQLite file — a message the other process pushes is durable at
799    /// once but would leave only on the next start. This reads [`MessageStore::pending`] again
800    /// and queues every entry whose [`Seq`] the engine does not already hold, queued or in
801    /// flight, so calling it twice queues nothing twice.
802    ///
803    /// Among messages not yet sent, stored ones are ordered by `Seq`, so each producer's
804    /// messages leave in the order it pushed them — what per-transaction ordering requires
805    /// (1.6 §3.7, E04.FR.01–03), since one transaction's messages come from one producer. A
806    /// message already sent is never reordered. Adoption obeys
807    /// [`OfflinePolicy::max_queued`]: what does not fit stays in the store, still counted by
808    /// [`MessageStore::len`], and is adopted by a later call. During a
809    /// [`shutdown`](Self::shutdown) drain nothing is adopted.
810    ///
811    /// Only one engine may drain a store. A second one would adopt — and send — every entry
812    /// the first holds; other processes push and never drain.
813    ///
814    /// Returns how many entries were queued. The Tokio station calls this on connect and
815    /// periodically when built with `store_poll`.
816    ///
817    /// # Errors
818    ///
819    /// The store's error from `pending()`. The queue is unchanged.
820    pub fn adopt_pending(&mut self, now: Instant) -> Result<usize, StoreError> {
821        self.advance(now);
822        if self.draining.is_some() {
823            return Ok(0);
824        }
825        let held: BTreeSet<Seq> = self
826            .queue
827            .iter()
828            .filter_map(|entry| entry.seq)
829            .chain(self.inflight.as_ref().and_then(|inflight| inflight.seq))
830            .collect();
831        let mut room = self
832            .config
833            .offline
834            .max_queued
835            .saturating_sub(self.queue.len());
836        let mut adopted = 0;
837        for (seq, entry) in self.store.pending()? {
838            if held.contains(&seq) {
839                continue;
840            }
841            if room == 0 {
842                break;
843            }
844            let pending = self.stored(seq, entry);
845            let at = self
846                .queue
847                .iter()
848                .position(|queued| queued.seq.is_some_and(|queued| queued > seq))
849                .unwrap_or(self.queue.len());
850            self.queue.insert(at, pending);
851            room -= 1;
852            adopted += 1;
853        }
854        if adopted > 0 {
855            self.pump();
856        }
857        Ok(adopted)
858    }
859
860    /// The queue entry for a message read back from the store.
861    fn stored(&mut self, seq: Seq, entry: QueuedCall) -> Pending {
862        Pending {
863            token: self.mint_token(),
864            action: entry.action,
865            payload: entry.payload,
866            kind: entry.kind,
867            transactional: entry.transactional,
868            attempts: entry.attempts,
869            seq: Some(seq),
870            not_before: None,
871            triggered: false,
872            queue_when_offline: true,
873        }
874    }
875
876    /// Changes the message timeout.
877    ///
878    /// 2.x sources it from the active `NetworkConnectionProfile.messageTimeout`, falling back
879    /// to `OCPPCommCtrlr.MessageTimeout[Default]` — so it changes when the station fails over
880    /// to a different network configuration slot, and it must be changeable at run time.
881    /// A call that is already outstanding keeps the deadline it was given.
882    pub fn set_call_timeout(&mut self, timeout: Duration) {
883        self.config.call_timeout = timeout;
884    }
885
886    /// Replaces the [`IdGenerator`].
887    ///
888    /// A Local Controller uses this to guarantee that the ids it invents cannot collide with
889    /// the CSMS's (Part 4 §6.4).
890    pub fn set_id_generator(&mut self, ids: Box<dyn IdGenerator + Send>) {
891        self.ids = ids;
892    }
893
894    /// The configuration this engine was built with.
895    #[must_use]
896    pub fn config(&self) -> &EngineConfig {
897        &self.config
898    }
899
900    /// The negotiated version.
901    #[must_use]
902    pub fn version(&self) -> Version {
903        self.version
904    }
905
906    /// Whether the transport is currently up.
907    #[must_use]
908    pub fn is_connected(&self) -> bool {
909        self.connected
910    }
911
912    /// The boot state machine's current state.
913    #[must_use]
914    pub fn boot_state(&self) -> BootState {
915        self.boot
916    }
917
918    /// The heartbeat interval the CSMS asked for, once boot succeeded.
919    #[must_use]
920    pub fn heartbeat_interval(&self) -> Option<Duration> {
921        self.heartbeat_interval
922    }
923
924    /// How many messages are waiting to be sent.
925    ///
926    /// This is what `GetTransactionStatus.messagesInQueue` reports.
927    #[must_use]
928    pub fn queued(&self) -> usize {
929        self.queue.len()
930    }
931
932    /// The durable store.
933    pub fn store(&self) -> &S {
934        &self.store
935    }
936
937    /// Whether one of *our* calls is currently outstanding.
938    #[must_use]
939    pub fn has_outstanding_call(&self) -> bool {
940        self.inflight.is_some()
941    }
942
943    /// How many of the *peer's* calls are waiting for an answer.
944    ///
945    /// More than one means the peer broke the one-outstanding-`CALL` rule and
946    /// [`InboundConcurrency::Serve`] let it.
947    #[must_use]
948    pub fn awaiting_response(&self) -> usize {
949        self.peer_inflight.len()
950    }
951
952    // -- driver interface ---------------------------------------------------
953
954    /// Feeds one event into the state machine at time `now`.
955    ///
956    /// `now` is the driver's monotonic clock, taken on every input rather than only on
957    /// [`Input::Timeout`]: every input can arm a deadline, and one computed from a stale
958    /// clock fires the moment it is armed.
959    pub fn handle(&mut self, now: Instant, input: Input<'_>) {
960        self.advance(now);
961        match input {
962            Input::Connected { version } => self.on_connected(version),
963            Input::Received(text) => self.on_received(text),
964            Input::Disconnected => self.on_disconnected(),
965            Input::Timeout => self.on_timeout(),
966        }
967    }
968
969    /// Moves the clock forward, never backwards: an older instant must not resurrect a
970    /// deadline that has already passed.
971    fn advance(&mut self, now: Instant) {
972        if now > self.now {
973            self.now = now;
974        }
975    }
976
977    /// The engine's view of the driver's clock.
978    #[must_use]
979    pub fn now(&self) -> Instant {
980        self.now
981    }
982
983    /// Takes the next thing the driver must do.
984    pub fn poll_output(&mut self) -> Option<Output> {
985        self.outputs.pop_front()
986    }
987
988    /// Takes everything the driver must do, in order.
989    pub fn drain(&mut self) -> Vec<Output> {
990        self.outputs.drain(..).collect()
991    }
992
993    // -- application interface ----------------------------------------------
994
995    /// Starts a `CALL` (or a `SEND`, if that is what the action is).
996    ///
997    /// The call is accepted immediately and reaches the wire when the one-outstanding rule,
998    /// the boot gate and the connection allow it. The returned [`CallToken`] appears again
999    /// in the matching [`CallOutcome`].
1000    pub fn call(
1001        &mut self,
1002        now: Instant,
1003        action: &str,
1004        payload: Box<RawValue>,
1005    ) -> Result<CallToken, EngineError> {
1006        self.call_with(now, action, payload, CallOptions::default())
1007    }
1008
1009    /// Starts a call with per-call overrides.
1010    pub fn call_with(
1011        &mut self,
1012        now: Instant,
1013        action: &str,
1014        payload: Box<RawValue>,
1015        options: CallOptions,
1016    ) -> Result<CallToken, EngineError> {
1017        self.advance(now);
1018        if self.draining.is_some() {
1019            return Err(EngineError::ShuttingDown);
1020        }
1021        let Some(kind) = actions::kind(self.version, action) else {
1022            return Err(EngineError::UnknownAction(action.to_string()));
1023        };
1024        let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
1025        if !allows(origin, self.config.role.sends()) {
1026            return Err(EngineError::WrongDirection(action.to_string()));
1027        }
1028        if kind == MessageKind::Send && !self.version.has_extended_message_types() {
1029            return Err(EngineError::SendNotSupported(action.to_string()));
1030        }
1031
1032        let transactional = actions::is_transaction_related(self.version, action);
1033        let persist = options.persist.unwrap_or(transactional);
1034        let queue_when_offline = options
1035            .queue_when_offline
1036            .unwrap_or(transactional || self.config.offline.queue_all_messages);
1037
1038        let token = self.mint_token();
1039        if !self.connected && !queue_when_offline {
1040            // Nothing about this message survives an outage, and there is no outage to wait
1041            // out — reporting that now beats letting it sit in a queue it was never meant to
1042            // enter until the *next* disconnection notices it.
1043            self.fail(token, None, action, CallFailure::Disconnected);
1044            return Ok(token);
1045        }
1046        if self.queue.len() >= self.config.offline.max_queued {
1047            self.fail(token, None, action, CallFailure::QueueFull);
1048            return Ok(token);
1049        }
1050
1051        let mut seq = None;
1052        if persist {
1053            let entry = QueuedCall {
1054                action: action.to_string(),
1055                payload: payload.clone(),
1056                kind,
1057                attempts: 0,
1058                transactional,
1059            };
1060            match self.store.push(&entry) {
1061                Ok(value) => seq = Some(value),
1062                Err(error) => {
1063                    self.outputs
1064                        .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1065                    self.fail(token, None, action, CallFailure::QueueFull);
1066                    return Ok(token);
1067                }
1068            }
1069        }
1070
1071        // The CSMS records what it asked the station for, so the boot gate can tell a
1072        // solicited follow-up call from an unsolicited one (B02.FR.09).
1073        if self.config.role == Role::Csms {
1074            self.remember_solicited(action, &payload);
1075        }
1076
1077        self.queue.push_back(Pending {
1078            token,
1079            action: action.to_string(),
1080            payload,
1081            kind,
1082            transactional,
1083            attempts: 0,
1084            seq,
1085            not_before: None,
1086            triggered: options.triggered,
1087            queue_when_offline,
1088        });
1089        self.pump();
1090        Ok(token)
1091    }
1092
1093    /// Answers an outstanding request with a `CALLRESULT`.
1094    pub fn respond(
1095        &mut self,
1096        now: Instant,
1097        id: &MessageId,
1098        payload: &RawValue,
1099    ) -> Result<(), EngineError> {
1100        self.advance(now);
1101        self.take_peer_request(id)?;
1102        // The CSMS side learns the boot verdict from the answer it is sending.
1103        if self.config.role == Role::Csms {
1104            self.observe_boot_answer(payload, /* outgoing */ true);
1105        }
1106        let frame = Frame::CallResult {
1107            id: id.clone(),
1108            payload: alloc::borrow::Cow::Borrowed(payload),
1109        };
1110        self.transmit(&frame);
1111        Ok(())
1112    }
1113
1114    /// Answers an outstanding request with a `CALLERROR`.
1115    pub fn respond_error(
1116        &mut self,
1117        now: Instant,
1118        id: &MessageId,
1119        error: CallError,
1120    ) -> Result<(), EngineError> {
1121        self.advance(now);
1122        self.take_peer_request(id)?;
1123        let frame = Frame::CallError {
1124            id: id.clone(),
1125            error: error.into(),
1126        };
1127        self.transmit(&frame);
1128        Ok(())
1129    }
1130
1131    /// Tells the peer that the `CALLRESULT` it sent could not be used (OCPP 2.1
1132    /// `CALLRESULTERROR`).
1133    ///
1134    /// Before 2.1 no such message exists, and the failure can only be logged locally.
1135    pub fn reject_result(
1136        &mut self,
1137        now: Instant,
1138        id: &MessageId,
1139        error: CallError,
1140    ) -> Result<(), EngineError> {
1141        self.advance(now);
1142        if !self.version.has_extended_message_types() {
1143            return Err(EngineError::CallResultErrorNotSupported);
1144        }
1145        let frame = Frame::CallResultError {
1146            id: id.clone(),
1147            error: error.into(),
1148        };
1149        self.transmit(&frame);
1150        Ok(())
1151    }
1152
1153    /// Abandons a call that has not been transmitted yet.
1154    ///
1155    /// Returns `true` if it was still in the queue. A call that is already outstanding
1156    /// cannot be withdrawn — the peer will answer it.
1157    pub fn cancel(&mut self, token: CallToken) -> bool {
1158        let Some(index) = self.queue.iter().position(|entry| entry.token == token) else {
1159            return false;
1160        };
1161        let entry = self.queue.remove(index).expect("index from position");
1162        self.ack_store(entry.seq);
1163        self.outputs.push_back(Output::Outcome(CallOutcome {
1164            token,
1165            id: None,
1166            action: entry.action,
1167            result: Err(CallFailure::Cancelled),
1168        }));
1169        true
1170    }
1171
1172    /// Starts a graceful drain: no new calls are accepted, the outstanding call is allowed
1173    /// to finish and the queue is flushed, then [`Output::Close`] is emitted.
1174    ///
1175    /// If `deadline` passes first, the connection is closed with
1176    /// [`CloseReason::DrainTimedOut`] and the queue is left in the durable store.
1177    pub fn shutdown(&mut self, now: Instant, deadline: Instant) {
1178        self.advance(now);
1179        if self.draining.is_some() {
1180            return;
1181        }
1182        self.draining = Some(deadline);
1183        self.outputs.push_back(Output::SetTimer {
1184            timer: Timer::DrainDeadline,
1185            at: deadline,
1186        });
1187        self.check_drain();
1188    }
1189
1190    // -- inbound -------------------------------------------------------------
1191
1192    fn on_connected(&mut self, version: Version) {
1193        self.version = version;
1194        self.connected = true;
1195        self.peer_inflight.clear();
1196        // The engine survives reconnects (Part 4 §5.4: no repeat `BootNotification`), so an
1197        // already-accepted station has to pick its heartbeat back up here — nothing else
1198        // will re-arm it.
1199        self.arm_heartbeat();
1200        self.pump();
1201    }
1202
1203    fn on_disconnected(&mut self) {
1204        self.connected = false;
1205        self.peer_inflight.clear();
1206        self.outputs
1207            .push_back(Output::ClearTimer(Timer::CallTimeout));
1208        self.outputs.push_back(Output::ClearTimer(Timer::Heartbeat));
1209        self.heartbeat_at = None;
1210
1211        if let Some(inflight) = self.inflight.take() {
1212            self.requeue_or_fail(inflight, CallFailure::Disconnected);
1213        }
1214        // Messages that must not survive the outage are failed now, in order.
1215        let mut kept = VecDeque::with_capacity(self.queue.len());
1216        while let Some(entry) = self.queue.pop_front() {
1217            if entry.queue_when_offline {
1218                kept.push_back(entry);
1219            } else {
1220                self.ack_store(entry.seq);
1221                self.outputs.push_back(Output::Outcome(CallOutcome {
1222                    token: entry.token,
1223                    id: None,
1224                    action: entry.action,
1225                    result: Err(CallFailure::Disconnected),
1226                }));
1227            }
1228        }
1229        self.queue = kept;
1230        self.check_drain();
1231    }
1232
1233    fn on_timeout(&mut self) {
1234        let now = self.now;
1235
1236        if let Some(deadline) = self.inflight.as_ref().map(|f| f.deadline) {
1237            if now >= deadline {
1238                let inflight = self.inflight.take().expect("checked");
1239                self.outputs
1240                    .push_back(Output::ClearTimer(Timer::CallTimeout));
1241                self.requeue_or_fail(inflight, CallFailure::Timeout);
1242            }
1243        }
1244
1245        if let Some(at) = self.heartbeat_at {
1246            if now >= at {
1247                self.heartbeat_at = None;
1248                if self.connected && self.boot.allows_traffic() {
1249                    self.send_heartbeat();
1250                }
1251                // Sending re-arms the idle timer by way of `transmit`; this covers the cases
1252                // where nothing was sent, or the `Heartbeat` had to queue behind a call.
1253                self.arm_heartbeat();
1254            }
1255        }
1256
1257        if let Some(at) = self.boot_retry_at {
1258            if now >= at {
1259                self.boot_retry_at = None;
1260                // B02.FR.04 / FR.08: the station re-sends BootNotification once the interval
1261                // has passed. Only the application can build the payload, so the engine
1262                // reports the transition and re-opens the gate.
1263                self.boot = BootState::Idle;
1264                self.outputs.push_back(Output::BootState(BootState::Idle));
1265            }
1266        }
1267
1268        if let Some(deadline) = self.draining {
1269            if now >= deadline && !self.drain_complete() {
1270                self.outputs
1271                    .push_back(Output::Close(CloseReason::DrainTimedOut));
1272                self.draining = None;
1273                return;
1274            }
1275        }
1276
1277        self.pump();
1278        self.check_drain();
1279    }
1280
1281    fn on_received(&mut self, text: &str) {
1282        // `HeartbeatInterval` is defined as an interval of *inactivity*, so traffic in either
1283        // direction postpones the next `Heartbeat`.
1284        self.arm_heartbeat();
1285        let frame = match Frame::parse(text, self.version) {
1286            Ok(frame) => frame,
1287            Err(error) => {
1288                let reply = error.reply(self.version);
1289                let reply_id = error.reply_id();
1290                let code = error.error_code();
1291                // One violation per frame: the specific one when the frame got far enough to
1292                // name what was wrong with it, the general one otherwise.
1293                self.outputs.push_back(Output::Violation(match &error {
1294                    FrameError::UnknownMessageType { number } => {
1295                        ProtocolViolation::UnknownMessageType {
1296                            number: number.clone(),
1297                        }
1298                    }
1299                    _ => ProtocolViolation::MalformedFrame { error },
1300                }));
1301                // §4.2.3 — a CALL gets a CALLERROR, a CALLRESULT gets a CALLRESULTERROR, and
1302                // a SEND or a broken error frame gets nothing at all.
1303                let answer = match reply {
1304                    FrameReply::Ignore => return,
1305                    FrameReply::CallError => Frame::CallError {
1306                        id: reply_id,
1307                        error: CallError::new(code, "frame could not be processed").into(),
1308                    },
1309                    FrameReply::CallResultError => Frame::CallResultError {
1310                        id: reply_id,
1311                        error: CallError::new(code, "result could not be processed").into(),
1312                    },
1313                };
1314                self.transmit(&answer);
1315                return;
1316            }
1317        };
1318
1319        if !frame.id().is_conforming() {
1320            self.outputs.push_back(Output::Violation(
1321                ProtocolViolation::NonConformingMessageId {
1322                    id: frame.id().clone(),
1323                },
1324            ));
1325        }
1326
1327        match frame {
1328            Frame::Call {
1329                id,
1330                action,
1331                payload,
1332            } => {
1333                self.on_call(id, &action, payload.into_owned(), MessageKind::Call);
1334            }
1335            Frame::Send {
1336                id,
1337                action,
1338                payload,
1339            } => {
1340                self.on_call(id, &action, payload.into_owned(), MessageKind::Send);
1341            }
1342            Frame::CallResult { id, payload } => self.on_call_result(&id, payload.into_owned()),
1343            Frame::CallError { id, error } => self.on_call_error(&id, &error),
1344            Frame::CallResultError { id, error } => {
1345                self.outputs.push_back(Output::ResultRejected {
1346                    id,
1347                    error: error.to_call_error(),
1348                });
1349            }
1350        }
1351    }
1352
1353    fn on_call(
1354        &mut self,
1355        id: MessageId,
1356        action: &str,
1357        payload: Box<RawValue>,
1358        received: MessageKind,
1359    ) {
1360        let Some(expected) = actions::kind(self.version, action) else {
1361            self.reject(&id, received, CallError::not_implemented(action));
1362            return;
1363        };
1364        if expected != received {
1365            // N15.FR.01: a SEND-only action must not arrive as a CALL, and a CALL must not
1366            // arrive as a SEND.
1367            self.outputs
1368                .push_back(Output::Violation(ProtocolViolation::WrongMessageKind {
1369                    action: action.to_string(),
1370                    received,
1371                }));
1372            self.reject(
1373                &id,
1374                received,
1375                CallError::new(
1376                    ErrorCode::ProtocolError,
1377                    format!("{action} is a {expected:?} message, not a {received:?} message"),
1378                ),
1379            );
1380            return;
1381        }
1382
1383        let origin = actions::origin(self.version, action).unwrap_or(Origin::Both);
1384        if !allows(origin, self.config.role.receives()) {
1385            self.outputs
1386                .push_back(Output::Violation(ProtocolViolation::WrongDirection {
1387                    action: action.to_string(),
1388                }));
1389            self.reject(&id, received, CallError::not_supported(action));
1390            return;
1391        }
1392
1393        if received == MessageKind::Call {
1394            // §4.2.3 lists "an existing message with the same unique identifier is being
1395            // handled already" as a CALLERROR condition — and answering it as an ordinary
1396            // request would make the two answers indistinguishable to the peer.
1397            if self.peer_inflight.contains(&id) {
1398                self.outputs
1399                    .push_back(Output::Violation(ProtocolViolation::DuplicateMessageId {
1400                        id: id.clone(),
1401                    }));
1402                self.reject(
1403                    &id,
1404                    received,
1405                    CallError::new(
1406                        ErrorCode::RpcFrameworkError,
1407                        "a CALL with this MessageId is already being handled (Part 4 §4.2.3)",
1408                    ),
1409                );
1410                return;
1411            }
1412            if !self.peer_inflight.is_empty() {
1413                self.outputs
1414                    .push_back(Output::Violation(ProtocolViolation::ConcurrentCall {
1415                        id: id.clone(),
1416                    }));
1417                // Serving extra calls is a kindness to non-conforming peers, not an
1418                // invitation to hold unbounded state on their behalf.
1419                let over_limit = self.peer_inflight.len() >= self.config.max_peer_requests;
1420                if over_limit {
1421                    self.outputs.push_back(Output::Violation(
1422                        ProtocolViolation::TooManyPeerRequests { id: id.clone() },
1423                    ));
1424                }
1425                if over_limit || self.config.inbound_concurrency == InboundConcurrency::Reject {
1426                    self.reject(
1427                        &id,
1428                        received,
1429                        CallError::new(
1430                            ErrorCode::ProtocolError,
1431                            "a CALL is already outstanding in this direction (Part 4 §4.1.1)",
1432                        ),
1433                    );
1434                    return;
1435                }
1436            }
1437        }
1438
1439        // B01.FR.10 / B02.FR.09 — a CSMS answers an unsolicited call with SecurityError once
1440        // it has told the station it is *not* accepted. The precondition is "the Charging
1441        // Station has received a BootNotificationResponse with a status other than
1442        // Accepted", so it does **not** apply before any BootNotification has been answered:
1443        // Part 4 §5.4 explicitly lets a station reconnect without repeating one.
1444        // BootNotification itself is always allowed, and so is anything the CSMS asked for.
1445        if self.config.role == Role::Csms
1446            && self.config.enforce_boot_gate
1447            && self.boot.blocks_unsolicited_traffic()
1448            && action != "BootNotification"
1449            && !self.solicited.contains(action)
1450        {
1451            self.reject(
1452                &id,
1453                received,
1454                CallError::security(format!(
1455                    "{action} is not allowed while the charging station is {:?} (B02.FR.09)",
1456                    self.boot
1457                )),
1458            );
1459            return;
1460        }
1461
1462        if self.config.role == Role::Csms && action == "BootNotification" {
1463            self.boot = BootState::Idle;
1464        }
1465
1466        if received == MessageKind::Call {
1467            self.peer_inflight.insert(id.clone());
1468        }
1469        self.outputs.push_back(Output::Request(IncomingRequest {
1470            id,
1471            action: action.to_string(),
1472            payload,
1473            kind: received,
1474        }));
1475    }
1476
1477    fn on_call_result(&mut self, id: &MessageId, payload: Box<RawValue>) {
1478        let Some(inflight) = self.take_inflight(id) else {
1479            self.outputs
1480                .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1481                    id: id.clone(),
1482                }));
1483            return;
1484        };
1485        self.ack_store(inflight.seq);
1486        self.outputs
1487            .push_back(Output::ClearTimer(Timer::CallTimeout));
1488
1489        match inflight.action.as_str() {
1490            "BootNotification" if self.config.role == Role::ChargingStation => {
1491                self.observe_boot_answer(&payload, false);
1492            }
1493            "Heartbeat" => {
1494                if let Ok(answer) = serde_json::from_str::<HeartbeatAnswer>(payload.get()) {
1495                    self.outputs.push_back(Output::ClockSample(ClockSample {
1496                        csms_time: answer.current_time,
1497                        at: self.now,
1498                    }));
1499                }
1500            }
1501            _ => {}
1502        }
1503
1504        self.outputs.push_back(Output::Outcome(CallOutcome {
1505            token: inflight.token,
1506            id: Some(inflight.id),
1507            action: inflight.action,
1508            result: Ok(Answer::Result(payload)),
1509        }));
1510        self.pump();
1511        self.check_drain();
1512    }
1513
1514    fn on_call_error(&mut self, id: &MessageId, error: &CallErrorRef<'_>) {
1515        let Some(inflight) = self.take_inflight(id) else {
1516            self.outputs
1517                .push_back(Output::Violation(ProtocolViolation::UnexpectedResponse {
1518                    id: id.clone(),
1519                }));
1520            return;
1521        };
1522        // A CALLERROR is a definitive answer, so it is not retried — unlike a timeout or a
1523        // dropped connection, retrying it would just produce the same error.
1524        self.ack_store(inflight.seq);
1525        self.outputs
1526            .push_back(Output::ClearTimer(Timer::CallTimeout));
1527        self.outputs.push_back(Output::Outcome(CallOutcome {
1528            token: inflight.token,
1529            id: Some(inflight.id),
1530            action: inflight.action,
1531            result: Err(CallFailure::Rejected(error.to_call_error())),
1532        }));
1533        self.pump();
1534        self.check_drain();
1535    }
1536
1537    // -- helpers -------------------------------------------------------------
1538
1539    fn mint_token(&mut self) -> CallToken {
1540        let token = CallToken(self.next_token);
1541        self.next_token += 1;
1542        token
1543    }
1544
1545    fn take_inflight(&mut self, id: &MessageId) -> Option<InFlight> {
1546        match self.inflight.as_ref() {
1547            Some(inflight) if &inflight.id == id => self.inflight.take(),
1548            _ => None,
1549        }
1550    }
1551
1552    fn take_peer_request(&mut self, id: &MessageId) -> Result<(), EngineError> {
1553        if self.peer_inflight.remove(id) {
1554            return Ok(());
1555        }
1556        Err(EngineError::NoSuchRequest(id.clone()))
1557    }
1558
1559    fn reject(&mut self, id: &MessageId, kind: MessageKind, error: CallError) {
1560        // FR.07 — a SEND is never answered, not even to report that it was unusable.
1561        if kind == MessageKind::Send {
1562            return;
1563        }
1564        let frame = Frame::CallError {
1565            id: id.clone(),
1566            error: error.into(),
1567        };
1568        self.transmit(&frame);
1569    }
1570
1571    fn transmit(&mut self, frame: &Frame<'_>) {
1572        match frame.to_json(self.version) {
1573            Ok(text) => {
1574                self.outputs.push_back(Output::Transmit(text));
1575                self.arm_heartbeat();
1576            }
1577            Err(error) => {
1578                self.outputs
1579                    .push_back(Output::Violation(ProtocolViolation::StoreFailure {
1580                        error: StoreError::new(format!("frame could not be serialized: {error}")),
1581                    }));
1582            }
1583        }
1584    }
1585
1586    fn ack_store(&mut self, seq: Option<Seq>) {
1587        if let Some(seq) = seq {
1588            if let Err(error) = self.store.ack(seq) {
1589                self.outputs
1590                    .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1591            }
1592        }
1593    }
1594
1595    fn fail(&mut self, token: CallToken, id: Option<MessageId>, action: &str, why: CallFailure) {
1596        self.outputs.push_back(Output::Outcome(CallOutcome {
1597            token,
1598            id,
1599            action: action.to_string(),
1600            result: Err(why),
1601        }));
1602    }
1603
1604    /// Decides what happens to a call that lost its answer: a transaction message goes back
1605    /// on the queue for its next scheduled attempt; anything else fails now.
1606    ///
1607    /// Only transaction messages are replayed, and deliberately so. They are the ones the
1608    /// specification makes idempotent — a CSMS deduplicates `TransactionEvent` by
1609    /// `transactionId` and `seqNo` — so a second copy is harmless. Re-sending an
1610    /// `Authorize` or a `SetVariables` whose answer merely went missing is not obviously
1611    /// safe, and the caller, which knows what the message meant, gets to decide.
1612    fn requeue_or_fail(&mut self, inflight: InFlight, why: CallFailure) {
1613        let attempts = inflight.attempts;
1614        if inflight.transactional && self.config.retry.may_retry(attempts) {
1615            let delay = self.config.retry.delay_after(attempts);
1616            let not_before = self.now.saturating_add(delay);
1617            if let Some(seq) = inflight.seq {
1618                if let Err(error) = self.store.set_attempts(seq, attempts) {
1619                    self.outputs
1620                        .push_back(Output::Violation(ProtocolViolation::StoreFailure { error }));
1621                }
1622            }
1623            self.queue.push_front(Pending {
1624                token: inflight.token,
1625                action: inflight.action,
1626                payload: inflight.payload,
1627                kind: MessageKind::Call,
1628                transactional: true,
1629                attempts,
1630                seq: inflight.seq,
1631                not_before: Some(not_before),
1632                triggered: inflight.triggered,
1633                queue_when_offline: inflight.queue_when_offline,
1634            });
1635            self.outputs.push_back(Output::SetTimer {
1636                timer: Timer::TransactionRetry,
1637                at: not_before,
1638            });
1639            return;
1640        }
1641        let why = if inflight.transactional {
1642            CallFailure::RetriesExhausted
1643        } else {
1644            why
1645        };
1646        self.ack_store(inflight.seq);
1647        self.outputs.push_back(Output::Outcome(CallOutcome {
1648            token: inflight.token,
1649            id: Some(inflight.id),
1650            action: inflight.action,
1651            result: Err(why),
1652        }));
1653    }
1654
1655    /// Whether the entry at `index` may go out right now.
1656    ///
1657    /// Two rules decide it. B02.FR.02 gates everything before the CSMS accepts the station.
1658    /// And 1.6 §3.7 — carried into 2.x — says transaction-related messages are delivered *in
1659    /// chronological order*: "the delivery of new transaction-related messages SHALL wait
1660    /// until the queue has been emptied". So a transaction message may only go out if it is
1661    /// the oldest one queued, even when a later one is due and it is still waiting out its
1662    /// retry interval. Messages that are *not* transaction-related are explicitly allowed to
1663    /// overtake the queue, so that an `Authorize` is not held up behind a stuck meter value.
1664    fn eligible(&self, index: usize) -> bool {
1665        let entry = &self.queue[index];
1666        if entry.not_before.is_some_and(|at| self.now < at) {
1667            return false;
1668        }
1669        if entry.transactional {
1670            let oldest = self
1671                .queue
1672                .iter()
1673                .position(|other| other.transactional)
1674                .expect("this entry is transactional");
1675            if oldest != index {
1676                return false;
1677            }
1678        }
1679        if !self.config.enforce_boot_gate || self.config.role != Role::ChargingStation {
1680            return true;
1681        }
1682        // B02.FR.02 — before the CSMS accepts the station, only BootNotification and
1683        // messages the CSMS explicitly asked for may be sent.
1684        self.boot.allows_traffic() || entry.action == "BootNotification" || entry.triggered
1685    }
1686
1687    fn pump(&mut self) {
1688        if !self.connected {
1689            return;
1690        }
1691
1692        // Part 4 §4.2.4 — a SEND is exempt from the one-outstanding-CALL rule, so it goes
1693        // out whether or not a CALL is in flight, and completes as soon as it is written.
1694        while let Some(index) = (0..self.queue.len())
1695            .find(|index| self.queue[*index].kind == MessageKind::Send && self.eligible(*index))
1696        {
1697            let entry = self.queue.remove(index).expect("index from position");
1698            let id = self.ids.next_id();
1699            let frame = Frame::Send {
1700                id: id.clone(),
1701                action: (&entry.action).into(),
1702                payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1703            };
1704            self.transmit(&frame);
1705            self.ack_store(entry.seq);
1706            self.outputs.push_back(Output::Outcome(CallOutcome {
1707                token: entry.token,
1708                id: Some(id),
1709                action: entry.action,
1710                result: Ok(Answer::Sent),
1711            }));
1712        }
1713
1714        while self.inflight.is_none() {
1715            let Some(index) = (0..self.queue.len()).find(|index| {
1716                self.queue[*index].kind == MessageKind::Call && self.eligible(*index)
1717            }) else {
1718                break;
1719            };
1720            let entry = self.queue.remove(index).expect("index from position");
1721            let id = self.ids.next_id();
1722            let frame = Frame::Call {
1723                id: id.clone(),
1724                action: (&entry.action).into(),
1725                payload: alloc::borrow::Cow::Borrowed(entry.payload.as_ref()),
1726            };
1727            self.transmit(&frame);
1728            let deadline = self.now.saturating_add(self.config.call_timeout);
1729            self.outputs.push_back(Output::SetTimer {
1730                timer: Timer::CallTimeout,
1731                at: deadline,
1732            });
1733            self.inflight = Some(InFlight {
1734                id,
1735                token: entry.token,
1736                action: entry.action,
1737                transactional: entry.transactional,
1738                attempts: entry.attempts + 1,
1739                seq: entry.seq,
1740                payload: entry.payload,
1741                triggered: entry.triggered,
1742                queue_when_offline: entry.queue_when_offline,
1743                deadline,
1744            });
1745        }
1746    }
1747
1748    fn send_heartbeat(&mut self) {
1749        // `HeartbeatRequest` is an empty object in 1.6 and 2.x alike.
1750        let now = self.now;
1751        let _ = self.call_with(
1752            now,
1753            "Heartbeat",
1754            empty_payload(),
1755            CallOptions::default().queue_when_offline(false),
1756        );
1757    }
1758
1759    /// (Re-)arms the inactivity timer that triggers the next `Heartbeat`.
1760    ///
1761    /// `OCPPCommCtrlr.HeartbeatInterval` is the interval of inactivity after which a station
1762    /// sends `Heartbeat`, so this is called for every frame in either direction — not once
1763    /// per period. A `Heartbeat` that times out or is answered with a `CALLERROR` therefore
1764    /// cannot stop the sequence, which is what a fixed schedule anchored on the response
1765    /// would do.
1766    fn arm_heartbeat(&mut self) {
1767        if self.config.heartbeat != HeartbeatPolicy::Automatic
1768            || self.config.role != Role::ChargingStation
1769        {
1770            return;
1771        }
1772        let Some(interval) = self.heartbeat_interval.filter(|d| !d.is_zero()) else {
1773            return;
1774        };
1775        let at = self.now.saturating_add(interval);
1776        if self.heartbeat_at == Some(at) {
1777            return;
1778        }
1779        self.heartbeat_at = Some(at);
1780        self.outputs.push_back(Output::SetTimer {
1781            timer: Timer::Heartbeat,
1782            at,
1783        });
1784    }
1785
1786    /// Reads `status`, `interval` and `currentTime` out of a `BootNotificationResponse`.
1787    fn observe_boot_answer(&mut self, payload: &RawValue, outgoing: bool) {
1788        let Ok(answer) = serde_json::from_str::<BootAnswer<'_>>(payload.get()) else {
1789            return;
1790        };
1791        let state = match answer.status {
1792            "Accepted" => BootState::Accepted,
1793            "Pending" => BootState::Pending,
1794            "Rejected" => BootState::Rejected,
1795            _ => return,
1796        };
1797        self.boot = state;
1798        self.outputs.push_back(Output::BootState(state));
1799
1800        if let Some(time) = answer.current_time {
1801            if !outgoing {
1802                self.outputs.push_back(Output::ClockSample(ClockSample {
1803                    csms_time: time,
1804                    at: self.now,
1805                }));
1806            }
1807        }
1808
1809        let interval = answer.interval.map(Duration::from_secs);
1810        match state {
1811            BootState::Accepted => {
1812                self.heartbeat_interval = interval.filter(|d| !d.is_zero());
1813                if !outgoing {
1814                    self.arm_heartbeat();
1815                    self.pump();
1816                }
1817            }
1818            BootState::Pending | BootState::Rejected if !outgoing => {
1819                // B02.FR.04 / FR.07 / FR.08: wait `interval` before retrying, or a
1820                // locally chosen back-off when the CSMS said 0.
1821                let wait = interval
1822                    .filter(|d| !d.is_zero())
1823                    .unwrap_or(self.config.boot_retry_fallback);
1824                let at = self.now.saturating_add(wait);
1825                self.boot_retry_at = Some(at);
1826                self.outputs.push_back(Output::SetTimer {
1827                    timer: Timer::BootRetry,
1828                    at,
1829                });
1830            }
1831            _ => {}
1832        }
1833    }
1834
1835    /// Remembers the follow-up calls a CSMS request licenses the station to make.
1836    fn remember_solicited(&mut self, action: &str, payload: &RawValue) {
1837        if action == "TriggerMessage" || action == "ExtendedTriggerMessage" {
1838            if let Ok(trigger) = serde_json::from_str::<TriggerRequest<'_>>(payload.get()) {
1839                if let Some(requested) = trigger.requested_message {
1840                    self.solicited.insert(requested.to_string());
1841                    // 1.6 and 2.x both name the message, not the action, so a couple of
1842                    // aliases are needed.
1843                    if requested == "SignChargePointCertificate" {
1844                        self.solicited.insert("SignCertificate".to_string());
1845                    }
1846                }
1847            }
1848        }
1849        for follow_up in actions::solicited_by(self.version, action) {
1850            self.solicited.insert((*follow_up).to_string());
1851        }
1852    }
1853
1854    fn drain_complete(&self) -> bool {
1855        self.inflight.is_none() && self.queue.is_empty()
1856    }
1857
1858    fn check_drain(&mut self) {
1859        if self.draining.is_some() && self.drain_complete() {
1860            self.draining = None;
1861            self.outputs
1862                .push_back(Output::ClearTimer(Timer::DrainDeadline));
1863            self.outputs.push_back(Output::Close(CloseReason::Drained));
1864        }
1865    }
1866}
1867
1868/// The best [`IdGenerator`] the build offers.
1869///
1870/// Random ids when an entropy source is available, because Part 4 §4.1.4 requires ids to be
1871/// unique across *every* connection under one identity, not just within one. Without one,
1872/// a counter — which the caller must then prefix per boot; see
1873/// [`CounterIds`](crate::types::CounterIds).
1874fn default_ids() -> Box<dyn IdGenerator + Send> {
1875    #[cfg(feature = "getrandom")]
1876    {
1877        Box::new(crate::types::RandomIds::new())
1878    }
1879    #[cfg(not(feature = "getrandom"))]
1880    {
1881        Box::new(crate::types::CounterIds::default())
1882    }
1883}
1884
1885fn allows(origin: Origin, side: Origin) -> bool {
1886    match side {
1887        Origin::ChargingStation => origin.from_charging_station(),
1888        Origin::Csms => origin.from_csms(),
1889        Origin::Both => true,
1890    }
1891}
1892
1893fn empty_payload() -> Box<RawValue> {
1894    RawValue::from_string("{}".to_string()).expect("`{}` is valid JSON")
1895}