use std::{
collections::VecDeque,
sync::{
Arc, Mutex, MutexGuard,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use async_trait::async_trait;
use tokio::time;
use crate::worker::{
BoxWorkerError, OutboxClaim, OutboxHandler, OutboxItem, OutboxItemState, OutboxStore, Worker,
WorkerContext, WorkerTick,
};
#[derive(Debug, Clone)]
pub struct CountingWorker {
name: &'static str,
calls: Arc<AtomicU64>,
processed_per_tick: u64,
}
impl CountingWorker {
#[must_use]
pub fn new(name: &'static str) -> Self {
Self {
name,
calls: Arc::new(AtomicU64::new(0)),
processed_per_tick: 1,
}
}
#[must_use]
pub fn calls(&self) -> u64 {
self.calls.load(Ordering::SeqCst)
}
#[must_use]
pub const fn with_processed_per_tick(mut self, processed_per_tick: u64) -> Self {
self.processed_per_tick = processed_per_tick;
self
}
}
#[async_trait]
impl Worker for CountingWorker {
fn name(&self) -> &str {
self.name
}
async fn run_once(&self, _context: WorkerContext) -> Result<WorkerTick, BoxWorkerError> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(WorkerTick::new(self.processed_per_tick))
}
}
pub async fn run_once<W>(worker: &W) -> Result<WorkerTick, BoxWorkerError>
where
W: Worker + ?Sized,
{
worker.run_once(WorkerContext::default()).await
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestOutboxItem {
id: String,
attempts: u32,
action: TestOutboxAction,
}
impl TestOutboxItem {
#[must_use]
pub fn succeeded(id: impl Into<String>) -> Self {
Self::new(id, TestOutboxAction::Succeeded)
}
#[must_use]
pub fn retry(id: impl Into<String>, reason: impl Into<String>, delay: Duration) -> Self {
Self::new(
id,
TestOutboxAction::Retry {
reason: reason.into(),
delay,
},
)
}
#[must_use]
pub fn skipped(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::Skipped {
reason: reason.into(),
},
)
}
#[must_use]
pub fn failed(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::Failed {
reason: reason.into(),
},
)
}
#[must_use]
pub fn handler_error(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::HandlerError {
reason: reason.into(),
},
)
}
#[must_use]
pub fn slow(id: impl Into<String>, delay: Duration) -> Self {
Self::new(id, TestOutboxAction::Slow { delay })
}
#[must_use]
pub fn new(id: impl Into<String>, action: TestOutboxAction) -> Self {
Self {
id: id.into(),
attempts: 0,
action,
}
}
#[must_use]
pub const fn with_attempts(mut self, attempts: u32) -> Self {
self.attempts = attempts;
self
}
#[must_use]
pub fn action(&self) -> &TestOutboxAction {
&self.action
}
}
impl OutboxItem for TestOutboxItem {
fn outbox_attempts(&self) -> u32 {
self.attempts
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TestOutboxAction {
Succeeded,
Skipped {
#[doc = "The reason for this outcome."]
reason: String,
},
Retry {
#[doc = "The reason for this outcome."]
reason: String,
#[doc = "The delay before the next action."]
delay: Duration,
},
Failed {
#[doc = "The reason for this outcome."]
reason: String,
},
HandlerError {
#[doc = "The reason for this outcome."]
reason: String,
},
Slow {
#[doc = "The delay before the next action."]
delay: Duration,
},
}
#[derive(Debug, Clone, Default)]
pub struct TestOutboxStore {
items: Arc<Mutex<VecDeque<TestOutboxItem>>>,
states: Arc<Mutex<Vec<(String, OutboxItemState)>>>,
}
impl TestOutboxStore {
#[must_use]
pub fn with_items(items: impl IntoIterator<Item = TestOutboxItem>) -> Self {
let store = Self::default();
store.push_items(items);
store
}
pub fn try_push_items(
&self,
items: impl IntoIterator<Item = TestOutboxItem>,
) -> Result<(), BoxWorkerError> {
lock_test_outbox(&self.items, "items")?.extend(items);
Ok(())
}
pub fn push_items(&self, items: impl IntoIterator<Item = TestOutboxItem>) {
self.try_push_items(items)
.unwrap_or_else(|error| panic!("test outbox items should be writable: {error}"));
}
pub fn try_states(&self) -> Result<Vec<(String, OutboxItemState)>, BoxWorkerError> {
Ok(lock_test_outbox(&self.states, "states")?.clone())
}
#[must_use]
pub fn states(&self) -> Vec<(String, OutboxItemState)> {
self.try_states()
.unwrap_or_else(|error| panic!("test outbox states should be readable: {error}"))
}
pub fn try_dead_letters(&self) -> Result<Vec<(String, String)>, BoxWorkerError> {
Ok(lock_test_outbox(&self.states, "states")?
.iter()
.filter_map(|(id, state)| match state {
OutboxItemState::Failed { reason } => Some((id.clone(), reason.clone())),
_ => None,
})
.collect())
}
#[must_use]
pub fn dead_letters(&self) -> Vec<(String, String)> {
self.try_dead_letters()
.unwrap_or_else(|error| panic!("test outbox dead letters should be readable: {error}"))
}
}
#[async_trait]
impl OutboxStore<TestOutboxItem> for TestOutboxStore {
async fn claim_due(
&self,
claim: OutboxClaim,
_context: WorkerContext,
) -> Result<Vec<TestOutboxItem>, BoxWorkerError> {
let mut items = lock_test_outbox(&self.items, "items")?;
let count = items.len().min(claim.limit() as usize);
Ok(items.drain(..count).collect())
}
async fn persist_transition(
&self,
item: &TestOutboxItem,
state: OutboxItemState,
_context: WorkerContext,
) -> Result<(), BoxWorkerError> {
lock_test_outbox(&self.states, "states")?.push((item.id.clone(), state));
Ok(())
}
}
fn lock_test_outbox<'a, T>(
mutex: &'a Mutex<T>,
name: &'static str,
) -> Result<MutexGuard<'a, T>, BoxWorkerError> {
mutex
.lock()
.map_err(|_| std::io::Error::other(format!("test outbox {name} lock poisoned")).into())
}
#[derive(Debug, Clone, Copy, Default)]
pub struct TestOutboxHandler;
#[async_trait]
impl OutboxHandler<TestOutboxItem> for TestOutboxHandler {
async fn handle(
&self,
item: &TestOutboxItem,
_context: WorkerContext,
) -> Result<OutboxItemState, BoxWorkerError> {
match item.action() {
TestOutboxAction::Succeeded => Ok(OutboxItemState::Succeeded),
TestOutboxAction::Skipped { reason } => Ok(OutboxItemState::skipped(reason)),
TestOutboxAction::Retry { reason, delay } => Ok(OutboxItemState::retry(reason, *delay)),
TestOutboxAction::Failed { reason } => Ok(OutboxItemState::failed(reason)),
TestOutboxAction::HandlerError { reason } => Err(reason.clone().into()),
TestOutboxAction::Slow { delay } => {
time::sleep(*delay).await;
Ok(OutboxItemState::Succeeded)
}
}
}
}