1use std::collections::BTreeMap;
14
15use schedr_db::attempts::{ActiveAttempt, ReadyInstance};
16use schedr_model::{Dag, DagId, Task, TaskId};
17
18#[cfg(test)]
19mod tests;
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct Active {
24 loaded: bool,
26 attempts: BTreeMap<String, Holder>,
28 dags: BTreeMap<DagId, Counted>,
30 runs: BTreeMap<String, BTreeMap<TaskId, u32>>,
32}
33
34#[derive(Debug, Clone, PartialEq, Eq)]
36struct Holder {
37 dag: DagId,
38 run: String,
39 task: TaskId,
40}
41
42#[derive(Debug, Clone, Default, PartialEq, Eq)]
44struct Counted {
45 all: u32,
46 tasks: BTreeMap<TaskId, u32>,
47}
48
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
51pub struct Reached {
52 pub name: &'static str,
54 pub value: u32,
56}
57
58impl Reached {
59 #[must_use]
61 pub fn reason(&self) -> String {
62 format!("waiting: `{}` ({}) reached", self.name, self.value)
63 }
64}
65
66impl Active {
67 #[must_use]
69 pub fn new() -> Self {
70 Self::default()
71 }
72
73 #[must_use]
75 pub const fn is_loaded(&self) -> bool {
76 self.loaded
77 }
78
79 pub fn load(&mut self, attempts: Vec<ActiveAttempt>) {
81 *self = Self::default();
82 for a in attempts {
83 self.add(&a.attempt_id, a.dag_id, a.run_id, a.task_id);
84 }
85 self.loaded = true;
86 }
87
88 pub fn add(&mut self, attempt_id: &str, dag_id: DagId, run_id: String, task_id: TaskId) {
90 if self.attempts.contains_key(attempt_id) {
91 return;
92 }
93 let dag = self.dags.entry(dag_id.clone()).or_default();
94 dag.all += 1;
95 *dag.tasks.entry(task_id.clone()).or_default() += 1;
96 *self
97 .runs
98 .entry(run_id.clone())
99 .or_default()
100 .entry(task_id.clone())
101 .or_default() += 1;
102 self.attempts.insert(
103 attempt_id.to_owned(),
104 Holder {
105 dag: dag_id,
106 run: run_id,
107 task: task_id,
108 },
109 );
110 }
111
112 pub fn assigned(&mut self, attempt_id: &str, ready: &ReadyInstance) {
114 let (dag, run, task) = (&ready.dag.id, &ready.run_id, &ready.task_id);
115 self.add(attempt_id, dag.clone(), run.clone(), task.clone());
116 }
117
118 pub fn remove(&mut self, attempt_id: &str) {
120 let Some(holder) = self.attempts.remove(attempt_id) else {
121 return;
122 };
123 if let Some(dag) = self.dags.get_mut(&holder.dag) {
124 dag.all = dag.all.saturating_sub(1);
125 decrement(&mut dag.tasks, &holder.task);
126 if dag.all == 0 {
127 self.dags.remove(&holder.dag);
128 }
129 }
130 if let Some(run) = self.runs.get_mut(&holder.run) {
131 decrement(run, &holder.task);
132 if run.is_empty() {
133 self.runs.remove(&holder.run);
134 }
135 }
136 }
137
138 #[must_use]
140 pub fn of_dag(&self, dag_id: &DagId) -> u32 {
141 self.dags.get(dag_id).map_or(0, |d| d.all)
142 }
143
144 #[must_use]
146 pub fn of_task(&self, dag_id: &DagId, task_id: &TaskId) -> u32 {
147 self.dags
148 .get(dag_id)
149 .and_then(|d| d.tasks.get(task_id))
150 .copied()
151 .unwrap_or(0)
152 }
153
154 #[must_use]
156 pub fn of_run_task(&self, run_id: &str, task_id: &TaskId) -> u32 {
157 self.runs
158 .get(run_id)
159 .and_then(|r| r.get(task_id))
160 .copied()
161 .unwrap_or(0)
162 }
163
164 #[cfg(test)]
166 pub(crate) fn attempt_ids(&self) -> std::collections::BTreeSet<&str> {
167 self.attempts.keys().map(String::as_str).collect()
168 }
169
170 #[must_use]
175 pub fn reached(
176 &self,
177 (current, own): (&Dag, &Dag),
178 run_id: &str,
179 task_id: &TaskId,
180 ) -> Option<Reached> {
181 self.reached_with(
182 (current, own),
183 (current.task(task_id), own.task(task_id)),
184 run_id,
185 task_id,
186 )
187 }
188
189 #[must_use]
193 pub fn reached_with(
194 &self,
195 (current, own): (&Dag, &Dag),
196 (in_current, in_own): (Option<&Task>, Option<&Task>),
197 run_id: &str,
198 task_id: &TaskId,
199 ) -> Option<Reached> {
200 let dag_id = &own.id;
201 let reached = |name, limit: Option<u32>, count: u32| {
202 limit
203 .filter(|&value| count >= value)
204 .map(|value| Reached { name, value })
205 };
206 if let Some(cap) = reached(
210 "max_active_tasks",
211 current.max_active_tasks,
212 self.of_dag(dag_id),
213 ) {
214 return Some(cap);
215 }
216 let task_limit = in_current.or(in_own).and_then(|t| t.settings.max_active);
217 if let Some(task) = reached("max_active", task_limit, self.of_task(dag_id, task_id)) {
218 return Some(task);
219 }
220 let per_run = in_own.and_then(|t| t.settings.max_active_per_run);
221 reached(
222 "max_active_per_run",
223 per_run,
224 self.of_run_task(run_id, task_id),
225 )
226 }
227}
228
229fn decrement(counts: &mut BTreeMap<TaskId, u32>, key: &TaskId) {
231 if let Some(n) = counts.get_mut(key) {
232 *n = n.saturating_sub(1);
233 if *n == 0 {
234 counts.remove(key);
235 }
236 }
237}