1use std::time::Duration;
10
11use jiff::Timestamp;
12use schedr_db::commands::{CommandRecord, PendingCommand};
13use schedr_db::{Database, DbError};
14use schedr_model::commands::{AskedEvent, BackfillRequest};
15use schedr_model::commands::{
16 CONNECTION_CHECK_TIMEOUT_MS, Command, CommandStatus, ConnectionJobResult, ConnectionsResult,
17 JobState, MAX_CONNECTION_TEST_MS,
18};
19use schedr_model::{DagId, RunState, TaskId, TaskInstanceState};
20use schedr_proto::pb;
21use schedr_proto::pb::master_message;
22use serde_json::json;
23
24use crate::dispatch::{DispatchError, Dispatcher, Outgoing, ReadBack};
25use crate::execution::{ExecutionError, TaskCancel, TaskRetry};
26use crate::metrics::{CommandLabels, MasterMetrics};
27use crate::quiet::WakeReason;
28use crate::scheduler::backfill::BackfillAsk;
29use crate::scheduler::{Scheduler, SchedulerError};
30
31pub const COMMANDS_PER_ROUND: u32 = 50;
34#[cfg(test)]
35mod tests;
36
37#[derive(Debug, thiserror::Error)]
39pub enum CommandError {
40 #[error(transparent)]
42 Db(#[from] DbError),
43 #[error(transparent)]
45 Dispatch(#[from] DispatchError),
46}
47
48impl CommandError {
49 #[must_use]
51 pub const fn commit_unknown(&self) -> bool {
52 match self {
53 Self::Db(error) => matches!(error, DbError::CommitUnknown),
54 Self::Dispatch(error) => error.commit_unknown(),
55 }
56 }
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
61pub struct Decided {
62 pub id: String,
64 pub status: CommandStatus,
66 pub reason: Option<String>,
68 pub result: Option<serde_json::Value>,
70}
71
72#[derive(Debug, Default)]
74pub struct Applied {
75 pub decided: Vec<Decided>,
77 pub outgoing: Vec<Outgoing>,
79 pub drained: Vec<(String, bool)>,
81 pub connection_jobs: Vec<SentJob>,
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct SentJob {
89 pub job_id: String,
91 pub worker_id: String,
93 pub allowed: Duration,
95}
96
97enum Outcome {
99 Applied(serde_json::Value),
100 Rejected(String),
101}
102
103#[derive(Debug, Clone)]
105pub struct Commander {
106 db: Database,
107 metrics: MasterMetrics,
108 backfill_max_runs: u32,
110 per_round: u32,
112}
113
114type Decision = (CommandStatus, Option<String>, Option<serde_json::Value>);
116
117impl Commander {
118 #[must_use]
120 pub fn new(db: Database) -> Self {
121 Self {
122 db,
123 metrics: MasterMetrics::default(),
124 backfill_max_runs: crate::scheduler::backfill::DEFAULT_MAX_RUNS,
125 per_round: COMMANDS_PER_ROUND,
126 }
127 }
128
129 #[must_use]
131 pub const fn with_commands_per_round(mut self, per_round: u32) -> Self {
132 self.per_round = per_round;
133 self
134 }
135
136 #[must_use]
139 pub const fn with_backfill_max_runs(mut self, max_runs: u32) -> Self {
140 self.backfill_max_runs = max_runs;
141 self
142 }
143
144 pub fn set_metrics(&mut self, metrics: MasterMetrics) {
146 self.metrics = metrics;
147 }
148
149 pub async fn apply_pending(
156 &self,
157 scheduler: &Scheduler,
158 dispatcher: &mut Dispatcher,
159 now: Timestamp,
160 ) -> Result<Applied, CommandError> {
161 let mut applied = Applied::default();
162 self.apply_into(scheduler, dispatcher, &mut applied, now)
163 .await?;
164 Ok(applied)
165 }
166
167 pub async fn apply_into(
174 &self,
175 scheduler: &Scheduler,
176 dispatcher: &mut Dispatcher,
177 applied: &mut Applied,
178 now: Timestamp,
179 ) -> Result<(), CommandError> {
180 for pending in self.pending().await? {
181 self.apply_one(pending, scheduler, dispatcher, applied, now)
182 .await?;
183 }
184 Ok(())
185 }
186
187 pub async fn pending(&self) -> Result<Vec<PendingCommand>, CommandError> {
195 Ok(self.db.pending_commands(self.per_round).await?)
196 }
197
198 pub async fn apply_one(
208 &self,
209 pending: PendingCommand,
210 scheduler: &Scheduler,
211 dispatcher: &mut Dispatcher,
212 applied: &mut Applied,
213 now: Timestamp,
214 ) -> Result<(), CommandError> {
215 let sent_before = (
216 applied.outgoing.len(),
217 applied.connection_jobs.len(),
218 applied.drained.len(),
219 );
220 let keeps_memory = !matches!(
222 pending.command,
223 Ok(Command::TriggerRun { .. }
224 | Command::Backfill(_)
225 | Command::RestartTrigger { .. }
226 | Command::SkipTriggerRun { .. }
227 | Command::UnpauseDag { .. }
228 | Command::SwitchOnSensor { .. })
229 | Err(_)
230 );
231 let memory = keeps_memory.then(|| dispatcher.memory());
232 let db = self.db.clone();
233 self.metrics.stage();
235 let stored = Box::pin(
236 db.atomically(self.apply_stored(&pending, scheduler, dispatcher, applied, now)),
237 )
238 .await;
239 let decided = match stored {
240 Ok(decided) => Ok(decided),
241 Err(error) if error.commit_unknown() => self
242 .landed(&pending.id, dispatcher.read_back())
243 .await
244 .ok_or(error),
245 Err(error) => Err(error),
246 };
247 match decided {
248 Ok((status, reason, result)) => {
249 self.metrics.count_staged();
250 self.count(&pending, status, now);
251 applied.decided.push(Decided {
252 id: pending.id,
253 status,
254 reason,
255 result,
256 });
257 Ok(())
258 }
259 Err(error) => {
260 self.metrics.drop_staged();
261 applied.outgoing.truncate(sent_before.0);
262 applied.connection_jobs.truncate(sent_before.1);
263 applied.drained.truncate(sent_before.2);
264 if let Some(memory) = memory {
265 dispatcher.restore(memory);
266 }
267 if error.commit_unknown() {
268 dispatcher.recount();
270 }
271 Err(error)
272 }
273 }
274 }
275
276 async fn landed(&self, id: &str, read_back: ReadBack) -> Option<Decision> {
279 let decided = |record: &CommandRecord| record.status != CommandStatus::Pending;
280 let stored = read_back
281 .stored(|| async {
282 matches!(self.db.command(id).await, Ok(Some(record)) if decided(&record))
283 })
284 .await;
285 if !stored {
286 return None;
287 }
288 match self.db.command(id).await {
289 Ok(Some(record)) if decided(&record) => {
290 Some((record.status, record.reason, record.result))
291 }
292 _ => None,
293 }
294 }
295
296 async fn apply_stored(
298 &self,
299 pending: &PendingCommand,
300 scheduler: &Scheduler,
301 dispatcher: &mut Dispatcher,
302 applied: &mut Applied,
303 now: Timestamp,
304 ) -> Result<Decision, CommandError> {
305 if !pending.applying {
308 self.db.mark_applying(&pending.id, now).await?;
309 }
310 let outcome = self
311 .apply(pending, scheduler, dispatcher, applied, now)
312 .await?;
313 let (status, reason, result) = match outcome {
314 Outcome::Applied(result) => (CommandStatus::Applied, None, Some(result)),
315 Outcome::Rejected(reason) => (CommandStatus::Rejected, Some(reason), None),
316 };
317 self.db
318 .decide_command(&pending.id, status, reason.as_deref(), result.as_ref(), now)
319 .await?;
320 Ok((status, reason, result))
321 }
322
323 fn count(&self, pending: &PendingCommand, status: CommandStatus, now: Timestamp) {
324 let kind = pending.command.as_ref().map_or("unreadable", Command::kind);
325 self.metrics
326 .commands
327 .get_or_create(&CommandLabels {
328 kind: kind.to_owned(),
329 decision: match status {
330 CommandStatus::Applied => "applied",
331 CommandStatus::Rejected => "rejected",
332 CommandStatus::Pending => "pending",
333 }
334 .to_owned(),
335 })
336 .inc();
337 let waited = now.duration_since(pending.requested_at).as_secs_f64();
338 self.metrics.command_latency.observe(waited.max(0.0));
339 }
340
341 async fn asked_event(
344 &self,
345 dag_id: &DagId,
346 asked: Option<&AskedEvent>,
347 ) -> Result<Result<Option<schedr_model::RunEvent>, String>, CommandError> {
348 let (key, data, at) = match asked {
349 None => return Ok(Ok(None)),
350 Some(AskedEvent::Stored { key }) => {
351 let found = self.db.stored_event(dag_id.as_str(), key).await?;
352 let batches = self.db.stored_dag(dag_id).await?.is_some_and(|dag| {
353 dag.current
354 .is_some_and(|current| batches(¤t.dag.trigger))
355 });
356 return Ok(found.map_or_else(
357 || Err(format!("no event `{key}` of DAG `{dag_id}`")),
358 |event| Ok(Some(if batches { one_batch(event) } else { event })),
359 ));
360 }
361 Some(AskedEvent::Given { key, data, at }) => (key, data, *at),
362 };
363 if let Err(why) = schedr_model::trigger::check_event_key(key) {
364 return Ok(Err(why));
365 }
366 let stored = self.db.stored_dag(dag_id).await?;
367 let stored_trigger = stored
368 .as_ref()
369 .and_then(|dag| dag.current.as_ref())
370 .map(|current| current.dag.trigger.clone());
371 let limit =
372 stored
373 .and_then(|dag| dag.current)
374 .and_then(|current| match ¤t.dag.trigger {
375 schedr_model::Trigger::Event { task, .. } => {
376 Some(task.settings.max_output_size)
377 }
378 _ => None,
379 });
380 let size = serde_json::to_vec(data).map_or(0, |bytes| bytes.len());
381 if limit.is_some_and(|limit| u64::try_from(size).unwrap_or(u64::MAX) > limit) {
382 return Ok(Err(format!(
383 "the event's data is {size} bytes, over its trigger's `max_output_size`"
384 )));
385 }
386 let named = stored_trigger
389 .as_ref()
390 .is_some_and(|trigger| matches!(trigger, schedr_model::Trigger::EventNamed { .. }));
391 Ok(Ok(Some(schedr_model::RunEvent {
392 key: key.clone(),
393 data: if named {
394 schedr_model::params::escape_tags(data)
395 } else {
396 data.clone()
397 },
398 at,
399 })))
400 }
401
402 async fn switch(
405 &self,
406 dag_id: &DagId,
407 paused: bool,
408 now: Timestamp,
409 ) -> Result<Option<Outcome>, CommandError> {
410 if self.db.stored_dag(dag_id).await?.is_none() {
411 return Ok(Some(no_dag(dag_id)));
412 }
413 if self.db.set_paused_at(dag_id, paused, now).await? {
415 return Ok(None);
416 }
417 Ok(Some(Outcome::Rejected(format!(
418 "DAG `{dag_id}` has no trigger: it runs only when started, so pausing changes \
419 nothing (cancel its runs with `schedr runs cancel`)"
420 ))))
421 }
422
423 async fn restart_trigger(&self, dag_id: &DagId) -> Result<Outcome, CommandError> {
425 let Some(dag) = self.db.stored_dag(dag_id).await? else {
426 return Ok(no_dag(dag_id));
427 };
428 let event = dag
429 .current
430 .is_some_and(|current| current.dag.trigger.is_event());
431 if !event {
432 return Ok(Outcome::Rejected(format!(
433 "DAG `{dag_id}` has no event trigger"
434 )));
435 }
436 self.db.restart_trigger(dag_id.as_str()).await?;
437 Ok(Outcome::Applied(json!({})))
438 }
439
440 async fn skip_trigger_run(
443 &self,
444 dag_id: &DagId,
445 pending: &PendingCommand,
446 ) -> Result<Outcome, CommandError> {
447 let Some(dag) = self.db.stored_dag(dag_id).await? else {
448 return Ok(no_dag(dag_id));
449 };
450 let Some(current) = dag.current else {
451 return Ok(no_dag(dag_id));
452 };
453 let why = format!(
456 "skipped by {} (command {})",
457 pending.requested_by, pending.id
458 );
459 let passed =
460 crate::core::triggers::pass_handed_run(&self.db, ¤t.dag, &why, None).await?;
461 Ok(match passed {
462 Ok(run) => Outcome::Applied(json!({ "run_id": run })),
463 Err(refused) => {
464 let record = self.db.trigger(dag_id.as_str()).await?;
467 let done = record
468 .and_then(|r| r.last_error)
469 .filter(|_| pending.applying)
470 .and_then(|error| {
471 let rest = error.strip_prefix("passed run ")?;
472 let (run, said) = rest.split_once(": ")?;
473 (said == why).then(|| run.to_owned())
474 });
475 match done {
476 Some(run) => Outcome::Applied(json!({ "run_id": run })),
477 None => Outcome::Rejected(refused),
478 }
479 }
480 })
481 }
482
483 async fn switch_on(&self, dag_id: &DagId, sensor: &TaskId) -> Result<Outcome, CommandError> {
485 let Some(dag) = self.db.stored_dag(dag_id).await? else {
486 return Ok(no_dag(dag_id));
487 };
488 let is_sensor = dag.current.is_some_and(|current| {
489 let trigger = matches!(
490 ¤t.dag.trigger,
491 schedr_model::Trigger::Event { task, .. } if &task.id == sensor
492 );
493 trigger
494 || current
495 .dag
496 .task(sensor)
497 .is_some_and(|task| matches!(task.kind, schedr_model::TaskKind::Sensor { .. }))
498 });
499 if !is_sensor {
500 return Ok(Outcome::Rejected(format!(
501 "no wait step `{sensor}` in DAG `{dag_id}`"
502 )));
503 }
504 self.db
505 .clear_wait_step(dag_id.as_str(), sensor.as_str())
506 .await?;
507 Ok(Outcome::Applied(json!({})))
508 }
509
510 async fn apply(
511 &self,
512 pending: &PendingCommand,
513 scheduler: &Scheduler,
514 dispatcher: &mut Dispatcher,
515 applied: &mut Applied,
516 now: Timestamp,
517 ) -> Result<Outcome, CommandError> {
518 let outgoing = &mut applied.outgoing;
519 let command = match &pending.command {
520 Ok(command) => command,
521 Err(reason) => return Ok(Outcome::Rejected(format!("invalid command: {reason}"))),
522 };
523 if let Command::TriggerRun { dag_id, .. }
525 | Command::PauseDag { dag_id, .. }
526 | Command::UnpauseDag { dag_id } = command
527 {
528 scheduler.wakes().wake(dag_id, WakeReason::Command);
529 }
530 match command {
531 Command::TriggerRun {
532 dag_id,
533 planned_for,
534 params,
535 event,
536 } => {
537 let requested = (*planned_for, params.as_ref(), event.as_ref());
538 self.trigger(pending, scheduler, dag_id, requested, now)
539 .await
540 }
541 Command::Backfill(request) => self.backfill(pending, scheduler, request, now).await,
542 Command::CancelBackfill { backfill_id } => {
543 self.cancel_backfill(pending, backfill_id, (dispatcher, outgoing), now)
544 .await
545 }
546 Command::RestartTrigger { dag_id } => self.restart_trigger(dag_id).await,
547 Command::SkipTriggerRun { dag_id } => self.skip_trigger_run(dag_id, pending).await,
548 Command::CancelRun { run_id } => {
549 self.cancel_run(pending, run_id, (dispatcher, outgoing), now)
550 .await
551 }
552 Command::PauseDag {
553 dag_id,
554 cancel_runs,
555 } => {
556 if let Some(refused) = self.switch(dag_id, true, now).await? {
557 return Ok(refused);
558 }
559 let mut cancelled = Vec::new();
560 if *cancel_runs {
561 for run_id in self.db.runs_in_progress(dag_id).await? {
562 cancel(dispatcher, &run_id, outgoing, now).await?;
563 cancelled.push(run_id);
564 }
565 }
566 Ok(Outcome::Applied(json!({"cancelled_runs": cancelled})))
567 }
568 Command::UnpauseDag { dag_id } => {
569 if let Some(refused) = self.switch(dag_id, false, now).await? {
570 return Ok(refused);
571 }
572 Ok(Outcome::Applied(json!({})))
573 }
574 Command::SwitchOnSensor { dag_id, sensor } => self.switch_on(dag_id, sensor).await,
575 Command::CancelTask {
576 run_id,
577 task_id,
578 map_index,
579 } => {
580 let instance = (task_id, *map_index);
581 cancel_task(dispatcher, pending, run_id, instance, outgoing, now).await
582 }
583 Command::RetryTask {
584 run_id,
585 task_id,
586 map_index,
587 } => retry_task(dispatcher, pending, run_id, (task_id, *map_index), now).await,
588 Command::DrainWorker { worker_id } => {
589 if !self.db.set_worker_drained(worker_id, true).await? {
590 return Ok(no_worker(worker_id));
591 }
592 outgoing.extend(dispatcher.drain(worker_id));
593 applied.drained.push((worker_id.clone(), true));
594 let running = dispatcher
595 .workers()
596 .get(worker_id)
597 .map_or(0, |w| w.attempts.len() + w.wait_steps.len());
598 Ok(Outcome::Applied(json!({"running": running})))
599 }
600 Command::ResumeWorker { worker_id } => {
601 self.resume(pending, worker_id, dispatcher, applied, now)
602 .await
603 }
604 Command::CheckConnections { .. } | Command::TestConnection { .. } => Ok(
605 connections_command(dispatcher, &pending.id, command, applied),
606 ),
607 }
608 }
609}
610
611fn connections_command(
613 dispatcher: &Dispatcher,
614 command_id: &str,
615 command: &Command,
616 applied: &mut Applied,
617) -> Outcome {
618 match command {
619 Command::CheckConnections { root, name, worker } => check_connections(
620 dispatcher,
621 command_id,
622 (root.as_deref(), name.as_deref(), worker.as_deref()),
623 applied,
624 ),
625 Command::TestConnection {
626 name,
627 root,
628 worker,
629 timeout_ms,
630 } => test_connection(
631 dispatcher,
632 command_id,
633 (name, root.as_deref(), worker.as_deref(), *timeout_ms),
634 applied,
635 ),
636 _ => Outcome::Rejected(format!("`{}` isn't a connections command", command.kind())),
637 }
638}
639
640fn check_connections(
642 dispatcher: &Dispatcher,
643 command_id: &str,
644 (root, name, worker): (Option<&str>, Option<&str>, Option<&str>),
645 applied: &mut Applied,
646) -> Outcome {
647 let roots = match root {
648 Some(root) => vec![root.to_owned()],
649 None => dispatcher.connection_roots(),
650 };
651 if roots.is_empty() {
652 return Outcome::Rejected("no root defines connections".to_owned());
653 }
654 let mut jobs = Vec::new();
655 for root in roots {
656 let Some(registry) = dispatcher.registry(&root) else {
657 return Outcome::Rejected(format!("root `{root}` defines no connections"));
658 };
659 let registry = match name {
660 Some(name)
661 if !registry.connections.contains_key(name)
662 && !registry.refused.contains_key(name) =>
663 {
664 return Outcome::Rejected(format!("root `{root}` defines no connection `{name}`"));
665 }
666 Some(name) => registry.only(&[name.to_owned()]),
667 None => (**registry).clone(),
668 };
669 let (worker, hash) = match dispatcher.connection_worker(&root, worker) {
670 Ok(found) => found,
671 Err(why) => return Outcome::Rejected(why),
672 };
673 jobs.push(connection_job(
674 command_id, &root, &worker, &hash, ®istry, None,
675 ));
676 }
677 let allowed = Duration::from_millis(CONNECTION_CHECK_TIMEOUT_MS);
678 Outcome::Applied(sent(jobs, allowed, applied))
679}
680
681fn test_connection(
684 dispatcher: &Dispatcher,
685 command_id: &str,
686 (name, root, worker, timeout_ms): (&str, Option<&str>, Option<&str>, u64),
687 applied: &mut Applied,
688) -> Outcome {
689 if timeout_ms == 0 || timeout_ms > MAX_CONNECTION_TEST_MS {
690 return Outcome::Rejected(format!(
691 "a test's timeout is 1 ms to {} s",
692 MAX_CONNECTION_TEST_MS / 1000
693 ));
694 }
695 let defining: Vec<String> = dispatcher
696 .connection_roots()
697 .into_iter()
698 .filter(|r| root.is_none_or(|given| given == r))
699 .filter(|r| {
700 dispatcher.registry(r).is_some_and(|registry| {
701 registry.connections.contains_key(name) || registry.refused.contains_key(name)
702 })
703 })
704 .collect();
705 let root = match defining.as_slice() {
706 [root] => root.clone(),
707 [] => {
708 return Outcome::Rejected(match root {
709 Some(root) => format!("root `{root}` defines no connection `{name}`"),
710 None => format!("no root defines connection `{name}`"),
711 });
712 }
713 several => {
714 return Outcome::Rejected(format!(
715 "connection `{name}` is defined in roots {}: give one (`--root`)",
716 several.join(", ")
717 ));
718 }
719 };
720 let registry = dispatcher
721 .registry(&root)
722 .map(|registry| registry.only(&[name.to_owned()]))
723 .unwrap_or_default();
724 if let Some(why) = registry.refused.get(name) {
725 return Outcome::Rejected(why.clone());
726 }
727 let (worker, hash) = match dispatcher.connection_worker(&root, worker) {
728 Ok(found) => found,
729 Err(why) => return Outcome::Rejected(why),
730 };
731 let test = pb::ConnectionTest {
732 name: name.to_owned(),
733 timeout_ms,
734 };
735 let job = connection_job(command_id, &root, &worker, &hash, ®istry, Some(test));
736 let allowed = Duration::from_millis(timeout_ms);
737 Outcome::Applied(sent(vec![job], allowed, applied))
738}
739
740fn sent(
743 jobs: Vec<(Outgoing, ConnectionJobResult)>,
744 allowed: Duration,
745 applied: &mut Applied,
746) -> serde_json::Value {
747 let mut result = ConnectionsResult::default();
748 for (outgoing, job) in jobs {
749 applied.connection_jobs.push(SentJob {
750 job_id: job_id(&outgoing),
751 worker_id: outgoing.worker_id.clone(),
752 allowed,
753 });
754 applied.outgoing.push(outgoing);
755 result.jobs.push(job);
756 }
757 serde_json::to_value(result).unwrap_or_default()
758}
759
760#[must_use]
763pub fn connection_job_id(command_id: &str, root: &str) -> String {
764 format!("{command_id}/{root}")
765}
766
767#[must_use]
769pub fn parse_connection_job_id(job_id: &str) -> Option<(&str, &str)> {
770 job_id.split_once('/')
771}
772
773fn job_id(outgoing: &Outgoing) -> String {
774 match &outgoing.message.message {
775 Some(master_message::Message::ConnectionJob(job)) => job.job_id.clone(),
776 _ => String::new(),
777 }
778}
779
780fn connection_job(
781 command_id: &str,
782 root: &str,
783 worker: &str,
784 hash: &str,
785 registry: &schedr_model::connection::Registry,
786 test: Option<pb::ConnectionTest>,
787) -> (Outgoing, ConnectionJobResult) {
788 let message = pb::ConnectionJob {
789 job_id: connection_job_id(command_id, root),
790 root: Some(pb::RootHash {
791 kind: pb::RootKind::Dag.into(),
792 root: root.to_owned(),
793 content_hash: hash.to_owned(),
794 }),
795 connections_json: serde_json::to_vec(registry).unwrap_or_default(),
796 test,
797 };
798 (
799 Outgoing {
800 worker_id: worker.to_owned(),
801 message: pb::MasterMessage {
802 message: Some(master_message::Message::ConnectionJob(message)),
803 clock: None,
804 },
805 },
806 ConnectionJobResult {
807 root: root.to_owned(),
808 worker: worker.to_owned(),
809 state: JobState::Running,
810 reason: None,
811 connections: Vec::new(),
812 },
813 )
814}
815
816impl Commander {
817 async fn trigger(
821 &self,
822 pending: &PendingCommand,
823 scheduler: &Scheduler,
824 dag_id: &DagId,
825 (planned_for, params, asked): (
826 Option<Timestamp>,
827 Option<&serde_json::Map<String, serde_json::Value>>,
828 Option<&AskedEvent>,
829 ),
830 now: Timestamp,
831 ) -> Result<Outcome, CommandError> {
832 if pending.applying && self.db.run_tasks(&pending.id).await?.is_some() {
833 return Ok(Outcome::Applied(json!({"run_id": pending.id})));
834 }
835 let event = match self.asked_event(dag_id, asked).await? {
836 Ok(event) => event,
837 Err(why) => return Ok(Outcome::Rejected(why)),
838 };
839 let created = scheduler
840 .trigger_as(
841 Some(&pending.id),
842 dag_id,
843 planned_for,
844 (params, event.as_ref()),
845 &pending.requested_by,
846 now,
847 )
848 .await;
849 match created {
850 Ok(run) => Ok(Outcome::Applied(json!({"run_id": run.run_id}))),
851 Err(SchedulerError::Db(error)) => Err(error.into()),
852 Err(error) => Ok(Outcome::Rejected(error.to_string())),
853 }
854 }
855
856 async fn backfill(
859 &self,
860 pending: &PendingCommand,
861 scheduler: &Scheduler,
862 request: &BackfillRequest,
863 now: Timestamp,
864 ) -> Result<Outcome, CommandError> {
865 let dag_id = &request.dag_id;
866 let ask = BackfillAsk {
867 from: request.from,
868 to: request.to,
869 all: request.all,
870 params: request.params.as_ref(),
871 dry_run: request.dry_run,
872 };
873 if pending.applying
874 && let Some(done) = self.db.backfill(&pending.id).await?
875 {
876 return Ok(Outcome::Applied(json!({
877 "backfill_id": done.id,
878 "fire_times": done.fire_times,
879 "created": done.created_runs,
880 "skipped": done.fire_times.saturating_sub(done.created_runs),
881 "dry_run": false,
882 })));
883 }
884 let by = (pending.requested_by.as_str(), self.backfill_max_runs);
885 match scheduler.backfill(&pending.id, dag_id, ask, by, now).await {
886 Ok(count) => Ok(Outcome::Applied(json!({
887 "backfill_id": count.backfill_id,
888 "fire_times": count.fire_times,
889 "created": count.created,
890 "skipped": count.skipped,
891 "dry_run": ask.dry_run,
892 }))),
893 Err(SchedulerError::Db(error)) => Err(error.into()),
894 Err(error) => Ok(Outcome::Rejected(error.to_string())),
895 }
896 }
897
898 async fn cancel_run(
901 &self,
902 pending: &PendingCommand,
903 run_id: &str,
904 (dispatcher, outgoing): (&mut Dispatcher, &mut Vec<Outgoing>),
905 now: Timestamp,
906 ) -> Result<Outcome, CommandError> {
907 let Some(run) = self.db.run_tasks(run_id).await? else {
908 return Ok(Outcome::Rejected(format!("no run `{run_id}`")));
909 };
910 if run.state.is_final() {
911 if pending.applying && run.state == RunState::Cancelled {
912 return Ok(Outcome::Applied(json!({"stopping_attempts": 0})));
914 }
915 return Ok(Outcome::Rejected(format!(
916 "run `{run_id}` already finished ({})",
917 run.state
918 )));
919 }
920 let stopping = cancel(dispatcher, run_id, outgoing, now).await?;
921 Ok(Outcome::Applied(json!({"stopping_attempts": stopping})))
922 }
923
924 async fn cancel_backfill(
927 &self,
928 pending: &PendingCommand,
929 backfill_id: &str,
930 (dispatcher, outgoing): (&mut Dispatcher, &mut Vec<Outgoing>),
931 now: Timestamp,
932 ) -> Result<Outcome, CommandError> {
933 let Some(backfill) = self.db.backfill(backfill_id).await? else {
934 return Ok(Outcome::Rejected(format!("no backfill `{backfill_id}`")));
935 };
936 let runs = self.db.unfinished_backfill_runs(&backfill.id).await?;
937 if runs.is_empty() && !pending.applying {
938 return Ok(Outcome::Rejected(format!(
939 "backfill `{backfill_id}` has no queued or running run left"
940 )));
941 }
942 let mut stopping = 0;
943 for run_id in &runs {
944 stopping += cancel(dispatcher, run_id, outgoing, now).await?;
945 }
946 Ok(Outcome::Applied(
947 json!({"cancelled_runs": runs, "stopping_attempts": stopping}),
948 ))
949 }
950
951 async fn resume(
955 &self,
956 pending: &PendingCommand,
957 worker_id: &str,
958 dispatcher: &mut Dispatcher,
959 applied: &mut Applied,
960 now: Timestamp,
961 ) -> Result<Outcome, CommandError> {
962 match self.db.resume_worker(worker_id).await? {
963 None => Ok(no_worker(worker_id)),
964 Some(false) if !pending.applying => Ok(Outcome::Rejected(format!(
965 "worker `{worker_id}` isn't drained"
966 ))),
967 Some(_) => {
968 dispatcher.resume(worker_id, now).await?;
969 applied.drained.push((worker_id.to_owned(), false));
970 Ok(Outcome::Applied(json!({})))
971 }
972 }
973 }
974}
975
976async fn cancel_task(
980 dispatcher: &mut Dispatcher,
981 pending: &PendingCommand,
982 run_id: &str,
983 (task_id, map_index): (&TaskId, Option<i32>),
984 outgoing: &mut Vec<Outgoing>,
985 now: Timestamp,
986) -> Result<Outcome, CommandError> {
987 let cancelled = dispatcher
988 .cancel_task(run_id, (task_id, map_index), now)
989 .await;
990 let (cancelled, messages) = match cancelled {
991 Ok(done) => done,
992 Err(DispatchError::Execution(
993 unknown @ (ExecutionError::UnknownRun(_)
994 | ExecutionError::UnknownTask { .. }
995 | ExecutionError::UnknownInstance { .. }),
996 )) => return Ok(Outcome::Rejected(unknown.to_string())),
997 Err(error) => return Err(error.into()),
998 };
999 let stopping = messages.len();
1000 outgoing.extend(messages);
1001 Ok(match cancelled {
1002 TaskCancel::Cancelled(_) => Outcome::Applied(json!({"state": "cancelled"})),
1003 TaskCancel::Stopping => {
1004 Outcome::Applied(json!({"state": "stopping", "stopping_attempts": stopping}))
1005 }
1006 TaskCancel::AlreadyFinished(TaskInstanceState::Cancelled)
1007 | TaskCancel::RunFinished(RunState::Cancelled)
1008 if pending.applying =>
1009 {
1010 Outcome::Applied(json!({"state": "cancelled"}))
1011 }
1012 TaskCancel::AlreadyFinished(state) => Outcome::Rejected(format!(
1013 "task `{task_id}` of run `{run_id}` already finished ({state})"
1014 )),
1015 TaskCancel::RunFinished(state) => {
1016 Outcome::Rejected(format!("run `{run_id}` already finished ({state})"))
1017 }
1018 TaskCancel::RunQueued => Outcome::Rejected(format!(
1019 "run `{run_id}` hasn't started its tasks yet: cancel the run \
1020 (`schedr runs cancel`), or try again once it runs"
1021 )),
1022 })
1023}
1024
1025async fn retry_task(
1029 dispatcher: &mut Dispatcher,
1030 pending: &PendingCommand,
1031 run_id: &str,
1032 (task_id, map_index): (&TaskId, Option<i32>),
1033 now: Timestamp,
1034) -> Result<Outcome, CommandError> {
1035 let retried = match dispatcher
1036 .retry_task(run_id, (task_id, map_index), now)
1037 .await
1038 {
1039 Ok(retried) => retried,
1040 Err(DispatchError::Execution(
1041 unknown @ (ExecutionError::UnknownRun(_)
1042 | ExecutionError::UnknownTask { .. }
1043 | ExecutionError::UnknownInstance { .. }),
1044 )) => return Ok(Outcome::Rejected(unknown.to_string())),
1045 Err(error) => return Err(error.into()),
1046 };
1047 Ok(match retried {
1048 TaskRetry::Queued(_) => Outcome::Applied(json!({"state": "queued"})),
1049 TaskRetry::NotUnschedulable(TaskInstanceState::Queued) if pending.applying => {
1050 Outcome::Applied(json!({"state": "queued"}))
1051 }
1052 TaskRetry::NotUnschedulable(state) => Outcome::Rejected(format!(
1053 "task `{task_id}` of run `{run_id}` is {state}, not unschedulable: only an \
1054 unschedulable task is retried (a failed one is retried by its `retries`)"
1055 )),
1056 TaskRetry::RunFinished(state) => Outcome::Rejected(format!(
1057 "run `{run_id}` already finished ({state}): trigger a new run"
1058 )),
1059 TaskRetry::RunQueued => Outcome::Rejected(format!(
1060 "run `{run_id}` hasn't started its tasks yet: nothing to retry"
1061 )),
1062 })
1063}
1064
1065async fn cancel(
1067 dispatcher: &mut Dispatcher,
1068 run_id: &str,
1069 outgoing: &mut Vec<Outgoing>,
1070 now: Timestamp,
1071) -> Result<usize, CommandError> {
1072 match dispatcher.cancel_run(run_id, now).await {
1073 Ok(messages) => {
1074 let count = messages.len();
1075 outgoing.extend(messages);
1076 Ok(count)
1077 }
1078 Err(DispatchError::Execution(ExecutionError::UnknownRun(_))) => Ok(0),
1079 Err(error) => Err(error.into()),
1080 }
1081}
1082
1083fn no_worker(worker_id: &str) -> Outcome {
1084 Outcome::Rejected(format!(
1085 "no worker `{worker_id}` (`schedr workers list` shows the workers the master has seen)"
1086 ))
1087}
1088
1089fn no_dag(dag_id: &DagId) -> Outcome {
1090 Outcome::Rejected(format!("no DAG `{dag_id}`"))
1091}
1092
1093fn batches(trigger: &schedr_model::Trigger) -> bool {
1095 matches!(
1096 trigger,
1097 schedr_model::Trigger::Event { task, .. }
1098 if matches!(task.kind, schedr_model::TaskKind::Sensor { batch_ms: Some(_), .. })
1099 )
1100}
1101
1102fn one_batch(item: schedr_model::RunEvent) -> schedr_model::RunEvent {
1105 let at = item.at.map_or(
1106 serde_json::Value::Null,
1107 |at| serde_json::json!({"$datetime": at.to_string()}),
1108 );
1109 schedr_model::RunEvent {
1110 data: serde_json::json!([{"key": item.key, "data": item.data, "at": at}]),
1111 key: item.key,
1112 at: None,
1113 }
1114}