1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-07-29 22:01:14 +03:00

Make HTTP request layers convert to Bytes

Add layer to convert a request's Bytes to a Body.
This commit is contained in:
Kévin Commaille
2022-08-19 18:01:16 +02:00
committed by Quentin Gliech
parent 669a1867b7
commit 348044afdc
8 changed files with 102 additions and 22 deletions

View File

@ -20,7 +20,8 @@ use tower::{layer::util::Stack, Service, ServiceBuilder};
use tower_http::cors::CorsLayer;
use crate::layers::{
body_to_bytes::{BodyToBytes, BodyToBytesLayer},
body_to_bytes_response::{BodyToBytesResponse, BodyToBytesResponseLayer},
bytes_to_body_request::{BytesToBodyRequest, BytesToBodyRequestLayer},
catch_http_codes::{CatchHttpCodes, CatchHttpCodesLayer},
form_urlencoded_request::{FormUrlencodedRequest, FormUrlencodedRequestLayer},
json_request::{JsonRequest, JsonRequestLayer},
@ -69,8 +70,12 @@ impl CorsLayerExt for CorsLayer {
}
pub trait ServiceExt<Body>: Sized {
fn response_body_to_bytes(self) -> BodyToBytes<Self> {
BodyToBytes::new(self)
fn request_bytes_to_body(self) -> BytesToBodyRequest<Self> {
BytesToBodyRequest::new(self)
}
fn response_body_to_bytes(self) -> BodyToBytesResponse<Self> {
BodyToBytesResponse::new(self)
}
fn json_response<T>(self) -> JsonResponse<Self, T> {
@ -104,7 +109,8 @@ pub trait ServiceExt<Body>: Sized {
impl<S, B> ServiceExt<B> for S where S: Service<Request<B>> {}
pub trait ServiceBuilderExt<L>: Sized {
fn response_body_to_bytes(self) -> ServiceBuilder<Stack<BodyToBytesLayer, L>>;
fn request_bytes_to_body(self) -> ServiceBuilder<Stack<BytesToBodyRequestLayer, L>>;
fn response_body_to_bytes(self) -> ServiceBuilder<Stack<BodyToBytesResponseLayer, L>>;
fn json_response<T>(self) -> ServiceBuilder<Stack<JsonResponseLayer<T>, L>>;
fn json_request<T>(self) -> ServiceBuilder<Stack<JsonRequestLayer<T>, L>>;
fn form_urlencoded_request<T>(self) -> ServiceBuilder<Stack<FormUrlencodedRequestLayer<T>, L>>;
@ -131,8 +137,12 @@ pub trait ServiceBuilderExt<L>: Sized {
}
impl<L> ServiceBuilderExt<L> for ServiceBuilder<L> {
fn response_body_to_bytes(self) -> ServiceBuilder<Stack<BodyToBytesLayer, L>> {
self.layer(BodyToBytesLayer::default())
fn request_bytes_to_body(self) -> ServiceBuilder<Stack<BytesToBodyRequestLayer, L>> {
self.layer(BytesToBodyRequestLayer::default())
}
fn response_body_to_bytes(self) -> ServiceBuilder<Stack<BodyToBytesResponseLayer, L>> {
self.layer(BodyToBytesResponseLayer::default())
}
fn json_response<T>(self) -> ServiceBuilder<Stack<JsonResponseLayer<T>, L>> {

View File

@ -39,17 +39,17 @@ impl<S, B> Error<S, B> {
}
#[derive(Clone)]
pub struct BodyToBytes<S> {
pub struct BodyToBytesResponse<S> {
inner: S,
}
impl<S> BodyToBytes<S> {
impl<S> BodyToBytesResponse<S> {
pub const fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for BodyToBytes<S>
impl<S, ReqBody, ResBody> Service<Request<ReqBody>> for BodyToBytesResponse<S>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
S::Future: Send + 'static,
@ -85,12 +85,12 @@ where
}
#[derive(Default, Clone, Copy)]
pub struct BodyToBytesLayer;
pub struct BodyToBytesResponseLayer;
impl<S> Layer<S> for BodyToBytesLayer {
type Service = BodyToBytes<S>;
impl<S> Layer<S> for BodyToBytesResponseLayer {
type Service = BodyToBytesResponse<S>;
fn layer(&self, inner: S) -> Self::Service {
BodyToBytes::new(inner)
BodyToBytesResponse::new(inner)
}
}

View File

@ -0,0 +1,66 @@
// Copyright 2022 The Matrix.org Foundation C.I.C.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use bytes::Bytes;
use http::Request;
use http_body::Full;
use tower::{Layer, Service};
#[derive(Clone)]
pub struct BytesToBodyRequest<S> {
inner: S,
}
impl<S> BytesToBodyRequest<S> {
pub const fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S> Service<Request<Bytes>> for BytesToBodyRequest<S>
where
S: Service<Request<Full<Bytes>>>,
S::Future: Send + 'static,
{
type Error = S::Error;
type Response = S::Response;
type Future = S::Future;
fn poll_ready(
&mut self,
cx: &mut std::task::Context<'_>,
) -> std::task::Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, request: Request<Bytes>) -> Self::Future {
let (parts, body) = request.into_parts();
let body = Full::new(body);
let request = Request::from_parts(parts, body);
self.inner.call(request)
}
}
#[derive(Default, Clone, Copy)]
pub struct BytesToBodyRequestLayer;
impl<S> Layer<S> for BytesToBodyRequestLayer {
type Service = BytesToBodyRequest<S>;
fn layer(&self, inner: S) -> Self::Service {
BytesToBodyRequest::new(inner)
}
}

View File

@ -21,7 +21,6 @@ use futures_util::{
};
use headers::{ContentType, HeaderMapExt};
use http::Request;
use http_body::Full;
use serde::Serialize;
use thiserror::Error;
use tower::{Layer, Service};
@ -65,7 +64,7 @@ impl<S, T> FormUrlencodedRequest<S, T> {
impl<S, T> Service<Request<T>> for FormUrlencodedRequest<S, T>
where
S: Service<Request<Full<Bytes>>>,
S: Service<Request<Bytes>>,
S::Future: Send + 'static,
S::Error: 'static,
T: Serialize,
@ -87,7 +86,7 @@ where
parts.headers.typed_insert(ContentType::form_url_encoded());
let body = match serde_urlencoded::to_string(&body) {
Ok(body) => Full::new(Bytes::from(body)),
Ok(body) => Bytes::from(body),
Err(err) => return std::future::ready(Err(Error::serialize(err))).left_future(),
};

View File

@ -21,7 +21,6 @@ use futures_util::{
};
use headers::{ContentType, HeaderMapExt};
use http::Request;
use http_body::Full;
use serde::Serialize;
use thiserror::Error;
use tower::{Layer, Service};
@ -65,7 +64,7 @@ impl<S, T> JsonRequest<S, T> {
impl<S, T> Service<Request<T>> for JsonRequest<S, T>
where
S: Service<Request<Full<Bytes>>>,
S: Service<Request<Bytes>>,
S::Future: Send + 'static,
S::Error: 'static,
T: Serialize,
@ -87,7 +86,7 @@ where
parts.headers.typed_insert(ContentType::json());
let body = match serde_json::to_vec(&body) {
Ok(body) => Full::new(Bytes::from(body)),
Ok(body) => Bytes::from(body),
Err(err) => return std::future::ready(Err(Error::serialize(err))).left_future(),
};

View File

@ -12,7 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub mod body_to_bytes;
pub mod body_to_bytes_response;
pub mod bytes_to_body_request;
pub mod catch_http_codes;
pub mod form_urlencoded_request;
pub mod json_request;

View File

@ -39,7 +39,8 @@ pub use self::{
},
future_service::FutureService,
layers::{
body_to_bytes::{self, BodyToBytes, BodyToBytesLayer},
body_to_bytes_response::{self, BodyToBytesResponse, BodyToBytesResponseLayer},
bytes_to_body_request::{self, BytesToBodyRequest, BytesToBodyRequestLayer},
catch_http_codes::{self, CatchHttpCodes, CatchHttpCodesLayer},
client::ClientLayer,
form_urlencoded_request::{self, FormUrlencodedRequest, FormUrlencodedRequestLayer},

View File

@ -79,7 +79,10 @@ async fn test_json_request_body() {
Ok(res)
}
let svc = ServiceBuilder::new().json_request().service_fn(handle);
let svc = ServiceBuilder::new()
.json_request()
.request_bytes_to_body()
.service_fn(handle);
let request = Request::new(serde_json::json!({"hello": "world"}));
@ -141,6 +144,7 @@ async fn test_urlencoded_request_body() {
let svc = ServiceBuilder::new()
.form_urlencoded_request()
.request_bytes_to_body()
.service_fn(handle);
let request = Request::new(serde_json::json!({"hello": "world"}));