1mod control;
2mod edge;
3mod executor;
4mod interface;
5mod observer;
6mod options;
7mod progress;
8mod retry;
9
10use async_trait::async_trait;
11use serde::{Deserialize, Serialize};
12use std::collections::HashMap;
13use std::fmt;
14use std::sync::Arc;
15use std::time::Duration;
16use thiserror::Error;
17
18pub type Data = HashMap<String, Value>;
20pub type Value = Arc<dyn std::any::Any + Send + Sync>;
21pub type Outputs = HashMap<String, Data>;
22pub type BoxTask = Arc<dyn Task>;
23pub const INFINITE_ATTEMPTS: i64 = -1;
24
25#[derive(Error, Debug)]
26pub enum Error {
27 #[error("circular dependency detected: {0}")]
28 CircularDependency(String),
29 #[error("task {task:?} depends on unknown task {dependency:?}")]
30 UnknownDependency { task: String, dependency: String },
31 #[error("task map key {key:?} does not match task name {name:?}")]
32 TaskNameMismatch { key: String, name: String },
33 #[error("this DAG has already been executed")]
34 AlreadyExecuted,
35 #[error("task {0:?} exited without a result")]
36 TaskAbandoned(String),
37 #[error("task execution failed: {0}")]
38 TaskExecution(String),
39 #[error(transparent)]
40 TaskError(#[from] Box<dyn std::error::Error + Send + Sync>),
41 #[error("task {task:?} emitted the reserved trigger {trigger:?}")]
42 InvalidEmit { task: String, trigger: Trigger },
43 #[error("execution canceled: {0}")]
44 ContextCancelled(String),
45 #[error("retries exhausted: {last}")]
46 RetryFailed {
47 #[source]
48 last: Box<Error>,
49 },
50 #[error("non-retryable error: {0}")]
51 NonRetryable(#[source] Box<Error>),
52 #[error("execution canceled during retry wait; last attempt: {last}")]
53 RetryInterrupted {
54 #[source]
55 last: Box<Error>,
56 },
57 #[error("task {task:?} panicked on attempt {attempt}: {message}")]
58 TaskPanic {
59 task: String,
60 attempt: i64,
61 message: String,
62 stack: String,
63 #[source]
64 source: Option<Box<Error>>,
65 },
66 #[error("observer panicked on event for task {task:?}: {message}")]
67 ObserverPanic {
68 task: String,
69 message: String,
70 stack: String,
71 },
72 #[error("unknown task {0:?}")]
73 UnknownTask(String),
74 #[error("task {0:?} already reached a terminal state")]
75 TaskAlreadyDone(String),
76 #[error("task {task:?} canceled")]
77 TaskCanceled {
78 task: String,
79 reason: CancelReason,
80 #[source]
81 last: Option<Box<Error>>,
82 },
83 #[error("run canceled")]
84 RunCanceled {
85 reason: CancelReason,
86 #[source]
87 last: Option<Box<Error>>,
88 },
89 #[error("context deadline exceeded")]
90 DeadlineExceeded,
91 #[error("context deadline exceeded: {last}")]
92 DeadlineInterrupted {
93 #[source]
94 last: Box<Error>,
95 },
96}
97
98impl Error {
99 pub(crate) fn is_non_retryable(&self) -> bool {
100 match self {
101 Self::NonRetryable(_) | Self::InvalidEmit { .. } => true,
102 Self::RetryFailed { last } | Self::RetryInterrupted { last } => last.is_non_retryable(),
103 Self::TaskPanic { source, .. } => source.as_deref().is_some_and(Self::is_non_retryable),
104 _ => false,
105 }
106 }
107
108 pub(crate) fn is_context_error(&self) -> bool {
109 match self {
110 Self::ContextCancelled(_)
111 | Self::DeadlineExceeded
112 | Self::DeadlineInterrupted { .. }
113 | Self::RetryInterrupted { .. } => true,
114 Self::RetryFailed { last } | Self::NonRetryable(last) => last.is_context_error(),
115 Self::TaskPanic { source, .. } => source.as_deref().is_some_and(Self::is_context_error),
116 _ => false,
117 }
118 }
119
120 pub(crate) fn is_interruption(&self) -> bool {
121 self.is_context_error()
122 || self.is_run_canceled()
123 || match self {
124 Self::TaskCanceled { .. } => true,
125 Self::RetryFailed { last } | Self::NonRetryable(last) => last.is_interruption(),
126 Self::TaskPanic { source, .. } => {
127 source.as_deref().is_some_and(Self::is_interruption)
128 }
129 _ => false,
130 }
131 }
132
133 pub(crate) fn is_run_canceled(&self) -> bool {
134 match self {
135 Self::RunCanceled { .. } => true,
136 Self::RetryFailed { last }
137 | Self::RetryInterrupted { last }
138 | Self::NonRetryable(last) => last.is_run_canceled(),
139 Self::TaskPanic { source, .. } => source.as_deref().is_some_and(Self::is_run_canceled),
140 _ => false,
141 }
142 }
143}
144
145#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
146pub enum State {
147 #[default]
148 Pending,
149 Success,
150 Skipped,
151 Canceled,
152 Failed,
153}
154
155impl fmt::Display for State {
156 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
157 f.write_str(match self {
158 Self::Pending => "pending",
159 Self::Success => "success",
160 Self::Skipped => "skipped",
161 Self::Canceled => "canceled",
162 Self::Failed => "failed",
163 })
164 }
165}
166
167impl State {
168 pub fn done(self) -> bool {
169 self != Self::Pending
170 }
171}
172
173#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
174pub enum Phase {
175 #[default]
176 Pending,
177 Running,
178 Success,
179 Canceled,
180 Failed,
181}
182
183impl fmt::Display for Phase {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 f.write_str(match self {
186 Self::Pending => "pending",
187 Self::Running => "running",
188 Self::Success => "success",
189 Self::Canceled => "canceled",
190 Self::Failed => "failed",
191 })
192 }
193}
194
195impl Phase {
196 pub fn done(self) -> bool {
197 matches!(self, Self::Success | Self::Canceled | Self::Failed)
198 }
199}
200
201#[derive(Debug, Clone)]
202pub struct TaskResult {
203 pub state: State,
204 pub err: Option<Arc<Error>>,
205 pub attempts: i64,
206}
207
208#[derive(Debug, Clone)]
209pub struct TaskFailure {
210 pub task: String,
211 pub error: Arc<Error>,
212}
213
214#[derive(Debug)]
215pub struct RunError {
216 pub failures: Vec<TaskFailure>,
217 pub observer_failures: Vec<ObserverFailure>,
218 pub run_error: Option<Box<Error>>,
219}
220
221impl RunError {
222 pub fn is_already_executed(&self) -> bool {
223 matches!(self.run_error.as_deref(), Some(Error::AlreadyExecuted))
224 }
225}
226
227impl fmt::Display for RunError {
228 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
229 if let Some(error) = &self.run_error {
230 return error.fmt(f);
231 }
232 for (index, err) in self
233 .failures
234 .iter()
235 .map(|entry| &entry.error)
236 .chain(self.observer_failures.iter().map(|entry| &entry.error))
237 .enumerate()
238 {
239 if index > 0 {
240 writeln!(f)?;
241 }
242 write!(f, "{err}")?;
243 }
244 Ok(())
245 }
246}
247
248impl std::error::Error for RunError {
249 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
250 self.run_error
251 .as_deref()
252 .map(|error| error as &dyn std::error::Error)
253 .or_else(|| {
254 self.failures
255 .first()
256 .map(|failure| failure.error.as_ref() as _)
257 })
258 .or_else(|| {
259 self.observer_failures
260 .first()
261 .map(|failure| failure.error.as_ref() as _)
262 })
263 }
264}
265
266#[derive(Debug, Clone, Default, Serialize, Deserialize)]
267pub struct RetryPolicy {
268 pub interval: Duration,
269 pub max_interval: Duration,
270 pub max_attempts: i64,
272 pub multiplier: f64,
273 pub jitter: f64,
274}
275
276#[async_trait]
277pub trait Task: Send + Sync {
278 fn name(&self) -> &str;
279
280 fn dependencies(&self) -> DependencySpec {
281 DependencySpec::default()
282 }
283
284 fn retry_policy(&self) -> RetryPolicy {
285 RetryPolicy::default()
286 }
287
288 async fn pre_execution(&self, _ctx: TaskContext, _attempt: i64, _input: &Input) {}
289
290 async fn execute(
291 &self,
292 ctx: TaskContext,
293 attempt: i64,
294 input: &Input,
295 ) -> (Output, Option<Error>);
296
297 async fn post_execution(
298 &self,
299 _ctx: TaskContext,
300 _attempt: i64,
301 _output: &Output,
302 _err: Option<&Error>,
303 ) {
304 }
305}
306
307pub use control::{
308 with_cause, CancelCause, CancelKind, CancelOption, CancelReason, Context, TaskContext,
309};
310pub use edge::{
311 after, DependencyEdge, DependencySpec, Input, JoinPolicy, Output, Trigger, ON_FAILURE,
312 ON_SUCCESS,
313};
314pub use executor::{validate, Scheduler};
315pub use interface::{Control, SchedulerApi};
316pub use observer::{Event, ObserverFailure};
317pub use options::{with_max_concurrency, with_observer, SchedulerOption};
318pub use progress::Progress;