From e8c8d0bf8ad0a7d1e624cfcaa4ba900624a0978f Mon Sep 17 00:00:00 2001 From: Quentin Gliech Date: Wed, 23 Nov 2022 13:51:17 +0100 Subject: [PATCH] Remove the `ServerLayer` from `mas-http` --- crates/cli/Cargo.toml | 2 +- crates/cli/src/commands/server.rs | 9 ++-- crates/cli/src/server.rs | 21 +++++++-- crates/http/Cargo.toml | 8 +++- crates/http/src/layers/mod.rs | 2 +- crates/http/src/layers/server.rs | 75 ------------------------------- crates/http/src/lib.rs | 11 ++--- 7 files changed, 37 insertions(+), 91 deletions(-) delete mode 100644 crates/http/src/layers/server.rs diff --git a/crates/cli/Cargo.toml b/crates/cli/Cargo.toml index c9529d1c..9875a38a 100644 --- a/crates/cli/Cargo.toml +++ b/crates/cli/Cargo.toml @@ -24,7 +24,7 @@ serde_json = "1.0.89" serde_yaml = "0.9.14" tokio = { version = "1.22.0", features = ["full"] } tower = { version = "0.4.13", features = ["full"] } -tower-http = { version = "0.3.5", features = ["fs"] } +tower-http = { version = "0.3.5", features = ["fs", "compression-full"] } url = "2.3.1" watchman_client = "0.8.0" diff --git a/crates/cli/src/commands/server.rs b/crates/cli/src/commands/server.rs index cf4dd5fc..827f0a3d 100644 --- a/crates/cli/src/commands/server.rs +++ b/crates/cli/src/commands/server.rs @@ -21,7 +21,6 @@ use itertools::Itertools; use mas_config::RootConfig; use mas_email::Mailer; use mas_handlers::{AppState, HttpClientFactory, MatrixHomeserver}; -use mas_http::ServerLayer; use mas_listener::{server::Server, shutdown::ShutdownStream}; use mas_policy::PolicyFactory; use mas_router::UrlBuilder; @@ -29,7 +28,6 @@ use mas_storage::MIGRATOR; use mas_tasks::TaskQueue; use mas_templates::Templates; use tokio::signal::unix::SignalKind; -use tower::Layer; use tracing::{error, info, log::warn}; #[derive(Parser, Debug, Default)] @@ -220,8 +218,11 @@ impl Options { }; // and build the router - let router = crate::server::build_router(state.clone(), &config.resources); - let router = ServerLayer::new(config.name.clone()).layer(router); + let router = crate::server::build_router( + state.clone(), + &config.resources, + config.name.as_deref(), + ); // Display some informations about where we'll be serving connections let is_tls = config.tls.is_some(); diff --git a/crates/cli/src/server.rs b/crates/cli/src/server.rs index 614c34c3..fab20f0e 100644 --- a/crates/cli/src/server.rs +++ b/crates/cli/src/server.rs @@ -24,16 +24,22 @@ use hyper::StatusCode; use listenfd::ListenFd; use mas_config::{HttpBindConfig, HttpResource, HttpTlsConfig, UnixOrTcp}; use mas_handlers::AppState; +use mas_http::otel::TraceLayer; use mas_listener::{unix_or_tcp::UnixOrTcpListener, ConnectionInfo}; use mas_router::Route; use mas_spa::ViteManifestService; use mas_templates::Templates; +use opentelemetry::KeyValue; use rustls::ServerConfig; use tower::Layer; -use tower_http::services::ServeDir; +use tower_http::{compression::CompressionLayer, services::ServeDir}; #[allow(clippy::trait_duplication_in_bounds)] -pub fn build_router(state: AppState, resources: &[HttpResource]) -> Router<(), B> +pub fn build_router( + state: AppState, + resources: &[HttpResource], + name: Option<&str>, +) -> Router<(), B> where B: HttpBody + Send + 'static, ::Data: Into + Send, @@ -106,7 +112,16 @@ where } } - router.with_state(state) + let mut trace_layer = TraceLayer::axum(); + + if let Some(name) = name { + trace_layer = trace_layer.with_static_attribute(KeyValue::new("listener", name.to_owned())); + } + + router + .layer(trace_layer) + .layer(CompressionLayer::new()) + .with_state(state) } pub fn build_tls_server_config(config: &HttpTlsConfig) -> Result { diff --git a/crates/http/Cargo.toml b/crates/http/Cargo.toml index 2e2acbff..37cd063d 100644 --- a/crates/http/Cargo.toml +++ b/crates/http/Cargo.toml @@ -27,8 +27,8 @@ serde_json = "1.0.89" serde_urlencoded = "0.7.1" thiserror = "1.0.37" tokio = { version = "1.22.0", features = ["sync", "parking_lot"], optional = true } -tower = { version = "0.4.13", features = ["limit"] } -tower-http = { version = "0.3.5", features = ["timeout", "follow-redirect", "decompression-full", "set-header", "compression-full", "cors", "util"] } +tower = { version = "0.4.13", features = [] } +tower-http = { version = "0.3.5", features = ["cors"] } tracing = "0.1.37" tracing-opentelemetry = "0.18.0" webpki = { version = "0.22.0", optional = true } @@ -51,4 +51,8 @@ client = [ "dep:hyper-rustls", "dep:tokio", "dep:webpki", + "tower/limit", + "tower-http/timeout", + "tower-http/follow-redirect", + "tower-http/set-header", ] diff --git a/crates/http/src/layers/mod.rs b/crates/http/src/layers/mod.rs index a1e08fcc..f489f1b9 100644 --- a/crates/http/src/layers/mod.rs +++ b/crates/http/src/layers/mod.rs @@ -20,5 +20,5 @@ pub mod json_request; pub mod json_response; pub mod otel; +#[cfg(feature = "client")] pub(crate) mod client; -pub(crate) mod server; diff --git a/crates/http/src/layers/server.rs b/crates/http/src/layers/server.rs deleted file mode 100644 index 84ee6182..00000000 --- a/crates/http/src/layers/server.rs +++ /dev/null @@ -1,75 +0,0 @@ -// 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 std::marker::PhantomData; - -use http::{Request, Response}; -use opentelemetry::KeyValue; -use tower::{util::BoxCloneService, Layer, Service, ServiceExt}; -use tower_http::compression::{CompressionBody, CompressionLayer}; - -use super::otel::TraceLayer; - -#[derive(Debug, Default)] -pub struct ServerLayer { - listener_name: Option, - _t: PhantomData, -} - -impl Clone for ServerLayer { - fn clone(&self) -> Self { - Self { - listener_name: self.listener_name.clone(), - _t: PhantomData, - } - } -} - -impl ServerLayer { - #[must_use] - pub fn new(listener_name: Option) -> Self { - Self { - listener_name, - _t: PhantomData, - } - } -} - -impl Layer for ServerLayer -where - S: Service, Response = Response> + Clone + Send + 'static, - S::Future: Send + 'static, - S::Error: std::fmt::Display, - ReqBody: http_body::Body + 'static, - ResBody: http_body::Body + Send + 'static, -{ - #[allow(clippy::type_complexity)] - type Service = BoxCloneService, Response>, S::Error>; - - fn layer(&self, inner: S) -> Self::Service { - let compression = CompressionLayer::new(); - - #[cfg(feature = "axum")] - let mut trace = TraceLayer::axum(); - - #[cfg(not(feature = "axum"))] - let mut trace = TraceLayer::http_server(); - - if let Some(name) = &self.listener_name { - trace = trace.with_static_attribute(KeyValue::new("listener", name.clone())); - } - - (compression, trace).layer(inner).boxed_clone() - } -} diff --git a/crates/http/src/lib.rs b/crates/http/src/lib.rs index d343f516..81546cc7 100644 --- a/crates/http/src/lib.rs +++ b/crates/http/src/lib.rs @@ -31,9 +31,12 @@ mod layers; mod service; #[cfg(feature = "client")] -pub use self::client::{ - make_traced_client, make_traced_connector, make_untraced_client, ClientInitError, TracedClient, - TracedConnector, UntracedClient, UntracedConnector, +pub use self::{ + client::{ + make_traced_client, make_traced_connector, make_untraced_client, ClientInitError, + TracedClient, TracedConnector, UntracedClient, UntracedConnector, + }, + layers::client::{ClientLayer, ClientService}, }; pub use self::{ ext::{set_propagator, CorsLayerExt, ServiceExt as HttpServiceExt}, @@ -41,12 +44,10 @@ pub use self::{ body_to_bytes_response::{self, BodyToBytesResponse, BodyToBytesResponseLayer}, bytes_to_body_request::{self, BytesToBodyRequest, BytesToBodyRequestLayer}, catch_http_codes::{self, CatchHttpCodes, CatchHttpCodesLayer}, - client::{ClientLayer, ClientService}, form_urlencoded_request::{self, FormUrlencodedRequest, FormUrlencodedRequestLayer}, json_request::{self, JsonRequest, JsonRequestLayer}, json_response::{self, JsonResponse, JsonResponseLayer}, otel, - server::ServerLayer, }, service::{BoxCloneSyncService, HttpService}, };