servlet 1.2.0

A small application runtime with an explicit operational contract
Documentation
//! Cooperative polling with explicit in-flight cancellation behavior.

use std::{
    future::Future,
    sync::{Arc, Mutex},
    time::Duration,
};

use tokio::time::Instant;

use super::{Result, WorkerContext};

/// The next action after one successful attempt. Return an error to fail the task.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollOutcome {
    /// Work completed. Yield to the executor, then poll again.
    Worked,
    /// Polling succeeded and found no work. Wait for the idle interval.
    Idle,
    /// Retry after an application-selected delay.
    RetryAfter(Duration),
}

/// What to do when shutdown is requested during an attempt.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PollShutdown {
    /// Drop the current future promptly.
    CancelAttempt,
    /// Let the current attempt finish within Servlet's drain budget.
    FinishAttempt,
}

/// Waiting and shutdown behavior for a supervised polling task.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PollPolicy {
    /// How long to wait after a successful idle poll.
    pub idle_interval: Duration,
    /// Whether an in-flight attempt may be cancelled.
    pub shutdown: PollShutdown,
}

/// Current progress for an observed polling task.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PollSnapshot {
    /// Most recent successful result, including idle polls.
    pub last_success: Option<Instant>,
    /// Most recent completed unit of work.
    pub last_work: Option<Instant>,
    /// Total idle polls since progress observation began.
    pub idle_polls: u64,
    /// Total attempts whose result requested a retry.
    pub retries: u64,
}

/// A cloneable observation handle for a single polling task.
#[derive(Clone, Debug, Default)]
pub struct PollProgress {
    state: Arc<Mutex<PollSnapshot>>,
}

impl PollProgress {
    /// Read a consistent progress snapshot.
    pub fn snapshot(&self) -> PollSnapshot {
        *self.state.lock().unwrap_or_else(|error| error.into_inner())
    }

    fn record(&self, outcome: PollOutcome) {
        let mut state = self.state.lock().unwrap_or_else(|error| error.into_inner());
        match outcome {
            PollOutcome::Worked => {
                let now = Instant::now();
                state.last_success = Some(now);
                state.last_work = Some(now);
            }
            PollOutcome::Idle => {
                state.last_success = Some(Instant::now());
                state.idle_polls = state.idle_polls.saturating_add(1);
            }
            PollOutcome::RetryAfter(_) => state.retries = state.retries.saturating_add(1),
        }
    }
}

impl WorkerContext {
    /// Announce readiness, then poll until shutdown or an attempt returns an error.
    ///
    /// Each attempt owns its deadline, durable claim, and retry decisions. Idle
    /// waits always stop promptly. A finishing attempt remains subject to the
    /// coordinator's existing drain timeout.
    pub async fn poll<F, Fut>(
        &self,
        policy: PollPolicy,
        progress: Option<&PollProgress>,
        mut attempt: F,
    ) -> Result
    where
        F: FnMut() -> Fut,
        Fut: Future<Output = std::result::Result<PollOutcome, super::BoxError>>,
    {
        self.ready();
        let shutdown = self.shutdown();

        while !shutdown.is_requested() {
            let outcome = match policy.shutdown {
                PollShutdown::CancelAttempt => tokio::select! {
                    biased;
                    () = shutdown.cancelled() => return Ok(()),
                    outcome = async { attempt().await } => outcome?,
                },
                PollShutdown::FinishAttempt => attempt().await?,
            };
            if let Some(progress) = progress {
                progress.record(outcome);
            }

            let delay = match outcome {
                PollOutcome::Worked => Duration::ZERO,
                PollOutcome::Idle => policy.idle_interval,
                PollOutcome::RetryAfter(delay) => delay,
            };
            if delay.is_zero() {
                tokio::task::yield_now().await;
            } else {
                tokio::select! {
                    biased;
                    () = shutdown.cancelled() => return Ok(()),
                    () = tokio::time::sleep(delay) => {}
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
#[path = "poll_test.rs"]
mod tests;