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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
//! HTTP handlers for `/job/*` endpoints.

use std::str::FromStr;

use log::error;
use serde::Deserialize;
use actix_web::{web, HttpResponse, Responder, ResponseError};

use crate::models::{job, ApplicationState, OcyError};

#[derive(Deserialize)]
pub struct JobFields {
    fields: Option<String>,
}

/// Handles `GET /job/{job_id}` requests.
///
/// # Returns
///
/// * 200 - JSON response containing all data about a job
/// * 400 - bad request error if any requested fields were not recognised
/// * 404 - not found error if no job with given `job_id` is found
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn index(
    path: web::Path<u64>,
    query: web::Query<JobFields>,
    data: web::Data<ApplicationState>,
) -> impl Responder {
    let job_id = path.into_inner();
    let fields = match query.into_inner().fields {
        Some(raw_fields) => {
            let mut fields = Vec::new();
            for raw_field in raw_fields.split(',') {
                match job::Field::from_str(raw_field) {
                    Ok(field) => fields.push(field),
                    Err(_) => {
                        return HttpResponse::BadRequest()
                            .body(format!("Unrecognised field: {}", raw_field))
                    }
                }
            }
            Some(fields)
        }
        None => None,
    };

    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.job_fields(&mut conn, job_id, fields.as_deref()).await {
        Ok(job) => HttpResponse::Ok().json(job),
        Err(err @ OcyError::NoSuchJob(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed to fetch metadata fields: {}", job_id, err);
            err.error_response()
        },
    }
}

/// Handles `GET /job/{job_id}/status` requests.
///
/// # Returns
///
/// * 200 - JSON response containing status string
/// * 404 - not found error if no job with given `job_id` is found
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn status(path: web::Path<u64>, data: web::Data<ApplicationState>) -> impl Responder {
    let job_id = path.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.job_status(&mut conn, job_id).await {
        Ok(status) => HttpResponse::Ok().json(status),
        Err(err @ OcyError::NoSuchJob(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed to fetch status: {}", job_id, err);
            err.error_response()
        },
    }
}

/// Handles `PATCH /job/{job_id}` requests. This endpoint allows a job's status and/or output to
/// be updated via a JSON request.
///
/// # Returns
///
/// * 204 - update successfully performed
/// * 400 - bad request, could not perform update with given JSON request
/// * 404 - not found error if no job with given `job_id` is found
/// * 409 - conflict, job not in state where updates allowed
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn update(
    path: web::Path<u64>,
    json: web::Json<job::UpdateRequest>,
    data: web::Data<ApplicationState>,
) -> impl Responder {
    let job_id = path.into_inner();
    let update_req = json.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.update_job(&mut conn, job_id, &update_req).await {
        Ok(_) => HttpResponse::NoContent().into(),
        Err(err @ OcyError::BadRequest(_) | err @ OcyError::Conflict(_) | err @ OcyError::NoSuchJob(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed to update metadata: {}", job_id, err);
            err.error_response()
        },
    }
}

/// Handles `PUT /job/{job_id}/heartbeat` requests. This endpoint updates the last heartbeat time
/// for a job (heartbeat is used to detect jobs that have timed out).
///
/// # Returns
///
/// * 204 - update successfully performed
/// * 404 - not found error if no job with given `job_id` is found
/// * 409 - unable to update heartbeat, job not in `running` state
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn heartbeat(path: web::Path<u64>, data: web::Data<ApplicationState>) -> impl Responder {
    let job_id = path.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.update_job_heartbeat(&mut conn, job_id).await {
        Ok(_) => HttpResponse::NoContent()
            .reason("Heartbeat updated")
            .finish(),
        Err(err @ OcyError::NoSuchJob(_)) | Err(err @ OcyError::Conflict(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed to update heartbeat: {}", job_id, err);
            err.error_response()
        },
    }
}

/// Handles `DELETE /job/{job_id}` requests. This endpoint deletes a job from the DB regardless of the
/// state of execution it's in.
///
/// Generally intended to be called after a job has completed/failed, and clients have retrieved any
/// data they need from it.
///
/// Running/queued jobs can be more gracefully removed by updating the job's status to `cancelled`.
///
/// # Returns
///
/// * 204 - update successfully performed
/// * 404 - not found error if no job with given `job_id` is found
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn delete(path: web::Path<u64>, data: web::Data<ApplicationState>) -> impl Responder {
    let job_id = path.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.delete_job(&mut conn, job_id).await {
        Ok(true) => HttpResponse::NoContent().reason("Job deleted").finish(),
        Ok(false) => HttpResponse::NotFound().into(),
        Err(err) => {
            error!("[job:{}] failed to delete: {}", job_id, err);
            err.error_response()
        },
    }
}

/// Handles `GET /job/{job_id}/output` requests. Gets the current output for a given job.
///
/// # Returns
///
/// * 200 - JSON response containing job output, if any
/// * 404 - not found error if no job with given `job_id` is found
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn output(path: web::Path<u64>, data: web::Data<ApplicationState>) -> impl Responder {
    let job_id = path.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.job_output(&mut conn, job_id).await {
        Ok(v) => HttpResponse::Ok().json(v),
        Err(err @ OcyError::NoSuchJob(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed to fetch output: {}", job_id, err);
            err.error_response()
        }
    }
}

/// Handles `PUT /job/{job_id}/output` requests. Replaces the job's output with given JSON.
///
/// # Returns
///
/// * 204 - if output was successfully updated
/// * 404 - not found error if no job with given `job_id` is found
/// * 409 - job not in "running" state, so output cannot be updated
/// * 500 - unexpected internal error
/// * 503 - Redis connection unavailable
pub async fn set_output(
    path: web::Path<u64>,
    json: web::Json<serde_json::Value>,
    data: web::Data<ApplicationState>,
) -> impl Responder {
    let job_id = path.into_inner();
    let value = json.into_inner();
    let mut conn = match data.pool.get().await {
        Ok(conn) => conn,
        Err(err) => return OcyError::RedisConnection(err).error_response(),
    };

    match data.redis_manager.set_job_output(&mut conn, job_id, &value).await {
        Ok(_) => HttpResponse::NoContent().into(),
        Err(err @ OcyError::NoSuchJob(_) | err @ OcyError::BadRequest(_) | err @ OcyError::Conflict(_)) => err.error_response(),
        Err(err) => {
            error!("[job:{}] failed set output: {}", job_id, err);
            err.error_response()
        },
    }
}