Vendor asic-rs 0.8.1 (280 crates, offline builds) + wxWidgets 3.3.3 (pristine + patch queue); UI spec + ADR-0003; M1 on asic-rs

This commit is contained in:
2026-09-15 10:41:00 -06:00
parent 6dc77e8eb0
commit a2b65bb47f
16427 changed files with 6972976 additions and 3 deletions
+116
View File
@@ -0,0 +1,116 @@
use super::{DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, OnBodyChunk, OnEos, OnFailure};
use crate::classify::ClassifyEos;
use http_body::{Body, Frame};
use pin_project_lite::pin_project;
use std::{
fmt,
pin::Pin,
task::{ready, Context, Poll},
time::Instant,
};
use tracing::Span;
pin_project! {
/// Response body for [`Trace`].
///
/// [`Trace`]: super::Trace
pub struct ResponseBody<B, C, OnBodyChunk = DefaultOnBodyChunk, OnEos = DefaultOnEos, OnFailure = DefaultOnFailure> {
#[pin]
pub(crate) inner: B,
pub(crate) classify_eos: Option<C>,
pub(crate) on_eos: Option<(OnEos, Instant)>,
pub(crate) on_body_chunk: OnBodyChunk,
pub(crate) on_failure: Option<OnFailure>,
pub(crate) start: Instant,
pub(crate) span: Span,
}
}
impl<B, C, OnBodyChunkT, OnEosT, OnFailureT> Body
for ResponseBody<B, C, OnBodyChunkT, OnEosT, OnFailureT>
where
B: Body,
B::Error: fmt::Display + 'static,
C: ClassifyEos,
OnEosT: OnEos,
OnBodyChunkT: OnBodyChunk<B::Data>,
OnFailureT: OnFailure<C::FailureClass>,
{
type Data = B::Data;
type Error = B::Error;
fn poll_frame(
self: Pin<&mut Self>,
cx: &mut Context<'_>,
) -> Poll<Option<Result<http_body::Frame<Self::Data>, Self::Error>>> {
let this = self.project();
let _guard = this.span.enter();
let result = ready!(this.inner.poll_frame(cx));
let latency = this.start.elapsed();
*this.start = Instant::now();
match result {
Some(Ok(frame)) => {
let frame = match frame.into_data() {
Ok(chunk) => {
this.on_body_chunk.on_body_chunk(&chunk, latency, this.span);
Frame::data(chunk)
}
Err(frame) => frame,
};
let frame = match frame.into_trailers() {
Ok(trailers) => {
if let Some((classify_eos, mut on_failure)) =
this.classify_eos.take().zip(this.on_failure.take())
{
if let Err(failure_class) = classify_eos.classify_eos(Some(&trailers)) {
on_failure.on_failure(failure_class, latency, this.span);
}
}
if let Some((on_eos, stream_start)) = this.on_eos.take() {
on_eos.on_eos(Some(&trailers), stream_start.elapsed(), this.span);
}
Frame::trailers(trailers)
}
Err(frame) => frame,
};
Poll::Ready(Some(Ok(frame)))
}
Some(Err(err)) => {
if let Some((classify_eos, mut on_failure)) =
this.classify_eos.take().zip(this.on_failure.take())
{
let failure_class = classify_eos.classify_error(&err);
on_failure.on_failure(failure_class, latency, this.span);
}
Poll::Ready(Some(Err(err)))
}
None => {
if let Some((classify_eos, mut on_failure)) =
this.classify_eos.take().zip(this.on_failure.take())
{
if let Err(failure_class) = classify_eos.classify_eos(None) {
on_failure.on_failure(failure_class, latency, this.span);
}
}
if let Some((on_eos, stream_start)) = this.on_eos.take() {
on_eos.on_eos(None, stream_start.elapsed(), this.span);
}
Poll::Ready(None)
}
}
}
fn is_end_stream(&self) -> bool {
self.inner.is_end_stream()
}
fn size_hint(&self) -> http_body::SizeHint {
self.inner.size_hint()
}
}
+116
View File
@@ -0,0 +1,116 @@
use super::{
DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, DefaultOnResponse, OnBodyChunk, OnEos,
OnFailure, OnResponse, ResponseBody,
};
use crate::classify::{ClassifiedResponse, ClassifyResponse};
use http::Response;
use http_body::Body;
use pin_project_lite::pin_project;
use std::{
future::Future,
pin::Pin,
task::{ready, Context, Poll},
time::Instant,
};
use tracing::Span;
pin_project! {
/// Response future for [`Trace`].
///
/// [`Trace`]: super::Trace
pub struct ResponseFuture<F, C, OnResponse = DefaultOnResponse, OnBodyChunk = DefaultOnBodyChunk, OnEos = DefaultOnEos, OnFailure = DefaultOnFailure> {
#[pin]
pub(crate) inner: F,
pub(crate) span: Span,
pub(crate) classifier: Option<C>,
pub(crate) on_response: Option<OnResponse>,
pub(crate) on_body_chunk: Option<OnBodyChunk>,
pub(crate) on_eos: Option<OnEos>,
pub(crate) on_failure: Option<OnFailure>,
pub(crate) start: Instant,
}
}
impl<Fut, ResBody, E, C, OnResponseT, OnBodyChunkT, OnEosT, OnFailureT> Future
for ResponseFuture<Fut, C, OnResponseT, OnBodyChunkT, OnEosT, OnFailureT>
where
Fut: Future<Output = Result<Response<ResBody>, E>>,
ResBody: Body,
ResBody::Error: std::fmt::Display + 'static,
E: std::fmt::Display + 'static,
C: ClassifyResponse,
OnResponseT: OnResponse<ResBody>,
OnFailureT: OnFailure<C::FailureClass>,
OnBodyChunkT: OnBodyChunk<ResBody::Data>,
OnEosT: OnEos,
{
type Output = Result<
Response<ResponseBody<ResBody, C::ClassifyEos, OnBodyChunkT, OnEosT, OnFailureT>>,
E,
>;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let this = self.project();
let _guard = this.span.enter();
let result = ready!(this.inner.poll(cx));
let latency = this.start.elapsed();
let classifier = this.classifier.take().unwrap();
let on_eos = this.on_eos.take();
let on_body_chunk = this.on_body_chunk.take().unwrap();
let mut on_failure = this.on_failure.take().unwrap();
match result {
Ok(res) => {
let classification = classifier.classify_response(&res);
let start = *this.start;
this.on_response
.take()
.unwrap()
.on_response(&res, latency, this.span);
match classification {
ClassifiedResponse::Ready(classification) => {
if let Err(failure_class) = classification {
on_failure.on_failure(failure_class, latency, this.span);
}
let span = this.span.clone();
let res = res.map(|body| ResponseBody {
inner: body,
classify_eos: None,
on_eos: on_eos.zip(Some(Instant::now())),
on_body_chunk,
on_failure: Some(on_failure),
start,
span,
});
Poll::Ready(Ok(res))
}
ClassifiedResponse::RequiresEos(classify_eos) => {
let span = this.span.clone();
let res = res.map(|body| ResponseBody {
inner: body,
classify_eos: Some(classify_eos),
on_eos: on_eos.zip(Some(Instant::now())),
on_body_chunk,
on_failure: Some(on_failure),
start,
span,
});
Poll::Ready(Ok(res))
}
}
}
Err(err) => {
let failure_class = classifier.classify_error(&err);
on_failure.on_failure(failure_class, latency, this.span);
Poll::Ready(Err(err))
}
}
}
}
+236
View File
@@ -0,0 +1,236 @@
use super::{
DefaultMakeSpan, DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, DefaultOnRequest,
DefaultOnResponse, GrpcMakeClassifier, HttpMakeClassifier, Trace,
};
use crate::classify::{
GrpcErrorsAsFailures, MakeClassifier, ServerErrorsAsFailures, SharedClassifier,
};
use tower_layer::Layer;
/// [`Layer`] that adds high level [tracing] to a [`Service`].
///
/// See the [module docs](crate::trace) for more details.
///
/// [`Layer`]: tower_layer::Layer
/// [tracing]: https://crates.io/crates/tracing
/// [`Service`]: tower_service::Service
#[derive(Debug, Copy, Clone)]
pub struct TraceLayer<
M,
MakeSpan = DefaultMakeSpan,
OnRequest = DefaultOnRequest,
OnResponse = DefaultOnResponse,
OnBodyChunk = DefaultOnBodyChunk,
OnEos = DefaultOnEos,
OnFailure = DefaultOnFailure,
> {
pub(crate) make_classifier: M,
pub(crate) make_span: MakeSpan,
pub(crate) on_request: OnRequest,
pub(crate) on_response: OnResponse,
pub(crate) on_body_chunk: OnBodyChunk,
pub(crate) on_eos: OnEos,
pub(crate) on_failure: OnFailure,
}
impl<M> TraceLayer<M> {
/// Create a new [`TraceLayer`] using the given [`MakeClassifier`].
pub fn new(make_classifier: M) -> Self
where
M: MakeClassifier,
{
Self {
make_classifier,
make_span: DefaultMakeSpan::new(),
on_failure: DefaultOnFailure::default(),
on_request: DefaultOnRequest::default(),
on_eos: DefaultOnEos::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_response: DefaultOnResponse::default(),
}
}
}
impl<M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>
TraceLayer<M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>
{
/// Customize what to do when a request is received.
///
/// `NewOnRequest` is expected to implement [`OnRequest`].
///
/// [`OnRequest`]: super::OnRequest
pub fn on_request<NewOnRequest>(
self,
new_on_request: NewOnRequest,
) -> TraceLayer<M, MakeSpan, NewOnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure> {
TraceLayer {
on_request: new_on_request,
on_failure: self.on_failure,
on_eos: self.on_eos,
on_body_chunk: self.on_body_chunk,
make_span: self.make_span,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a response has been produced.
///
/// `NewOnResponse` is expected to implement [`OnResponse`].
///
/// [`OnResponse`]: super::OnResponse
pub fn on_response<NewOnResponse>(
self,
new_on_response: NewOnResponse,
) -> TraceLayer<M, MakeSpan, OnRequest, NewOnResponse, OnBodyChunk, OnEos, OnFailure> {
TraceLayer {
on_response: new_on_response,
on_request: self.on_request,
on_eos: self.on_eos,
on_body_chunk: self.on_body_chunk,
on_failure: self.on_failure,
make_span: self.make_span,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a body chunk has been sent.
///
/// `NewOnBodyChunk` is expected to implement [`OnBodyChunk`].
///
/// [`OnBodyChunk`]: super::OnBodyChunk
pub fn on_body_chunk<NewOnBodyChunk>(
self,
new_on_body_chunk: NewOnBodyChunk,
) -> TraceLayer<M, MakeSpan, OnRequest, OnResponse, NewOnBodyChunk, OnEos, OnFailure> {
TraceLayer {
on_body_chunk: new_on_body_chunk,
on_eos: self.on_eos,
on_failure: self.on_failure,
on_request: self.on_request,
make_span: self.make_span,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a streaming response has closed.
///
/// `NewOnEos` is expected to implement [`OnEos`].
///
/// [`OnEos`]: super::OnEos
pub fn on_eos<NewOnEos>(
self,
new_on_eos: NewOnEos,
) -> TraceLayer<M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, NewOnEos, OnFailure> {
TraceLayer {
on_eos: new_on_eos,
on_body_chunk: self.on_body_chunk,
on_failure: self.on_failure,
on_request: self.on_request,
make_span: self.make_span,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a response has been classified as a failure.
///
/// `NewOnFailure` is expected to implement [`OnFailure`].
///
/// [`OnFailure`]: super::OnFailure
pub fn on_failure<NewOnFailure>(
self,
new_on_failure: NewOnFailure,
) -> TraceLayer<M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, NewOnFailure> {
TraceLayer {
on_failure: new_on_failure,
on_request: self.on_request,
on_eos: self.on_eos,
on_body_chunk: self.on_body_chunk,
make_span: self.make_span,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize how to make [`Span`]s that all request handling will be wrapped in.
///
/// `NewMakeSpan` is expected to implement [`MakeSpan`].
///
/// [`MakeSpan`]: super::MakeSpan
/// [`Span`]: tracing::Span
pub fn make_span_with<NewMakeSpan>(
self,
new_make_span: NewMakeSpan,
) -> TraceLayer<M, NewMakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure> {
TraceLayer {
make_span: new_make_span,
on_request: self.on_request,
on_failure: self.on_failure,
on_body_chunk: self.on_body_chunk,
on_eos: self.on_eos,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
}
impl TraceLayer<HttpMakeClassifier> {
/// Create a new [`TraceLayer`] using [`ServerErrorsAsFailures`] which supports classifying
/// regular HTTP responses based on the status code.
pub fn new_for_http() -> Self {
Self {
make_classifier: SharedClassifier::new(ServerErrorsAsFailures::default()),
make_span: DefaultMakeSpan::new(),
on_response: DefaultOnResponse::default(),
on_request: DefaultOnRequest::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_eos: DefaultOnEos::default(),
on_failure: DefaultOnFailure::default(),
}
}
}
impl TraceLayer<GrpcMakeClassifier> {
/// Create a new [`TraceLayer`] using [`GrpcErrorsAsFailures`] which supports classifying
/// gRPC responses and streams based on the `grpc-status` header.
pub fn new_for_grpc() -> Self {
Self {
make_classifier: SharedClassifier::new(GrpcErrorsAsFailures::default()),
make_span: DefaultMakeSpan::new(),
on_response: DefaultOnResponse::default(),
on_request: DefaultOnRequest::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_eos: DefaultOnEos::default(),
on_failure: DefaultOnFailure::default(),
}
}
}
impl<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure> Layer<S>
for TraceLayer<M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>
where
M: Clone,
MakeSpan: Clone,
OnRequest: Clone,
OnResponse: Clone,
OnEos: Clone,
OnBodyChunk: Clone,
OnFailure: Clone,
{
type Service = Trace<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>;
fn layer(&self, inner: S) -> Self::Service {
Trace {
inner,
make_classifier: self.make_classifier.clone(),
make_span: self.make_span.clone(),
on_request: self.on_request.clone(),
on_eos: self.on_eos.clone(),
on_body_chunk: self.on_body_chunk.clone(),
on_response: self.on_response.clone(),
on_failure: self.on_failure.clone(),
}
}
}
+113
View File
@@ -0,0 +1,113 @@
use http::Request;
use tracing::{Level, Span};
use super::DEFAULT_MESSAGE_LEVEL;
/// Trait used to generate [`Span`]s from requests. [`Trace`] wraps all request handling in this
/// span.
///
/// [`Span`]: tracing::Span
/// [`Trace`]: super::Trace
pub trait MakeSpan<B> {
/// Make a span from a request.
fn make_span(&mut self, request: &Request<B>) -> Span;
}
impl<B> MakeSpan<B> for Span {
fn make_span(&mut self, _request: &Request<B>) -> Span {
self.clone()
}
}
impl<F, B> MakeSpan<B> for F
where
F: FnMut(&Request<B>) -> Span,
{
fn make_span(&mut self, request: &Request<B>) -> Span {
self(request)
}
}
/// The default way [`Span`]s will be created for [`Trace`].
///
/// [`Span`]: tracing::Span
/// [`Trace`]: super::Trace
#[derive(Debug, Clone)]
pub struct DefaultMakeSpan {
level: Level,
include_headers: bool,
}
impl DefaultMakeSpan {
/// Create a new `DefaultMakeSpan`.
pub fn new() -> Self {
Self {
level: DEFAULT_MESSAGE_LEVEL,
include_headers: false,
}
}
/// Set the [`Level`] used for the [tracing span].
///
/// Defaults to [`Level::DEBUG`].
///
/// [tracing span]: https://docs.rs/tracing/latest/tracing/#spans
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
/// Include request headers on the [`Span`].
///
/// By default headers are not included.
///
/// [`Span`]: tracing::Span
pub fn include_headers(mut self, include_headers: bool) -> Self {
self.include_headers = include_headers;
self
}
}
impl Default for DefaultMakeSpan {
fn default() -> Self {
Self::new()
}
}
impl<B> MakeSpan<B> for DefaultMakeSpan {
fn make_span(&mut self, request: &Request<B>) -> Span {
// This ugly macro is needed, unfortunately, because `tracing::span!`
// required the level argument to be static. Meaning we can't just pass
// `self.level`.
macro_rules! make_span {
($level:expr) => {
if self.include_headers {
tracing::span!(
$level,
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
headers = ?request.headers(),
)
} else {
tracing::span!(
$level,
"request",
method = %request.method(),
uri = %request.uri(),
version = ?request.version(),
)
}
}
}
match self.level {
Level::ERROR => make_span!(Level::ERROR),
Level::WARN => make_span!(Level::WARN),
Level::INFO => make_span!(Level::INFO),
Level::DEBUG => make_span!(Level::DEBUG),
Level::TRACE => make_span!(Level::TRACE),
}
}
}
+817
View File
@@ -0,0 +1,817 @@
//! Middleware that adds high level [tracing] to a [`Service`].
//!
//! # Example
//!
//! Adding tracing to your service can be as simple as:
//!
//! ```rust
//! use http::{Request, Response};
//! use tower::{ServiceBuilder, ServiceExt, Service};
//! use tower_http::trace::TraceLayer;
//! use std::convert::Infallible;
//! use http_body_util::Full;
//! use bytes::Bytes;
//!
//! async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! Ok(Response::new(Full::default()))
//! }
//!
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! // Setup tracing
//! tracing_subscriber::fmt::init();
//!
//! let mut service = ServiceBuilder::new()
//! .layer(TraceLayer::new_for_http())
//! .service_fn(handle);
//!
//! let request = Request::new(Full::from("foo"));
//!
//! let response = service
//! .ready()
//! .await?
//! .call(request)
//! .await?;
//! # Ok(())
//! # }
//! ```
//!
//! If you run this application with `RUST_LOG=tower_http=trace cargo run` you should see logs like:
//!
//! ```text
//! Mar 05 20:50:28.523 DEBUG request{method=GET path="/foo"}: tower_http::trace::on_request: started processing request
//! Mar 05 20:50:28.524 DEBUG request{method=GET path="/foo"}: tower_http::trace::on_response: finished processing request latency=1 ms status=200
//! ```
//!
//! # Customization
//!
//! [`Trace`] comes with good defaults but also supports customizing many aspects of the output.
//!
//! The default behaviour supports some customization:
//!
//! ```rust
//! use http::{Request, Response, HeaderMap, StatusCode};
//! use http_body_util::Full;
//! use bytes::Bytes;
//! use tower::ServiceBuilder;
//! use tracing::Level;
//! use tower_http::{
//! LatencyUnit,
//! trace::{TraceLayer, DefaultMakeSpan, DefaultOnRequest, DefaultOnResponse},
//! };
//! use std::time::Duration;
//! # use tower::{ServiceExt, Service};
//! # use std::convert::Infallible;
//!
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! # Ok(Response::new(Full::from("foo")))
//! # }
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # tracing_subscriber::fmt::init();
//! #
//! let service = ServiceBuilder::new()
//! .layer(
//! TraceLayer::new_for_http()
//! .make_span_with(
//! DefaultMakeSpan::new().include_headers(true)
//! )
//! .on_request(
//! DefaultOnRequest::new().level(Level::INFO)
//! )
//! .on_response(
//! DefaultOnResponse::new()
//! .level(Level::INFO)
//! .latency_unit(LatencyUnit::Micros)
//! )
//! // and so on for `on_eos`, `on_body_chunk`, and `on_failure`
//! )
//! .service_fn(handle);
//! # let mut service = service;
//! # let response = service
//! # .ready()
//! # .await?
//! # .call(Request::new(Full::from("foo")))
//! # .await?;
//! # Ok(())
//! # }
//! ```
//!
//! However for maximum control you can provide callbacks:
//!
//! ```rust
//! use http::{Request, Response, HeaderMap, StatusCode};
//! use http_body_util::Full;
//! use bytes::Bytes;
//! use tower::ServiceBuilder;
//! use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
//! use std::time::Duration;
//! use tracing::Span;
//! # use tower::{ServiceExt, Service};
//! # use std::convert::Infallible;
//!
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! # Ok(Response::new(Full::from("foo")))
//! # }
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # tracing_subscriber::fmt::init();
//! #
//! let service = ServiceBuilder::new()
//! .layer(
//! TraceLayer::new_for_http()
//! .make_span_with(|request: &Request<Full<Bytes>>| {
//! tracing::debug_span!("http-request")
//! })
//! .on_request(|request: &Request<Full<Bytes>>, _span: &Span| {
//! tracing::debug!("started {} {}", request.method(), request.uri().path())
//! })
//! .on_response(|response: &Response<Full<Bytes>>, latency: Duration, _span: &Span| {
//! tracing::debug!("response generated in {:?}", latency)
//! })
//! .on_body_chunk(|chunk: &Bytes, latency: Duration, _span: &Span| {
//! tracing::debug!("sending {} bytes", chunk.len())
//! })
//! .on_eos(|trailers: Option<&HeaderMap>, stream_duration: Duration, _span: &Span| {
//! tracing::debug!("stream closed after {:?}", stream_duration)
//! })
//! .on_failure(|error: ServerErrorsFailureClass, latency: Duration, _span: &Span| {
//! tracing::debug!("something went wrong")
//! })
//! )
//! .service_fn(handle);
//! # let mut service = service;
//! # let response = service
//! # .ready()
//! # .await?
//! # .call(Request::new(Full::from("foo")))
//! # .await?;
//! # Ok(())
//! # }
//! ```
//!
//! ## Disabling something
//!
//! Setting the behaviour to `()` will be disable that particular step:
//!
//! ```rust
//! use http::StatusCode;
//! use tower::ServiceBuilder;
//! use tower_http::{classify::ServerErrorsFailureClass, trace::TraceLayer};
//! use std::time::Duration;
//! use tracing::Span;
//! # use tower::{ServiceExt, Service};
//! # use http_body_util::Full;
//! # use bytes::Bytes;
//! # use http::{Response, Request};
//! # use std::convert::Infallible;
//!
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! # Ok(Response::new(Full::from("foo")))
//! # }
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # tracing_subscriber::fmt::init();
//! #
//! let service = ServiceBuilder::new()
//! .layer(
//! // This configuration will only emit events on failures
//! TraceLayer::new_for_http()
//! .on_request(())
//! .on_response(())
//! .on_body_chunk(())
//! .on_eos(())
//! .on_failure(|error: ServerErrorsFailureClass, latency: Duration, _span: &Span| {
//! tracing::debug!("something went wrong")
//! })
//! )
//! .service_fn(handle);
//! # let mut service = service;
//! # let response = service
//! # .ready()
//! # .await?
//! # .call(Request::new(Full::from("foo")))
//! # .await?;
//! # Ok(())
//! # }
//! ```
//!
//! # When the callbacks are called
//!
//! ### `on_request`
//!
//! The `on_request` callback is called when the request arrives at the
//! middleware in [`Service::call`] just prior to passing the request to the
//! inner service.
//!
//! ### `on_response`
//!
//! The `on_response` callback is called when the inner service's response
//! future completes with `Ok(response)` regardless if the response is
//! classified as a success or a failure.
//!
//! For example if you're using [`ServerErrorsAsFailures`] as your classifier
//! and the inner service responds with `500 Internal Server Error` then the
//! `on_response` callback is still called. `on_failure` would _also_ be called
//! in this case since the response was classified as a failure.
//!
//! ### `on_body_chunk`
//!
//! The `on_body_chunk` callback is called when the response body produces a new
//! chunk, that is when [`Body::poll_frame`] returns a data frame.
//!
//! `on_body_chunk` is called even if the chunk is empty.
//!
//! ### `on_eos`
//!
//! The `on_eos` callback is called when a streaming response body ends, that is
//! when [`Body::poll_frame`] returns a trailers frame.
//!
//! `on_eos` is called even if the trailers produced are `None`.
//!
//! ### `on_failure`
//!
//! The `on_failure` callback is called when:
//!
//! - The inner [`Service`]'s response future resolves to an error.
//! - A response is classified as a failure.
//! - [`Body::poll_frame`] returns an error.
//! - An end-of-stream is classified as a failure.
//!
//! # Recording fields on the span
//!
//! All callbacks receive a reference to the [tracing] [`Span`], corresponding to this request,
//! produced by the closure passed to [`TraceLayer::make_span_with`]. It can be used to [record
//! field values][record] that weren't known when the span was created.
//!
//! ```rust
//! use http::{Request, Response, HeaderMap, StatusCode};
//! use http_body_util::Full;
//! use bytes::Bytes;
//! use tower::ServiceBuilder;
//! use tower_http::trace::TraceLayer;
//! use tracing::Span;
//! use std::time::Duration;
//! # use std::convert::Infallible;
//!
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! # Ok(Response::new(Full::from("foo")))
//! # }
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # tracing_subscriber::fmt::init();
//! #
//! let service = ServiceBuilder::new()
//! .layer(
//! TraceLayer::new_for_http()
//! .make_span_with(|request: &Request<Full<Bytes>>| {
//! tracing::debug_span!(
//! "http-request",
//! status_code = tracing::field::Empty,
//! )
//! })
//! .on_response(|response: &Response<Full<Bytes>>, _latency: Duration, span: &Span| {
//! span.record("status_code", &tracing::field::display(response.status()));
//!
//! tracing::debug!("response generated")
//! })
//! )
//! .service_fn(handle);
//! # Ok(())
//! # }
//! ```
//!
//! # Providing classifiers
//!
//! Tracing requires determining if a response is a success or failure. [`MakeClassifier`] is used
//! to create a classifier for the incoming request. See the docs for [`MakeClassifier`] and
//! [`ClassifyResponse`] for more details on classification.
//!
//! A [`MakeClassifier`] can be provided when creating a [`TraceLayer`]:
//!
//! ```rust
//! use http::{Request, Response};
//! use http_body_util::Full;
//! use bytes::Bytes;
//! use tower::ServiceBuilder;
//! use tower_http::{
//! trace::TraceLayer,
//! classify::{
//! MakeClassifier, ClassifyResponse, ClassifiedResponse, NeverClassifyEos,
//! SharedClassifier,
//! },
//! };
//! use std::convert::Infallible;
//!
//! # async fn handle(request: Request<Full<Bytes>>) -> Result<Response<Full<Bytes>>, Infallible> {
//! # Ok(Response::new(Full::from("foo")))
//! # }
//! # #[tokio::main]
//! # async fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # tracing_subscriber::fmt::init();
//! #
//! // Our `MakeClassifier` that always crates `MyClassifier` classifiers.
//! #[derive(Copy, Clone)]
//! struct MyMakeClassify;
//!
//! impl MakeClassifier for MyMakeClassify {
//! type Classifier = MyClassifier;
//! type FailureClass = &'static str;
//! type ClassifyEos = NeverClassifyEos<&'static str>;
//!
//! fn make_classifier<B>(&self, req: &Request<B>) -> Self::Classifier {
//! MyClassifier
//! }
//! }
//!
//! // A classifier that classifies failures as `"something went wrong..."`.
//! #[derive(Copy, Clone)]
//! struct MyClassifier;
//!
//! impl ClassifyResponse for MyClassifier {
//! type FailureClass = &'static str;
//! type ClassifyEos = NeverClassifyEos<&'static str>;
//!
//! fn classify_response<B>(
//! self,
//! res: &Response<B>
//! ) -> ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
//! // Classify based on the status code.
//! if res.status().is_server_error() {
//! ClassifiedResponse::Ready(Err("something went wrong..."))
//! } else {
//! ClassifiedResponse::Ready(Ok(()))
//! }
//! }
//!
//! fn classify_error<E>(self, error: &E) -> Self::FailureClass
//! where
//! E: std::fmt::Display + 'static,
//! {
//! "something went wrong..."
//! }
//! }
//!
//! let service = ServiceBuilder::new()
//! // Create a trace layer that uses our classifier.
//! .layer(TraceLayer::new(MyMakeClassify))
//! .service_fn(handle);
//!
//! // Since `MyClassifier` is `Clone` we can also use `SharedClassifier`
//! // to avoid having to define a separate `MakeClassifier`.
//! let service = ServiceBuilder::new()
//! .layer(TraceLayer::new(SharedClassifier::new(MyClassifier)))
//! .service_fn(handle);
//! # Ok(())
//! # }
//! ```
//!
//! [`TraceLayer`] comes with convenience methods for using common classifiers:
//!
//! - [`TraceLayer::new_for_http`] classifies based on the status code. It doesn't consider
//! streaming responses.
//! - [`TraceLayer::new_for_grpc`] classifies based on the gRPC protocol and supports streaming
//! responses.
//!
//! [tracing]: https://crates.io/crates/tracing
//! [`Service`]: tower_service::Service
//! [`Service::call`]: tower_service::Service::call
//! [`MakeClassifier`]: crate::classify::MakeClassifier
//! [`ClassifyResponse`]: crate::classify::ClassifyResponse
//! [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
//! [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
//! [`Span`]: tracing::Span
//! [`ServerErrorsAsFailures`]: crate::classify::ServerErrorsAsFailures
//! [`Body::poll_frame`]: http_body::Body::poll_frame
use std::{fmt, time::Duration};
use tracing::Level;
pub use self::{
body::ResponseBody,
future::ResponseFuture,
layer::TraceLayer,
make_span::{DefaultMakeSpan, MakeSpan},
on_body_chunk::{DefaultOnBodyChunk, OnBodyChunk},
on_eos::{DefaultOnEos, OnEos},
on_failure::{DefaultOnFailure, OnFailure},
on_request::{DefaultOnRequest, OnRequest},
on_response::{DefaultOnResponse, OnResponse},
service::Trace,
};
use crate::{
classify::{GrpcErrorsAsFailures, ServerErrorsAsFailures, SharedClassifier},
LatencyUnit,
};
/// MakeClassifier for HTTP requests.
pub type HttpMakeClassifier = SharedClassifier<ServerErrorsAsFailures>;
/// MakeClassifier for gRPC requests.
pub type GrpcMakeClassifier = SharedClassifier<GrpcErrorsAsFailures>;
macro_rules! event_dynamic_lvl {
( $(target: $target:expr,)? $(parent: $parent:expr,)? $lvl:expr, $($tt:tt)* ) => {
match $lvl {
tracing::Level::ERROR => {
tracing::event!(
$(target: $target,)?
$(parent: $parent,)?
tracing::Level::ERROR,
$($tt)*
);
}
tracing::Level::WARN => {
tracing::event!(
$(target: $target,)?
$(parent: $parent,)?
tracing::Level::WARN,
$($tt)*
);
}
tracing::Level::INFO => {
tracing::event!(
$(target: $target,)?
$(parent: $parent,)?
tracing::Level::INFO,
$($tt)*
);
}
tracing::Level::DEBUG => {
tracing::event!(
$(target: $target,)?
$(parent: $parent,)?
tracing::Level::DEBUG,
$($tt)*
);
}
tracing::Level::TRACE => {
tracing::event!(
$(target: $target,)?
$(parent: $parent,)?
tracing::Level::TRACE,
$($tt)*
);
}
}
};
}
mod body;
mod future;
mod layer;
mod make_span;
mod on_body_chunk;
mod on_eos;
mod on_failure;
mod on_request;
mod on_response;
mod service;
const DEFAULT_MESSAGE_LEVEL: Level = Level::DEBUG;
const DEFAULT_ERROR_LEVEL: Level = Level::ERROR;
struct Latency {
unit: LatencyUnit,
duration: Duration,
}
impl fmt::Display for Latency {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.unit {
LatencyUnit::Seconds => write!(f, "{} s", self.duration.as_secs_f64()),
LatencyUnit::Millis => write!(f, "{} ms", self.duration.as_millis()),
LatencyUnit::Micros => write!(f, "{} μs", self.duration.as_micros()),
LatencyUnit::Nanos => write!(f, "{} ns", self.duration.as_nanos()),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::classify::ServerErrorsFailureClass;
use crate::test_helpers::Body;
use bytes::Bytes;
use http::{HeaderMap, Request, Response};
use once_cell::sync::Lazy;
use std::{
sync::atomic::{AtomicU32, Ordering},
time::Duration,
};
use tower::{BoxError, Service, ServiceBuilder, ServiceExt};
use tracing::Span;
#[tokio::test]
async fn unary_request() {
static ON_REQUEST_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_RESPONSE_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_BODY_CHUNK_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_EOS: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_FAILURE: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
let trace_layer = TraceLayer::new_for_http()
.make_span_with(|_req: &Request<Body>| {
tracing::info_span!("test-span", foo = tracing::field::Empty)
})
.on_request(|_req: &Request<Body>, span: &Span| {
span.record("foo", 42);
ON_REQUEST_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_response(|_res: &Response<Body>, _latency: Duration, _span: &Span| {
ON_RESPONSE_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| {
ON_BODY_CHUNK_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_eos(
|_trailers: Option<&HeaderMap>, _latency: Duration, _span: &Span| {
ON_EOS.fetch_add(1, Ordering::SeqCst);
},
)
.on_failure(
|_class: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
ON_FAILURE.fetch_add(1, Ordering::SeqCst);
},
);
let mut svc = ServiceBuilder::new().layer(trace_layer).service_fn(echo);
let res = svc
.ready()
.await
.unwrap()
.call(Request::new(Body::from("foobar")))
.await
.unwrap();
assert_eq!(1, ON_REQUEST_COUNT.load(Ordering::SeqCst), "request");
assert_eq!(1, ON_RESPONSE_COUNT.load(Ordering::SeqCst), "request");
assert_eq!(0, ON_BODY_CHUNK_COUNT.load(Ordering::SeqCst), "body chunk");
assert_eq!(0, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(0, ON_FAILURE.load(Ordering::SeqCst), "failure");
crate::test_helpers::to_bytes(res.into_body())
.await
.unwrap();
assert_eq!(1, ON_BODY_CHUNK_COUNT.load(Ordering::SeqCst), "body chunk");
assert_eq!(1, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(0, ON_FAILURE.load(Ordering::SeqCst), "failure");
}
#[tokio::test]
async fn streaming_response() {
static ON_REQUEST_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_RESPONSE_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_BODY_CHUNK_COUNT: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_EOS: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_FAILURE: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
let trace_layer = TraceLayer::new_for_http()
.on_request(|_req: &Request<Body>, _span: &Span| {
ON_REQUEST_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_response(|_res: &Response<Body>, _latency: Duration, _span: &Span| {
ON_RESPONSE_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_body_chunk(|_chunk: &Bytes, _latency: Duration, _span: &Span| {
ON_BODY_CHUNK_COUNT.fetch_add(1, Ordering::SeqCst);
})
.on_eos(
|_trailers: Option<&HeaderMap>, _latency: Duration, _span: &Span| {
ON_EOS.fetch_add(1, Ordering::SeqCst);
},
)
.on_failure(
|_class: ServerErrorsFailureClass, _latency: Duration, _span: &Span| {
ON_FAILURE.fetch_add(1, Ordering::SeqCst);
},
);
let mut svc = ServiceBuilder::new()
.layer(trace_layer)
.service_fn(streaming_body);
let res = svc
.ready()
.await
.unwrap()
.call(Request::new(Body::empty()))
.await
.unwrap();
assert_eq!(1, ON_REQUEST_COUNT.load(Ordering::SeqCst), "request");
assert_eq!(1, ON_RESPONSE_COUNT.load(Ordering::SeqCst), "request");
assert_eq!(0, ON_BODY_CHUNK_COUNT.load(Ordering::SeqCst), "body chunk");
assert_eq!(0, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(0, ON_FAILURE.load(Ordering::SeqCst), "failure");
crate::test_helpers::to_bytes(res.into_body())
.await
.unwrap();
assert_eq!(3, ON_BODY_CHUNK_COUNT.load(Ordering::SeqCst), "body chunk");
assert_eq!(1, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(0, ON_FAILURE.load(Ordering::SeqCst), "failure");
}
#[tokio::test]
async fn classify_eos_on_trailers_success() {
static ON_EOS: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_FAILURE: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
let trace_layer = TraceLayer::new(TestClassify::new(false))
.on_eos(
|_trailers: Option<&HeaderMap>, _latency: Duration, _span: &Span| {
ON_EOS.fetch_add(1, Ordering::SeqCst);
},
)
.on_failure(|_class: &'static str, _latency: Duration, _span: &Span| {
ON_FAILURE.fetch_add(1, Ordering::SeqCst);
});
let mut svc = ServiceBuilder::new()
.layer(trace_layer)
.service_fn(body_with_trailers);
let res = svc
.ready()
.await
.unwrap()
.call(Request::new(Body::empty()))
.await
.unwrap();
crate::test_helpers::to_bytes(res.into_body())
.await
.unwrap();
assert_eq!(1, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(0, ON_FAILURE.load(Ordering::SeqCst), "failure");
}
#[tokio::test]
async fn classify_eos_on_trailers_failure() {
static ON_EOS: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_FAILURE: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
let trace_layer = TraceLayer::new(TestClassify::new(true))
.on_eos(
|_trailers: Option<&HeaderMap>, _latency: Duration, _span: &Span| {
ON_EOS.fetch_add(1, Ordering::SeqCst);
},
)
.on_failure(|_class: &'static str, _latency: Duration, _span: &Span| {
ON_FAILURE.fetch_add(1, Ordering::SeqCst);
});
let mut svc = ServiceBuilder::new()
.layer(trace_layer)
.service_fn(body_with_trailers);
let res = svc
.ready()
.await
.unwrap()
.call(Request::new(Body::empty()))
.await
.unwrap();
crate::test_helpers::to_bytes(res.into_body())
.await
.unwrap();
assert_eq!(1, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(1, ON_FAILURE.load(Ordering::SeqCst), "failure");
}
#[tokio::test]
async fn classify_eos_on_empty_stream() {
static ON_EOS: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
static ON_FAILURE: Lazy<AtomicU32> = Lazy::new(|| AtomicU32::new(0));
let trace_layer = TraceLayer::new(TestClassify::new(true))
.on_eos(
|_trailers: Option<&HeaderMap>, _latency: Duration, _span: &Span| {
ON_EOS.fetch_add(1, Ordering::SeqCst);
},
)
.on_failure(|_class: &'static str, _latency: Duration, _span: &Span| {
ON_FAILURE.fetch_add(1, Ordering::SeqCst);
});
let mut svc = ServiceBuilder::new()
.layer(trace_layer)
.service_fn(streaming_body);
let res = svc
.ready()
.await
.unwrap()
.call(Request::new(Body::empty()))
.await
.unwrap();
crate::test_helpers::to_bytes(res.into_body())
.await
.unwrap();
assert_eq!(1, ON_EOS.load(Ordering::SeqCst), "eos");
assert_eq!(1, ON_FAILURE.load(Ordering::SeqCst), "failure");
}
async fn echo(req: Request<Body>) -> Result<Response<Body>, BoxError> {
Ok(Response::new(req.into_body()))
}
async fn streaming_body(_req: Request<Body>) -> Result<Response<Body>, BoxError> {
use futures_util::stream::iter;
let stream = iter(vec![
Ok::<_, BoxError>(Bytes::from("one")),
Ok::<_, BoxError>(Bytes::from("two")),
Ok::<_, BoxError>(Bytes::from("three")),
]);
let body = Body::from_stream(stream);
Ok(Response::new(body))
}
async fn body_with_trailers(_req: Request<Body>) -> Result<Response<Body>, BoxError> {
let mut trailers = HeaderMap::new();
trailers.insert("x-test-trailer", "value".parse().unwrap());
let body = Body::new(Body::from(Bytes::from("data")).with_trailers(trailers));
Ok(Response::new(body))
}
#[derive(Clone)]
struct TestClassify {
reject: bool,
}
impl TestClassify {
fn new(reject: bool) -> Self {
Self { reject }
}
}
impl crate::classify::MakeClassifier for TestClassify {
type FailureClass = &'static str;
type ClassifyEos = TestClassifyEos;
type Classifier = TestClassifyResponse;
fn make_classifier<B>(&self, _req: &Request<B>) -> Self::Classifier {
TestClassifyResponse {
reject: self.reject,
}
}
}
#[derive(Clone)]
struct TestClassifyResponse {
reject: bool,
}
impl crate::classify::ClassifyResponse for TestClassifyResponse {
type FailureClass = &'static str;
type ClassifyEos = TestClassifyEos;
fn classify_response<B>(
self,
_res: &Response<B>,
) -> crate::classify::ClassifiedResponse<Self::FailureClass, Self::ClassifyEos> {
crate::classify::ClassifiedResponse::RequiresEos(TestClassifyEos {
reject: self.reject,
})
}
fn classify_error<E>(self, _error: &E) -> Self::FailureClass
where
E: std::fmt::Display + 'static,
{
"error"
}
}
#[derive(Clone)]
struct TestClassifyEos {
reject: bool,
}
impl crate::classify::ClassifyEos for TestClassifyEos {
type FailureClass = &'static str;
fn classify_eos(self, _trailers: Option<&HeaderMap>) -> Result<(), Self::FailureClass> {
if self.reject {
Err("classified as failure")
} else {
Ok(())
}
}
fn classify_error<E>(self, _error: &E) -> Self::FailureClass
where
E: std::fmt::Display + 'static,
{
"error"
}
}
}
+64
View File
@@ -0,0 +1,64 @@
use std::time::Duration;
use tracing::Span;
/// Trait used to tell [`Trace`] what to do when a body chunk has been sent.
///
/// See the [module docs](../trace/index.html#on_body_chunk) for details on exactly when the
/// `on_body_chunk` callback is called.
///
/// [`Trace`]: super::Trace
pub trait OnBodyChunk<B> {
/// Do the thing.
///
/// `latency` is the duration since the response was sent or since the last body chunk as sent.
///
/// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
/// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
/// that weren't known when the span was created.
///
/// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
/// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
///
/// If you're using [hyper] as your server `B` will most likely be [`Bytes`].
///
/// [hyper]: https://hyper.rs
/// [`Bytes`]: https://docs.rs/bytes/latest/bytes/struct.Bytes.html
/// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span);
}
impl<B, F> OnBodyChunk<B> for F
where
F: FnMut(&B, Duration, &Span),
{
fn on_body_chunk(&mut self, chunk: &B, latency: Duration, span: &Span) {
self(chunk, latency, span)
}
}
impl<B> OnBodyChunk<B> for () {
#[inline]
fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
}
/// The default [`OnBodyChunk`] implementation used by [`Trace`].
///
/// Simply does nothing.
///
/// [`Trace`]: super::Trace
#[derive(Debug, Default, Clone)]
pub struct DefaultOnBodyChunk {
_priv: (),
}
impl DefaultOnBodyChunk {
/// Create a new `DefaultOnBodyChunk`.
pub fn new() -> Self {
Self { _priv: () }
}
}
impl<B> OnBodyChunk<B> for DefaultOnBodyChunk {
#[inline]
fn on_body_chunk(&mut self, _: &B, _: Duration, _: &Span) {}
}
+107
View File
@@ -0,0 +1,107 @@
use super::{Latency, DEFAULT_MESSAGE_LEVEL};
use crate::{classify::grpc_errors_as_failures::ParsedGrpcStatus, LatencyUnit};
use http::header::HeaderMap;
use std::time::Duration;
use tracing::{Level, Span};
/// Trait used to tell [`Trace`] what to do when a stream closes.
///
/// See the [module docs](../trace/index.html#on_eos) for details on exactly when the `on_eos`
/// callback is called.
///
/// [`Trace`]: super::Trace
pub trait OnEos {
/// Do the thing.
///
/// `stream_duration` is the duration since the response was sent.
///
/// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
/// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
/// that weren't known when the span was created.
///
/// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
/// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
/// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, span: &Span);
}
impl OnEos for () {
#[inline]
fn on_eos(self, _: Option<&HeaderMap>, _: Duration, _: &Span) {}
}
impl<F> OnEos for F
where
F: FnOnce(Option<&HeaderMap>, Duration, &Span),
{
fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, span: &Span) {
self(trailers, stream_duration, span)
}
}
/// The default [`OnEos`] implementation used by [`Trace`].
///
/// [`Trace`]: super::Trace
#[derive(Clone, Debug)]
pub struct DefaultOnEos {
level: Level,
latency_unit: LatencyUnit,
}
impl Default for DefaultOnEos {
fn default() -> Self {
Self {
level: DEFAULT_MESSAGE_LEVEL,
latency_unit: LatencyUnit::Millis,
}
}
}
impl DefaultOnEos {
/// Create a new [`DefaultOnEos`].
pub fn new() -> Self {
Self::default()
}
/// Set the [`Level`] used for [tracing events].
///
/// Defaults to [`Level::DEBUG`].
///
/// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
/// [`Level::DEBUG`]: https://docs.rs/tracing/latest/tracing/struct.Level.html#associatedconstant.DEBUG
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
/// Set the [`LatencyUnit`] latencies will be reported in.
///
/// Defaults to [`LatencyUnit::Millis`].
pub fn latency_unit(mut self, latency_unit: LatencyUnit) -> Self {
self.latency_unit = latency_unit;
self
}
}
impl OnEos for DefaultOnEos {
fn on_eos(self, trailers: Option<&HeaderMap>, stream_duration: Duration, _span: &Span) {
let stream_duration = Latency {
unit: self.latency_unit,
duration: stream_duration,
};
let status = trailers.and_then(|trailers| {
match crate::classify::grpc_errors_as_failures::classify_grpc_metadata(
trailers,
crate::classify::GrpcCode::Ok.into_bitmask(),
) {
ParsedGrpcStatus::Success
| ParsedGrpcStatus::HeaderNotString
| ParsedGrpcStatus::HeaderNotInt => Some(0),
ParsedGrpcStatus::NonSuccess(status) => Some(status.get()),
ParsedGrpcStatus::GrpcStatusHeaderMissing => None,
}
});
event_dynamic_lvl!(self.level, %stream_duration, status, "end of stream");
}
}
+100
View File
@@ -0,0 +1,100 @@
use super::{Latency, DEFAULT_ERROR_LEVEL};
use crate::LatencyUnit;
use std::{fmt, time::Duration};
use tracing::{Level, Span};
/// Trait used to tell [`Trace`] what to do when a request fails.
///
/// See the [module docs](../trace/index.html#on_failure) for details on exactly when the
/// `on_failure` callback is called.
///
/// [`Trace`]: super::Trace
pub trait OnFailure<FailureClass> {
/// Do the thing.
///
/// `latency` is the duration since the request was received.
///
/// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
/// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
/// that weren't known when the span was created.
///
/// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
/// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
/// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
fn on_failure(&mut self, failure_classification: FailureClass, latency: Duration, span: &Span);
}
impl<FailureClass> OnFailure<FailureClass> for () {
#[inline]
fn on_failure(&mut self, _: FailureClass, _: Duration, _: &Span) {}
}
impl<F, FailureClass> OnFailure<FailureClass> for F
where
F: FnMut(FailureClass, Duration, &Span),
{
fn on_failure(&mut self, failure_classification: FailureClass, latency: Duration, span: &Span) {
self(failure_classification, latency, span)
}
}
/// The default [`OnFailure`] implementation used by [`Trace`].
///
/// [`Trace`]: super::Trace
#[derive(Clone, Debug)]
pub struct DefaultOnFailure {
level: Level,
latency_unit: LatencyUnit,
}
impl Default for DefaultOnFailure {
fn default() -> Self {
Self {
level: DEFAULT_ERROR_LEVEL,
latency_unit: LatencyUnit::Millis,
}
}
}
impl DefaultOnFailure {
/// Create a new `DefaultOnFailure`.
pub fn new() -> Self {
Self::default()
}
/// Set the [`Level`] used for [tracing events].
///
/// Defaults to [`Level::ERROR`].
///
/// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
/// Set the [`LatencyUnit`] latencies will be reported in.
///
/// Defaults to [`LatencyUnit::Millis`].
pub fn latency_unit(mut self, latency_unit: LatencyUnit) -> Self {
self.latency_unit = latency_unit;
self
}
}
impl<FailureClass> OnFailure<FailureClass> for DefaultOnFailure
where
FailureClass: fmt::Display,
{
fn on_failure(&mut self, failure_classification: FailureClass, latency: Duration, _: &Span) {
let latency = Latency {
unit: self.latency_unit,
duration: latency,
};
event_dynamic_lvl!(
self.level,
classification = %failure_classification,
%latency,
"response failed"
);
}
}
+82
View File
@@ -0,0 +1,82 @@
use super::DEFAULT_MESSAGE_LEVEL;
use http::Request;
use tracing::Level;
use tracing::Span;
/// Trait used to tell [`Trace`] what to do when a request is received.
///
/// See the [module docs](../trace/index.html#on_request) for details on exactly when the
/// `on_request` callback is called.
///
/// [`Trace`]: super::Trace
pub trait OnRequest<B> {
/// Do the thing.
///
/// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
/// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
/// that weren't known when the span was created.
///
/// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
/// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
/// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
fn on_request(&mut self, request: &Request<B>, span: &Span);
}
impl<B> OnRequest<B> for () {
#[inline]
fn on_request(&mut self, _: &Request<B>, _: &Span) {}
}
impl<B, F> OnRequest<B> for F
where
F: FnMut(&Request<B>, &Span),
{
fn on_request(&mut self, request: &Request<B>, span: &Span) {
self(request, span)
}
}
/// The default [`OnRequest`] implementation used by [`Trace`].
///
/// [`Trace`]: super::Trace
#[derive(Clone, Debug)]
pub struct DefaultOnRequest {
level: Level,
}
impl Default for DefaultOnRequest {
fn default() -> Self {
Self {
level: DEFAULT_MESSAGE_LEVEL,
}
}
}
impl DefaultOnRequest {
/// Create a new `DefaultOnRequest`.
pub fn new() -> Self {
Self::default()
}
/// Set the [`Level`] used for [tracing events].
///
/// Please note that while this will set the level for the tracing events
/// themselves, it might cause them to lack expected information, like
/// request method or path. You can address this using
/// [`DefaultMakeSpan::level`].
///
/// Defaults to [`Level::DEBUG`].
///
/// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
/// [`DefaultMakeSpan::level`]: crate::trace::DefaultMakeSpan::level
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
}
impl<B> OnRequest<B> for DefaultOnRequest {
fn on_request(&mut self, _: &Request<B>, _: &Span) {
event_dynamic_lvl!(self.level, "started processing request");
}
}
+161
View File
@@ -0,0 +1,161 @@
use super::{Latency, DEFAULT_MESSAGE_LEVEL};
use crate::LatencyUnit;
use http::Response;
use std::time::Duration;
use tracing::Level;
use tracing::Span;
/// Trait used to tell [`Trace`] what to do when a response has been produced.
///
/// See the [module docs](../trace/index.html#on_response) for details on exactly when the
/// `on_response` callback is called.
///
/// [`Trace`]: super::Trace
pub trait OnResponse<B> {
/// Do the thing.
///
/// `latency` is the duration since the request was received.
///
/// `span` is the `tracing` [`Span`], corresponding to this request, produced by the closure
/// passed to [`TraceLayer::make_span_with`]. It can be used to [record field values][record]
/// that weren't known when the span was created.
///
/// [`Span`]: https://docs.rs/tracing/latest/tracing/span/index.html
/// [record]: https://docs.rs/tracing/latest/tracing/span/struct.Span.html#method.record
/// [`TraceLayer::make_span_with`]: crate::trace::TraceLayer::make_span_with
fn on_response(self, response: &Response<B>, latency: Duration, span: &Span);
}
impl<B> OnResponse<B> for () {
#[inline]
fn on_response(self, _: &Response<B>, _: Duration, _: &Span) {}
}
impl<B, F> OnResponse<B> for F
where
F: FnOnce(&Response<B>, Duration, &Span),
{
fn on_response(self, response: &Response<B>, latency: Duration, span: &Span) {
self(response, latency, span)
}
}
/// The default [`OnResponse`] implementation used by [`Trace`].
///
/// [`Trace`]: super::Trace
#[derive(Clone, Debug)]
pub struct DefaultOnResponse {
level: Level,
latency_unit: LatencyUnit,
include_headers: bool,
}
impl Default for DefaultOnResponse {
fn default() -> Self {
Self {
level: DEFAULT_MESSAGE_LEVEL,
latency_unit: LatencyUnit::Millis,
include_headers: false,
}
}
}
impl DefaultOnResponse {
/// Create a new `DefaultOnResponse`.
pub fn new() -> Self {
Self::default()
}
/// Set the [`Level`] used for [tracing events].
///
/// Please note that while this will set the level for the tracing events
/// themselves, it might cause them to lack expected information, like
/// request method or path. You can address this using
/// [`DefaultMakeSpan::level`].
///
/// Defaults to [`Level::DEBUG`].
///
/// [tracing events]: https://docs.rs/tracing/latest/tracing/#events
/// [`DefaultMakeSpan::level`]: crate::trace::DefaultMakeSpan::level
pub fn level(mut self, level: Level) -> Self {
self.level = level;
self
}
/// Set the [`LatencyUnit`] latencies will be reported in.
///
/// Defaults to [`LatencyUnit::Millis`].
pub fn latency_unit(mut self, latency_unit: LatencyUnit) -> Self {
self.latency_unit = latency_unit;
self
}
/// Include response headers on the [`Event`].
///
/// By default headers are not included.
///
/// [`Event`]: tracing::Event
pub fn include_headers(mut self, include_headers: bool) -> Self {
self.include_headers = include_headers;
self
}
}
impl<B> OnResponse<B> for DefaultOnResponse {
fn on_response(self, response: &Response<B>, latency: Duration, _: &Span) {
let latency = Latency {
unit: self.latency_unit,
duration: latency,
};
let response_headers = self
.include_headers
.then(|| tracing::field::debug(response.headers()));
event_dynamic_lvl!(
self.level,
%latency,
status = status(response),
response_headers,
"finished processing request"
);
}
}
fn status<B>(res: &Response<B>) -> Option<i32> {
use crate::classify::grpc_errors_as_failures::ParsedGrpcStatus;
// gRPC-over-HTTP2 uses the "application/grpc[+format]" content type, and gRPC-Web uses
// "application/grpc-web[+format]" or "application/grpc-web-text[+format]", where "format" is
// the message format, e.g. +proto, +json.
//
// So, valid grpc content types include (but are not limited to):
// - application/grpc
// - application/grpc+proto
// - application/grpc-web+proto
// - application/grpc-web-text+proto
//
// For simplicity, we simply check that the content type starts with "application/grpc".
let is_grpc = res
.headers()
.get(http::header::CONTENT_TYPE)
.map_or(false, |value| {
value.as_bytes().starts_with("application/grpc".as_bytes())
});
if is_grpc {
match crate::classify::grpc_errors_as_failures::classify_grpc_metadata(
res.headers(),
crate::classify::GrpcCode::Ok.into_bitmask(),
) {
ParsedGrpcStatus::Success
| ParsedGrpcStatus::HeaderNotString
| ParsedGrpcStatus::HeaderNotInt => Some(0),
ParsedGrpcStatus::NonSuccess(status) => Some(status.get()),
// if `grpc-status` is missing then its a streaming response and there is no status
// _yet_, so its neither success nor error
ParsedGrpcStatus::GrpcStatusHeaderMissing => None,
}
} else {
Some(res.status().as_u16().into())
}
}
+325
View File
@@ -0,0 +1,325 @@
use super::{
DefaultMakeSpan, DefaultOnBodyChunk, DefaultOnEos, DefaultOnFailure, DefaultOnRequest,
DefaultOnResponse, GrpcMakeClassifier, HttpMakeClassifier, MakeSpan, OnBodyChunk, OnEos,
OnFailure, OnRequest, OnResponse, ResponseBody, ResponseFuture, TraceLayer,
};
use crate::classify::{
GrpcErrorsAsFailures, MakeClassifier, ServerErrorsAsFailures, SharedClassifier,
};
use http::{Request, Response};
use http_body::Body;
use std::{
fmt,
task::{Context, Poll},
time::Instant,
};
use tower_service::Service;
/// Middleware that adds high level [tracing] to a [`Service`].
///
/// See the [module docs](crate::trace) for an example.
///
/// [tracing]: https://crates.io/crates/tracing
/// [`Service`]: tower_service::Service
#[derive(Debug, Clone, Copy)]
pub struct Trace<
S,
M,
MakeSpan = DefaultMakeSpan,
OnRequest = DefaultOnRequest,
OnResponse = DefaultOnResponse,
OnBodyChunk = DefaultOnBodyChunk,
OnEos = DefaultOnEos,
OnFailure = DefaultOnFailure,
> {
pub(crate) inner: S,
pub(crate) make_classifier: M,
pub(crate) make_span: MakeSpan,
pub(crate) on_request: OnRequest,
pub(crate) on_response: OnResponse,
pub(crate) on_body_chunk: OnBodyChunk,
pub(crate) on_eos: OnEos,
pub(crate) on_failure: OnFailure,
}
impl<S, M> Trace<S, M> {
/// Create a new [`Trace`] using the given [`MakeClassifier`].
pub fn new(inner: S, make_classifier: M) -> Self
where
M: MakeClassifier,
{
Self {
inner,
make_classifier,
make_span: DefaultMakeSpan::new(),
on_request: DefaultOnRequest::default(),
on_response: DefaultOnResponse::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_eos: DefaultOnEos::default(),
on_failure: DefaultOnFailure::default(),
}
}
/// Returns a new [`Layer`] that wraps services with a [`TraceLayer`] middleware.
///
/// [`Layer`]: tower_layer::Layer
pub fn layer(make_classifier: M) -> TraceLayer<M>
where
M: MakeClassifier,
{
TraceLayer::new(make_classifier)
}
}
impl<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>
Trace<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure>
{
define_inner_service_accessors!();
/// Customize what to do when a request is received.
///
/// `NewOnRequest` is expected to implement [`OnRequest`].
///
/// [`OnRequest`]: super::OnRequest
pub fn on_request<NewOnRequest>(
self,
new_on_request: NewOnRequest,
) -> Trace<S, M, MakeSpan, NewOnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure> {
Trace {
on_request: new_on_request,
inner: self.inner,
on_failure: self.on_failure,
on_eos: self.on_eos,
on_body_chunk: self.on_body_chunk,
make_span: self.make_span,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a response has been produced.
///
/// `NewOnResponse` is expected to implement [`OnResponse`].
///
/// [`OnResponse`]: super::OnResponse
pub fn on_response<NewOnResponse>(
self,
new_on_response: NewOnResponse,
) -> Trace<S, M, MakeSpan, OnRequest, NewOnResponse, OnBodyChunk, OnEos, OnFailure> {
Trace {
on_response: new_on_response,
inner: self.inner,
on_request: self.on_request,
on_failure: self.on_failure,
on_body_chunk: self.on_body_chunk,
on_eos: self.on_eos,
make_span: self.make_span,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a body chunk has been sent.
///
/// `NewOnBodyChunk` is expected to implement [`OnBodyChunk`].
///
/// [`OnBodyChunk`]: super::OnBodyChunk
pub fn on_body_chunk<NewOnBodyChunk>(
self,
new_on_body_chunk: NewOnBodyChunk,
) -> Trace<S, M, MakeSpan, OnRequest, OnResponse, NewOnBodyChunk, OnEos, OnFailure> {
Trace {
on_body_chunk: new_on_body_chunk,
on_eos: self.on_eos,
make_span: self.make_span,
inner: self.inner,
on_failure: self.on_failure,
on_request: self.on_request,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a streaming response has closed.
///
/// `NewOnEos` is expected to implement [`OnEos`].
///
/// [`OnEos`]: super::OnEos
pub fn on_eos<NewOnEos>(
self,
new_on_eos: NewOnEos,
) -> Trace<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, NewOnEos, OnFailure> {
Trace {
on_eos: new_on_eos,
make_span: self.make_span,
inner: self.inner,
on_failure: self.on_failure,
on_request: self.on_request,
on_body_chunk: self.on_body_chunk,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize what to do when a response has been classified as a failure.
///
/// `NewOnFailure` is expected to implement [`OnFailure`].
///
/// [`OnFailure`]: super::OnFailure
pub fn on_failure<NewOnFailure>(
self,
new_on_failure: NewOnFailure,
) -> Trace<S, M, MakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, NewOnFailure> {
Trace {
on_failure: new_on_failure,
inner: self.inner,
make_span: self.make_span,
on_body_chunk: self.on_body_chunk,
on_request: self.on_request,
on_eos: self.on_eos,
on_response: self.on_response,
make_classifier: self.make_classifier,
}
}
/// Customize how to make [`Span`]s that all request handling will be wrapped in.
///
/// `NewMakeSpan` is expected to implement [`MakeSpan`].
///
/// [`MakeSpan`]: super::MakeSpan
/// [`Span`]: tracing::Span
pub fn make_span_with<NewMakeSpan>(
self,
new_make_span: NewMakeSpan,
) -> Trace<S, M, NewMakeSpan, OnRequest, OnResponse, OnBodyChunk, OnEos, OnFailure> {
Trace {
make_span: new_make_span,
inner: self.inner,
on_failure: self.on_failure,
on_request: self.on_request,
on_body_chunk: self.on_body_chunk,
on_response: self.on_response,
on_eos: self.on_eos,
make_classifier: self.make_classifier,
}
}
}
impl<S>
Trace<
S,
HttpMakeClassifier,
DefaultMakeSpan,
DefaultOnRequest,
DefaultOnResponse,
DefaultOnBodyChunk,
DefaultOnEos,
DefaultOnFailure,
>
{
/// Create a new [`Trace`] using [`ServerErrorsAsFailures`] which supports classifying
/// regular HTTP responses based on the status code.
pub fn new_for_http(inner: S) -> Self {
Self {
inner,
make_classifier: SharedClassifier::new(ServerErrorsAsFailures::default()),
make_span: DefaultMakeSpan::new(),
on_request: DefaultOnRequest::default(),
on_response: DefaultOnResponse::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_eos: DefaultOnEos::default(),
on_failure: DefaultOnFailure::default(),
}
}
}
impl<S>
Trace<
S,
GrpcMakeClassifier,
DefaultMakeSpan,
DefaultOnRequest,
DefaultOnResponse,
DefaultOnBodyChunk,
DefaultOnEos,
DefaultOnFailure,
>
{
/// Create a new [`Trace`] using [`GrpcErrorsAsFailures`] which supports classifying
/// gRPC responses and streams based on the `grpc-status` header.
pub fn new_for_grpc(inner: S) -> Self {
Self {
inner,
make_classifier: SharedClassifier::new(GrpcErrorsAsFailures::default()),
make_span: DefaultMakeSpan::new(),
on_request: DefaultOnRequest::default(),
on_response: DefaultOnResponse::default(),
on_body_chunk: DefaultOnBodyChunk::default(),
on_eos: DefaultOnEos::default(),
on_failure: DefaultOnFailure::default(),
}
}
}
impl<
S,
ReqBody,
ResBody,
M,
OnRequestT,
OnResponseT,
OnFailureT,
OnBodyChunkT,
OnEosT,
MakeSpanT,
> Service<Request<ReqBody>>
for Trace<S, M, MakeSpanT, OnRequestT, OnResponseT, OnBodyChunkT, OnEosT, OnFailureT>
where
S: Service<Request<ReqBody>, Response = Response<ResBody>>,
ReqBody: Body,
ResBody: Body,
ResBody::Error: fmt::Display + 'static,
S::Error: fmt::Display + 'static,
M: MakeClassifier,
M::Classifier: Clone,
MakeSpanT: MakeSpan<ReqBody>,
OnRequestT: OnRequest<ReqBody>,
OnResponseT: OnResponse<ResBody> + Clone,
OnBodyChunkT: OnBodyChunk<ResBody::Data> + Clone,
OnEosT: OnEos + Clone,
OnFailureT: OnFailure<M::FailureClass> + Clone,
{
type Response =
Response<ResponseBody<ResBody, M::ClassifyEos, OnBodyChunkT, OnEosT, OnFailureT>>;
type Error = S::Error;
type Future =
ResponseFuture<S::Future, M::Classifier, OnResponseT, OnBodyChunkT, OnEosT, OnFailureT>;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.inner.poll_ready(cx)
}
fn call(&mut self, req: Request<ReqBody>) -> Self::Future {
let start = Instant::now();
let span = self.make_span.make_span(&req);
let classifier = self.make_classifier.make_classifier(&req);
let future = {
let _guard = span.enter();
self.on_request.on_request(&req, &span);
self.inner.call(req)
};
ResponseFuture {
inner: future,
span,
classifier: Some(classifier),
on_response: Some(self.on_response.clone()),
on_body_chunk: Some(self.on_body_chunk.clone()),
on_eos: Some(self.on_eos.clone()),
on_failure: Some(self.on_failure.clone()),
start,
}
}
}