1use chrono::{DateTime, Utc};
4use chrono_tz::Tz;
5use cron::Schedule;
6use std::{
7 collections::HashMap,
8 fs,
9 path::{Path, PathBuf},
10 sync::{Arc, RwLock},
11};
12use tokio::sync::watch;
13use uuid::Uuid;
14
15use super::{Inner, LEGACY_TASK_OWNER, NewTask, StoredTask, Task, TaskError};
16
17#[derive(Clone)]
18pub struct TaskRegistry {
19 inner: Arc<Inner>,
20}
21
22impl TaskRegistry {
23 pub fn load(directory: impl AsRef<Path>) -> Result<Self, TaskError> {
25 let directory = directory.as_ref().to_path_buf();
26 fs::create_dir_all(&directory).map_err(storage_error)?;
27 let (changed, _) = watch::channel(0);
28 let registry = Self {
29 inner: Arc::new(Inner {
30 directory: directory.clone(),
31 agents: RwLock::new(Vec::new()),
32 tasks: RwLock::new(HashMap::new()),
33 changed,
34 }),
35 };
36 let mut tasks = HashMap::new();
37 let mut names = std::collections::HashSet::new();
38 for entry in fs::read_dir(&directory).map_err(storage_error)? {
39 let path = entry.map_err(storage_error)?.path();
40 if path.extension().and_then(|x| x.to_str()) != Some("toml") {
41 continue;
42 }
43 let raw = fs::read_to_string(&path).map_err(storage_error)?;
44 let old: StoredTask = toml::from_str(&raw)
45 .map_err(|e| TaskError::Invalid(format!("{}: {e}", path.display())))?;
46 let persisted_next_run = old.next_run;
47 let id = old.id.unwrap_or_else(Uuid::new_v4);
48 let user_id = old.user_id.unwrap_or_else(|| LEGACY_TASK_OWNER.into());
49 if user_id.trim().is_empty() {
50 return Err(TaskError::Invalid("user_id cannot be empty".into()));
51 }
52 let mut task = Task {
53 id,
54 user_id,
55 name: old.name,
56 description: old.description,
57 agent: old.agent,
58 prompt: old.prompt,
59 schedule: old.schedule,
60 at: old.at,
61 timezone: old.timezone,
62 family_id: old.family_id,
63 enabled: old.enabled,
64 next_run: None,
65 };
66 validate(&task)?;
67 task.next_run = if !task.enabled {
68 None
69 } else if let Some(next) = persisted_next_run {
70 Some(next)
71 } else if task.schedule.is_none() {
72 task.at.map(|at| at.with_timezone(&Utc))
75 } else {
76 next_run(&task, Utc::now())?
77 };
78 if !names.insert((task.user_id.clone(), task.name.clone())) {
79 return Err(TaskError::Invalid(format!(
80 "duplicate task name '{}' for user '{}'",
81 task.name, task.user_id
82 )));
83 }
84 if tasks.insert(id, task.clone()).is_some() {
85 return Err(TaskError::Invalid(format!("duplicate task id {id}")));
86 }
87 let canonical = directory.join(format!("{id}.toml"));
88 if path != canonical
89 || !raw.contains("user_id")
90 || !raw.contains("id")
91 || persisted_next_run.is_none()
92 {
93 registry.persist(&task)?;
94 if path != canonical {
95 fs::remove_file(path).map_err(storage_error)?;
96 }
97 }
98 }
99 *registry.inner.tasks.write().map_err(lock_error)? = tasks;
100 Ok(registry)
101 }
102 pub fn validate_agents(
103 &self,
104 names: impl IntoIterator<Item = String>,
105 ) -> Result<(), TaskError> {
106 let names: Vec<_> = names.into_iter().collect();
107 for task in self.inner.tasks.read().map_err(lock_error)?.values() {
108 if !names.contains(&task.agent) {
109 return Err(TaskError::Invalid(format!(
110 "task '{}' references unknown agent '{}'",
111 task.name, task.agent
112 )));
113 }
114 }
115 *self.inner.agents.write().map_err(lock_error)? = names;
116 Ok(())
117 }
118 pub fn subscribe(&self) -> watch::Receiver<u64> {
119 self.inner.changed.subscribe()
120 }
121 pub fn snapshot(&self) -> Vec<Task> {
122 self.inner
123 .tasks
124 .read()
125 .expect("task lock poisoned")
126 .values()
127 .cloned()
128 .collect()
129 }
130 pub fn migrate_owner(&self, old_user: &str, new_user: &str) -> Result<(), TaskError> {
132 if old_user == new_user {
133 return Ok(());
134 }
135 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
136 let mut migrating = tasks
137 .values()
138 .filter(|task| task.user_id == old_user)
139 .cloned()
140 .collect::<Vec<_>>();
141 if migrating.is_empty() {
142 return Ok(());
143 }
144 for task in &migrating {
145 if tasks.values().any(|other| {
146 other.user_id == new_user && other.name == task.name && other.id != task.id
147 }) {
148 return Err(TaskError::Invalid(format!(
149 "cannot migrate task '{}': a task with that name already exists",
150 task.name
151 )));
152 }
153 }
154 for task in &mut migrating {
155 task.user_id = new_user.to_owned();
156 self.persist(task)?;
157 }
158 for task in migrating {
159 tasks.insert(task.id, task);
160 }
161 self.notify();
162 Ok(())
163 }
164
165 pub fn list(&self, user: &str) -> Vec<Task> {
166 let mut result: Vec<_> = self
167 .snapshot()
168 .into_iter()
169 .filter(|t| t.user_id == user)
170 .collect();
171 result.sort_by(|a, b| a.name.cmp(&b.name));
172 result
173 }
174 pub fn add(&self, user: &str, task: NewTask) -> Result<Task, TaskError> {
175 if user.trim().is_empty() {
176 return Err(TaskError::Invalid("authenticated user is missing".into()));
177 }
178 let mut value = Task {
179 id: Uuid::new_v4(),
180 user_id: user.into(),
181 name: task.name,
182 description: task.description,
183 agent: task.agent,
184 prompt: task.prompt,
185 schedule: task.schedule,
186 at: task.at,
187 timezone: task.timezone,
188 family_id: task.family_id,
189 enabled: true,
190 next_run: None,
191 };
192 validate(&value)?;
193 if !self
194 .inner
195 .agents
196 .read()
197 .map_err(lock_error)?
198 .contains(&value.agent)
199 {
200 return Err(TaskError::Invalid(format!(
201 "unknown agent '{}'",
202 value.agent
203 )));
204 }
205 value.next_run = next_run(&value, Utc::now())?;
206 if value.next_run.is_none() {
207 return Err(TaskError::Invalid(
208 "one-time task must be scheduled in the future".into(),
209 ));
210 }
211 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
212 if tasks
213 .values()
214 .any(|t| t.user_id == user && t.name == value.name)
215 {
216 return Err(TaskError::Invalid(
217 "task name already exists for this user".into(),
218 ));
219 }
220 self.persist(&value)?;
221 tasks.insert(value.id, value.clone());
222 self.notify();
223 Ok(value)
224 }
225 pub fn update(
227 &self,
228 user: &str,
229 id: Uuid,
230 task: NewTask,
231 enabled: bool,
232 ) -> Result<Task, TaskError> {
233 if user.trim().is_empty() {
234 return Err(TaskError::Invalid("authenticated user is missing".into()));
235 }
236 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
237 if !tasks.get(&id).is_some_and(|value| value.user_id == user) {
238 return Err(TaskError::NotFound);
239 }
240 let mut value = Task {
241 id,
242 user_id: user.into(),
243 name: task.name,
244 description: task.description,
245 agent: task.agent,
246 prompt: task.prompt,
247 schedule: task.schedule,
248 at: task.at,
249 timezone: task.timezone,
250 family_id: task.family_id,
251 enabled,
252 next_run: None,
253 };
254 validate(&value)?;
255 if !self
256 .inner
257 .agents
258 .read()
259 .map_err(lock_error)?
260 .contains(&value.agent)
261 {
262 return Err(TaskError::Invalid(format!(
263 "unknown agent '{}'",
264 value.agent
265 )));
266 }
267 if tasks
268 .values()
269 .any(|other| other.id != id && other.user_id == user && other.name == value.name)
270 {
271 return Err(TaskError::Invalid(
272 "task name already exists for this user".into(),
273 ));
274 }
275 value.next_run = next_run(&value, Utc::now())?;
276 if value.enabled && value.schedule.is_none() && value.next_run.is_none() {
277 return Err(TaskError::Invalid(
278 "one-time task must be scheduled in the future".into(),
279 ));
280 }
281 self.persist(&value)?;
282 tasks.insert(id, value.clone());
283 self.notify();
284 Ok(value)
285 }
286
287 pub fn set_enabled(&self, user: &str, id: Uuid, enabled: bool) -> Result<Task, TaskError> {
289 let current = self
290 .inner
291 .tasks
292 .read()
293 .map_err(lock_error)?
294 .get(&id)
295 .filter(|task| task.user_id == user)
296 .cloned()
297 .ok_or(TaskError::NotFound)?;
298 self.update(
299 user,
300 id,
301 NewTask {
302 name: current.name,
303 description: current.description,
304 agent: current.agent,
305 prompt: current.prompt,
306 schedule: current.schedule,
307 at: current.at,
308 timezone: current.timezone,
309 family_id: current.family_id,
310 },
311 enabled,
312 )
313 }
314
315 pub(crate) fn set_next_run(&self, id: Uuid, next: DateTime<Utc>) -> Result<(), TaskError> {
316 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
317 let task = tasks.get_mut(&id).ok_or(TaskError::NotFound)?;
318 task.next_run = Some(next);
319 self.persist(task)
322 }
323 pub fn remove(&self, user: &str, id: Uuid) -> Result<(), TaskError> {
324 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
325 if !tasks.get(&id).is_some_and(|t| t.user_id == user) {
326 return Err(TaskError::NotFound);
327 }
328 fs::remove_file(self.path(id)).map_err(storage_error)?;
329 tasks.remove(&id);
330 self.notify();
331 Ok(())
332 }
333 pub(crate) fn disable_after_execution(&self, id: Uuid) -> Result<(), TaskError> {
336 let mut tasks = self.inner.tasks.write().map_err(lock_error)?;
337 let Some(task) = tasks.get_mut(&id) else {
338 return Ok(());
339 };
340 task.enabled = false;
341 task.next_run = None;
342 let persisted = task.clone();
343 self.notify();
344 self.persist(&persisted)
347 }
348 fn path(&self, id: Uuid) -> PathBuf {
349 self.inner.directory.join(format!("{id}.toml"))
350 }
351 fn persist(&self, t: &Task) -> Result<(), TaskError> {
352 let path = self.path(t.id);
353 let tmp = self
354 .inner
355 .directory
356 .join(format!(".{}.tmp", Uuid::new_v4()));
357 let stored = StoredTask {
358 id: Some(t.id),
359 user_id: Some(t.user_id.clone()),
360 name: t.name.clone(),
361 description: t.description.clone(),
362 agent: t.agent.clone(),
363 prompt: t.prompt.clone(),
364 schedule: t.schedule.clone(),
365 at: t.at,
366 timezone: t.timezone.clone(),
367 family_id: t.family_id,
368 enabled: t.enabled,
369 next_run: t.next_run,
370 };
371 fs::write(
372 &tmp,
373 toml::to_string_pretty(&stored).map_err(storage_error)?,
374 )
375 .map_err(storage_error)?;
376 if let Err(e) = fs::rename(&tmp, &path) {
377 let _ = fs::remove_file(tmp);
378 return Err(storage_error(e));
379 }
380 Ok(())
381 }
382 fn notify(&self) {
383 self.inner.changed.send_modify(|v| *v = v.wrapping_add(1));
384 }
385}
386
387fn validate(t: &Task) -> Result<(), TaskError> {
388 if t.name.trim().is_empty() || t.agent.trim().is_empty() || t.prompt.trim().is_empty() {
389 return Err(TaskError::Invalid(
390 "name, agent and prompt are required".into(),
391 ));
392 }
393 if t.schedule.is_some() == t.at.is_some() {
394 return Err(TaskError::Invalid(
395 "exactly one of schedule or at is required".into(),
396 ));
397 }
398 if let Some(s) = &t.schedule {
399 s.parse::<Schedule>()
400 .map_err(|e| TaskError::Invalid(format!("invalid cron: {e}")))?;
401 }
402 if let Some(z) = &t.timezone {
403 if t.schedule.is_none() {
404 return Err(TaskError::Invalid("timezone requires schedule".into()));
405 }
406 z.parse::<Tz>()
407 .map_err(|e| TaskError::Invalid(format!("invalid timezone: {e}")))?;
408 }
409 Ok(())
410}
411pub(super) fn next_run(t: &Task, now: DateTime<Utc>) -> Result<Option<DateTime<Utc>>, TaskError> {
412 if !t.enabled {
413 return Ok(None);
414 }
415 if let Some(s) = &t.schedule {
416 let schedule = s.parse::<Schedule>().map_err(storage_error)?;
417 let tz: Tz = t
418 .timezone
419 .as_deref()
420 .unwrap_or("UTC")
421 .parse()
422 .map_err(storage_error)?;
423 return Ok(schedule
424 .after(&now.with_timezone(&tz))
425 .next()
426 .map(|d| d.with_timezone(&Utc)));
427 }
428 Ok(t.at.map(|d| d.with_timezone(&Utc)).filter(|d| *d > now))
429}
430fn storage_error(e: impl std::fmt::Display) -> TaskError {
431 TaskError::Storage(e.to_string())
432}
433fn lock_error<T>(_: std::sync::PoisonError<T>) -> TaskError {
434 TaskError::Storage("task registry lock poisoned".into())
435}