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    /// Read when an engine is built, so a Charging Station replays what a power cut
55    /// interrupted, and again by `Engine::adopt_pending`, which queues what another process
56    /// pushed since.
57    fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError>;
58
59    /// Removes a message that has been delivered (or definitively abandoned).
60    fn ack(&mut self, seq: Seq) -> Result<(), StoreError>;
61
62    /// Records a further transmission attempt for a message that is still queued.
63    fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError>;
64
65    /// How many messages are waiting.
66    ///
67    /// Answers `GetTransactionStatus.messagesInQueue`.
68    fn len(&self) -> Result<usize, StoreError>;
69
70    /// Whether the store is empty.
71    fn is_empty(&self) -> Result<bool, StoreError> {
72        Ok(self.len()? == 0)
73    }
74}
75
76/// A durable store failed.
77#[derive(Clone, Debug, PartialEq, Eq)]
78pub struct StoreError {
79    /// What went wrong, for logging.
80    pub reason: String,
81}
82
83impl StoreError {
84    /// Builds a store failure.
85    #[must_use]
86    pub fn new(reason: impl Into<String>) -> Self {
87        Self {
88            reason: reason.into(),
89        }
90    }
91}
92
93impl fmt::Display for StoreError {
94    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
95        f.write_str(&self.reason)
96    }
97}
98
99#[cfg(feature = "std")]
100impl std::error::Error for StoreError {}
101
102/// An in-memory [`MessageStore`]. The default, and all a CSMS ever needs.
103///
104/// A Charging Station should swap in a store that survives a reboot.
105#[derive(Debug, Default)]
106pub struct MemStore {
107    entries: VecDeque<(Seq, QueuedCall)>,
108    next_seq: Seq,
109    capacity: Option<usize>,
110}
111
112impl MemStore {
113    /// An unbounded in-memory store.
114    #[must_use]
115    pub fn new() -> Self {
116        Self::default()
117    }
118
119    /// A store that refuses to grow beyond `capacity` messages.
120    #[must_use]
121    pub fn bounded(capacity: usize) -> Self {
122        Self {
123            capacity: Some(capacity),
124            ..Self::default()
125        }
126    }
127
128    /// Every queued message, oldest first.
129    #[must_use]
130    pub fn entries(&self) -> Vec<&QueuedCall> {
131        self.entries.iter().map(|(_, entry)| entry).collect()
132    }
133}
134
135impl MessageStore for MemStore {
136    fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError> {
137        if let Some(capacity) = self.capacity {
138            if self.entries.len() >= capacity {
139                return Err(StoreError::new("offline queue is full"));
140            }
141        }
142        let seq = self.next_seq;
143        self.next_seq += 1;
144        self.entries.push_back((seq, entry.clone()));
145        Ok(seq)
146    }
147
148    fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError> {
149        Ok(self.entries.iter().cloned().collect())
150    }
151
152    fn ack(&mut self, seq: Seq) -> Result<(), StoreError> {
153        self.entries.retain(|(s, _)| *s != seq);
154        Ok(())
155    }
156
157    fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError> {
158        if let Some((_, entry)) = self.entries.iter_mut().find(|(s, _)| *s == seq) {
159            entry.attempts = attempts;
160        }
161        Ok(())
162    }
163
164    fn len(&self) -> Result<usize, StoreError> {
165        Ok(self.entries.len())
166    }
167}
168
169/// How often, and how far apart, transaction-related messages are retried.
170///
171/// Both 1.6 (§3.7.1, `TransactionMessageAttempts` / `TransactionMessageRetryInterval`) and
172/// 2.x (`OCPPCommCtrlr.MessageAttempts[TransactionEvent]` /
173/// `MessageAttemptInterval[TransactionEvent]`) prescribe the same **linear** schedule: wait
174/// `interval × number of preceding transmissions` before each retry. It is not exponential,
175/// and it applies to transaction messages only.
176#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub struct RetryPolicy {
178    /// Total number of transmissions, including the first. `1` disables retrying.
179    pub attempts: u32,
180    /// The base interval.
181    pub interval: Duration,
182}
183
184impl Default for RetryPolicy {
185    /// The OCPP 1.6 defaults: three attempts, 60 s apart.
186    fn default() -> Self {
187        Self {
188            attempts: 3,
189            interval: Duration::from_secs(60),
190        }
191    }
192}
193
194impl RetryPolicy {
195    /// Retrying disabled.
196    #[must_use]
197    pub const fn none() -> Self {
198        Self {
199            attempts: 1,
200            interval: Duration::ZERO,
201        }
202    }
203
204    /// The wait before the retry that follows `attempts_made` transmissions.
205    ///
206    /// `interval × attempts_made`, per 1.6 §3.7.1 ("wait the retry interval multiplied by
207    /// the number of preceding transmissions").
208    #[must_use]
209    pub fn delay_after(&self, attempts_made: u32) -> Duration {
210        self.interval.saturating_mul(attempts_made)
211    }
212
213    /// Whether another transmission is allowed after `attempts_made`.
214    #[must_use]
215    pub const fn may_retry(&self, attempts_made: u32) -> bool {
216        attempts_made < self.attempts
217    }
218}
219
220#[cfg(test)]
221mod tests {
222    use super::*;
223
224    #[test]
225    fn retry_schedule_is_linear_not_exponential() {
226        let policy = RetryPolicy::default();
227        assert_eq!(policy.delay_after(1).as_secs(), 60);
228        assert_eq!(policy.delay_after(2).as_secs(), 120);
229        assert_eq!(policy.delay_after(3).as_secs(), 180);
230        assert!(policy.may_retry(2));
231        assert!(!policy.may_retry(3));
232    }
233
234    #[test]
235    fn bounded_store_refuses_to_grow_without_limit() {
236        let mut store = MemStore::bounded(1);
237        let entry = QueuedCall {
238            action: "TransactionEvent".into(),
239            payload: RawValue::from_string("{}".into()).unwrap(),
240            kind: MessageKind::Call,
241            attempts: 0,
242            transactional: true,
243        };
244        assert!(store.push(&entry).is_ok());
245        assert!(store.push(&entry).is_err());
246        assert_eq!(store.len().unwrap(), 1);
247    }
248}