use std::collections::{BTreeMap, BTreeSet};
use std::time::{Duration, SystemTime};
use crate::admission::Key;
use crate::api::Waiting;
use crate::github::QueuedJob;
pub mod engine;
pub mod priority;
pub mod warm;
use priority::{Around, Backfill, Candidate, Caps, Held, Older, Runner};
pub use priority::{Barrier, Drained, PRIORITY_AFTER, SERVED_PRIORITY_AFTER, Scarce, Wait, Waits};
pub const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
#[derive(Debug, Clone, Copy)]
pub struct Hold {
pub until: SystemTime,
pub cause: crate::api::HoldCause,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct Pool {
pub repository: String,
pub profile: String,
}
impl From<&crate::config::Repository> for Pool {
fn from(repository: &crate::config::Repository) -> Pool {
Pool {
repository: repository.name.clone(),
profile: repository.profile.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct Repository {
pub name: String,
pub profile: String,
pub labels: Vec<String>,
pub paused: bool,
pub held: Option<Hold>,
pub queued: Vec<QueuedJob>,
pub runner_memory: Option<u64>,
pub runner_cpu: Option<u64>,
pub waits: Waits,
pub usual: Option<Duration>,
pub warm: usize,
}
impl Repository {
pub fn pool(&self) -> Pool {
Pool {
repository: self.name.clone(),
profile: self.profile.clone(),
}
}
}
#[derive(Debug, Clone)]
pub struct Profile {
pub memory: u64,
pub cpus: u64,
pub preparing: Option<Preparing>,
pub upkeep_due: bool,
pub count: usize,
pub slots: Vec<Slot>,
pub ran: Vec<Option<Key>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Preparing {
Reseeding,
PullingImage,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Slot {
Free,
Runner(RunnerSlot),
Closed,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RunnerSlot {
pub repository: String,
pub busy: bool,
pub started_at: SystemTime,
pub memory: u64,
pub cpu: u64,
pub usual: Option<Duration>,
}
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
pub struct SlotRef {
pub profile: String,
pub index: usize,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Decision {
Start {
slot: SlotRef,
repository: String,
memory: u64,
cpu: u64,
warm: bool,
replacing: Vec<SlotRef>,
behind: Option<u64>,
},
Stop {
slot: SlotRef,
reason: StopReason,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Demand {
pub pool: Pool,
pub job: u64,
pub scarce: Scarce,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum StopReason {
Expired,
Room,
Upkeep,
Paused,
Closed,
Changed,
OverBudget,
Clean,
Shutdown,
}
impl StopReason {
pub fn as_str(self) -> &'static str {
match self {
StopReason::Expired => "expired",
StopReason::Room => "room",
StopReason::Upkeep => "upkeep",
StopReason::Paused => "paused",
StopReason::Closed => "closed",
StopReason::Changed => "changed",
StopReason::OverBudget => "over_budget",
StopReason::Clean => "clean",
StopReason::Shutdown => "shutdown",
}
}
pub fn words(self) -> &'static str {
match self {
StopReason::Expired => "no job came for it",
StopReason::Room => "a queued job takes its room",
StopReason::Upkeep => "its profile's upkeep waits for it",
StopReason::Paused => "its repository is paused",
StopReason::Closed => "its slot closed",
StopReason::Changed => "the config or runnerd changed its runners",
StopReason::OverBudget => "raised for a heavier job, it does not fit the budget",
StopReason::Clean => "a cache clean needs its volumes",
StopReason::Shutdown => "runnerd stops",
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Plan {
pub decisions: Vec<Decision>,
pub waiting: BTreeMap<u64, Waiting>,
pub warm: BTreeSet<SlotRef>,
pub slot_waiting: BTreeSet<u64>,
pub held: Vec<Demand>,
pub barrier: Option<Barrier>,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Budget {
pub memory: Option<i64>,
pub cpu: Option<i64>,
pub host: Option<i64>,
pub held: bool,
pub drained: Drained,
pub credit_room: u64,
}
const GITHUB_HOSTED: &[&str] = &[
"ubuntu-slim",
"ubuntu-latest",
"ubuntu-26.04",
"ubuntu-24.04",
"ubuntu-22.04",
"ubuntu-26.04-arm",
"ubuntu-24.04-arm",
"ubuntu-22.04-arm",
"windows-latest",
"windows-2025",
"windows-2025-vs2026",
"windows-2022",
"windows-11-arm",
"windows-11-vs2026-arm",
"macos-latest",
"macos-26",
"macos-15",
"macos-14",
"macos-26-intel",
"macos-15-intel",
"xcode-27",
"macos-latest-large",
"macos-26-large",
"macos-15-large",
"macos-14-large",
"macos-latest-xlarge",
"macos-26-xlarge",
"macos-15-xlarge",
"macos-14-xlarge",
"xcode-27-xlarge",
];
fn hosted_by_github(job: &QueuedJob) -> bool {
matches!(&job.labels[..], [label] if GITHUB_HOSTED.iter().any(|hosted| hosted.eq_ignore_ascii_case(label)))
}
pub fn matches(job: &QueuedJob, labels: &[String]) -> bool {
crate::config::labels_match(&job.labels, labels)
}
pub fn plan(
repositories: &[Repository],
profiles: &BTreeMap<String, Profile>,
budget: Budget,
now: SystemTime,
) -> Plan {
let mut decided = Plan::default();
unserved(repositories, &mut decided);
let ToServe {
mut wanted,
jobs,
warm: warm_wanted,
} = to_serve(repositories, profiles, now, &mut decided);
let mut warm = Warm::new(&decided.warm, profiles, budget.held);
let mut taken = taken_slots(profiles);
let mut left = Left {
memory: budget.memory,
cpu: budget.cpu,
host: budget.host,
};
let mut started = Started::new(&taken, left);
let mut slot_bound = SlotBound::default();
let drained = (!budget.held).then_some(budget.drained);
let mut behind = Behind::new(profiles);
for (position, &(job, repository)) in jobs.iter().enumerate() {
let Some(missing) = wanted.get_mut(&pool_key(repository)) else {
continue;
};
if *missing == 0 {
continue;
}
let (Some(profile), Some(taken)) = (
profiles.get(&repository.profile),
taken.get_mut(repository.profile.as_str()),
) else {
continue;
};
let memory = repository.runner_memory.unwrap_or(profile.memory);
let cpu = repository.runner_cpu.unwrap_or(profile.cpus);
let free_index = free_slot(taken, profile, repository, job, &jobs[position + 1..]);
let fits = free_index.is_some() && left.fits(memory, cpu);
let turn = Turn {
repository,
profile,
job,
memory,
cpu,
free_slot: free_index.is_some(),
left,
started: &started,
};
if let Some(barrier) = decided.barrier {
let candidate = Candidate {
profile: &repository.profile,
free_slots: taken.iter().filter(|taken| !**taken).count(),
usual: repository.usual,
caps: profile.caps(),
};
if !fits || !behind.admits(candidate) {
turn.behind(barrier, &mut decided);
continue;
}
}
let room = if fits || profile.preparing.is_some() {
None
} else {
warm.make_room(repository, free_index.is_none(), left, memory, cpu)
};
let index = match (room.as_ref(), free_index) {
(Some(room), free) => free.or(room.slot).unwrap_or_default(),
(None, Some(index)) if fits => index,
(None, _) => {
turn.waits(drained, &mut slot_bound, now, &mut decided);
let job = Older {
profile: &repository.profile,
free_slot: free_index.is_some() || profile.preparing.is_some(),
memory,
cpu,
};
behind.left_waiting(job, decided.barrier, left, &budget, now);
continue;
}
};
let replacing = room.map_or_else(Vec::new, |room| stop_for(room, &mut left, &mut decided));
taken[index] = true;
*missing -= 1;
started.note(&repository.profile, job);
left.take(memory, cpu);
behind.started(&repository.profile, profile.caps(), memory, cpu, now);
decided.decisions.push(start(
repository,
index,
memory,
cpu,
replacing,
decided.barrier,
));
}
if !budget.held {
start_warm(&warm_wanted, profiles, &mut taken, left, &mut decided);
}
decided
}
fn stop_for(room: Room, left: &mut Left, decided: &mut Plan) -> Vec<SlotRef> {
left.give(room.memory, room.cpu);
for slot in &room.stopped {
decided.warm.remove(slot);
decided.decisions.push(Decision::Stop {
slot: slot.clone(),
reason: StopReason::Room,
});
}
room.stopped
}
struct Behind<'plan> {
runners: Vec<Runner<'plan>>,
older: Vec<Older<'plan>>,
backfill: Option<Backfill<'plan>>,
}
impl<'plan> Behind<'plan> {
fn new(profiles: &'plan BTreeMap<String, Profile>) -> Behind<'plan> {
let mut runners = Vec::new();
for (name, profile) in profiles {
for slot in &profile.slots {
if let Slot::Runner(runner) = slot {
runners.push(Runner {
profile: name,
started_at: runner.started_at,
usual: runner.usual.filter(|_| runner.busy),
memory: runner.memory,
cpu: runner.cpu,
caps: profile.caps(),
});
}
}
}
Behind {
runners,
older: Vec::new(),
backfill: None,
}
}
fn left_waiting(
&mut self,
job: Older<'plan>,
barrier: Option<Barrier>,
left: Left,
budget: &Budget,
now: SystemTime,
) {
let Some(barrier) = barrier else {
self.older.push(job);
return;
};
let around = Around {
left,
credit_room: budget.credit_room,
drained: budget.drained,
runners: &self.runners,
older: &self.older,
};
self.backfill = Backfill::behind(barrier, job.profile, around, now);
}
fn admits(&mut self, candidate: Candidate<'_>) -> bool {
let backfill = self.backfill.as_mut();
backfill.is_some_and(|backfill| backfill.admits(candidate))
}
fn started(&mut self, profile: &'plan str, caps: Caps, memory: u64, cpu: u64, now: SystemTime) {
self.runners.push(Runner {
profile,
started_at: now,
usual: None,
memory,
cpu,
caps,
});
}
}
struct ToServe<'plan> {
wanted: BTreeMap<(&'plan str, &'plan str), usize>,
jobs: Vec<(u64, &'plan Repository)>,
warm: Vec<(&'plan Repository, usize)>,
}
fn to_serve<'plan>(
repositories: &'plan [Repository],
profiles: &BTreeMap<String, Profile>,
now: SystemTime,
decided: &mut Plan,
) -> ToServe<'plan> {
let mut serve = ToServe {
wanted: BTreeMap::new(),
jobs: Vec::new(),
warm: Vec::new(),
};
for repository in repositories {
if let Some(sorted) = sort_out(repository, profiles, now, decided) {
serve
.wanted
.insert(pool_key(repository), sorted.serve.len());
serve
.jobs
.extend(sorted.serve.into_iter().map(|job| (job, repository)));
serve.warm.push((repository, sorted.warm));
}
}
serve.jobs.sort_by_key(|(id, _)| *id);
serve
}
#[derive(Debug, Default)]
struct SlotBound {
memory: u64,
cpu: u64,
}
impl SlotBound {
fn takes(&mut self, left: Left, memory: u64, cpu: u64) -> bool {
let mut spare = left;
spare.take(self.memory, self.cpu);
let fits = spare.fits(memory, cpu);
if fits {
self.memory = self.memory.saturating_add(memory);
self.cpu = self.cpu.saturating_add(cpu);
}
fits
}
}
fn free_slot(
taken: &[bool],
profile: &Profile,
repository: &Repository,
job: u64,
later: &[(u64, &Repository)],
) -> Option<usize> {
let ran = |index: usize| profile.ran.get(index).and_then(Option::as_ref);
let ran_it = |index: usize, repository: &Repository, job: u64| {
let queued = repository.queued.iter().find(|queued| queued.id == job);
queued.zip(ran(index)).is_some_and(|(queued, key)| {
key.repository == repository.name
&& key.workflow == queued.workflow
&& key.name == queued.name
})
};
taken
.iter()
.enumerate()
.filter(|(_, taken)| !**taken)
.map(|(index, _)| index)
.min_by_key(|&index| {
let wanted_later = later.iter().any(|&(id, other)| {
other.profile == repository.profile && ran_it(index, other, id)
});
let same_repository = ran(index).is_some_and(|key| key.repository == repository.name);
(
!ran_it(index, repository, job),
wanted_later,
!same_repository,
index,
)
})
}
fn hold(repository: &Repository, job: u64, scarce: Scarce, decided: &mut Plan) {
let pool = repository.pool();
let held = decided
.held
.iter()
.any(|demand| demand.pool == pool && demand.scarce == scarce);
if !held {
decided.held.push(Demand { pool, job, scarce });
}
}
struct Turn<'plan> {
repository: &'plan Repository,
profile: &'plan Profile,
job: u64,
memory: u64,
cpu: u64,
free_slot: bool,
left: Left,
started: &'plan Started<'plan>,
}
impl Turn<'_> {
fn why(&self) -> (Waiting, Short) {
why_waits(
&self.repository.profile,
self.profile,
self.free_slot,
self.memory,
self.cpu,
self.left,
self.started,
)
}
fn waits(
self,
drained: Option<Drained>,
slot_bound: &mut SlotBound,
now: SystemTime,
decided: &mut Plan,
) {
let (reason, short) = self.why();
decided.waiting.insert(self.job, reason);
if !self.free_slot
&& self.profile.preparing.is_none()
&& slot_bound.takes(self.left, self.memory, self.cpu)
{
decided.slot_waiting.insert(self.job);
}
let Some(scarce) = short.scarce() else {
return;
};
if drained.is_some() {
hold(self.repository, self.job, scarce, decided);
}
decided.barrier = Barrier::of(
priority::Short {
job: self.job,
scarce,
held: short.held(),
memory: self.memory,
cpu: self.cpu,
},
&self.repository.waits,
drained,
now,
);
}
fn behind(self, barrier: Barrier, decided: &mut Plan) {
if self.free_slot && self.left.fits(self.memory, self.cpu) {
decided.waiting.insert(self.job, barrier.reason());
return;
}
let (reason, short) = self.why();
let reason = if self.free_slot {
barrier.reason()
} else {
reason
};
decided.waiting.insert(self.job, reason);
if let Some(scarce) = short.scarce() {
hold(self.repository, self.job, scarce, decided);
}
}
}
fn pool_key(repository: &Repository) -> (&str, &str) {
(&repository.name, &repository.profile)
}
fn unserved(repositories: &[Repository], decided: &mut Plan) {
let mut seen = BTreeSet::new();
for repository in repositories {
if !seen.insert(repository.name.as_str()) {
continue;
}
let pools: Vec<&Repository> = repositories
.iter()
.filter(|pool| pool.name == repository.name)
.collect();
decided.waiting.extend(
repository
.queued
.iter()
.filter(|job| {
!hosted_by_github(job) && !pools.iter().any(|pool| matches(job, &pool.labels))
})
.map(|job| {
(
job.id,
Waiting::NoPool {
labels: job.labels.clone(),
},
)
}),
);
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Short {
Slot,
Memory,
Host,
Cpu,
}
impl Short {
fn scarce(self) -> Option<Scarce> {
match self {
Short::Slot => None,
Short::Memory | Short::Host => Some(Scarce::Memory),
Short::Cpu => Some(Scarce::Cpu),
}
}
fn held(self) -> Held {
match self {
Short::Host => Held::ByHost,
Short::Slot | Short::Memory | Short::Cpu => Held::ByBudget,
}
}
}
fn why_waits(
name: &str,
profile: &Profile,
free_slot: bool,
memory: u64,
cpu: u64,
left: Left,
started: &Started<'_>,
) -> (Waiting, Short) {
let profile_name = || name.to_owned();
if !free_slot {
let reason = match profile.preparing {
Some(Preparing::Reseeding) => Waiting::Reseeding {
profile: profile_name(),
},
Some(Preparing::PullingImage) => Waiting::PullingImage {
profile: profile_name(),
},
None => started.for_slot(
name,
Waiting::NoSlot {
profile: profile_name(),
},
),
};
return (reason, Short::Slot);
}
match (left.memory, left.host, left.cpu) {
(Some(free), _, _) if free < signed(memory) => (
started.for_memory(
memory,
Waiting::Memory {
needs: memory,
free: unsigned(free),
},
),
Short::Memory,
),
(_, Some(free), _) if free < signed(memory) => (
started.for_host(
memory,
Waiting::HostMemory {
needs: memory,
free: unsigned(free),
},
),
Short::Host,
),
(_, _, Some(free)) => (
started.for_cpu(
cpu,
Waiting::Cpu {
needs: cpu,
free: unsigned(free),
},
),
Short::Cpu,
),
(_, _, None) => (
Waiting::NoSlot {
profile: profile_name(),
},
Short::Slot,
),
}
}
fn start(
repository: &Repository,
index: usize,
memory: u64,
cpu: u64,
replacing: Vec<SlotRef>,
barrier: Option<Barrier>,
) -> Decision {
Decision::Start {
slot: SlotRef {
profile: repository.profile.clone(),
index,
},
repository: repository.name.clone(),
memory,
cpu,
warm: false,
replacing,
behind: barrier.map(|barrier| barrier.job),
}
}
fn start_warm(
wanted: &[(&Repository, usize)],
profiles: &BTreeMap<String, Profile>,
taken: &mut BTreeMap<&str, Vec<bool>>,
mut left: Left,
decided: &mut Plan,
) {
let room_wanted = decided.waiting.values().any(|reason| {
matches!(
reason,
Waiting::NoSlot { .. }
| Waiting::Memory { .. }
| Waiting::HostMemory { .. }
| Waiting::Cpu { .. }
| Waiting::BehindCpu { .. }
| Waiting::BehindMemory { .. }
| Waiting::BehindStart { .. }
)
});
if room_wanted {
return;
}
for round in 0.. {
let mut any = false;
for (repository, wants) in wanted {
if *wants <= round {
continue;
}
let (Some(profile), Some(taken)) = (
profiles.get(&repository.profile),
taken.get_mut(repository.profile.as_str()),
) else {
continue;
};
let (memory, cpu) = (profile.memory, profile.cpus);
let Some(index) = taken.iter().position(|taken| !taken) else {
continue;
};
if !left.fits(memory, cpu) {
continue;
}
taken[index] = true;
left.take(memory, cpu);
any = true;
decided.decisions.push(Decision::Start {
slot: SlotRef {
profile: repository.profile.clone(),
index,
},
repository: repository.name.clone(),
memory,
cpu,
warm: true,
replacing: Vec::new(),
behind: None,
});
}
if !any {
break;
}
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct Left {
pub(crate) memory: Option<i64>,
pub(crate) cpu: Option<i64>,
pub(crate) host: Option<i64>,
}
impl Profile {
fn caps(&self) -> Caps {
Caps {
memory: self.memory,
cpu: self.cpus,
}
}
}
impl Left {
fn fits(self, memory: u64, cpu: u64) -> bool {
let fits = |free: Option<i64>, needs: u64| free.is_none_or(|free| free >= signed(needs));
fits(self.memory, memory) && fits(self.host, memory) && fits(self.cpu, cpu)
}
fn short(self, memory: u64, cpu: u64) -> Left {
let lacks = |free: Option<i64>, needs: u64| {
free.map(|free| signed(needs).saturating_sub(free).max(0))
};
Left {
memory: lacks(self.memory, memory).max(lacks(self.host, memory)),
cpu: lacks(self.cpu, cpu),
host: None,
}
}
fn take(&mut self, memory: u64, cpu: u64) {
let take = |free: &mut Option<i64>, used: u64| {
*free = free.map(|free| free.saturating_sub(signed(used)));
};
take(&mut self.memory, memory);
take(&mut self.host, memory);
take(&mut self.cpu, cpu);
}
fn give(&mut self, memory: u64, cpu: u64) {
let give = |free: &mut Option<i64>, freed: u64| {
*free = free.map(|free| free.saturating_add(signed(freed)));
};
give(&mut self.memory, memory);
give(&mut self.host, memory);
give(&mut self.cpu, cpu);
}
}
fn left(budget: u64, in_use: u64) -> i64 {
signed(budget).saturating_sub(signed(in_use))
}
fn signed(amount: u64) -> i64 {
i64::try_from(amount).unwrap_or(i64::MAX)
}
fn unsigned(free: i64) -> u64 {
u64::try_from(free).unwrap_or(0)
}
struct Sorted {
serve: Vec<u64>,
warm: usize,
}
fn sort_out(
repository: &Repository,
profiles: &BTreeMap<String, Profile>,
now: SystemTime,
decided: &mut Plan,
) -> Option<Sorted> {
let mut matching: Vec<&QueuedJob> = repository
.queued
.iter()
.filter(|job| matches(job, &repository.labels))
.collect();
let profile = profiles.get(&repository.profile);
let mut warm = repository.warm;
if repository.paused {
decided
.waiting
.extend(matching.iter().map(|job| (job.id, Waiting::Paused)));
matching.clear();
warm = 0;
}
let upkeep_due = profile.is_some_and(|profile| profile.upkeep_due);
let stop_now = upkeep_due || repository.paused;
if upkeep_due {
warm = 0;
}
let (idle, closing): (Vec<(SlotRef, &RunnerSlot)>, Vec<_>) = profile
.into_iter()
.flat_map(|profile| profile.slots.iter().enumerate())
.filter_map(|(index, slot)| match slot {
Slot::Runner(runner) if runner.repository == repository.name && !runner.busy => Some((
SlotRef {
profile: repository.profile.clone(),
index,
},
runner,
)),
_ => None,
})
.partition(|(slot, _)| profile.is_none_or(|profile| slot.index < profile.count));
decided
.decisions
.extend(closing.into_iter().map(|(slot, _)| Decision::Stop {
slot,
reason: StopReason::Closed,
}));
let surplus = idle.len().saturating_sub(matching.len());
let stops: Vec<SlotRef> = idle
.iter()
.filter(|(_, runner)| {
stop_now
|| now
.duration_since(runner.started_at)
.is_ok_and(|waited| waited >= IDLE_TIMEOUT)
})
.take(surplus.saturating_sub(warm))
.map(|(slot, _)| slot.clone())
.collect();
let kept: Vec<&SlotRef> = idle
.iter()
.map(|(slot, _)| slot)
.filter(|slot| !stops.contains(slot))
.collect();
decided
.warm
.extend(kept.iter().skip(matching.len()).map(|slot| (*slot).clone()));
let warm = warm.saturating_sub(kept.len().saturating_sub(matching.len()));
decided
.decisions
.extend(stops.into_iter().map(|slot| Decision::Stop {
slot,
reason: if repository.paused {
StopReason::Paused
} else if upkeep_due {
StopReason::Upkeep
} else {
StopReason::Expired
},
}));
let missing = matching.len().saturating_sub(idle.len());
let skip = matching.len() - missing;
decided.waiting.extend(
matching
.iter()
.take(skip)
.map(|job| (job.id, Waiting::RunnerStarting)),
);
let serve = matching.iter().skip(skip).map(|job| job.id);
match repository.held.filter(|held| held.until > now) {
Some(held) => {
let until = crate::time::ms(held.until) / 1000;
decided.waiting.extend(serve.map(|job| {
(
job,
Waiting::Backoff {
until,
cause: held.cause,
},
)
}));
None
}
None => Some(Sorted {
serve: serve.collect(),
warm,
}),
}
}
struct Warm<'plan> {
runners: Vec<Option<(SlotRef, &'plan RunnerSlot)>>,
}
struct Room {
stopped: Vec<SlotRef>,
slot: Option<usize>,
memory: u64,
cpu: u64,
}
impl<'plan> Warm<'plan> {
fn new(
warm: &BTreeSet<SlotRef>,
profiles: &'plan BTreeMap<String, Profile>,
held: bool,
) -> Warm<'plan> {
let runners = warm
.iter()
.filter(|_| !held)
.filter_map(
|slot| match profiles.get(&slot.profile)?.slots.get(slot.index)? {
Slot::Runner(runner) => Some(Some((slot.clone(), runner))),
Slot::Free | Slot::Closed => None,
},
)
.collect();
Warm { runners }
}
fn make_room(
&mut self,
repository: &Repository,
slot: bool,
left: Left,
needs_memory: u64,
needs_cpu: u64,
) -> Option<Room> {
let short = left.short(needs_memory, needs_cpu);
let (memory, cpu) = (
unsigned(short.memory.unwrap_or(0)),
unsigned(short.cpu.unwrap_or(0)),
);
let mut candidates: Vec<usize> = self
.runners
.iter()
.enumerate()
.filter_map(|(at, runner)| {
runner
.as_ref()
.filter(|(slot, runner)| {
runner.repository != repository.name || slot.profile != repository.profile
})
.map(|_| at)
})
.collect();
candidates.sort_by_key(|at| {
self.runners[*at]
.as_ref()
.is_some_and(|(slot, _)| slot.profile != repository.profile)
});
let mut room = Room {
stopped: Vec::new(),
slot: None,
memory: 0,
cpu: 0,
};
let mut picked = Vec::new();
for at in candidates {
let short = (slot && room.slot.is_none()) || room.memory < memory || room.cpu < cpu;
if !short {
break;
}
let Some((ref_, runner)) = &self.runners[at] else {
continue;
};
let gives_slot = ref_.profile == repository.profile;
let helps = (gives_slot && slot && room.slot.is_none())
|| (room.memory < memory && runner.memory > 0)
|| (room.cpu < cpu && runner.cpu > 0);
if !helps {
continue;
}
if gives_slot && room.slot.is_none() {
room.slot = Some(ref_.index);
}
room.memory += runner.memory;
room.cpu += runner.cpu;
room.stopped.push(ref_.clone());
picked.push(at);
}
let mut after = left;
after.give(room.memory, room.cpu);
if (slot && room.slot.is_none()) || !after.fits(needs_memory, needs_cpu) {
return None;
}
for at in picked {
self.runners[at] = None;
}
Some(room)
}
}
struct Started<'plan> {
free_slots: BTreeSet<&'plan str>,
before: Left,
by_profile: BTreeMap<&'plan str, u64>,
first: Option<u64>,
}
impl<'plan> Started<'plan> {
fn new(taken: &BTreeMap<&'plan str, Vec<bool>>, before: Left) -> Started<'plan> {
Started {
free_slots: taken
.iter()
.filter(|(_, slots)| slots.contains(&false))
.map(|(name, _)| *name)
.collect(),
before,
by_profile: BTreeMap::new(),
first: None,
}
}
fn note(&mut self, profile: &'plan str, job: u64) {
self.by_profile.entry(profile).or_insert(job);
self.first.get_or_insert(job);
}
fn for_slot(&self, profile: &str, reason: Waiting) -> Waiting {
match self.by_profile.get(profile) {
Some(older) if self.free_slots.contains(profile) => {
Waiting::BehindStart { job: *older }
}
_ => reason,
}
}
fn for_memory(&self, needs: u64, reason: Waiting) -> Waiting {
Self::behind(self.first, self.before.memory, needs).unwrap_or(reason)
}
fn for_host(&self, needs: u64, reason: Waiting) -> Waiting {
Self::behind(self.first, self.before.host, needs).unwrap_or(reason)
}
fn for_cpu(&self, needs: u64, reason: Waiting) -> Waiting {
Self::behind(self.first, self.before.cpu, needs).unwrap_or(reason)
}
fn behind(first: Option<u64>, free: Option<i64>, needs: u64) -> Option<Waiting> {
first
.filter(|_| free.is_some_and(|free| free >= signed(needs)))
.map(|job| Waiting::BehindStart { job })
}
}
fn taken_slots(profiles: &BTreeMap<String, Profile>) -> BTreeMap<&str, Vec<bool>> {
profiles
.iter()
.map(|(name, profile)| {
let taken = profile
.slots
.iter()
.map(|slot| profile.preparing.is_some() || *slot != Slot::Free)
.collect();
(name.as_str(), taken)
})
.collect()
}
#[cfg(test)]
mod tests;