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