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>;
57
58 fn ack(&mut self, seq: Seq) -> Result<(), StoreError>;
60
61 fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError>;
63
64 fn len(&self) -> Result<usize, StoreError>;
68
69 fn is_empty(&self) -> Result<bool, StoreError> {
71 Ok(self.len()? == 0)
72 }
73}
74
75#[derive(Clone, Debug, PartialEq, Eq)]
77pub struct StoreError {
78 pub reason: String,
80}
81
82impl StoreError {
83 #[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#[derive(Debug, Default)]
105pub struct MemStore {
106 entries: VecDeque<(Seq, QueuedCall)>,
107 next_seq: Seq,
108 capacity: Option<usize>,
109}
110
111impl MemStore {
112 #[must_use]
114 pub fn new() -> Self {
115 Self::default()
116 }
117
118 #[must_use]
120 pub fn bounded(capacity: usize) -> Self {
121 Self {
122 capacity: Some(capacity),
123 ..Self::default()
124 }
125 }
126
127 #[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#[derive(Clone, Copy, Debug, PartialEq, Eq)]
176pub struct RetryPolicy {
177 pub attempts: u32,
179 pub interval: Duration,
181}
182
183impl Default for RetryPolicy {
184 fn default() -> Self {
186 Self {
187 attempts: 3,
188 interval: Duration::from_secs(60),
189 }
190 }
191}
192
193impl RetryPolicy {
194 #[must_use]
196 pub const fn none() -> Self {
197 Self {
198 attempts: 1,
199 interval: Duration::ZERO,
200 }
201 }
202
203 #[must_use]
208 pub fn delay_after(&self, attempts_made: u32) -> Duration {
209 self.interval.saturating_mul(attempts_made)
210 }
211
212 #[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}