footing 0.1.1

Feature-gated foundations for Rust backend services
Documentation
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,
    WorkerTick,
};

#[derive(Debug, Clone)]
/// Represents counting worker.
pub struct CountingWorker {
    name: &'static str,
    calls: Arc<AtomicU64>,
    processed_per_tick: u64,
}

impl CountingWorker {
    #[must_use]
    /// Creates a new instance.
    pub fn new(name: &'static str) -> Self {
        Self {
            name,
            calls: Arc::new(AtomicU64::new(0)),
            processed_per_tick: 1,
        }
    }

    #[must_use]
    /// Returns the calls.
    pub fn calls(&self) -> u64 {
        self.calls.load(Ordering::SeqCst)
    }

    #[must_use]
    /// Configures processed per tick and returns the updated value.
    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) -> Result<WorkerTick, BoxWorkerError> {
        self.calls.fetch_add(1, Ordering::SeqCst);
        Ok(WorkerTick::new(self.processed_per_tick))
    }
}

/// Runs once.
pub async fn run_once<W>(worker: &W) -> Result<WorkerTick, BoxWorkerError>
where
    W: Worker,
{
    worker.run_once().await
}

#[derive(Debug, Clone, PartialEq, Eq)]
/// Represents test outbox item.
pub struct TestOutboxItem {
    id: String,
    attempts: u32,
    action: TestOutboxAction,
}

impl TestOutboxItem {
    #[must_use]
    /// Creates succeeded.
    pub fn succeeded(id: impl Into<String>) -> Self {
        Self::new(id, TestOutboxAction::Succeeded)
    }

    #[must_use]
    /// Creates retry.
    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]
    /// Creates skipped.
    pub fn skipped(id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::new(
            id,
            TestOutboxAction::Skipped {
                reason: reason.into(),
            },
        )
    }

    #[must_use]
    /// Creates failed.
    pub fn failed(id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::new(
            id,
            TestOutboxAction::Failed {
                reason: reason.into(),
            },
        )
    }

    #[must_use]
    /// Creates handler error.
    pub fn handler_error(id: impl Into<String>, reason: impl Into<String>) -> Self {
        Self::new(
            id,
            TestOutboxAction::HandlerError {
                reason: reason.into(),
            },
        )
    }

    #[must_use]
    /// Creates slow.
    pub fn slow(id: impl Into<String>, delay: Duration) -> Self {
        Self::new(id, TestOutboxAction::Slow { delay })
    }

    #[must_use]
    /// Creates a new instance.
    pub fn new(id: impl Into<String>, action: TestOutboxAction) -> Self {
        Self {
            id: id.into(),
            attempts: 0,
            action,
        }
    }

    #[must_use]
    /// Configures attempts and returns the updated value.
    pub const fn with_attempts(mut self, attempts: u32) -> Self {
        self.attempts = attempts;
        self
    }

    #[must_use]
    /// Returns the action.
    pub fn action(&self) -> &TestOutboxAction {
        &self.action
    }
}

impl OutboxItem for TestOutboxItem {
    fn outbox_id(&self) -> String {
        self.id.clone()
    }

    fn outbox_attempts(&self) -> u32 {
        self.attempts
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Enumerates the supported test outbox action values.
pub enum TestOutboxAction {
    /// Indicates succeeded.
    Succeeded,
    /// Indicates skipped.
    Skipped {
        #[doc = "The reason for this outcome."]
        reason: String,
    },
    /// Indicates retry.
    Retry {
        #[doc = "The reason for this outcome."]
        reason: String,
        #[doc = "The delay before the next action."]
        delay: Duration,
    },
    /// Indicates failed.
    Failed {
        #[doc = "The reason for this outcome."]
        reason: String,
    },
    /// Indicates handler error.
    HandlerError {
        #[doc = "The reason for this outcome."]
        reason: String,
    },
    /// Indicates slow.
    Slow {
        #[doc = "The delay before the next action."]
        delay: Duration,
    },
}

#[derive(Debug, Clone, Default)]
/// Storage abstraction for test outbox.
pub struct TestOutboxStore {
    items: Arc<Mutex<VecDeque<TestOutboxItem>>>,
    states: Arc<Mutex<Vec<(String, OutboxItemState)>>>,
    dead_letters: Arc<Mutex<Vec<(String, String)>>>,
}

impl TestOutboxStore {
    #[must_use]
    /// Configures items and returns the updated value.
    pub fn with_items(items: impl IntoIterator<Item = TestOutboxItem>) -> Self {
        let store = Self::default();
        store.push_items(items);
        store
    }

    /// Attempts to append items to the in-memory store.
    pub fn try_push_items(
        &self,
        items: impl IntoIterator<Item = TestOutboxItem>,
    ) -> Result<(), BoxWorkerError> {
        lock_test_outbox(&self.items, "items")?.extend(items);
        Ok(())
    }

    /// Appends items.
    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}"));
    }

    /// Attempts to snapshot recorded item states.
    pub fn try_states(&self) -> Result<Vec<(String, OutboxItemState)>, BoxWorkerError> {
        Ok(lock_test_outbox(&self.states, "states")?.clone())
    }

    #[must_use]
    /// Returns the states.
    pub fn states(&self) -> Vec<(String, OutboxItemState)> {
        self.try_states()
            .unwrap_or_else(|error| panic!("test outbox states should be readable: {error}"))
    }

    /// Attempts to snapshot recorded dead letters.
    pub fn try_dead_letters(&self) -> Result<Vec<(String, String)>, BoxWorkerError> {
        Ok(lock_test_outbox(&self.dead_letters, "dead_letters")?.clone())
    }

    #[must_use]
    /// Returns the dead letters.
    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) -> Result<Vec<TestOutboxItem>, BoxWorkerError> {
        let mut items = lock_test_outbox(&self.items, "items")?;
        Ok((0..claim.limit())
            .filter_map(|_| items.pop_front())
            .collect())
    }

    async fn record_state(
        &self,
        item: &TestOutboxItem,
        state: OutboxItemState,
    ) -> Result<(), BoxWorkerError> {
        lock_test_outbox(&self.states, "states")?.push((item.outbox_id(), state));
        Ok(())
    }

    async fn record_dead_letter(
        &self,
        item: &TestOutboxItem,
        reason: &str,
    ) -> Result<(), BoxWorkerError> {
        lock_test_outbox(&self.dead_letters, "dead_letters")?
            .push((item.outbox_id(), reason.to_owned()));
        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)]
/// Represents test outbox handler.
pub struct TestOutboxHandler;

#[async_trait]
impl OutboxHandler<TestOutboxItem> for TestOutboxHandler {
    async fn handle(&self, item: &TestOutboxItem) -> 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)
            }
        }
    }
}