use std::time::Instant;
use crate::config::WorkersConfig;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SlotState {
Spawning,
Idle,
Busy,
Stopping,
Dead,
}
pub struct SlotInfo {
pub state: SlotState,
pub pid: Option<u32>,
pub jobs_handled: u64,
pub created_at: Instant,
}
impl SlotInfo {
pub fn new() -> Self {
Self {
state: SlotState::Spawning,
pid: None,
jobs_handled: 0,
created_at: Instant::now(),
}
}
pub fn should_recycle(&self, cfg: &WorkersConfig) -> bool {
if self.jobs_handled >= cfg.max_jobs {
return true;
}
if self.created_at.elapsed() >= cfg.ttl {
return true;
}
false
}
pub fn mark_ready(&mut self, pid: u32) {
debug_assert!(matches!(self.state, SlotState::Spawning));
self.state = SlotState::Idle;
self.pid = Some(pid);
}
pub fn mark_busy(&mut self) {
debug_assert!(matches!(self.state, SlotState::Idle));
self.state = SlotState::Busy;
}
pub fn mark_idle(&mut self) {
debug_assert!(matches!(self.state, SlotState::Busy | SlotState::Stopping));
self.jobs_handled += 1;
if matches!(self.state, SlotState::Busy) {
self.state = SlotState::Idle;
}
}
pub fn mark_dead(&mut self) {
self.state = SlotState::Dead;
}
pub fn request_stop(&mut self) {
if matches!(self.state, SlotState::Idle | SlotState::Busy) {
self.state = SlotState::Stopping;
}
}
}
impl Default for SlotInfo {
fn default() -> Self {
Self::new()
}
}