footing 0.6.2

Feature-gated foundations for Rust backend services
Documentation
//! Optional, latest-value observations of one worker runner.

use std::time::Instant;

use tokio::sync::watch;

use crate::clock::SharedClock;

use super::WorkerTickOutcome;

/// The runner's current activity, rather than an application health verdict.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WorkerPhase {
    /// The options have not yet been consumed by a polled runner.
    Pending,
    /// Waiting for the configured startup delay.
    StartupDelay,
    /// Acquiring a lease, renewing before a tick, or waiting to retry acquisition.
    LeaseWait,
    /// Executing a tick, including any concurrent lease renewal.
    Running,
    /// Waiting for the ordinary polling interval after a successful tick.
    Poll,
    /// Waiting for a queue notification or its polling fallback.
    QueueIdle,
    /// Enforcing the minimum spacing between queue ticks.
    QueueSpacing,
    /// Waiting for a successful tick's explicit `WorkerSchedule::After` delay.
    Delay,
    /// Waiting for failure backoff; notifications cannot interrupt this phase.
    Backoff,
    /// Draining an active tick or releasing the runner's lease.
    Shutdown,
    /// The runner returned successfully, including when disabled.
    Stopped,
    /// The runner returned a `WorkerRunError`.
    Failed,
    /// The options or runner future were dropped before returning a result.
    /// Includes task abortion and panic unwinding.
    Cancelled,
}

/// A snapshot of one runner, published only when activity changes.
///
/// Obtain a native [`watch::Receiver`] from
/// [`super::WorkerRunOptions::subscribe_status`]. Updates may be coalesced; this
/// is not an event history. Clone the receiver for independent readers and copy
/// its snapshot before awaiting, rather than retaining a `watch::Ref`.
///
/// Times use the clock installed in `WorkerRunOptions`. The most recently
/// started tick can still be running; the finish time and outcome describe the
/// most recently **completed** attempt, including a configured tick timeout
/// recorded as failure. Abort, lease loss, or an expired shutdown deadline
/// interrupts the tick without a completion record.
/// Normal waits, including lease contention, do not imply unhealthy work.
///
/// Existing diagnostics probes can apply application-specific health policy:
///
/// ```no_run
/// # #[cfg(feature = "diagnostics")]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use std::time::Duration;
/// use footing::{
///     diagnostics::{ResourceDescriptor, ResourceDiagnostic, ResourceKind, resource_probe},
///     worker::{WorkerPhase, WorkerRunOptions},
/// };
///
/// let mut options = WorkerRunOptions::new();
/// let status = options.subscribe_status();
/// let probe = resource_probe(
///     ResourceDescriptor::required("delivery", "Delivery worker", ResourceKind::Worker)?,
///     move |resource| {
///         let status = *status.borrow();
///         async move {
///             // This application's expected batch duration is below 30 seconds.
///             let diagnostic = match status.phase() {
///                 WorkerPhase::Failed | WorkerPhase::Cancelled =>
///                     ResourceDiagnostic::unhealthy(resource, "worker stopped unexpectedly"),
///                 WorkerPhase::Running if status.phase_since().elapsed() > Duration::from_secs(30) =>
///                     ResourceDiagnostic::unhealthy(resource, "worker execution is overdue"),
///                 WorkerPhase::Pending | WorkerPhase::Stopped | WorkerPhase::Shutdown =>
///                     ResourceDiagnostic::unknown(resource, "worker is not serving"),
///                 WorkerPhase::Backoff =>
///                     ResourceDiagnostic::degraded(resource, "worker is retrying"),
///                 _ => ResourceDiagnostic::healthy(resource, "worker is active"),
///             };
///             Ok(diagnostic)
///         }
///     },
/// );
/// // Register the probe, then move options into the worker runner.
/// # let _ = (probe, options);
/// # Ok(())
/// # }
/// # #[cfg(not(feature = "diagnostics"))]
/// # fn main() {}
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct WorkerStatus {
    phase: WorkerPhase,
    phase_since: Instant,
    last_tick_started_at: Option<Instant>,
    last_tick_finished_at: Option<Instant>,
    last_tick_outcome: Option<WorkerTickOutcome>,
}

impl WorkerStatus {
    /// Returns the current runner activity.
    #[must_use]
    pub const fn phase(&self) -> WorkerPhase {
        self.phase
    }

    /// Returns when the runner entered its current phase.
    #[must_use]
    pub const fn phase_since(&self) -> Instant {
        self.phase_since
    }

    /// Returns when the most recently started tick began.
    #[must_use]
    pub const fn last_tick_started_at(&self) -> Option<Instant> {
        self.last_tick_started_at
    }

    /// Returns when the most recently completed tick finished.
    #[must_use]
    pub const fn last_tick_finished_at(&self) -> Option<Instant> {
        self.last_tick_finished_at
    }

    /// Returns the most recently completed tick's outcome.
    #[must_use]
    pub const fn last_tick_outcome(&self) -> Option<WorkerTickOutcome> {
        self.last_tick_outcome
    }
}

pub(super) struct StatusPublisher {
    sender: watch::Sender<WorkerStatus>,
    clock: SharedClock,
}

impl StatusPublisher {
    pub(super) fn new(clock: SharedClock) -> (Self, watch::Receiver<WorkerStatus>) {
        let (sender, receiver) = watch::channel(WorkerStatus {
            phase: WorkerPhase::Pending,
            phase_since: clock.now(),
            last_tick_started_at: None,
            last_tick_finished_at: None,
            last_tick_outcome: None,
        });
        (Self { sender, clock }, receiver)
    }

    pub(super) fn subscribe(&self) -> watch::Receiver<WorkerStatus> {
        self.sender.subscribe()
    }

    pub(super) fn set_clock(&mut self, clock: SharedClock) {
        self.clock = clock;
        self.sender
            .send_modify(|status| status.phase_since = self.clock.now());
    }

    pub(super) fn set_phase(&self, phase: WorkerPhase) {
        self.sender.send_if_modified(|status| {
            if status.phase == phase {
                return false;
            }
            status.phase = phase;
            status.phase_since = self.clock.now();
            true
        });
    }

    pub(super) fn tick_started(&self) {
        self.sender.send_modify(|status| {
            let now = self.clock.now();
            status.phase = WorkerPhase::Running;
            status.phase_since = now;
            status.last_tick_started_at = Some(now);
        });
    }

    pub(super) fn tick_finished(&self, outcome: WorkerTickOutcome) {
        self.sender.send_modify(|status| {
            status.last_tick_finished_at = Some(self.clock.now());
            status.last_tick_outcome = Some(outcome);
        });
    }
}

impl Drop for StatusPublisher {
    fn drop(&mut self) {
        self.sender.send_if_modified(|status| {
            if matches!(status.phase, WorkerPhase::Stopped | WorkerPhase::Failed) {
                return false;
            }
            status.phase = WorkerPhase::Cancelled;
            status.phase_since = self.clock.now();
            true
        });
    }
}