1use std::collections::{BTreeMap, BTreeSet};
6use std::time::{Duration, SystemTime};
7
8use crate::admission::Key;
9use crate::api::Waiting;
10use crate::github::QueuedJob;
11
12pub mod engine;
13pub mod warm;
14
15pub const IDLE_TIMEOUT: Duration = Duration::from_secs(300);
18
19pub const CPU_PRIORITY_AFTER: Duration = Duration::from_secs(120);
22
23#[derive(Debug, Clone, Copy)]
25pub struct Hold {
26 pub until: SystemTime,
28 pub cause: crate::api::HoldCause,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
35pub struct Pool {
36 pub repository: String,
38 pub profile: String,
40}
41
42impl From<&crate::config::Repository> for Pool {
43 fn from(repository: &crate::config::Repository) -> Pool {
44 Pool {
45 repository: repository.name.clone(),
46 profile: repository.profile.clone(),
47 }
48 }
49}
50
51#[derive(Debug, Clone)]
54pub struct Repository {
55 pub name: String,
57 pub profile: String,
59 pub labels: Vec<String>,
61 pub paused: bool,
63 pub held: Option<Hold>,
65 pub queued: Vec<QueuedJob>,
67 pub runner_memory: Option<u64>,
70 pub runner_cpu: Option<u64>,
73 pub cpu_waiting_since: Option<SystemTime>,
75 pub warm: usize,
77}
78
79impl Repository {
80 pub fn pool(&self) -> Pool {
82 Pool {
83 repository: self.name.clone(),
84 profile: self.profile.clone(),
85 }
86 }
87
88 fn starved_of_cpu(&self, now: SystemTime) -> bool {
90 self.cpu_waiting_since
91 .and_then(|since| now.duration_since(since).ok())
92 .is_some_and(|waited| waited >= CPU_PRIORITY_AFTER)
93 }
94}
95
96#[derive(Debug, Clone)]
98pub struct Profile {
99 pub memory: u64,
101 pub cpus: u64,
104 pub preparing: Option<Preparing>,
106 pub upkeep_due: bool,
109 pub count: usize,
111 pub slots: Vec<Slot>,
113 pub ran: Vec<Option<Key>>,
116}
117
118#[derive(Debug, Clone, Copy, PartialEq, Eq)]
120pub enum Preparing {
121 Reseeding,
123 PullingImage,
125}
126
127#[derive(Debug, Clone, PartialEq, Eq)]
129pub enum Slot {
130 Free,
132 Runner(RunnerSlot),
134 Closed,
137}
138
139#[derive(Debug, Clone, PartialEq, Eq)]
141pub struct RunnerSlot {
142 pub repository: String,
144 pub busy: bool,
146 pub started_at: SystemTime,
148 pub memory: u64,
150 pub cpu: u64,
152}
153
154#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
156pub struct SlotRef {
157 pub profile: String,
159 pub index: usize,
161}
162
163#[derive(Debug, Clone, PartialEq, Eq)]
165pub enum Decision {
166 Start {
168 slot: SlotRef,
170 repository: String,
172 memory: u64,
174 cpu: u64,
176 warm: bool,
178 replacing: Vec<SlotRef>,
181 },
182 HeldForCpu {
185 repository: String,
187 profile: String,
189 },
190 Stop {
193 slot: SlotRef,
195 },
196}
197
198#[derive(Debug, Clone, Default, PartialEq, Eq)]
200pub struct Plan {
201 pub decisions: Vec<Decision>,
203 pub waiting: BTreeMap<u64, Waiting>,
207 pub warm: BTreeSet<SlotRef>,
209 pub slot_waiting: BTreeSet<u64>,
214}
215
216#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
218pub struct Budget {
219 pub memory: Option<i64>,
222 pub cpu: Option<i64>,
225 pub host: Option<i64>,
228 pub held: bool,
231}
232
233const GITHUB_HOSTED: &[&str] = &[
239 "ubuntu-slim",
240 "ubuntu-latest",
241 "ubuntu-26.04",
242 "ubuntu-24.04",
243 "ubuntu-22.04",
244 "ubuntu-26.04-arm",
245 "ubuntu-24.04-arm",
246 "ubuntu-22.04-arm",
247 "windows-latest",
248 "windows-2025",
249 "windows-2025-vs2026",
250 "windows-2022",
251 "windows-11-arm",
252 "windows-11-vs2026-arm",
253 "macos-latest",
254 "macos-26",
255 "macos-15",
256 "macos-14",
257 "macos-26-intel",
258 "macos-15-intel",
259 "xcode-27",
260 "macos-latest-large",
261 "macos-26-large",
262 "macos-15-large",
263 "macos-14-large",
264 "macos-latest-xlarge",
265 "macos-26-xlarge",
266 "macos-15-xlarge",
267 "macos-14-xlarge",
268 "xcode-27-xlarge",
269];
270
271fn hosted_by_github(job: &QueuedJob) -> bool {
275 matches!(&job.labels[..], [label] if GITHUB_HOSTED.iter().any(|hosted| hosted.eq_ignore_ascii_case(label)))
276}
277
278pub fn matches(job: &QueuedJob, labels: &[String]) -> bool {
281 crate::config::labels_match(&job.labels, labels)
282}
283
284pub fn plan(
299 repositories: &[Repository],
300 profiles: &BTreeMap<String, Profile>,
301 budget: Budget,
302 now: SystemTime,
303) -> Plan {
304 let mut decided = Plan::default();
305 unserved(repositories, &mut decided);
306 let ToServe {
307 mut wanted,
308 jobs,
309 warm: warm_wanted,
310 } = to_serve(repositories, profiles, now, &mut decided);
311
312 let mut warm = Warm::new(&decided.warm, profiles, budget.held);
313 let mut taken = taken_slots(profiles);
314 let mut left = Left {
315 memory: budget.memory,
316 cpu: budget.cpu,
317 host: budget.host,
318 };
319 let mut started = Started::new(&taken, left);
320 let mut slot_bound = SlotBound::default();
321 let mut first_for_cpu = None;
323 for (position, &(job, repository)) in jobs.iter().enumerate() {
324 let Some(missing) = wanted.get_mut(&pool_key(repository)) else {
325 continue;
326 };
327 if *missing == 0 {
328 continue;
329 }
330 let (Some(profile), Some(taken)) = (
331 profiles.get(&repository.profile),
332 taken.get_mut(repository.profile.as_str()),
333 ) else {
334 continue;
335 };
336 if let Some(older) = first_for_cpu {
337 decided
338 .waiting
339 .insert(job, Waiting::BehindCpu { job: older });
340 continue;
341 }
342 let memory = repository.runner_memory.unwrap_or(profile.memory);
343 let cpu = repository.runner_cpu.unwrap_or(profile.cpus);
344 let free_index = free_slot(taken, profile, repository, job, &jobs[position + 1..]);
345 let fits = free_index.is_some() && left.fits(memory, cpu);
346 let room = if fits || profile.preparing.is_some() {
347 None
348 } else {
349 warm.make_room(repository, free_index.is_none(), left, memory, cpu)
350 };
351 let index = match (room.as_ref(), free_index) {
352 (Some(room), free) => free.or(room.slot).unwrap_or_default(),
353 (None, Some(index)) if fits => index,
354 (None, free) => {
355 let (reason, short) = why_waits(
356 &repository.profile,
357 profile,
358 free.is_some(),
359 memory,
360 cpu,
361 left,
362 &started,
363 );
364 decided.waiting.insert(job, reason);
365 if free.is_none()
366 && profile.preparing.is_none()
367 && slot_bound.takes(left, memory, cpu)
368 {
369 decided.slot_waiting.insert(job);
370 }
371 if short == Short::Cpu {
372 let held = held_for_cpu(repository);
373 if !decided.decisions.contains(&held) {
374 decided.decisions.push(held);
375 }
376 if repository.starved_of_cpu(now) {
378 first_for_cpu = Some(job);
379 }
380 }
381 continue;
382 }
383 };
384 let replacing = room.map_or_else(Vec::new, |room| {
386 left.give(room.memory, room.cpu);
387 for slot in &room.stopped {
388 decided.warm.remove(slot);
389 decided
390 .decisions
391 .push(Decision::Stop { slot: slot.clone() });
392 }
393 room.stopped
394 });
395 taken[index] = true;
396 *missing -= 1;
397 started.note(&repository.profile, job);
398 left.take(memory, cpu);
399 decided
400 .decisions
401 .push(start(repository, index, memory, cpu, replacing));
402 }
403 if !budget.held {
404 start_warm(&warm_wanted, profiles, &mut taken, left, &mut decided);
405 }
406 decided
407}
408
409struct ToServe<'plan> {
411 wanted: BTreeMap<(&'plan str, &'plan str), usize>,
413 jobs: Vec<(u64, &'plan Repository)>,
415 warm: Vec<(&'plan Repository, usize)>,
417}
418
419fn to_serve<'plan>(
421 repositories: &'plan [Repository],
422 profiles: &BTreeMap<String, Profile>,
423 now: SystemTime,
424 decided: &mut Plan,
425) -> ToServe<'plan> {
426 let mut serve = ToServe {
427 wanted: BTreeMap::new(),
428 jobs: Vec::new(),
429 warm: Vec::new(),
430 };
431 for repository in repositories {
432 if let Some(sorted) = sort_out(repository, profiles, now, decided) {
433 serve
434 .wanted
435 .insert(pool_key(repository), sorted.serve.len());
436 serve
437 .jobs
438 .extend(sorted.serve.into_iter().map(|job| (job, repository)));
439 serve.warm.push((repository, sorted.warm));
440 }
441 }
442 serve.jobs.sort_by_key(|(id, _)| *id);
443 serve
444}
445
446#[derive(Debug, Default)]
449struct SlotBound {
450 memory: u64,
451 cpu: u64,
452}
453
454impl SlotBound {
455 fn takes(&mut self, left: Left, memory: u64, cpu: u64) -> bool {
457 let mut spare = left;
458 spare.take(self.memory, self.cpu);
459 let fits = spare.fits(memory, cpu);
460 if fits {
461 self.memory = self.memory.saturating_add(memory);
462 self.cpu = self.cpu.saturating_add(cpu);
463 }
464 fits
465 }
466}
467
468fn free_slot(
474 taken: &[bool],
475 profile: &Profile,
476 repository: &Repository,
477 job: u64,
478 later: &[(u64, &Repository)],
479) -> Option<usize> {
480 let ran = |index: usize| profile.ran.get(index).and_then(Option::as_ref);
481 let ran_it = |index: usize, repository: &Repository, job: u64| {
482 let queued = repository.queued.iter().find(|queued| queued.id == job);
483 queued.zip(ran(index)).is_some_and(|(queued, key)| {
484 key.repository == repository.name
485 && key.workflow == queued.workflow
486 && key.name == queued.name
487 })
488 };
489 taken
490 .iter()
491 .enumerate()
492 .filter(|(_, taken)| !**taken)
493 .map(|(index, _)| index)
494 .min_by_key(|&index| {
495 let wanted_later = later.iter().any(|&(id, other)| {
496 other.profile == repository.profile && ran_it(index, other, id)
497 });
498 let same_repository = ran(index).is_some_and(|key| key.repository == repository.name);
499 (
500 !ran_it(index, repository, job),
501 wanted_later,
502 !same_repository,
503 index,
504 )
505 })
506}
507
508fn held_for_cpu(repository: &Repository) -> Decision {
510 Decision::HeldForCpu {
511 repository: repository.name.clone(),
512 profile: repository.profile.clone(),
513 }
514}
515
516fn pool_key(repository: &Repository) -> (&str, &str) {
518 (&repository.name, &repository.profile)
519}
520
521fn unserved(repositories: &[Repository], decided: &mut Plan) {
523 let mut seen = BTreeSet::new();
524 for repository in repositories {
525 if !seen.insert(repository.name.as_str()) {
526 continue;
527 }
528 let pools: Vec<&Repository> = repositories
529 .iter()
530 .filter(|pool| pool.name == repository.name)
531 .collect();
532 decided.waiting.extend(
533 repository
534 .queued
535 .iter()
536 .filter(|job| {
537 !hosted_by_github(job) && !pools.iter().any(|pool| matches(job, &pool.labels))
538 })
539 .map(|job| {
540 (
541 job.id,
542 Waiting::NoPool {
543 labels: job.labels.clone(),
544 },
545 )
546 }),
547 );
548 }
549}
550
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
553enum Short {
554 Slot,
555 Memory,
556 Cpu,
557}
558
559fn why_waits(
562 name: &str,
563 profile: &Profile,
564 free_slot: bool,
565 memory: u64,
566 cpu: u64,
567 left: Left,
568 started: &Started<'_>,
569) -> (Waiting, Short) {
570 let profile_name = || name.to_owned();
571 if !free_slot {
572 let reason = match profile.preparing {
573 Some(Preparing::Reseeding) => Waiting::Reseeding {
574 profile: profile_name(),
575 },
576 Some(Preparing::PullingImage) => Waiting::PullingImage {
577 profile: profile_name(),
578 },
579 None => started.for_slot(
580 name,
581 Waiting::NoSlot {
582 profile: profile_name(),
583 },
584 ),
585 };
586 return (reason, Short::Slot);
587 }
588 match (left.memory, left.host, left.cpu) {
589 (Some(free), _, _) if free < signed(memory) => (
590 started.for_memory(
591 memory,
592 Waiting::Memory {
593 needs: memory,
594 free: unsigned(free),
595 },
596 ),
597 Short::Memory,
598 ),
599 (_, Some(free), _) if free < signed(memory) => (
600 started.for_host(
601 memory,
602 Waiting::HostMemory {
603 needs: memory,
604 free: unsigned(free),
605 },
606 ),
607 Short::Memory,
608 ),
609 (_, _, Some(free)) => (
610 started.for_cpu(
611 cpu,
612 Waiting::Cpu {
613 needs: cpu,
614 free: unsigned(free),
615 },
616 ),
617 Short::Cpu,
618 ),
619 (_, _, None) => (
621 Waiting::NoSlot {
622 profile: profile_name(),
623 },
624 Short::Slot,
625 ),
626 }
627}
628
629fn start(
632 repository: &Repository,
633 index: usize,
634 memory: u64,
635 cpu: u64,
636 replacing: Vec<SlotRef>,
637) -> Decision {
638 Decision::Start {
639 slot: SlotRef {
640 profile: repository.profile.clone(),
641 index,
642 },
643 repository: repository.name.clone(),
644 memory,
645 cpu,
646 warm: false,
647 replacing,
648 }
649}
650
651fn start_warm(
655 wanted: &[(&Repository, usize)],
656 profiles: &BTreeMap<String, Profile>,
657 taken: &mut BTreeMap<&str, Vec<bool>>,
658 mut left: Left,
659 decided: &mut Plan,
660) {
661 let room_wanted = decided.waiting.values().any(|reason| {
662 matches!(
663 reason,
664 Waiting::NoSlot { .. }
665 | Waiting::Memory { .. }
666 | Waiting::HostMemory { .. }
667 | Waiting::Cpu { .. }
668 | Waiting::BehindCpu { .. }
669 | Waiting::BehindStart { .. }
670 )
671 });
672 if room_wanted {
673 return;
674 }
675 for round in 0.. {
676 let mut any = false;
677 for (repository, wants) in wanted {
678 if *wants <= round {
679 continue;
680 }
681 let (Some(profile), Some(taken)) = (
682 profiles.get(&repository.profile),
683 taken.get_mut(repository.profile.as_str()),
684 ) else {
685 continue;
686 };
687 let (memory, cpu) = (profile.memory, profile.cpus);
688 let Some(index) = taken.iter().position(|taken| !taken) else {
689 continue;
690 };
691 if !left.fits(memory, cpu) {
692 continue;
693 }
694 taken[index] = true;
695 left.take(memory, cpu);
696 any = true;
697 decided.decisions.push(Decision::Start {
698 slot: SlotRef {
699 profile: repository.profile.clone(),
700 index,
701 },
702 repository: repository.name.clone(),
703 memory,
704 cpu,
705 warm: true,
706 replacing: Vec::new(),
707 });
708 }
709 if !any {
710 break;
711 }
712 }
713}
714
715#[derive(Debug, Clone, Copy)]
718struct Left {
719 memory: Option<i64>,
720 cpu: Option<i64>,
721 host: Option<i64>,
723}
724
725impl Left {
726 fn fits(self, memory: u64, cpu: u64) -> bool {
727 let fits = |free: Option<i64>, needs: u64| free.is_none_or(|free| free >= signed(needs));
728 fits(self.memory, memory) && fits(self.host, memory) && fits(self.cpu, cpu)
729 }
730
731 fn short(self, memory: u64, cpu: u64) -> Left {
734 let lacks = |free: Option<i64>, needs: u64| {
735 free.map(|free| signed(needs).saturating_sub(free).max(0))
736 };
737 Left {
738 memory: lacks(self.memory, memory).max(lacks(self.host, memory)),
739 cpu: lacks(self.cpu, cpu),
740 host: None,
741 }
742 }
743
744 fn take(&mut self, memory: u64, cpu: u64) {
745 let take = |free: &mut Option<i64>, used: u64| {
746 *free = free.map(|free| free.saturating_sub(signed(used)));
747 };
748 take(&mut self.memory, memory);
749 take(&mut self.host, memory);
750 take(&mut self.cpu, cpu);
751 }
752
753 fn give(&mut self, memory: u64, cpu: u64) {
754 let give = |free: &mut Option<i64>, freed: u64| {
755 *free = free.map(|free| free.saturating_add(signed(freed)));
756 };
757 give(&mut self.memory, memory);
758 give(&mut self.host, memory);
759 give(&mut self.cpu, cpu);
760 }
761}
762
763fn left(budget: u64, in_use: u64) -> i64 {
766 signed(budget).saturating_sub(signed(in_use))
767}
768
769fn signed(amount: u64) -> i64 {
771 i64::try_from(amount).unwrap_or(i64::MAX)
772}
773
774fn unsigned(free: i64) -> u64 {
776 u64::try_from(free).unwrap_or(0)
777}
778
779struct Sorted {
781 serve: Vec<u64>,
782 warm: usize,
783}
784
785fn sort_out(
789 repository: &Repository,
790 profiles: &BTreeMap<String, Profile>,
791 now: SystemTime,
792 decided: &mut Plan,
793) -> Option<Sorted> {
794 let mut matching: Vec<&QueuedJob> = repository
795 .queued
796 .iter()
797 .filter(|job| matches(job, &repository.labels))
798 .collect();
799 let profile = profiles.get(&repository.profile);
800 let mut warm = repository.warm;
801 if repository.paused {
802 decided
803 .waiting
804 .extend(matching.iter().map(|job| (job.id, Waiting::Paused)));
805 matching.clear();
807 warm = 0;
808 }
809 let upkeep_due = profile.is_some_and(|profile| profile.upkeep_due);
812 let stop_now = upkeep_due || repository.paused;
813 if upkeep_due {
814 warm = 0;
815 }
816 let (idle, closing): (Vec<(SlotRef, &RunnerSlot)>, Vec<_>) = profile
817 .into_iter()
818 .flat_map(|profile| profile.slots.iter().enumerate())
819 .filter_map(|(index, slot)| match slot {
820 Slot::Runner(runner) if runner.repository == repository.name && !runner.busy => Some((
821 SlotRef {
822 profile: repository.profile.clone(),
823 index,
824 },
825 runner,
826 )),
827 _ => None,
828 })
829 .partition(|(slot, _)| profile.is_none_or(|profile| slot.index < profile.count));
830 decided
832 .decisions
833 .extend(closing.into_iter().map(|(slot, _)| Decision::Stop { slot }));
834 let surplus = idle.len().saturating_sub(matching.len());
835 let stops: Vec<SlotRef> = idle
836 .iter()
837 .filter(|(_, runner)| {
838 stop_now
839 || now
840 .duration_since(runner.started_at)
841 .is_ok_and(|waited| waited >= IDLE_TIMEOUT)
842 })
843 .take(surplus.saturating_sub(warm))
844 .map(|(slot, _)| slot.clone())
845 .collect();
846 let kept: Vec<&SlotRef> = idle
848 .iter()
849 .map(|(slot, _)| slot)
850 .filter(|slot| !stops.contains(slot))
851 .collect();
852 decided
853 .warm
854 .extend(kept.iter().skip(matching.len()).map(|slot| (*slot).clone()));
855 let warm = warm.saturating_sub(kept.len().saturating_sub(matching.len()));
856 decided
857 .decisions
858 .extend(stops.into_iter().map(|slot| Decision::Stop { slot }));
859 let missing = matching.len().saturating_sub(idle.len());
860 let skip = matching.len() - missing;
862 decided.waiting.extend(
863 matching
864 .iter()
865 .take(skip)
866 .map(|job| (job.id, Waiting::RunnerStarting)),
867 );
868 let serve = matching.iter().skip(skip).map(|job| job.id);
869 match repository.held.filter(|held| held.until > now) {
870 Some(held) => {
871 let until = crate::time::ms(held.until) / 1000;
872 decided.waiting.extend(serve.map(|job| {
873 (
874 job,
875 Waiting::Backoff {
876 until,
877 cause: held.cause,
878 },
879 )
880 }));
881 None
882 }
883 None => Some(Sorted {
884 serve: serve.collect(),
885 warm,
886 }),
887 }
888}
889
890struct Warm<'plan> {
892 runners: Vec<Option<(SlotRef, &'plan RunnerSlot)>>,
894}
895
896struct Room {
898 stopped: Vec<SlotRef>,
900 slot: Option<usize>,
902 memory: u64,
903 cpu: u64,
904}
905
906impl<'plan> Warm<'plan> {
907 fn new(
909 warm: &BTreeSet<SlotRef>,
910 profiles: &'plan BTreeMap<String, Profile>,
911 held: bool,
912 ) -> Warm<'plan> {
913 let runners = warm
914 .iter()
915 .filter(|_| !held)
916 .filter_map(
917 |slot| match profiles.get(&slot.profile)?.slots.get(slot.index)? {
918 Slot::Runner(runner) => Some(Some((slot.clone(), runner))),
919 Slot::Free | Slot::Closed => None,
920 },
921 )
922 .collect();
923 Warm { runners }
924 }
925
926 fn make_room(
931 &mut self,
932 repository: &Repository,
933 slot: bool,
934 left: Left,
935 needs_memory: u64,
936 needs_cpu: u64,
937 ) -> Option<Room> {
938 let short = left.short(needs_memory, needs_cpu);
939 let (memory, cpu) = (
940 unsigned(short.memory.unwrap_or(0)),
941 unsigned(short.cpu.unwrap_or(0)),
942 );
943 let mut candidates: Vec<usize> = self
944 .runners
945 .iter()
946 .enumerate()
947 .filter_map(|(at, runner)| {
948 runner
949 .as_ref()
950 .filter(|(slot, runner)| {
951 runner.repository != repository.name || slot.profile != repository.profile
952 })
953 .map(|_| at)
954 })
955 .collect();
956 candidates.sort_by_key(|at| {
958 self.runners[*at]
959 .as_ref()
960 .is_some_and(|(slot, _)| slot.profile != repository.profile)
961 });
962 let mut room = Room {
963 stopped: Vec::new(),
964 slot: None,
965 memory: 0,
966 cpu: 0,
967 };
968 let mut picked = Vec::new();
969 for at in candidates {
970 let short = (slot && room.slot.is_none()) || room.memory < memory || room.cpu < cpu;
971 if !short {
972 break;
973 }
974 let Some((ref_, runner)) = &self.runners[at] else {
975 continue;
976 };
977 let gives_slot = ref_.profile == repository.profile;
978 let helps = (gives_slot && slot && room.slot.is_none())
980 || (room.memory < memory && runner.memory > 0)
981 || (room.cpu < cpu && runner.cpu > 0);
982 if !helps {
983 continue;
984 }
985 if gives_slot && room.slot.is_none() {
986 room.slot = Some(ref_.index);
987 }
988 room.memory += runner.memory;
989 room.cpu += runner.cpu;
990 room.stopped.push(ref_.clone());
991 picked.push(at);
992 }
993 let mut after = left;
995 after.give(room.memory, room.cpu);
996 if (slot && room.slot.is_none()) || !after.fits(needs_memory, needs_cpu) {
997 return None;
998 }
999 for at in picked {
1000 self.runners[at] = None;
1001 }
1002 Some(room)
1003 }
1004}
1005
1006struct Started<'plan> {
1009 free_slots: BTreeSet<&'plan str>,
1011 before: Left,
1013 by_profile: BTreeMap<&'plan str, u64>,
1015 first: Option<u64>,
1016}
1017
1018impl<'plan> Started<'plan> {
1019 fn new(taken: &BTreeMap<&'plan str, Vec<bool>>, before: Left) -> Started<'plan> {
1020 Started {
1021 free_slots: taken
1022 .iter()
1023 .filter(|(_, slots)| slots.contains(&false))
1024 .map(|(name, _)| *name)
1025 .collect(),
1026 before,
1027 by_profile: BTreeMap::new(),
1028 first: None,
1029 }
1030 }
1031
1032 fn note(&mut self, profile: &'plan str, job: u64) {
1034 self.by_profile.entry(profile).or_insert(job);
1035 self.first.get_or_insert(job);
1036 }
1037
1038 fn for_slot(&self, profile: &str, reason: Waiting) -> Waiting {
1040 match self.by_profile.get(profile) {
1041 Some(older) if self.free_slots.contains(profile) => {
1042 Waiting::BehindStart { job: *older }
1043 }
1044 _ => reason,
1045 }
1046 }
1047
1048 fn for_memory(&self, needs: u64, reason: Waiting) -> Waiting {
1050 Self::behind(self.first, self.before.memory, needs).unwrap_or(reason)
1051 }
1052
1053 fn for_host(&self, needs: u64, reason: Waiting) -> Waiting {
1055 Self::behind(self.first, self.before.host, needs).unwrap_or(reason)
1056 }
1057
1058 fn for_cpu(&self, needs: u64, reason: Waiting) -> Waiting {
1060 Self::behind(self.first, self.before.cpu, needs).unwrap_or(reason)
1061 }
1062
1063 fn behind(first: Option<u64>, free: Option<i64>, needs: u64) -> Option<Waiting> {
1064 first
1065 .filter(|_| free.is_some_and(|free| free >= signed(needs)))
1066 .map(|job| Waiting::BehindStart { job })
1067 }
1068}
1069
1070fn taken_slots(profiles: &BTreeMap<String, Profile>) -> BTreeMap<&str, Vec<bool>> {
1072 profiles
1073 .iter()
1074 .map(|(name, profile)| {
1075 let taken = profile
1076 .slots
1077 .iter()
1078 .map(|slot| profile.preparing.is_some() || *slot != Slot::Free)
1079 .collect();
1080 (name.as_str(), taken)
1081 })
1082 .collect()
1083}
1084
1085#[cfg(test)]
1086mod tests;