rama_http/layer/
collect_body.rs

1//! Collect the http `Body`
2
3use crate::dep::http_body_util::BodyExt;
4use crate::{dep::http_body::Body, Request, Response};
5use rama_core::{
6    error::{BoxError, ErrorContext, OpaqueError},
7    Context, Layer, Service,
8};
9use rama_utils::macros::define_inner_service_accessors;
10use std::fmt;
11
12/// An http layer to collect the http `Body`
13#[derive(Debug, Clone, Default)]
14#[non_exhaustive]
15pub struct CollectBodyLayer;
16
17impl CollectBodyLayer {
18    /// Create a new [`CollectBodyLayer`].
19    pub const fn new() -> Self {
20        Self
21    }
22}
23
24impl<S> Layer<S> for CollectBodyLayer {
25    type Service = CollectBody<S>;
26
27    fn layer(&self, inner: S) -> Self::Service {
28        CollectBody::new(inner)
29    }
30}
31
32/// Service to collect the http `Body`
33pub struct CollectBody<S> {
34    inner: S,
35}
36
37impl<S> CollectBody<S> {
38    /// Create a new [`CollectBody`].
39    pub const fn new(service: S) -> Self {
40        Self { inner: service }
41    }
42
43    define_inner_service_accessors!();
44}
45
46impl<S, State, ReqBody, ResBody> Service<State, Request<ReqBody>> for CollectBody<S>
47where
48    S: Service<State, Request<ReqBody>, Response = Response<ResBody>, Error: Into<BoxError>>,
49    State: Clone + Send + Sync + 'static,
50    ReqBody: Send + 'static,
51    ResBody:
52        Body<Data: Send, Error: std::error::Error + Send + Sync + 'static> + Send + Sync + 'static,
53{
54    type Response = Response;
55    type Error = BoxError;
56
57    async fn serve(
58        &self,
59        ctx: Context<State>,
60        req: Request<ReqBody>,
61    ) -> Result<Self::Response, Self::Error> {
62        let resp = self
63            .inner
64            .serve(ctx, req)
65            .await
66            .map_err(|err| OpaqueError::from_boxed(err.into()))
67            .context("CollectBody::inner:serve")?;
68        let (parts, body) = resp.into_parts();
69        let bytes = body.collect().await.context("collect body")?.to_bytes();
70        let body = crate::Body::from(bytes);
71        Ok(Response::from_parts(parts, body))
72    }
73}
74
75impl<S> fmt::Debug for CollectBody<S>
76where
77    S: fmt::Debug,
78{
79    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80        f.debug_struct("CollectBody")
81            .field("inner", &self.inner)
82            .finish()
83    }
84}
85
86impl<S> Clone for CollectBody<S>
87where
88    S: Clone,
89{
90    fn clone(&self) -> Self {
91        Self {
92            inner: self.inner.clone(),
93        }
94    }
95}