1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
use crate::Error;
use chrono::{NaiveDateTime, Utc};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::fmt::Debug;
use std::path::Path;
use uuid::Uuid;

#[derive(Serialize, Deserialize, PartialEq, Eq, Clone, Debug)]
pub enum State<
    JobRequest: Serialize + Clone,
    Step: Serialize + Clone,
    JobOutputInfo: Serialize + Clone,
> {
    Idle,
    RequestToStart {
        job_id: Uuid,
        request: JobRequest,
    },
    Running {
        job_id: Uuid,
        start: NaiveDateTime,
        request: JobRequest,
        step: Option<Step>,
    },
    Finished {
        job_id: Uuid,
        start: NaiveDateTime,
        end: NaiveDateTime,
        request: JobRequest,
        info: Option<JobOutputInfo>,
    },
    Failed {
        job_id: Uuid,
        start: NaiveDateTime,
        end: NaiveDateTime,
        request: JobRequest,
        info_msg: String,
    },
}

impl<JobRequest: Clone + Serialize, Step: Serialize + Clone, JobOutputInfo: Serialize + Clone>
    State<JobRequest, Step, JobOutputInfo>
{
    pub fn update_running_step(&mut self, new_step: Step) {
        if let State::Running { step, .. } = self {
            *step = Some(new_step);
        }
    }

    pub fn assert_is_finished(&self) {
        matches!(self, State::Finished { .. });
    }

    pub fn run_requested(&self) -> Option<(Uuid, JobRequest)> {
        match self {
            State::RequestToStart { job_id, request } => Some((*job_id, (*request).clone())),
            _ => None,
        }
    }

    pub fn new_run_requested(&mut self, request: JobRequest) -> Result<Uuid, Error> {
        match self {
            State::Idle | State::Finished { .. } => {
                let id = Uuid::new_v4();
                *self = State::RequestToStart {
                    job_id: id,
                    request,
                };
                Ok(id)
            }
            _ => Err(Error::JobInProgress),
        }
    }

    pub fn new_run_started(&mut self) -> Result<(), Error> {
        match self {
            State::RequestToStart { job_id, request } => {
                *self = State::Running {
                    job_id: *job_id,
                    start: Utc::now().naive_utc(),
                    request: request.clone(),
                    step: None,
                };
                Ok(())
            }
            _ => Err(Error::NoRequestToStart),
        }
    }

    pub fn run_finished(&mut self, info: Option<JobOutputInfo>) -> Result<(), Error> {
        match self {
            State::Running {
                job_id,
                start,
                request,
                ..
            } => {
                *self = State::Finished {
                    job_id: *job_id,
                    start: *start,
                    end: Utc::now().naive_utc(),
                    request: request.clone(),
                    info,
                };
                Ok(())
            }
            _ => Err(Error::JobNotStarted),
        }
    }

    pub fn has_id(&self, id: &Uuid) -> bool {
        match self {
            State::Idle => false,
            State::RequestToStart { job_id, .. } => job_id == id,
            State::Running { job_id, .. } => job_id == id,
            State::Finished { job_id, .. } => job_id == id,
            State::Failed { job_id, .. } => job_id == id,
        }
    }

    pub fn persist<P: AsRef<Path>>(&self, path: P) -> Result<(), Error> {
        use std::io::Write;
        let content = serde_yaml::to_string(&self).map_err(|e| Error::Serde(e.to_string()))?;
        let mut file = std::fs::File::create(&path).map_err(|e| Error::Io(e.to_string()))?;
        file.write_all(content.as_bytes())
            .map_err(|e| Error::Io(e.to_string()))?;
        Ok(())
    }
}

impl<
        JobRequest: Debug + Serialize + Clone,
        Step: Debug + Serialize + Clone,
        JobOutputInfo: Debug + Serialize + Clone,
    > fmt::Display for State<JobRequest, Step, JobOutputInfo>
{
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:?}", self)
    }
}