intrepid_core/
axum.rs

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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
use std::{collections::HashMap, convert::Infallible, usize};

use axum::{
    body::{to_bytes, Body},
    extract::Request,
    response::{IntoResponse, Response},
};
use bytes::Bytes;
use futures::future::BoxFuture;
use http::StatusCode;
use tower::Service;

use crate::{Error, Frame, MessageFrame, StatefulSystem, StatelessSystem};

impl Service<Request<Body>> for StatelessSystem {
    type Response = Response<Body>;
    type Error = Infallible;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let system = self.clone();
        let frame = HttpRequestFrame::from(request);

        Box::pin(async move {
            let frame = frame.into_frame().await;
            let response: Result<HttpFrameResponse, HttpFrameResponseError> = system
                .handle_frame(frame)
                .await
                .map(Into::into)
                .map_err(Into::into);

            Ok(response
                .map(|response| response.into_json_response())
                .into_response())
        })
    }
}

impl<State> Service<Request<Body>> for StatefulSystem<State>
where
    State: Clone + Sync + Send + 'static,
{
    type Response = Response<Body>;
    type Error = Infallible;
    type Future = BoxFuture<'static, Result<Self::Response, Self::Error>>;

    fn poll_ready(
        &mut self,
        _cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<std::result::Result<(), Self::Error>> {
        std::task::Poll::Ready(Ok(()))
    }

    fn call(&mut self, request: Request<Body>) -> Self::Future {
        let system = self.clone();
        let frame = HttpRequestFrame::from(request);

        Box::pin(async move {
            let frame = frame.into_frame().await;
            let response: Result<HttpFrameResponse, HttpFrameResponseError> = system
                .handle_frame(frame)
                .await
                .map(Into::into)
                .map_err(Into::into);

            Ok(response
                .map(|response| response.into_json_response())
                .into_response())
        })
    }
}

/// An intrepid frame being turned into an axum json response.
#[derive(Debug)]
pub struct HttpFrameResponse(Frame);

impl HttpFrameResponse {
    /// Get the status code of the frame.
    fn status_code(&self) -> StatusCode {
        match &self.0 {
            Frame::Anonymous(_) | Frame::Unit => StatusCode::OK,
            Frame::Message(MessageFrame { meta, .. }) => {
                match serde_json::from_slice::<HttpFrameMeta>(&meta) {
                    Ok(http_meta) => {
                        StatusCode::from_u16(http_meta.status).unwrap_or(StatusCode::OK)
                    }
                    Err(_) => StatusCode::OK,
                }
            }
            Frame::Error(_) => StatusCode::INTERNAL_SERVER_ERROR,
        }
    }

    /// Get the body of the frame.
    fn body(&self) -> Bytes {
        self.0.clone().into_bytes()
    }

    /// Become a plain response.
    pub fn into_plain_response(self) -> impl IntoResponse {
        PlainHttpFrameResponse(self)
    }

    /// Become a JSON response.
    pub fn into_json_response(self) -> impl IntoResponse {
        JsonHttpFrameResponse(self)
    }
}

impl From<HttpFrameResponse> for Frame {
    fn from(frame: HttpFrameResponse) -> Self {
        frame.0
    }
}

impl From<Frame> for HttpFrameResponse {
    fn from(frame: Frame) -> Self {
        Self(frame)
    }
}

/// An intrepid frame being turned into an axum json response.
#[derive(Debug)]
pub struct PlainHttpFrameResponse(HttpFrameResponse);

impl IntoResponse for PlainHttpFrameResponse {
    fn into_response(self) -> Response<Body> {
        (self.0.status_code(), self.0.body()).into_response()
    }
}

/// An intrepid frame being turned into an axum response.
#[derive(Debug)]
pub struct JsonHttpFrameResponse(HttpFrameResponse);

impl IntoResponse for JsonHttpFrameResponse {
    fn into_response(self) -> Response<Body> {
        use axum::Json;
        let body = self.0.body();
        let body = if body.is_empty() {
            return (self.0.status_code(), Json(serde_json::Value::Null)).into_response();
        } else {
            body
        };

        let value = match serde_json::from_slice::<serde_json::Value>(&body) {
            Ok(value) => value,
            Err(error) => {
                return (
                    StatusCode::INTERNAL_SERVER_ERROR,
                    Json(serde_json::json!({ "error": format!("Failed to parse response: {error}") })),
                )
                    .into_response();
            }
        };

        (self.0.status_code(), Json(value)).into_response()
    }
}

/// An intrepid error being turned into an axum response.
#[derive(Debug)]
pub struct HttpFrameResponseError(Error);

impl From<Error> for HttpFrameResponseError {
    fn from(error: Error) -> Self {
        Self(error)
    }
}

impl IntoResponse for HttpFrameResponseError {
    fn into_response(self) -> Response<Body> {
        (StatusCode::INTERNAL_SERVER_ERROR, self.0.to_string()).into_response()
    }
}

/// Metadata for a HTTP frame built from an axum request.
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq)]
pub struct HttpFrameMeta {
    /// The HTTP status code.
    #[serde(default = "default_status")]
    pub status: u16,
    /// The HTTP method.
    #[serde(default = "default_method")]
    pub method: String,
    /// Any additional details, like headers
    #[serde(flatten)]
    pub details: HashMap<String, String>,
}

fn default_status() -> u16 {
    200
}

fn default_method() -> String {
    "GET".to_string()
}

impl Default for HttpFrameMeta {
    fn default() -> Self {
        Self {
            status: 200,
            method: default_method(),
            details: HashMap::new(),
        }
    }
}

/// An HTTP frame built from an axum request.
#[derive(Default, Debug)]
pub struct HttpRequestFrame {
    uri: String,
    meta: HttpFrameMeta,
    body: Body,
}

impl HttpRequestFrame {
    /// Turn the HTTP frame into an intrepid frame.
    pub async fn into_frame(self) -> Frame {
        let meta = serde_json::to_vec(&self.meta).unwrap();
        let body = to_bytes(self.body, usize::MAX).await.unwrap();

        Frame::message(self.uri, body, meta)
    }
}

impl From<Request<Body>> for HttpRequestFrame {
    fn from(request: Request<Body>) -> Self {
        let (parts, body) = request.into_parts();
        let mut http_frame = Self {
            body,
            uri: parts.uri.to_string(),
            ..Default::default()
        };

        http_frame.meta.method = parts.method.to_string();
        http_frame.meta.details = parts
            .headers
            .iter()
            .map(|(key, value)| (key.to_string(), value.to_str().unwrap().to_string()))
            .collect();

        http_frame
    }
}

// fn wat() -> BoxCloneService<Request<Body>, Response<Body>, Infallible> {
//     use std::{iter::once, sync::Arc};
//     use tower::ServiceBuilder;
//     use tower_http::{
//         add_extension::AddExtensionLayer, compression::CompressionLayer,
//         propagate_header::PropagateHeaderLayer, sensitive_headers::SetSensitiveRequestHeadersLayer,
//         trace::TraceLayer, validate_request::ValidateRequestHeaderLayer,
//     };
//     let service = ServiceBuilder::new()
//         .boxed_clone()
//         .layer(SetSensitiveRequestHeadersLayer::new(once(AUTHORIZATION)))
//         .layer(TraceLayer::new_for_http())
//         .layer(AddExtensionLayer::new(Arc::new(())))
//         .layer(CompressionLayer::new())
//         .layer(PropagateHeaderLayer::new(HeaderName::from_static(
//             "x-request-id",
//         )))
//         .layer(ValidateRequestHeaderLayer::bearer("passwordlol"))
//         .layer(ValidateRequestHeaderLayer::accept("application/json"))
//         .service_fn(|_| async { Ok("hay gusy  lol".to_string().into_response()) });

//     service
// }

// mod wut {
//     use std::{convert::Infallible, iter::once, sync::Arc};

//     use axum::{
//         body::Body,
//         extract::Request,
//         response::{IntoResponse, Response},
//     };
//     use http::{
//         header::{AUTHORIZATION, CONTENT_TYPE},
//         HeaderName,
//     };
//     use tower::{util::BoxService, ServiceBuilder};
//     use tower_http::{
//         add_extension::AddExtensionLayer, compression::CompressionLayer,
//         propagate_header::PropagateHeaderLayer, sensitive_headers::SetSensitiveRequestHeadersLayer,
//         set_header::SetResponseHeaderLayer, trace::TraceLayer,
//         validate_request::ValidateRequestHeaderLayer,
//     };

//     fn wat() -> BoxService<Request, Response, Infallible> {
//         let service = ServiceBuilder::new()
//             .boxed()
//             // Mark the `Authorization` request header as sensitive so it doesn't show in logs
//             .layer(SetSensitiveRequestHeadersLayer::new(once(AUTHORIZATION)))
//             // High level logging of requests and responses
//             .layer(TraceLayer::new_for_http())
//             // Share an `Arc<State>` with all requests
//             .layer(AddExtensionLayer::new(Arc::new(())))
//             // Compress responses
//             .layer(CompressionLayer::new())
//             // Propagate `X-Request-Id`s from requests to responses
//             .layer(PropagateHeaderLayer::new(HeaderName::from_static(
//                 "x-request-id",
//             )))
//             // If the response has a known size set the `Content-Length` header
//             // Authorize requests using a token
//             .layer(ValidateRequestHeaderLayer::bearer("passwordlol"))
//             // Accept only application/json, application/* and */* in a request's ACCEPT header
//             .layer(ValidateRequestHeaderLayer::accept("application/json"))
//             // Wrap a `Service` in our middleware stack
//             .service_fn(|_| async { Ok("hay gusy  lol".to_string().into_response()) });

//         service
//     }
// }