use alloc::boxed::Box;
use alloc::collections::VecDeque;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;
use core::time::Duration;
use serde_json::value::RawValue;
use crate::message::MessageKind;
pub type Seq = u64;
#[derive(Clone, Debug)]
pub struct QueuedCall {
pub action: String,
pub payload: Box<RawValue>,
pub kind: MessageKind,
pub attempts: u32,
pub transactional: bool,
}
impl PartialEq for QueuedCall {
fn eq(&self, other: &Self) -> bool {
self.action == other.action
&& self.payload.get() == other.payload.get()
&& self.kind == other.kind
&& self.attempts == other.attempts
&& self.transactional == other.transactional
}
}
pub trait MessageStore {
fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError>;
fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError>;
fn ack(&mut self, seq: Seq) -> Result<(), StoreError>;
fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError>;
fn len(&self) -> Result<usize, StoreError>;
fn is_empty(&self) -> Result<bool, StoreError> {
Ok(self.len()? == 0)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StoreError {
pub reason: String,
}
impl StoreError {
#[must_use]
pub fn new(reason: impl Into<String>) -> Self {
Self {
reason: reason.into(),
}
}
}
impl fmt::Display for StoreError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.reason)
}
}
#[cfg(feature = "std")]
impl std::error::Error for StoreError {}
#[derive(Debug, Default)]
pub struct MemStore {
entries: VecDeque<(Seq, QueuedCall)>,
next_seq: Seq,
capacity: Option<usize>,
}
impl MemStore {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn bounded(capacity: usize) -> Self {
Self {
capacity: Some(capacity),
..Self::default()
}
}
#[must_use]
pub fn entries(&self) -> Vec<&QueuedCall> {
self.entries.iter().map(|(_, entry)| entry).collect()
}
}
impl MessageStore for MemStore {
fn push(&mut self, entry: &QueuedCall) -> Result<Seq, StoreError> {
if let Some(capacity) = self.capacity {
if self.entries.len() >= capacity {
return Err(StoreError::new("offline queue is full"));
}
}
let seq = self.next_seq;
self.next_seq += 1;
self.entries.push_back((seq, entry.clone()));
Ok(seq)
}
fn pending(&self) -> Result<Vec<(Seq, QueuedCall)>, StoreError> {
Ok(self.entries.iter().cloned().collect())
}
fn ack(&mut self, seq: Seq) -> Result<(), StoreError> {
self.entries.retain(|(s, _)| *s != seq);
Ok(())
}
fn set_attempts(&mut self, seq: Seq, attempts: u32) -> Result<(), StoreError> {
if let Some((_, entry)) = self.entries.iter_mut().find(|(s, _)| *s == seq) {
entry.attempts = attempts;
}
Ok(())
}
fn len(&self) -> Result<usize, StoreError> {
Ok(self.entries.len())
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RetryPolicy {
pub attempts: u32,
pub interval: Duration,
}
impl Default for RetryPolicy {
fn default() -> Self {
Self {
attempts: 3,
interval: Duration::from_secs(60),
}
}
}
impl RetryPolicy {
#[must_use]
pub const fn none() -> Self {
Self {
attempts: 1,
interval: Duration::ZERO,
}
}
#[must_use]
pub fn delay_after(&self, attempts_made: u32) -> Duration {
self.interval.saturating_mul(attempts_made)
}
#[must_use]
pub const fn may_retry(&self, attempts_made: u32) -> bool {
attempts_made < self.attempts
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn retry_schedule_is_linear_not_exponential() {
let policy = RetryPolicy::default();
assert_eq!(policy.delay_after(1).as_secs(), 60);
assert_eq!(policy.delay_after(2).as_secs(), 120);
assert_eq!(policy.delay_after(3).as_secs(), 180);
assert!(policy.may_retry(2));
assert!(!policy.may_retry(3));
}
#[test]
fn bounded_store_refuses_to_grow_without_limit() {
let mut store = MemStore::bounded(1);
let entry = QueuedCall {
action: "TransactionEvent".into(),
payload: RawValue::from_string("{}".into()).unwrap(),
kind: MessageKind::Call,
attempts: 0,
transactional: true,
};
assert!(store.push(&entry).is_ok());
assert!(store.push(&entry).is_err());
assert_eq!(store.len().unwrap(), 1);
}
}