1use std::collections::BTreeSet;
17
18use jiff::{SignedDuration, Timestamp};
19use schedr_db::runs::QueuedRun;
20use schedr_model::{Dag, RunKind};
21
22use crate::fire_times::FireTimes;
23
24#[cfg(test)]
25mod tests;
26
27pub const FOR_TOLERANCE: SignedDuration = SignedDuration::from_mins(1);
29
30pub const MAX_RUNS_PER_PASS: usize = 100;
33
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36pub struct RunTimes {
37 pub planned_for: Timestamp,
39 pub since: Timestamp,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
45pub enum ManualRunError {
46 #[error("`--for` must not be in the future ({planned_for} is after now, {now})")]
48 InFuture {
49 planned_for: Timestamp,
51 now: Timestamp,
53 },
54}
55
56#[derive(Debug, Clone)]
58pub struct Plan<'a> {
59 pub dag: &'a Dag,
61 pub fire_times: &'a FireTimes,
63 pub first_seen: Timestamp,
65 pub limits: PlanLimits,
67}
68
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
71pub struct PlanLimits {
72 pub runs_per_pass: usize,
74 pub for_tolerance: SignedDuration,
76}
77
78impl Default for PlanLimits {
79 fn default() -> Self {
81 Self {
82 runs_per_pass: MAX_RUNS_PER_PASS,
83 for_tolerance: FOR_TOLERANCE,
84 }
85 }
86}
87
88impl Plan<'_> {
89 #[must_use]
91 pub fn effective_start(&self) -> Timestamp {
92 self.dag.trigger.start().unwrap_or(self.first_seen)
93 }
94
95 #[must_use]
98 pub fn next_fire_after(&self, now: Timestamp) -> Option<Timestamp> {
99 let start = self.effective_start();
100 let next = if start > now {
101 self.fire_times.next_at_or_after(start)
102 } else {
103 self.fire_times.next_after(now)
104 };
105 next.filter(|t| self.dag.trigger.end().is_none_or(|end| *t <= end))
106 }
107
108 #[must_use]
110 pub fn fire_time_since(&self, planned_for: Timestamp) -> Timestamp {
111 if let Some(initial) = self.dag.initial_since
112 && self.fire_times.next_at_or_after(self.effective_start()) == Some(planned_for)
113 {
114 return initial;
115 }
116 self.fire_times
117 .previous_before(planned_for)
118 .or(self.dag.initial_since)
119 .unwrap_or(planned_for)
120 }
121
122 #[must_use]
127 pub fn fire_time_sinces(&self, times: &[Timestamp]) -> Vec<Timestamp> {
128 let first_fire = self
129 .dag
130 .initial_since
131 .and_then(|_| self.fire_times.next_at_or_after(self.effective_start()));
132 times
133 .iter()
134 .enumerate()
135 .map(|(i, t)| match (self.dag.initial_since, i.checked_sub(1)) {
136 (Some(initial), _) if first_fire == Some(*t) => initial,
137 (_, Some(before)) => times[before],
138 (_, None) => self.fire_time_since(*t),
139 })
140 .collect()
141 }
142
143 pub fn manual_times(
153 &self,
154 requested: Option<Timestamp>,
155 now: Timestamp,
156 nearest_earlier: Option<Timestamp>,
157 ) -> Result<RunTimes, ManualRunError> {
158 let planned_for = manual_planned_for(requested, now);
159 if now
160 .checked_add(self.limits.for_tolerance)
161 .is_ok_and(|limit| planned_for > limit)
162 {
163 return Err(ManualRunError::InFuture { planned_for, now });
164 }
165 let since = if self.fire_times.is_fire_time(planned_for) {
166 self.fire_time_since(planned_for)
167 } else {
168 nearest_earlier
169 .or(self.dag.initial_since)
170 .or_else(|| self.fire_times.previous_before(planned_for))
171 .unwrap_or(planned_for)
172 };
173 Ok(RunTimes { planned_for, since })
174 }
175
176 #[must_use]
180 pub fn scheduled_runs(
181 &self,
182 last_scheduled: Option<Timestamp>,
183 running: u32,
184 now: Timestamp,
185 ) -> Vec<RunTimes> {
186 self.scheduled_runs_except(last_scheduled, running, now, &BTreeSet::new())
187 }
188
189 #[must_use]
193 pub fn scheduled_runs_except(
194 &self,
195 last_scheduled: Option<Timestamp>,
196 running: u32,
197 now: Timestamp,
198 covered: &BTreeSet<Timestamp>,
199 ) -> Vec<RunTimes> {
200 let free = self.free_places(running).min(self.limits.runs_per_pass);
201 self.due_times(last_scheduled, free, now, covered)
202 .into_iter()
203 .map(|planned_for| RunTimes {
204 planned_for,
205 since: self.fire_time_since(planned_for),
206 })
207 .collect()
208 }
209
210 #[must_use]
214 pub fn first_waiting(
215 &self,
216 last_scheduled: Option<Timestamp>,
217 now: Timestamp,
218 covered: &BTreeSet<Timestamp>,
219 ) -> Option<Timestamp> {
220 self.due_times(last_scheduled, 1, now, covered)
221 .into_iter()
222 .next()
223 }
224
225 fn due_times(
228 &self,
229 last_scheduled: Option<Timestamp>,
230 free: usize,
231 now: Timestamp,
232 covered: &BTreeSet<Timestamp>,
233 ) -> Vec<Timestamp> {
234 if free == 0 {
235 return Vec::new();
236 }
237 let upper = self.dag.trigger.end().map_or(now, |end| end.min(now));
238 let start = self.effective_start();
239 let after = |t: Timestamp| t >= start && last_scheduled.is_none_or(|last| t > last);
240 let mut due = Vec::new();
241 if self.dag.trigger.catchup() {
242 let from = match last_scheduled {
243 Some(last) if last >= start => self.fire_times.next_after(last),
244 _ => self.fire_times.next_at_or_after(start),
245 };
246 let mut next = from;
247 while let Some(t) = next.filter(|t| *t <= upper && due.len() < free) {
248 if !covered.contains(&t) {
249 due.push(t);
250 }
251 next = self.fire_times.next_after(t);
252 }
253 } else if let Some(latest) = self
254 .fire_times
255 .last_at_or_before(upper)
256 .filter(|t| after(*t) && !covered.contains(t))
257 {
258 due.push(latest);
259 }
260 due
261 }
262
263 #[must_use]
265 pub fn free_places(&self, running: u32) -> usize {
266 self.dag.max_active_runs.map_or(usize::MAX, |limit| {
267 usize::try_from(limit.saturating_sub(running)).unwrap_or(usize::MAX)
268 })
269 }
270}
271
272#[must_use]
274pub fn manual_planned_for(requested: Option<Timestamp>, now: Timestamp) -> Timestamp {
275 requested.unwrap_or(now)
276}
277
278#[must_use]
281pub fn runs_to_start(queued: &[QueuedRun], free: usize) -> Vec<&QueuedRun> {
282 let mut ordered: Vec<&QueuedRun> = queued.iter().collect();
283 ordered.sort_by_key(|run| {
284 (
285 priority(run.kind),
286 run.triggered_at,
287 run.planned_for,
288 run.id.clone(),
289 )
290 });
291 ordered.truncate(free);
292 ordered
293}
294
295const fn priority(kind: RunKind) -> u8 {
296 match kind {
297 RunKind::Scheduled => 0,
298 RunKind::Manual | RunKind::Chained | RunKind::Event => 1,
299 RunKind::Backfill => 2,
300 }
301}