1use jiff::Timestamp;
8use schedr_db::backfills::NewBackfill;
9use schedr_model::{DagId, RunKind, RunState};
10
11use super::{Scheduler, SchedulerError, new_run, run_params};
12use crate::fire_times::FireTimes;
13use crate::planning::{Plan, RunTimes};
14use crate::quiet::WakeReason;
15
16pub const DEFAULT_MAX_RUNS: u32 = 1000;
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub struct BackfillAsk<'a> {
23 pub from: Timestamp,
25 pub to: Option<Timestamp>,
27 pub all: bool,
29 pub params: Option<&'a serde_json::Map<String, serde_json::Value>>,
31 pub dry_run: bool,
33}
34
35#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct BackfillCount {
38 pub fire_times: u32,
40 pub created: u32,
42 pub skipped: u32,
44 pub backfill_id: Option<String>,
46}
47
48impl Scheduler {
49 pub async fn backfill(
60 &self,
61 id: &str,
62 dag_id: &DagId,
63 ask: BackfillAsk<'_>,
64 (user, max_runs): (&str, u32),
65 now: Timestamp,
66 ) -> Result<BackfillCount, SchedulerError> {
67 let refused = |why: String| SchedulerError::Backfill {
68 dag_id: dag_id.clone(),
69 why,
70 };
71 let active = self
72 .db
73 .active_dags()
74 .await?
75 .into_iter()
76 .find(|d| &d.dag.id == dag_id)
77 .ok_or_else(|| SchedulerError::NotRunnable(dag_id.clone()))?;
78 if let Some(held) = active.held {
79 return Err(SchedulerError::Held {
80 dag_id: dag_id.clone(),
81 held,
82 });
83 }
84 let fire_times =
85 FireTimes::new(&active.dag.trigger).map_err(|error| SchedulerError::FireTimes {
86 dag_id: dag_id.clone(),
87 error,
88 })?;
89 if matches!(fire_times, FireTimes::None) {
90 return Err(refused(
91 "its trigger has no fire times (a backfill takes `Cron`, `Every` or `Once`); \
92 start a run with `schedr runs trigger` instead"
93 .to_owned(),
94 ));
95 }
96 let to = ask.to.map_or(now, |to| to.min(now));
97 if to < ask.from {
98 return Err(refused(format!(
99 "the range ends ({to}) before it starts ({}); a range ending later than now ends now",
100 ask.from
101 )));
102 }
103 let times = fire_times_in(&fire_times, ask.from, to, max_runs);
104 let Some(times) = times else {
105 return Err(refused(format!(
106 "its range has more than {max_runs} fire times, over `[backfill] max_runs`: \
107 split it"
108 )));
109 };
110 if times.is_empty() {
111 return Err(refused(format!("no fire time from {} to {to}", ask.from)));
112 }
113 let params = run_params(&active, ask.params)?;
115 let covered = if ask.all {
116 std::collections::BTreeSet::new()
117 } else {
118 self.db.covered_times(dag_id, ask.from, to).await?
119 };
120 let missing: Vec<Timestamp> = times
121 .iter()
122 .copied()
123 .filter(|t| !covered.contains(t))
124 .collect();
125 let count = |backfill_id| BackfillCount {
126 fire_times: u32::try_from(times.len()).unwrap_or(u32::MAX),
127 created: u32::try_from(missing.len()).unwrap_or(u32::MAX),
128 skipped: u32::try_from(times.len() - missing.len()).unwrap_or(u32::MAX),
129 backfill_id,
130 };
131 if ask.dry_run || missing.is_empty() {
132 return Ok(count(None));
133 }
134 let backfill = NewBackfill {
135 id,
136 dag_id,
137 range_from: ask.from,
138 range_to: to,
139 all_fire_times: ask.all,
140 requested_by: user,
141 created_at: now,
142 fire_times: count(None).fire_times,
143 created_runs: count(None).created,
144 };
145 self.store(
146 &active,
147 &fire_times,
148 &backfill,
149 (×, &missing, ¶ms),
150 now,
151 )
152 .await?;
153 Ok(count(Some(id.to_owned())))
154 }
155
156 async fn store(
159 &self,
160 active: &schedr_db::runs::ActiveDag,
161 fire_times: &FireTimes,
162 backfill: &NewBackfill<'_>,
163 (times, missing, params): (&[Timestamp], &[Timestamp], &serde_json::Value),
164 now: Timestamp,
165 ) -> Result<(), SchedulerError> {
166 let plan = Plan {
167 dag: &active.dag,
168 fire_times,
169 first_seen: active.first_seen,
170 limits: self.plan_limits,
171 };
172 let sinces: std::collections::BTreeMap<Timestamp, Timestamp> = times
173 .iter()
174 .copied()
175 .zip(plan.fire_time_sinces(times))
176 .collect();
177 let db = self.db.clone();
178 Box::pin(db.atomically(async {
180 if !self.db.insert_backfill(backfill).await? {
181 return Ok::<(), SchedulerError>(());
183 }
184 for planned_for in missing {
185 let window = RunTimes {
186 planned_for: *planned_for,
187 since: sinces
188 .get(planned_for)
189 .copied()
190 .unwrap_or_else(|| plan.fire_time_since(*planned_for)),
191 };
192 let by = backfill.requested_by;
193 let mut new = new_run(active, RunKind::Backfill, window, now, by, params);
194 new.state = RunState::Queued;
195 new.backfill_id = Some(backfill.id);
196 let run_id = uuid::Uuid::now_v7().to_string();
197 self.db.insert_run_as(&run_id, &new).await?;
198 }
199 Ok(())
200 }))
201 .await?;
202 self.wakes.wake(backfill.dag_id, WakeReason::RunQueued);
203 let running = self.db.running_count(backfill.dag_id).await?;
204 let queued = self.db.queued_runs(backfill.dag_id).await?;
205 self.start_queued(&queued, &plan, running, now).await?;
206 Ok(())
207 }
208}
209
210fn fire_times_in(
212 fire_times: &FireTimes,
213 from: Timestamp,
214 to: Timestamp,
215 max: u32,
216) -> Option<Vec<Timestamp>> {
217 fire_times.between(from, to, usize::try_from(max).unwrap_or(usize::MAX))
218}