Line data Source code
1 : use axum::{body::Body, response::Response};
2 : use compute_api::responses::{ComputeStatus, GenericAPIError};
3 : use http::{header::CONTENT_TYPE, StatusCode};
4 : use serde::Serialize;
5 : use tracing::error;
6 :
7 : mod extract;
8 : mod routes;
9 : pub mod server;
10 :
11 : /// Convenience response builder for JSON responses
12 : struct JsonResponse;
13 :
14 : impl JsonResponse {
15 : /// Helper for actually creating a response
16 0 : fn create_response(code: StatusCode, body: impl Serialize) -> Response {
17 0 : Response::builder()
18 0 : .status(code)
19 0 : .header(CONTENT_TYPE.as_str(), "application/json")
20 0 : .body(Body::from(serde_json::to_string(&body).unwrap()))
21 0 : .unwrap()
22 0 : }
23 :
24 : /// Create a successful error response
25 0 : pub(self) fn success(code: StatusCode, body: impl Serialize) -> Response {
26 0 : assert!({
27 0 : let code = code.as_u16();
28 0 :
29 0 : (200..300).contains(&code)
30 0 : });
31 :
32 0 : Self::create_response(code, body)
33 0 : }
34 :
35 : /// Create an error response
36 0 : pub(self) fn error(code: StatusCode, error: impl ToString) -> Response {
37 0 : assert!(code.as_u16() >= 400);
38 :
39 0 : let message = error.to_string();
40 0 : error!(message);
41 :
42 0 : Self::create_response(code, &GenericAPIError { error: message })
43 0 : }
44 :
45 : /// Create an error response related to the compute being in an invalid state
46 0 : pub(self) fn invalid_status(status: ComputeStatus) -> Response {
47 0 : Self::create_response(
48 0 : StatusCode::PRECONDITION_FAILED,
49 0 : &GenericAPIError {
50 0 : error: format!("invalid compute status: {status}"),
51 0 : },
52 0 : )
53 0 : }
54 : }
|