rama-http 0.3.0-rc1

rama http layers, services and other utilities
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
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
#![expect(
    clippy::allow_attributes,
    reason = "macro-generated `#[allow]` attributes whose underlying lints fire only for some expansions"
)]

use std::convert::Infallible;

use rama_core::{
    Service,
    service::{BoxService, StaticOutput},
};

use crate::{Body, Request, Response, matcher::HttpMatcher};

pub mod extract;
pub mod response;

use response::IntoResponse;

#[derive(Debug, Clone)]
pub(crate) struct Endpoint {
    pub(crate) matcher: HttpMatcher<Body>,
    pub(crate) service: BoxService<Request, Response, Infallible>,
}

/// utility trait to accept multiple types as an endpoint service for [`super::WebService`]
pub trait IntoEndpointService<T>: private::Sealed<T, ()> {
    type Service: Service<Request>;

    /// convert the type into a [`rama_core::Service`].
    fn into_endpoint_service(self) -> Self::Service;
}

pub trait IntoEndpointServiceWithState<T, State>: private::Sealed<T, State> {
    type Service: Service<Request>;

    /// convert the type into a [`rama_core::Service`] with state.
    fn into_endpoint_service_with_state(self, state: State) -> Self::Service;
}

impl<S> IntoEndpointService<(S,)> for S
where
    S: Service<Request>,
{
    type Service = Self;

    #[inline(always)]
    fn into_endpoint_service(self) -> Self::Service {
        self
    }
}

impl<S, State> IntoEndpointServiceWithState<(S,), State> for S
where
    S: Service<Request>,
{
    type Service = Self;

    fn into_endpoint_service_with_state(self, _state: State) -> Self::Service {
        self
    }
}

impl<O> IntoEndpointService<()> for Result<O, Infallible>
where
    O: Clone + Send + Sync + 'static,
{
    type Service = StaticOutput<O>;

    fn into_endpoint_service(self) -> Self::Service {
        StaticOutput::new(self.unwrap())
    }
}

impl<O> IntoEndpointService<Response> for O
where
    O: IntoResponse + Clone + Send + Sync + 'static,
{
    type Service = StaticOutput<O>;

    fn into_endpoint_service(self) -> Self::Service {
        StaticOutput::new(self)
    }
}

impl<O, State> IntoEndpointServiceWithState<(), State> for Result<O, Infallible>
where
    O: Clone + Send + Sync + 'static,
{
    type Service = StaticOutput<O>;

    fn into_endpoint_service_with_state(self, _state: State) -> Self::Service {
        self.into_endpoint_service()
    }
}

impl<O, State> IntoEndpointServiceWithState<Response, State> for O
where
    O: IntoResponse + Clone + Send + Sync + 'static,
{
    type Service = StaticOutput<O>;

    fn into_endpoint_service_with_state(self, _state: State) -> Self::Service {
        self.into_endpoint_service()
    }
}

mod service;
#[doc(inline)]
pub use service::EndpointServiceFn;

/// Wrapper svc used for creating a endpoint service from a function.
pub struct EndpointServiceFnWrapper<F, T, State> {
    inner: F,
    _marker: std::marker::PhantomData<fn(T)>,
    state: State,
}

impl<F: std::fmt::Debug, T, State: std::fmt::Debug> std::fmt::Debug
    for EndpointServiceFnWrapper<F, T, State>
{
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("EndpointServiceFnWrapper")
            .field("inner", &self.inner)
            .field("state", &self.state)
            .field(
                "_marker",
                &format_args!("{}", std::any::type_name::<fn(T)>()),
            )
            .finish()
    }
}

impl<F, T, State> Clone for EndpointServiceFnWrapper<F, T, State>
where
    F: Clone,
    State: Clone,
{
    fn clone(&self) -> Self {
        Self {
            inner: self.inner.clone(),
            _marker: std::marker::PhantomData,
            state: self.state.clone(),
        }
    }
}

impl<F, T, State> Service<Request> for EndpointServiceFnWrapper<F, T, State>
where
    F: EndpointServiceFn<T, State>,
    T: Send + 'static,
    State: Send + Sync + Clone + 'static,
{
    type Output = F::Output;
    type Error = F::Error;

    async fn serve(&self, req: Request) -> Result<Self::Output, Self::Error> {
        self.inner.call(req, &self.state).await
    }
}

impl<F, T> IntoEndpointService<(F, T)> for F
where
    F: EndpointServiceFn<T, ()>,
    T: Send + 'static,
{
    type Service = EndpointServiceFnWrapper<F, T, ()>;

    fn into_endpoint_service(self) -> Self::Service {
        EndpointServiceFnWrapper {
            inner: self,
            _marker: std::marker::PhantomData,
            state: (),
        }
    }
}

impl<F, T, State> IntoEndpointServiceWithState<(F, T), State> for F
where
    F: EndpointServiceFn<T, State>,
    T: Send + 'static,
    State: Send + Sync + Clone + 'static,
{
    type Service = EndpointServiceFnWrapper<F, T, State>;

    fn into_endpoint_service_with_state(self, state: State) -> Self::Service {
        EndpointServiceFnWrapper {
            inner: self,
            _marker: std::marker::PhantomData,
            state,
        }
    }
}

mod private {
    use super::*;

    pub trait Sealed<T, State> {}

    impl<S, State> Sealed<(S,), State> for S where S: Service<Request> {}

    impl<O, State> Sealed<(), State> for Result<O, Infallible> {}

    impl<O, State> Sealed<Response, State> for O {}

    impl<F, T, State> Sealed<(F, T), State> for F where F: EndpointServiceFn<T, State> {}
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::{Body, Method, Request, StatusCode, body::util::BodyExt};
    use extract::*;
    use rama_core::conversion::FromRef;

    fn assert_into_endpoint_service<T, I>(_: I)
    where
        I: IntoEndpointService<T>,
    {
    }

    #[test]
    fn test_into_endpoint_service_static() {
        assert_into_endpoint_service(StatusCode::OK);
        assert_into_endpoint_service("hello");
        assert_into_endpoint_service("hello".to_owned());
    }

    #[tokio::test]
    async fn test_into_endpoint_service_impl() {
        #[derive(Debug, Clone)]
        struct OkService;

        impl Service<Request> for OkService {
            type Output = StatusCode;
            type Error = Infallible;

            async fn serve(&self, _req: Request) -> Result<Self::Output, Self::Error> {
                Ok(StatusCode::OK)
            }
        }

        let svc = OkService;
        let resp = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp, StatusCode::OK);

        assert_into_endpoint_service(svc)
    }

    #[test]
    fn test_into_endpoint_service_fn_no_param() {
        assert_into_endpoint_service(async || StatusCode::OK);
        assert_into_endpoint_service(async || "hello");
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_no_param() {
        let svc = async || StatusCode::OK;
        let svc = svc.into_endpoint_service();

        let res = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res, StatusCode::OK);
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_single_param_request() {
        let svc = async |req: Request| req.uri().to_string();
        let svc = svc.into_endpoint_service();

        let res = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        // native Uri preserves the empty path (no forced trailing `/`)
        assert_eq!(res, "http://example.com")
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_with_state() {
        let state = "test_string".to_owned();
        let svc = async |State(state): State<String>| state;
        let svc = svc.into_endpoint_service_with_state(state.clone());

        let res = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res, "test_string");
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_with_derived_state() {
        #[derive(Clone, Debug, Default, FromRef)]
        #[allow(dead_code)]
        struct GlobalState {
            numbers: u8,
            text: String,
        }

        let state = GlobalState {
            text: "test_string".to_owned(),
            ..Default::default()
        };

        let svc = async |State(state): State<GlobalState>| state.text;
        let svc = svc.into_endpoint_service_with_state(state.clone());

        let res = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res, "test_string");
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_single_param_host() {
        let svc = async |Host(host): Host| host.to_string();
        let svc = svc.into_endpoint_service();

        let res = svc
            .serve(
                Request::builder()
                    .uri("http://example.com")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(res, "example.com")
    }

    #[tokio::test]
    async fn test_service_fn_wrapper_multi_param_host() {
        #[derive(Debug, Clone, serde::Deserialize)]
        struct Params {
            foo: String,
        }

        let svc = crate::service::web::WebService::default().with_get(
            "/{foo}/bar",
            async |Host(host): Host, Path(params): Path<Params>| {
                format!("{} => {}", host, params.foo)
            },
        );
        let svc = svc.into_endpoint_service();

        let resp = svc
            .serve(
                Request::builder()
                    .uri("http://example.com/42/bar")
                    .body(Body::empty())
                    .unwrap(),
            )
            .await
            .unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
        let body = resp.into_body().collect().await.unwrap().to_bytes();
        assert_eq!(body, "example.com => 42")
    }

    #[test]
    fn test_into_endpoint_service_fn_single_param() {
        #[derive(Debug, Clone, serde::Deserialize)]
        struct Params {
            foo: String,
        }

        assert_into_endpoint_service(async |_path: Path<Params>| StatusCode::OK);
        assert_into_endpoint_service(async |Path(params): Path<Params>| params.foo);
        assert_into_endpoint_service(async |Query(query): Query<Params>| query.foo);
        assert_into_endpoint_service(async |method: Method| method.to_string());
        assert_into_endpoint_service(async |req: Request| req.uri().to_string());
        assert_into_endpoint_service(async |_host: Host| StatusCode::OK);
        assert_into_endpoint_service(async |Host(_host): Host| StatusCode::OK);
    }
}