aurelin_framework/scheduling/
builder.rs1use std::{collections::HashSet, error::Error, future::Future, str::FromStr, sync::Arc, time::Duration};
2
3use chrono_tz::Tz;
4
5use super::{BoxError, Callback, Schedule, ScheduleInner, Task, TaskFuture};
6use crate::cache::Cache;
7
8#[derive(Debug, thiserror::Error)]
10pub enum ConfigurationError {
11 #[error("task name must be nonempty and unique: {0:?}")]
13 InvalidName(String),
14 #[error("invalid or unsupported cron expression {expression:?}: {reason}")]
16 InvalidCron { expression: String, reason: String },
17 #[error("invalid timezone: {0}")]
19 InvalidTimezone(String),
20 #[error("overlap prevention for {0:?} requires a cache and a positive whole-second lifetime")]
22 InvalidOverlap(String),
23 #[error("single-server election for {0:?} requires a cache")]
25 MissingElectionCache(String),
26}
27
28pub struct TaskBuilder {
30 name: String,
31 expression: String,
32 timezone: String,
33 callback: Arc<Callback>,
34 overlap: Option<Duration>,
35 one_server: bool,
36}
37
38impl TaskBuilder {
39 pub fn new<F, Fut, E>(name: impl Into<String>, expression: impl Into<String>, callback: F) -> Self
41 where
42 F: Fn() -> Fut + Send + Sync + 'static,
43 Fut: Future<Output = Result<(), E>> + Send + 'static,
44 E: Error + Send + Sync + 'static,
45 {
46 let callback = Arc::new(move || {
47 let future = callback();
48 Box::pin(async move { future.await.map_err(|error| Box::new(error) as BoxError) }) as TaskFuture
49 });
50 Self {
51 name: name.into(),
52 expression: expression.into(),
53 timezone: "UTC".into(),
54 callback,
55 overlap: None,
56 one_server: false,
57 }
58 }
59
60 pub fn timezone(mut self, timezone: impl Into<String>) -> Self {
62 self.timezone = timezone.into();
63 self
64 }
65
66 pub fn without_overlapping(mut self) -> Self {
68 self.overlap = Some(Duration::from_secs(86_400));
69 self
70 }
71
72 pub fn overlap_lifetime(mut self, lifetime: Duration) -> Self {
74 self.overlap = Some(lifetime);
75 self
76 }
77
78 pub fn on_one_server(mut self) -> Self {
80 self.one_server = true;
81 self
82 }
83}
84
85#[derive(Default)]
87pub struct ScheduleBuilder {
88 tasks: Vec<TaskBuilder>,
89 cache: Option<Cache>,
90}
91
92impl ScheduleBuilder {
93 pub fn cache(&mut self, cache: Cache) -> &mut Self {
95 self.cache = Some(cache);
96 self
97 }
98
99 pub fn task(&mut self, task: TaskBuilder) -> &mut Self {
101 self.tasks.push(task);
102 self
103 }
104
105 pub fn build(self) -> Result<Schedule, ConfigurationError> {
107 let mut names = HashSet::new();
108 let mut tasks = Vec::with_capacity(self.tasks.len());
109 for task in self.tasks {
110 if task.name.trim().is_empty() || !names.insert(task.name.clone()) {
111 return Err(ConfigurationError::InvalidName(task.name));
112 }
113 let timezone =
114 Tz::from_str(&task.timezone).map_err(|_| ConfigurationError::InvalidTimezone(task.timezone))?;
115 let expression = parse_expression(&task.expression)?;
116 let overlap_seconds = match task.overlap {
117 Some(duration) if self.cache.is_some() && duration.subsec_nanos() == 0 => {
118 let seconds = i64::try_from(duration.as_secs())
119 .ok()
120 .filter(|value| *value > 0)
121 .ok_or_else(|| ConfigurationError::InvalidOverlap(task.name.clone()))?;
122 Some(seconds)
123 }
124 Some(_) => return Err(ConfigurationError::InvalidOverlap(task.name)),
125 None => None,
126 };
127 if task.one_server && self.cache.is_none() {
128 return Err(ConfigurationError::MissingElectionCache(task.name));
129 }
130 tasks.push(Task {
131 name: task.name,
132 expression,
133 timezone,
134 callback: task.callback,
135 overlap_seconds,
136 one_server: task.one_server,
137 });
138 }
139 Ok(Schedule { inner: Arc::new(ScheduleInner { tasks, cache: self.cache }) })
140 }
141}
142
143fn parse_expression(expression: &str) -> Result<cron::Schedule, ConfigurationError> {
144 let fields: Vec<_> = expression.split_whitespace().collect();
145 let invalid =
146 |reason: &str| ConfigurationError::InvalidCron { expression: expression.into(), reason: reason.into() };
147 if fields.len() != 5 {
148 return Err(invalid("expected five cron fields"));
149 }
150 if fields[4].bytes().any(|byte| byte.is_ascii_digit()) {
153 return Err(invalid("numeric weekdays are unsupported; use weekday names"));
154 }
155 if fields[2] != "*" && fields[4] != "*" {
156 return Err(invalid("restrict either day of month or day of week, not both"));
157 }
158 cron::Schedule::from_str(&format!("0 {expression}")).map_err(|error| invalid(&error.to_string()))
159}