1use 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
14pub type Seq = u64;
16
17#[derive(Clone, Debug)]
19pub struct QueuedCall {
20 pub action: String,
22 pub payload: Box<RawValue>,
24 pub kind: MessageKind,
26 pub attempts: u32,
28 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
42pub trait MessageStore {
49 fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError>;
51
52 fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError>;
58
59 fn ack(&mut self, seq: Seq) -> Result<(), StoreError>;
61
62 fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError>;
64
65 fn len(&self) -> Result<usize, StoreError>;
69
70 fn is_empty(&self) -> Result<bool, StoreError> {
72 Ok(self.len()? == 0)
73 }
74}
75
76#[derive(Clone, Debug, PartialEq, Eq)]
78pub struct StoreError {
79 pub reason: String,
81}
82
83impl StoreError {
84 #[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#[derive(Debug, Default)]
106pub struct MemStore {
107 entries: VecDeque<(Seq, QueuedCall)>,
108 next_seq: Seq,
109 capacity: Option<usize>,
110}
111
112impl MemStore {
113 #[must_use]
115 pub fn new() -> Self {
116 Self::default()
117 }
118
119 #[must_use]
121 pub fn bounded(capacity: usize) -> Self {
122 Self {
123 capacity: Some(capacity),
124 ..Self::default()
125 }
126 }
127
128 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
177pub struct RetryPolicy {
178 pub attempts: u32,
180 pub interval: Duration,
182}
183
184impl Default for RetryPolicy {
185 fn default() -> Self {
187 Self {
188 attempts: 3,
189 interval: Duration::from_secs(60),
190 }
191 }
192}
193
194impl RetryPolicy {
195 #[must_use]
197 pub const fn none() -> Self {
198 Self {
199 attempts: 1,
200 interval: Duration::ZERO,
201 }
202 }
203
204 #[must_use]
209 pub fn delay_after(&self, attempts_made: u32) -> Duration {
210 self.interval.saturating_mul(attempts_made)
211 }
212
213 #[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}