use std::time::Instant;
use tokio::sync::watch;
use crate::clock::SharedClock;
use super::WorkerTickOutcome;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum WorkerPhase {
Pending,
StartupDelay,
LeaseWait,
Running,
Poll,
QueueIdle,
QueueSpacing,
Delay,
Backoff,
Shutdown,
Stopped,
Failed,
Cancelled,
}
#[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 {
#[must_use]
pub const fn phase(&self) -> WorkerPhase {
self.phase
}
#[must_use]
pub const fn phase_since(&self) -> Instant {
self.phase_since
}
#[must_use]
pub const fn last_tick_started_at(&self) -> Option<Instant> {
self.last_tick_started_at
}
#[must_use]
pub const fn last_tick_finished_at(&self) -> Option<Instant> {
self.last_tick_finished_at
}
#[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
});
}
}