Add TraceContext

This commit is contained in:
photino 2023-01-17 13:57:38 +08:00
parent dc94262fc5
commit b844f35d30
17 changed files with 178 additions and 33 deletions

View File

@ -3,6 +3,7 @@ use zino::{Request, RequestContext, Response};
pub(crate) async fn index(req: Request) -> zino::Result {
let mut res = Response::default();
res.set_context(&req);
res.set_data(json!({
"method": "GET",
"path": "/stats",

View File

@ -22,7 +22,8 @@ pub(crate) async fn new(mut req: Request) -> zino::Result {
pub(crate) async fn update(mut req: Request) -> zino::Result {
let mut user = User::new();
let validation = req.parse_body().await.map(|body| user.read_map(body))?;
let res = Response::from(validation);
let mut res = Response::from(validation);
res.set_context(&req);
Ok(res.into())
}

View File

@ -41,4 +41,4 @@ tracing = { version = "0.1.37" }
tracing-appender = { version = "0.2.2" }
tracing-subscriber = { version = "0.3.16", features = ["env-filter", "json", "local-time"] }
url = { version = "2.3.1" }
uuid = { version = "1.2.2", features = ["serde", "v4"] }
uuid = { version = "1.2.2", features = ["fast-rng", "serde", "v4", "v7"] }

View File

@ -23,6 +23,7 @@ pub mod request;
pub mod response;
pub mod schedule;
pub mod state;
pub mod trace;
/// A JSON key/value type.
pub type Map = serde_json::Map<String, serde_json::Value>;

View File

@ -6,10 +6,10 @@ use crate::{
database::{Model, Query},
datetime::DateTime,
response::{Rejection, Response, ResponseCode},
trace::TraceContext,
Map, Uuid,
};
use http::uri::Uri;
use http_types::{trace::TraceContext, Trailers};
use hyper::body::Bytes;
use serde::de::DeserializeOwned;
use serde_json::Value;
@ -81,10 +81,7 @@ pub trait RequestContext {
#[inline]
fn trace_context(&self) -> Option<TraceContext> {
let traceparent = self.get_header("traceparent")?;
let mut trailers = Trailers::new();
trailers.insert("traceparent", traceparent);
TraceContext::from_headers(&*trailers).unwrap_or(None)
TraceContext::from_traceparent(traceparent)
}
/// Returns the start time.
@ -342,10 +339,10 @@ pub trait RequestContext {
res.set_context(self);
Ok(res)
} else {
Err(Rejection::BadRequest(validation))
Err(validation.into())
}
}
Err(validation) => Err(Rejection::BadRequest(validation)),
Err(validation) => Err(validation.into()),
}
}
@ -366,10 +363,10 @@ pub trait RequestContext {
res.set_context(self);
Ok(res)
} else {
Err(Rejection::BadRequest(validation))
Err(validation.into())
}
}
Err(validation) => Err(Rejection::BadRequest(validation)),
Err(validation) => Err(validation.into()),
}
}

View File

@ -181,6 +181,7 @@ impl fmt::Display for Validation {
}
impl From<Validation> for http::Response<Full<Bytes>> {
#[inline]
fn from(validation: Validation) -> Self {
Response::from(validation).into()
}

View File

@ -2,12 +2,13 @@
use crate::{
request::{RequestContext, Validation},
trace::TraceContext,
SharedString, Uuid,
};
use bytes::Bytes;
use http::header::{self, HeaderValue};
use http_body::Full;
use http_types::trace::{Metric, ServerTiming, TraceContext};
use http_types::trace::{Metric, ServerTiming};
use serde::Serialize;
use serde_json::Value;
use std::{
@ -347,10 +348,10 @@ impl From<Response<http::StatusCode>> for http::Response<Full<Bytes>> {
},
};
let trace_context = match response.trace_context {
Some(ref trace_context) => trace_context.value(),
None => TraceContext::new().value(),
Some(ref trace_context) => trace_context.to_string(),
None => TraceContext::new().to_string(),
};
if let Ok(header_value) = HeaderValue::try_from(trace_context.as_str()) {
if let Ok(header_value) = HeaderValue::try_from(trace_context) {
res.headers_mut().insert("traceparent", header_value);
}

View File

@ -1,7 +1,7 @@
use crate::{request::Validation, response::Response, BoxError};
use bytes::Bytes;
use http_body::Full;
use std::{error, fmt};
use std::{error::Error, fmt};
use Rejection::*;
/// A rejection response type.
@ -33,42 +33,43 @@ impl Rejection {
/// Creates an `Unauthorized` rejection.
#[inline]
pub fn unauthorized(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn unauthorized(err: impl Error + Send + Sync + 'static) -> Self {
Unauthorized(Box::new(err))
}
/// Creates a `Forbidden` rejection.
#[inline]
pub fn forbidden(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn forbidden(err: impl Error + Send + Sync + 'static) -> Self {
Forbidden(Box::new(err))
}
/// Creates a `NotFound` rejection.
#[inline]
pub fn not_found(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn not_found(err: impl Error + Send + Sync + 'static) -> Self {
NotFound(Box::new(err))
}
/// Creates a `MethodNotAllowed` rejection.
#[inline]
pub fn method_not_allowed(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn method_not_allowed(err: impl Error + Send + Sync + 'static) -> Self {
MethodNotAllowed(Box::new(err))
}
/// Creates a `Conflict` rejection.
#[inline]
pub fn conflict(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn conflict(err: impl Error + Send + Sync + 'static) -> Self {
Conflict(Box::new(err))
}
/// Creates an `InternalServerError` rejection.
#[inline]
pub fn internal_server_error(err: impl std::error::Error + Send + Sync + 'static) -> Self {
pub fn internal_server_error(err: impl Error + Send + Sync + 'static) -> Self {
InternalServerError(Box::new(err))
}
}
impl From<Validation> for Rejection {
#[inline]
fn from(validation: Validation) -> Self {
BadRequest(validation)
}
@ -76,6 +77,7 @@ impl From<Validation> for Rejection {
impl From<sqlx::Error> for Rejection {
/// Converts to this type from the input type `sqlx::Error`.
#[inline]
fn from(err: sqlx::Error) -> Self {
InternalServerError(Box::new(err))
}
@ -95,7 +97,7 @@ impl fmt::Display for Rejection {
}
}
impl error::Error for Rejection {}
impl Error for Rejection {}
impl From<Rejection> for Response<http::StatusCode> {
fn from(rejection: Rejection) -> Self {
@ -184,6 +186,7 @@ impl<'a> From<&'a Rejection> for Response<http::StatusCode> {
}
impl From<Rejection> for http::Response<Full<Bytes>> {
#[inline]
fn from(rejection: Rejection) -> Self {
Response::from(rejection).into()
}

View File

@ -0,0 +1,5 @@
//! HTTP timings and traces.
mod trace_context;
pub use trace_context::TraceContext;

View File

@ -0,0 +1,143 @@
use std::fmt;
use tracing::Span;
/// The `sampled` flag.
const FLAG_SAMPLED: u8 = 1;
///The `random-trace-id` flag.
const FLAG_RANDOM_TRACE_ID: u8 = 2;
/// HTTP headers for distributed tracing.
/// See the [spec](https://w3c.github.io/trace-context).
#[derive(Debug)]
pub struct TraceContext {
/// Span identifier.
span_id: u64,
/// Version of the traceparent header.
version: u8,
/// Globally unique identifier.
/// All bytes as zero is considered an invalid value.
trace_id: u128,
/// Identifier of the request known by the caller.
parent_id: Option<u64>,
/// Trace flags.
trace_flags: u8,
}
impl TraceContext {
/// Creates a new instance without parent.
pub fn new() -> Self {
let span_id = Span::current()
.id()
.map(|t| t.into_u64())
.unwrap_or_else(rand::random);
Self {
span_id,
version: 0,
trace_id: rand::random(),
parent_id: None,
trace_flags: FLAG_SAMPLED | FLAG_RANDOM_TRACE_ID,
}
}
/// Creates a child of the current TraceContext.
pub fn child(&self) -> Self {
let span_id = Span::current()
.id()
.map(|t| t.into_u64())
.unwrap_or_else(rand::random);
Self {
span_id,
version: self.version,
trace_id: self.trace_id,
parent_id: Some(self.span_id),
trace_flags: self.trace_flags,
}
}
/// Constructs an instance of TraceContext from the `traceparent` header value.
pub fn from_traceparent(traceparent: &str) -> Option<Self> {
let span_id = Span::current()
.id()
.map(|t| t.into_u64())
.unwrap_or_else(rand::random);
let parts = traceparent.split('-').collect::<Vec<_>>();
(parts.len() == 4).then_some(Self {
span_id,
version: u8::from_str_radix(parts[0], 16).ok()?,
trace_id: u128::from_str_radix(parts[1], 16).ok()?,
parent_id: Some(u64::from_str_radix(parts[2], 16).ok()?),
trace_flags: u8::from_str_radix(parts[3], 16).ok()?,
})
}
/// Returns the `span-id` of the TraceContext.
#[inline]
pub fn span_id(&self) -> u64 {
self.span_id
}
/// Returns the `version` of the TraceContext spec used.
#[inline]
pub fn version(&self) -> u8 {
self.version
}
/// Returns the `trace-id` of the TraceContext.
#[inline]
pub fn trace_id(&self) -> u128 {
self.trace_id
}
/// Returns the `parent-id` of the parent TraceContext.
#[inline]
pub fn parent_id(&self) -> Option<u64> {
self.parent_id
}
/// Returns the `trace-flags` of the parent TraceContext.
#[inline]
pub fn trace_flags(&self) -> u8 {
self.trace_flags
}
/// Returns true if the `sampled` flag has been enabled.
#[inline]
pub fn sampled(&self) -> bool {
(self.trace_flags & FLAG_SAMPLED) == FLAG_SAMPLED
}
/// Returns true if the `random-trace-id` flag has been enabled.
#[inline]
pub fn random_trace_id(&self) -> bool {
(self.trace_flags & FLAG_RANDOM_TRACE_ID) == FLAG_RANDOM_TRACE_ID
}
/// Sets the `sampled` flag.
#[inline]
pub fn set_sampled(&mut self, sampled: bool) {
self.trace_flags ^= ((sampled as u8) ^ self.trace_flags) & FLAG_SAMPLED;
}
/// Sets the `random-trace-id` flag.
#[inline]
pub fn set_random_trace_id(&mut self, random: bool) {
self.trace_flags ^= ((random as u8) ^ self.trace_flags) & FLAG_RANDOM_TRACE_ID;
}
}
impl Default for TraceContext {
fn default() -> Self {
Self::new()
}
}
impl fmt::Display for TraceContext {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(
f,
"{:02x}-{:032x}-{:016x}-{:02x}",
self.version, self.trace_id, self.span_id, self.trace_flags
)
}
}

View File

@ -21,7 +21,6 @@ axum = ["dep:axum", "dep:tokio", "dep:tokio-stream", "dep:tower", "dep:tower-htt
[dependencies]
async-trait = { version = "0.1.60" }
futures = { version = "0.3.25" }
http-types = { version = "2.12.0" }
hyper = { version = "0.14.23" }
parking_lot = { version = "0.12.1" }
serde = { version = "1.0.152", features = ["derive"] }

View File

@ -2,14 +2,13 @@ use axum::{
body::{Body, BoxBody, Bytes},
http::{HeaderMap, Request, Response},
};
use http_types::{trace::TraceContext, Trailers};
use std::{sync::LazyLock, time::Duration};
use tower_http::{
classify::{SharedClassifier, StatusInRangeAsFailures, StatusInRangeFailureClass},
trace::TraceLayer,
};
use tracing::{field::Empty, Span};
use zino_core::Uuid;
use zino_core::{trace::TraceContext, Uuid};
// Type aliases.
type NewMakeSpan = fn(&Request<Body>) -> Span;
@ -70,13 +69,7 @@ fn new_on_response(response: &Response<BoxBody>, latency: Duration, span: &Span)
let trace_id = headers
.get("traceparent")
.and_then(|v| v.to_str().ok())
.and_then(|traceparent| {
let mut trailers = Trailers::new();
trailers.insert("traceparent", traceparent);
TraceContext::from_headers(&*trailers).ok().flatten()
})
.and_then(|v| v.to_str().ok().and_then(TraceContext::from_traceparent))
.map(|trace_context| Uuid::from_u128(trace_context.trace_id()).to_string());
span.record("trace_id", trace_id);
tracing::info!(