cala_server/job/
entity.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4use std::borrow::Cow;
5
6pub use crate::primitives::JobId;
7
8#[derive(Clone, Eq, Hash, PartialEq, Debug, Serialize, Deserialize, sqlx::Type)]
9#[sqlx(transparent)]
10#[serde(transparent)]
11pub struct JobType(Cow<'static, str>);
12impl JobType {
13    pub const fn new(job_type: &'static str) -> Self {
14        JobType(Cow::Borrowed(job_type))
15    }
16
17    pub(super) fn from_string(job_type: String) -> Self {
18        JobType(Cow::Owned(job_type))
19    }
20}
21
22impl std::fmt::Display for JobType {
23    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24        write!(f, "{}", self.0)
25    }
26}
27
28#[derive(Debug)]
29pub struct Job {
30    pub id: JobId,
31    pub name: String,
32    pub job_type: JobType,
33    pub description: Option<String>,
34    pub last_error: Option<String>,
35    state: serde_json::Value,
36    pub completed_at: Option<DateTime<Utc>>,
37}
38
39impl Job {
40    pub(super) fn new<T: serde::Serialize>(
41        name: String,
42        job_type: JobType,
43        description: Option<String>,
44        initial_state: T,
45    ) -> Self {
46        Self {
47            id: JobId::new(),
48            name,
49            job_type,
50            description,
51            state: serde_json::to_value(initial_state).expect("could not serialize job state"),
52            last_error: None,
53            completed_at: None,
54        }
55    }
56
57    pub fn state<T: serde::de::DeserializeOwned>(&self) -> Result<T, serde_json::Error> {
58        serde_json::from_value(self.state.clone())
59    }
60
61    pub(super) fn success(&mut self) {
62        self.completed_at = Some(Utc::now());
63        self.last_error = None;
64    }
65
66    pub(super) fn fail(&mut self, error: String) {
67        self.last_error = Some(error);
68    }
69}