footing 0.6.4

Feature-gated foundations for Rust backend services
Documentation
//! Small worker runtime primitives.
//!
//! Applications provide job acquisition and processing through [`Worker`].
//! Configuration, outbox processing, leasing, and loop orchestration live in
//! focused private modules and are re-exported as one feature-gated API.
//! Workers, batch jobs, outbox stores, and handlers can also be shared through
//! [`Arc`], including trait objects, without application-specific adapters.
//!
//! ```rust
//! use std::time::Duration;
//! use footing::worker::{BackoffConfig, RetryBackoff};
//!
//! let mut backoff = RetryBackoff::new(BackoffConfig::default());
//! assert_eq!(backoff.record_failure(), Duration::from_secs(1));
//! backoff.reset();
//! ```
//!
//! Queue jobs choose [`WorkerSchedule::Continue`] when another batch may be
//! ready, or [`WorkerSchedule::WaitForWork`] when idle. Ordinary workers keep
//! polling unless they explicitly choose a different schedule. Scheduling never
//! infers backlog from processed counts, and failure backoff cannot be woken.
//!
//! For the built-in outbox adapter, opt in with [`OutboxJob::with_queue_scheduling`]:
//!
//! ```no_run
//! use footing::worker::{
//!     BatchWorker, OutboxHandler, OutboxItem, OutboxJob, OutboxStore,
//!     ShutdownToken, WorkerConfig, WorkerRunError, WorkerRunOptions, WorkerWakeup,
//!     run_worker_until_shutdown_with_options,
//! };
//!
//! async fn serve_queue<S, H, I>(
//!     job: OutboxJob<S, H, I>,
//!     wakeup: WorkerWakeup,
//!     shutdown: ShutdownToken,
//! ) -> Result<(), WorkerRunError>
//! where
//!     S: OutboxStore<I>,
//!     H: OutboxHandler<I>,
//!     I: OutboxItem,
//! {
//!     // Enqueue producers retain a clone and call notify() after commit.
//!     let options = WorkerRunOptions::new().with_wakeup(wakeup);
//!     let worker = BatchWorker::new(job.with_queue_scheduling());
//!     run_worker_until_shutdown_with_options(
//!         worker, WorkerConfig::default(), shutdown, options,
//!     ).await?;
//!     Ok(())
//! }
//! ```
//!
//! Notifications are hints to check durable storage. Stores must enforce due
//! times and claims even when a notification arrives early. A new runner checks
//! the queue after its startup delay; idle polling also covers lost notifications
//! and retries outside the last batch. External listeners should subscribe before
//! checking existing work and repeat that check after reconnecting.

use std::{error::Error, sync::Arc};

use async_trait::async_trait;

mod config;
mod lease;
mod outbox;
mod runner;
mod schedule;
mod status;

pub use config::{BackoffConfig, RetryBackoff, WorkerConfig, WorkerConfigError, WorkerLeaseConfig};
pub use config::{BackoffSettings, WorkerLeaseSettings, WorkerSettings};
pub use lease::{LocalWorkerLeaseStore, WorkerLease, WorkerLeaseError, WorkerLeaseStore};
pub use outbox::OutboxWorkerSettings;
pub use outbox::{
    BatchRunSummary, BatchWorker, BatchWorkerJob, OutboxBatchError, OutboxClaim, OutboxHandler,
    OutboxItem, OutboxItemState, OutboxJob, OutboxRetryPolicy, OutboxStore, OutboxWorkerConfig,
};
pub use runner::{
    ShutdownToken, ShutdownTrigger, WorkerRunError, WorkerRunOptions, WorkerRunState,
    WorkerRunSummary, WorkerTick, WorkerTickOutcome, WorkerTickTimeout, run_worker_until_shutdown,
    run_worker_until_shutdown_with_options, shutdown_channel,
};
pub use schedule::{WorkerSchedule, WorkerWakeup};
pub use status::{WorkerPhase, WorkerStatus};

/// Boxed worker errors used by the generic worker trait.
pub type BoxWorkerError = Box<dyn Error + Send + Sync + 'static>;

/// Maximum supported worker name length.
pub const MAX_WORKER_NAME_LENGTH: usize = 128;
/// Maximum supported worker lease owner length.
pub const MAX_WORKER_LEASE_OWNER_LENGTH: usize = 128;

/// Execution metadata for one worker tick.
///
/// The fencing token is fixed for the entire tick, including lease renewals.
/// Applications must send it to protected resources, which must reject older
/// tokens. Merely receiving this context does not make effects exactly-once.
/// `Default` represents an execution without a runner lease.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct WorkerContext {
    fencing_token: Option<u64>,
}

impl WorkerContext {
    /// Returns the current runner lease's fencing token, if leasing is enabled.
    #[must_use]
    pub const fn fencing_token(self) -> Option<u64> {
        self.fencing_token
    }
}

/// One unit of repeatable background work.
///
/// Execution is at-least-once. A tick may be cancelled by its optional deadline
/// or during shutdown, and repeated after an ambiguous failure or lease loss.
/// Implementations must be
/// cancellation-safe and make externally visible effects idempotent. A worker
/// lease coordinates runners but cannot fence effects unless the application
/// propagates and enforces [`WorkerContext::fencing_token`] at the protected
/// resource. Shutdown drains an active tick within the configured timeout while
/// maintaining its lease; timeout or lease failure returns an error.
/// The optional [`WorkerSettings::tick_timeout`] instead records a tick failure
/// and applies normal failure backoff. Deadlines require futures that yield;
/// dropping a future does not terminate blocking tasks or undo remote effects.
#[async_trait]
pub trait Worker: Send + Sync + 'static {
    /// Human-readable worker name used in logs and metrics.
    fn name(&self) -> &str;

    /// Runs one worker tick.
    async fn run_once(&self, context: WorkerContext) -> Result<WorkerTick, BoxWorkerError>;
}

#[async_trait]
impl<T: Worker + ?Sized> Worker for Arc<T> {
    fn name(&self) -> &str {
        self.as_ref().name()
    }

    async fn run_once(&self, context: WorkerContext) -> Result<WorkerTick, BoxWorkerError> {
        self.as_ref().run_once(context).await
    }
}

#[cfg(test)]
use runner::ensure_worker_lease;
#[cfg(test)]
mod schedule_tests;
#[cfg(test)]
mod status_tests;
#[cfg(test)]
mod tests;
#[cfg(test)]
mod timeout_tests;