use super::*;
use core::cell::Cell;
use embassy_sync::blocking_mutex::Mutex;
use embassy_time::{Duration, Instant};
#[derive(Clone, Copy)]
pub struct PoolStats {
pub running: u8,
pub busy: u8,
pub min: u8,
pub max: u8,
}
impl PoolStats {
pub fn idle(&self) -> u8 {
self.running.saturating_sub(self.busy)
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum ScaleAction {
None,
Grow,
Shrink,
}
pub trait ScalingPolicy {
fn decide(&self, stats: PoolStats, now: Instant) -> ScaleAction;
fn deferred_until(&self) -> Option<Instant> {
None
}
}
pub struct DeferredShrink {
cooldown: Duration,
pending: Mutex<CriticalSectionRawMutex, Cell<Option<Instant>>>,
}
impl DeferredShrink {
pub const fn new(cooldown: Duration) -> Self {
Self {
cooldown,
pending: Mutex::new(Cell::new(None)),
}
}
}
impl ScalingPolicy for DeferredShrink {
fn decide(&self, s: PoolStats, now: Instant) -> ScaleAction {
if s.idle() == 0 && s.running < s.max {
self.pending.lock(|p| p.set(None));
return ScaleAction::Grow;
}
if s.idle() >= 2 && s.running > s.min {
match self.pending.lock(|p| p.get()) {
None => {
self.pending.lock(|p| p.set(Some(now + self.cooldown)));
ScaleAction::None
}
Some(deadline) if now >= deadline => {
let next = (s.idle() >= 3).then(|| now + self.cooldown);
self.pending.lock(|p| p.set(next));
ScaleAction::Shrink
}
Some(_) => ScaleAction::None, }
} else {
self.pending.lock(|p| p.set(None));
ScaleAction::None
}
}
fn deferred_until(&self) -> Option<Instant> {
self.pending.lock(|p| p.get())
}
}
pub enum PoolAction {
None,
Start(&'static TaskNode),
Stop(&'static TaskNode),
}
pub struct ElasticPool<P: ScalingPolicy> {
pub nodes: &'static [&'static TaskNode],
pub min: u8,
pub max: u8,
pub policy: P,
}
impl<P: ScalingPolicy> ElasticPool<P> {
pub fn member_index(&self, node: &'static TaskNode) -> Option<usize> {
self.nodes.iter().position(|m| core::ptr::eq(*m, node))
}
fn stats(&self) -> PoolStats {
let (running, busy) = self.nodes.iter().fold((0u8, 0u8), |(r, b), n| {
if n.is_running() {
(r + 1, b + n.is_busy() as u8)
} else {
(r, b)
}
});
PoolStats {
running,
busy,
min: self.min,
max: self.max,
}
}
}
pub trait Pool: Sync {
fn evaluate(&self, now: Instant) -> PoolAction;
fn deferred_until(&self) -> Option<Instant>;
fn members(&self) -> &'static [&'static TaskNode];
}
impl<P: ScalingPolicy + Sync> Pool for ElasticPool<P> {
fn evaluate(&self, now: Instant) -> PoolAction {
match self.policy.decide(self.stats(), now) {
ScaleAction::Grow => self
.nodes
.iter()
.find(|n| matches!(n.mode, Mode::OnDemand) && !n.is_running() && !n.is_disabled())
.map_or(PoolAction::None, |n| PoolAction::Start(n)),
ScaleAction::Shrink => self
.nodes
.iter()
.find(|n| matches!(n.mode, Mode::OnDemand) && n.is_running() && !n.is_busy())
.map_or(PoolAction::None, |n| PoolAction::Stop(n)),
ScaleAction::None => PoolAction::None,
}
}
fn deferred_until(&self) -> Option<Instant> {
self.policy.deferred_until()
}
fn members(&self) -> &'static [&'static TaskNode] {
self.nodes
}
}
async fn drive_pools<const N: usize>(
pools: &[&dyn Pool],
sup: &Supervisor<N>,
spawner: Spawner,
) -> Result<Option<Instant>, crate::ShutdownTimeout> {
let now = Instant::now();
let mut next: Option<Instant> = None;
for pool in pools {
match pool.evaluate(now) {
PoolAction::Start(n) => {
if sup.deps_running(n) && n.ready_deps_ok() {
let _ = sup.start_node(n, spawner).await;
}
}
PoolAction::Stop(n) => sup.stop_node(n).await?,
PoolAction::None => {}
}
if let Some(d) = pool.deferred_until() {
next = Some(next.map_or(d, |c| c.min(d)));
}
}
Ok(next)
}
async fn deadline_timer(deadline: Option<Instant>) {
match deadline {
Some(t) => Timer::at(t).await,
None => core::future::pending::<()>().await,
}
}
impl<const N: usize> Supervisor<N> {
pub async fn run_pools(&self, spawner: Spawner) -> crate::ShutdownTimeout {
loop {
let next = match drive_pools(self.pools, self, spawner).await {
Ok(next) => next,
Err(e) => return e,
};
select(wait_scale(), deadline_timer(next)).await;
}
}
}