1
0
mirror of https://github.com/matrix-org/matrix-authentication-service.git synced 2025-11-23 11:02:35 +03:00

Many improvements to the mas-http crate

- make `mas_http::client` implement Service directly instead of being
   an async function
 - a Get layer that makes a Service<Uri>
 - better error sources in the JSON layer
 - make the client have a proper error type
This commit is contained in:
Quentin Gliech
2022-02-15 08:28:25 +01:00
parent 497a3e006e
commit c5858e6ed5
10 changed files with 260 additions and 53 deletions

View File

@@ -32,7 +32,7 @@ use super::trace::OtelTraceLayer;
static MAS_USER_AGENT: HeaderValue =
HeaderValue::from_static("matrix-authentication-service/0.0.1");
type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
type BoxError = Box<dyn std::error::Error + Send + Sync>;
#[derive(Debug, Clone)]
pub struct ClientLayer<ReqBody> {
@@ -41,6 +41,7 @@ pub struct ClientLayer<ReqBody> {
}
impl<B> ClientLayer<B> {
#[must_use]
pub fn new(operation: &'static str) -> Self {
Self {
operation,
@@ -65,6 +66,13 @@ where
type Service = BoxCloneService<Request<ReqBody>, ClientResponse<ResBody>, BoxError>;
fn layer(&self, inner: S) -> Self::Service {
// Note that most layers here just forward the error type. Two notables
// exceptions are:
// - the TimeoutLayer
// - the DecompressionLayer
// Those layers do type erasure of the error.
// The body is also type-erased because of the DecompressionLayer.
ServiceBuilder::new()
.layer(DecompressionLayer::new())
.map_response(|r: Response<_>| r.map(BoxBody::new))
@@ -85,7 +93,7 @@ where
let cx = tracing::Span::current().context();
let mut injector = opentelemetry_http::HeaderInjector(r.headers_mut());
opentelemetry::global::get_text_map_propagator(|propagator| {
propagator.inject_context(&cx, &mut injector)
propagator.inject_context(&cx, &mut injector);
});
r

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 http::{Request, Uri};
use tower::{Layer, Service};
pub struct Get<S> {
inner: S,
}
impl<S> Get<S> {
pub const fn new(inner: S) -> Self {
Self { inner }
}
}
impl<S> Service<Uri> for Get<S>
where
S: Service<Request<http_body::Empty<()>>>,
{
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, req: Uri) -> Self::Future {
let body = http_body::Empty::new();
let req = Request::builder()
.method("GET")
.uri(req)
.body(body)
.unwrap();
self.inner.call(req)
}
}
#[derive(Default, Clone, Copy)]
pub struct GetLayer;
impl<S> Layer<S> for GetLayer
where
S: Service<Request<http_body::Empty<()>>>,
{
type Service = Get<S>;
fn layer(&self, inner: S) -> Self::Service {
Get::new(inner)
}
}

View File

@@ -23,12 +23,20 @@ use tower::{Layer, Service};
#[derive(Debug, Error)]
pub enum Error<Service, Body> {
#[error("service")]
#[error(transparent)]
Service { inner: Service },
#[error("body")]
Body { inner: Body },
#[error("json")]
Json { inner: serde_json::Error },
#[error("failed to fully read the request body")]
Body {
#[source]
inner: Body,
},
#[error("could not parse JSON payload")]
Json {
#[source]
inner: serde_json::Error,
},
}
impl<S, B> Error<S, B> {
@@ -75,15 +83,16 @@ where
self.inner.poll_ready(cx).map_err(Error::service)
}
fn call(&mut self, mut req: Request<B>) -> Self::Future {
req.headers_mut()
fn call(&mut self, mut request: Request<B>) -> Self::Future {
request
.headers_mut()
.insert(ACCEPT, HeaderValue::from_static("application/json"));
let fut = self.inner.call(req);
let fut = self.inner.call(request);
let fut = async {
let res = fut.await.map_err(Error::service)?;
let (parts, body) = res.into_parts();
let response = fut.await.map_err(Error::service)?;
let (parts, body) = response.into_parts();
futures_util::pin_mut!(body);
let bytes = hyper::body::to_bytes(&mut body)

View File

@@ -13,6 +13,7 @@
// limitations under the License.
pub(crate) mod client;
pub(crate) mod get;
pub(crate) mod json;
pub(crate) mod server;
pub(crate) mod trace;