Skip to main content

ocpp_kit/engine/
queue.rs

1//! The outgoing-call queue and its durable backing store.
2
3use alloc::boxed::Box;
4use alloc::collections::VecDeque;
5use alloc::string::String;
6use alloc::vec::Vec;
7use core::fmt;
8use core::time::Duration;
9
10use serde_json::value::RawValue;
11
12use crate::message::MessageKind;
13
14/// Monotonic sequence number of a stored message.
15pub type Seq = u64;
16
17/// One queued outgoing message.
18#[derive(Clone, Debug)]
19pub struct QueuedCall {
20    /// Action name.
21    pub action: String,
22    /// Serialized payload object.
23    pub payload: Box<RawValue>,
24    /// `CALL` or `SEND`.
25    pub kind: MessageKind,
26    /// How many times transmission has already been attempted.
27    pub attempts: u32,
28    /// Whether the message is transaction-related and therefore durable and retried.
29    pub transactional: bool,
30}
31
32impl PartialEq for QueuedCall {
33    fn eq(&self, other: &Self) -> bool {
34        self.action == other.action
35            && self.payload.get() == other.payload.get()
36            && self.kind == other.kind
37            && self.attempts == other.attempts
38            && self.transactional == other.transactional
39    }
40}
41
42/// Durable storage for transaction-related messages.
43///
44/// A Charging Station must survive a power cut with its queued `TransactionEvent`s intact
45/// and replay them in order (E04.FR.01–03, E08.FR.05–07, E12.FR.01–02), and must be able to
46/// answer `GetTransactionStatus.messagesInQueue` from it. The trait is deliberately tiny and
47/// synchronous so it can sit on flash, SQLite or Postgres alike.
48pub trait MessageStore {
49    /// Appends a message, returning its sequence number.
50    fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError>;
51
52    /// Every un-acknowledged message, oldest first.
53    ///
54    /// Called once when an engine starts, so a Charging Station replays what a power cut
55    /// interrupted.
56    fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError>;
57
58    /// Removes a message that has been delivered (or definitively abandoned).
59    fn ack(&mut self, seq: Seq) -> Result<(), StoreError>;
60
61    /// Records a further transmission attempt for a message that is still queued.
62    fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError>;
63
64    /// How many messages are waiting.
65    ///
66    /// Answers `GetTransactionStatus.messagesInQueue`.
67    fn len(&self) -> Result<usize, StoreError>;
68
69    /// Whether the store is empty.
70    fn is_empty(&self) -> Result<bool, StoreError> {
71        Ok(self.len()? == 0)
72    }
73}
74
75/// A durable store failed.
76#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct StoreError {
78    /// What went wrong, for logging.
79    pub reason: String,
80}
81
82impl StoreError {
83    /// Builds a store failure.
84    #[must_use]
85    pub fn new(reason: impl Into<String>) -> Self {
86        Self {
87            reason: reason.into(),
88        }
89    }
90}
91
92impl fmt::Display for StoreError {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str(&self.reason)
95    }
96}
97
98#[cfg(feature = "std")]
99impl std::error::Error for StoreError {}
100
101/// An in-memory [`MessageStore`]. The default, and all a CSMS ever needs.
102///
103/// A Charging Station should swap in a store that survives a reboot.
104#[derive(Debug, Default)]
105pub struct MemStore {
106    entries: VecDeque<(Seq, QueuedCall)>,
107    next_seq: Seq,
108    capacity: Option<usize>,
109}
110
111impl MemStore {
112    /// An unbounded in-memory store.
113    #[must_use]
114    pub fn new() -> Self {
115        Self::default()
116    }
117
118    /// A store that refuses to grow beyond `capacity` messages.
119    #[must_use]
120    pub fn bounded(capacity: usize) -> Self {
121        Self {
122            capacity: Some(capacity),
123            ..Self::default()
124        }
125    }
126
127    /// Every queued message, oldest first.
128    #[must_use]
129    pub fn entries(&self) -> Vec<&QueuedCall> {
130        self.entries.iter().map(|(_, entry)| entry).collect()
131    }
132}
133
134impl MessageStore for MemStore {
135    fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError> {
136        if let Some(capacity) = self.capacity {
137            if self.entries.len() >= capacity {
138                return Err(StoreError::new("offline queue is full"));
139            }
140        }
141        let seq = self.next_seq;
142        self.next_seq += 1;
143        self.entries.push_back((seq, entry.clone()));
144        Ok(seq)
145    }
146
147    fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError> {
148        Ok(self.entries.iter().cloned().collect())
149    }
150
151    fn ack(&mut self, seq: Seq) -> Result<(), StoreError> {
152        self.entries.retain(|(s, _)| *s != seq);
153        Ok(())
154    }
155
156    fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError> {
157        if let Some((_, entry)) = self.entries.iter_mut().find(|(s, _)| *s == seq) {
158            entry.attempts = attempts;
159        }
160        Ok(())
161    }
162
163    fn len(&self) -> Result<usize, StoreError> {
164        Ok(self.entries.len())
165    }
166}
167
168/// How often, and how far apart, transaction-related messages are retried.
169///
170/// Both 1.6 (§3.7.1, `TransactionMessageAttempts` / `TransactionMessageRetryInterval`) and
171/// 2.x (`OCPPCommCtrlr.MessageAttempts[TransactionEvent]` /
172/// `MessageAttemptInterval[TransactionEvent]`) prescribe the same **linear** schedule: wait
173/// `interval × number of preceding transmissions` before each retry. It is not exponential,
174/// and it applies to transaction messages only.
175#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub struct RetryPolicy {
177    /// Total number of transmissions, including the first. `1` disables retrying.
178    pub attempts: u32,
179    /// The base interval.
180    pub interval: Duration,
181}
182
183impl Default for RetryPolicy {
184    /// The OCPP 1.6 defaults: three attempts, 60 s apart.
185    fn default() -> Self {
186        Self {
187            attempts: 3,
188            interval: Duration::from_secs(60),
189        }
190    }
191}
192
193impl RetryPolicy {
194    /// Retrying disabled.
195    #[must_use]
196    pub const fn none() -> Self {
197        Self {
198            attempts: 1,
199            interval: Duration::ZERO,
200        }
201    }
202
203    /// The wait before the retry that follows `attempts_made` transmissions.
204    ///
205    /// `interval × attempts_made`, per 1.6 §3.7.1 ("wait the retry interval multiplied by
206    /// the number of preceding transmissions").
207    #[must_use]
208    pub fn delay_after(&self, attempts_made: u32) -> Duration {
209        self.interval.saturating_mul(attempts_made)
210    }
211
212    /// Whether another transmission is allowed after `attempts_made`.
213    #[must_use]
214    pub const fn may_retry(&self, attempts_made: u32) -> bool {
215        attempts_made < self.attempts
216    }
217}
218
219#[cfg(test)]
220mod tests {
221    use super::*;
222
223    #[test]
224    fn retry_schedule_is_linear_not_exponential() {
225        let policy = RetryPolicy::default();
226        assert_eq!(policy.delay_after(1).as_secs(), 60);
227        assert_eq!(policy.delay_after(2).as_secs(), 120);
228        assert_eq!(policy.delay_after(3).as_secs(), 180);
229        assert!(policy.may_retry(2));
230        assert!(!policy.may_retry(3));
231    }
232
233    #[test]
234    fn bounded_store_refuses_to_grow_without_limit() {
235        let mut store = MemStore::bounded(1);
236        let entry = QueuedCall {
237            action: "TransactionEvent".into(),
238            payload: RawValue::from_string("{}".into()).unwrap(),
239            kind: MessageKind::Call,
240            attempts: 0,
241            transactional: true,
242        };
243        assert!(store.push(&entry).is_ok());
244        assert!(store.push(&entry).is_err());
245        assert_eq!(store.len().unwrap(), 1);
246    }
247}