From ce3515a76ed0dff2ccb47a50dd09b0aa49481209 Mon Sep 17 00:00:00 2001 From: Fangdun Tsai Date: Mon, 1 Jan 2024 05:54:39 +0800 Subject: [PATCH] chore: revert async_trait --- viz-core/src/middleware/limits.rs | 7 +- viz-core/src/middleware/otel/metrics.rs | 51 +++++----- viz-core/src/middleware/otel/tracing.rs | 121 ++++++++++++------------ viz/src/lib.rs | 31 +++--- 4 files changed, 103 insertions(+), 107 deletions(-) diff --git a/viz-core/src/middleware/limits.rs b/viz-core/src/middleware/limits.rs index a2a4b3f6..3229f3a7 100644 --- a/viz-core/src/middleware/limits.rs +++ b/viz-core/src/middleware/limits.rs @@ -3,10 +3,7 @@ #[cfg(feature = "multipart")] use std::sync::Arc; -use crate::{ - async_trait, future::TryFutureExt, types, Handler, IntoResponse, Request, Response, Result, - Transform, -}; +use crate::{async_trait, types, Handler, IntoResponse, Request, Response, Result, Transform}; /// A configuration for [`LimitsMiddleware`]. #[derive(Debug, Clone)] @@ -83,6 +80,6 @@ where #[cfg(feature = "multipart")] req.extensions_mut().insert(self.config.multipart.clone()); - self.h.call(req).map_ok(IntoResponse::into_response).await + self.h.call(req).await.map(IntoResponse::into_response) } } diff --git a/viz-core/src/middleware/otel/metrics.rs b/viz-core/src/middleware/otel/metrics.rs index e798bb75..6cf1bb55 100644 --- a/viz-core/src/middleware/otel/metrics.rs +++ b/viz-core/src/middleware/otel/metrics.rs @@ -15,7 +15,8 @@ use opentelemetry_semantic_conventions::trace::{ }; use crate::{ - BoxFuture, Handler, IntoResponse, Request, RequestExt, Response, ResponseExt, Result, Transform, + async_trait, Handler, IntoResponse, Request, RequestExt, Response, ResponseExt, Result, + Transform, }; const HTTP_SERVER_ACTIVE_REQUESTS: &str = "http.server.active_requests"; @@ -95,52 +96,50 @@ pub struct MetricsMiddleware { response_size: Histogram, } +#[async_trait] impl Handler for MetricsMiddleware where - H: Handler> + Send + Clone + 'static, + H: Handler>, O: IntoResponse, { type Output = Result; - fn call(&self, req: Request) -> BoxFuture { + async fn call(&self, req: Request) -> Self::Output { let Self { active_requests, duration, request_size, response_size, h, - } = self.clone(); + } = self; - Box::pin(async move { - let timer = SystemTime::now(); - let mut attributes = build_attributes(&req, req.route_info().pattern.as_str()); + let timer = SystemTime::now(); + let mut attributes = build_attributes(&req, req.route_info().pattern.as_str()); - active_requests.add(1, &attributes); + active_requests.add(1, &attributes); - request_size.record(req.content_length().unwrap_or(0), &attributes); + request_size.record(req.content_length().unwrap_or(0), &attributes); - let resp = h - .call(req) - .await - .map(IntoResponse::into_response) - .map(|resp| { - active_requests.add(-1, &attributes); + let resp = h + .call(req) + .await + .map(IntoResponse::into_response) + .map(|resp| { + active_requests.add(-1, &attributes); - attributes - .push(HTTP_RESPONSE_STATUS_CODE.i64(i64::from(resp.status().as_u16()))); + attributes.push(HTTP_RESPONSE_STATUS_CODE.i64(i64::from(resp.status().as_u16()))); - response_size.record(resp.content_length().unwrap_or(0), &attributes); + response_size.record(resp.content_length().unwrap_or(0), &attributes); - resp - }); + resp + }); - duration.record( - timer.elapsed().map(|t| t.as_secs_f64()).unwrap_or_default(), - &attributes, - ); + duration.record( + timer.elapsed().map(|t| t.as_secs_f64()).unwrap_or_default(), + &attributes, + ); - resp - }) + resp } } diff --git a/viz-core/src/middleware/otel/tracing.rs b/viz-core/src/middleware/otel/tracing.rs index b2dbb501..7a8818ef 100644 --- a/viz-core/src/middleware/otel/tracing.rs +++ b/viz-core/src/middleware/otel/tracing.rs @@ -19,10 +19,10 @@ use opentelemetry_semantic_conventions::trace::{ }; use crate::{ + async_trait, header::{HeaderMap, HeaderName}, headers::UserAgent, - BoxFuture, Handler, IntoResponse, Request, RequestExt, Response, ResponseExt, Result, - Transform, + Handler, IntoResponse, Request, RequestExt, Response, ResponseExt, Result, Transform, }; /// `OpenTelemetry` tracing config. @@ -58,77 +58,76 @@ pub struct TracingMiddleware { tracer: Arc, } +#[async_trait] impl Handler for TracingMiddleware where - H: Handler> + Send + Clone + 'static, + H: Handler>, O: IntoResponse, T: Tracer + Send + Sync + Clone + 'static, T::Span: Send + Sync + 'static, { type Output = Result; - fn call(&self, req: Request) -> BoxFuture { - let Self { tracer, h } = self.clone(); - - Box::pin(async move { - let parent_context = global::get_text_map_propagator(|propagator| { - propagator.extract(&RequestHeaderCarrier::new(req.headers())) - }); - - let http_route = &req.route_info().pattern; - let attributes = build_attributes(&req, http_route.as_str()); - - let mut span = tracer - .span_builder(format!("{} {}", req.method(), http_route)) - .with_kind(SpanKind::Server) - .with_attributes(attributes) - .start_with_context(&*tracer, &parent_context); - - span.add_event("request.started".to_string(), vec![]); - - let resp = h - .call(req) - .with_context(Context::current_with_span(span)) - .await; - - let cx = Context::current(); - let span = cx.span(); - - match resp { - Ok(resp) => { - let resp = resp.into_response(); - span.add_event("request.completed".to_string(), vec![]); + async fn call(&self, req: Request) -> Self::Output { + let parent_context = global::get_text_map_propagator(|propagator| { + propagator.extract(&RequestHeaderCarrier::new(req.headers())) + }); + + let http_route = &req.route_info().pattern; + let attributes = build_attributes(&req, http_route.as_str()); + + let mut span = self + .tracer + .span_builder(format!("{} {}", req.method(), http_route)) + .with_kind(SpanKind::Server) + .with_attributes(attributes) + .start_with_context(&*self.tracer, &parent_context); + + span.add_event("request.started".to_string(), vec![]); + + let resp = self + .h + .call(req) + .with_context(Context::current_with_span(span)) + .await; + + let cx = Context::current(); + let span = cx.span(); + + match resp { + Ok(resp) => { + let resp = resp.into_response(); + span.add_event("request.completed".to_string(), vec![]); + span.set_attribute( + HTTP_RESPONSE_STATUS_CODE.i64(i64::from(resp.status().as_u16())), + ); + if let Some(content_length) = resp.content_length() { span.set_attribute( - HTTP_RESPONSE_STATUS_CODE.i64(i64::from(resp.status().as_u16())), - ); - if let Some(content_length) = resp.content_length() { - span.set_attribute( - HTTP_RESPONSE_BODY_SIZE - .i64(i64::try_from(content_length).unwrap_or(i64::MAX)), - ); - } - if resp.status().is_server_error() { - span.set_status(Status::error( - resp.status() - .canonical_reason() - .map(ToString::to_string) - .unwrap_or_default(), - )); - }; - span.end(); - Ok(resp) - } - Err(err) => { - span.add_event( - "request.error".to_string(), - vec![EXCEPTION_MESSAGE.string(err.to_string())], + HTTP_RESPONSE_BODY_SIZE + .i64(i64::try_from(content_length).unwrap_or(i64::MAX)), ); - span.set_status(Status::error(err.to_string())); - span.end(); - Err(err) } + if resp.status().is_server_error() { + span.set_status(Status::error( + resp.status() + .canonical_reason() + .map(ToString::to_string) + .unwrap_or_default(), + )); + }; + span.end(); + Ok(resp) } - }) + Err(err) => { + span.add_event( + "request.error".to_string(), + vec![EXCEPTION_MESSAGE.string(err.to_string())], + ); + span.set_status(Status::error(err.to_string())); + span.end(); + Err(err) + } + } } } diff --git a/viz/src/lib.rs b/viz/src/lib.rs index 303449e9..ddcec1b4 100644 --- a/viz/src/lib.rs +++ b/viz/src/lib.rs @@ -73,23 +73,22 @@ //! //! ``` //! # use std::sync::{Arc, atomic::{AtomicUsize, Ordering}}; -//! # use viz::{Handler, IntoResponse, Request, RequestExt, Response, Result, future::BoxFuture}; +//! # use viz::{async_trait, Handler, IntoResponse, Request, RequestExt, Response, Result}; //! #[derive(Clone)] //! struct MyHandler { //! code: Arc, //! } //! +//! #[async_trait] //! impl Handler for MyHandler { //! type Output = Result; //! -//! fn call(&self, req: Request) -> BoxFuture<'static, Self::Output> { +//! async fn call(&self, req: Request) -> Self::Output { //! let code = self.code.clone(); -//! Box::pin(async move { -//! let path = req.path(); -//! let method = req.method().clone(); -//! let code = code.fetch_add(1, Ordering::SeqCst); -//! Ok(format!("code = {}, method = {}, path = {}", code, method, path).into_response()) -//! }) +//! let path = req.path(); +//! let method = req.method().clone(); +//! let code = code.fetch_add(1, Ordering::SeqCst); +//! Ok(format!("code = {}, method = {}, path = {}", code, method, path).into_response()) //! } //! } //! ``` @@ -242,7 +241,7 @@ //! // middleware fn //! async fn around((req, handler): Next) -> Result //! where -//! H: Handler> + Send + Clone, +//! H: Handler> + Clone, //! { //! // before ... //! let result = handler.call(req).await; @@ -254,14 +253,15 @@ //! #[derive(Clone)] //! struct MyMiddleware {} //! +//! #[async_trait] //! impl Handler> for MyMiddleware //! where -//! H: Handler + Send + Clone + 'static, +//! H: Handler + Clone, //! { //! type Output = H::Output; //! -//! fn call(&self, (i, h): Next) -> BoxFuture<'static, Self::Output> { -//! Box::pin(h.call(i)) +//! async fn call(&self, (i, h): Next) -> Self::Output { +//! h.call(i).await //! } //! } //! @@ -288,14 +288,15 @@ //! #[derive(Clone)] //! struct TimeoutMiddleware(H, Duration); //! +//! #[async_trait] //! impl Handler for TimeoutMiddleware //! where -//! H: Handler + Send + Clone + 'static, +//! H: Handler + Clone, //! { //! type Output = H::Output; //! -//! fn call(&self, req: Request) -> BoxFuture<'static, Self::Output> { -//! Box::pin(self.0.call(req)) +//! async fn call(&self, req: Request) -> Self::Output { +//! self.0.call(req).await //! } //! } //!