use std::fmt;
use serde::{Deserialize, Deserializer, Serialize};
use thiserror::Error;
use uuid::Uuid;
use crate::result::{ClassifyError, ErrorKind};
pub const REQUEST_ID_HEADER_NAME: &str = "x-request-id";
pub const TRACEPARENT_HEADER_NAME: &str = "traceparent";
pub const MAX_REQUEST_ID_LENGTH: usize = 128;
pub const TRACEPARENT_LENGTH: usize = 55;
pub const MAX_TRACEPARENT_LENGTH: usize = 4096;
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct RequestId(String);
impl RequestId {
pub fn new(value: impl Into<String>) -> Result<Self, RequestIdError> {
let value = value.into();
validate_request_id(&value)?;
Ok(Self(value))
}
#[must_use]
pub fn generate() -> Self {
Self(format!("req_{}", Uuid::now_v7().simple()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Self::new(value).ok()
}
}
impl TryFrom<&str> for RequestId {
type Error = RequestIdError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<String> for RequestId {
type Error = RequestIdError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl Default for RequestId {
fn default() -> Self {
Self::generate()
}
}
impl fmt::Display for RequestId {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for RequestId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum RequestIdError {
#[error("request id must not be empty")]
Empty,
#[error("request id must be less than or equal to {max} bytes")]
TooLong {
#[doc = "The configured upper bound."]
max: usize,
},
#[error("request id contains unsupported characters")]
InvalidCharacters,
}
impl ClassifyError for RequestIdError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::Empty => "request_id_empty",
Self::TooLong { .. } => "request_id_too_long",
Self::InvalidCharacters => "request_id_invalid_characters",
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize)]
pub struct TraceParent(String);
impl TraceParent {
pub fn new(value: impl Into<String>) -> Result<Self, TraceParentError> {
let value = value.into().trim().to_owned();
validate_traceparent(&value)?;
Ok(Self(value))
}
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
Self::new(value).ok()
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
#[must_use]
pub fn version(&self) -> &str {
&self.0[..2]
}
#[must_use]
pub fn trace_id(&self) -> &str {
&self.0[3..35]
}
#[must_use]
pub fn span_id(&self) -> &str {
&self.0[36..52]
}
#[must_use]
pub fn trace_flags(&self) -> &str {
&self.0[53..55]
}
#[must_use]
pub fn sampled(&self) -> bool {
parse_hex_byte(self.trace_flags().as_bytes()).is_some_and(|flags| flags & 1 == 1)
}
}
impl TryFrom<&str> for TraceParent {
type Error = TraceParentError;
fn try_from(value: &str) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl TryFrom<String> for TraceParent {
type Error = TraceParentError;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::new(value)
}
}
impl fmt::Display for TraceParent {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for TraceParent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let value = String::deserialize(deserializer)?;
Self::new(value).map_err(serde::de::Error::custom)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[non_exhaustive]
pub enum TraceParentError {
#[error("traceparent header shape is invalid")]
InvalidFormat,
#[error("traceparent version is invalid")]
InvalidVersion,
#[error("traceparent trace id is invalid")]
InvalidTraceId,
#[error("traceparent span id is invalid")]
InvalidSpanId,
#[error("traceparent flags are invalid")]
InvalidFlags,
}
impl ClassifyError for TraceParentError {
fn error_kind(&self) -> ErrorKind {
ErrorKind::Validation
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::InvalidFormat => "traceparent_invalid_format",
Self::InvalidVersion => "traceparent_invalid_version",
Self::InvalidTraceId => "traceparent_invalid_trace_id",
Self::InvalidSpanId => "traceparent_invalid_span_id",
Self::InvalidFlags => "traceparent_invalid_flags",
})
}
}
#[must_use]
pub fn is_valid_request_id(value: &str) -> bool {
validate_request_id(value).is_ok()
}
fn validate_request_id(value: &str) -> Result<(), RequestIdError> {
if value.is_empty() {
return Err(RequestIdError::Empty);
}
if value.len() > MAX_REQUEST_ID_LENGTH {
return Err(RequestIdError::TooLong {
max: MAX_REQUEST_ID_LENGTH,
});
}
if !value
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
{
return Err(RequestIdError::InvalidCharacters);
}
Ok(())
}
#[must_use]
pub fn is_valid_traceparent(value: &str) -> bool {
validate_traceparent(value).is_ok()
}
fn validate_traceparent(value: &str) -> Result<(), TraceParentError> {
let bytes = value.as_bytes();
if !(TRACEPARENT_LENGTH..=MAX_TRACEPARENT_LENGTH).contains(&bytes.len())
|| bytes.get(2) != Some(&b'-')
|| bytes.get(35) != Some(&b'-')
|| bytes.get(52) != Some(&b'-')
{
return Err(TraceParentError::InvalidFormat);
}
let version = &bytes[..2];
let trace_id = &bytes[3..35];
let span_id = &bytes[36..52];
let flags = &bytes[53..55];
if !is_lower_hex(version) || version == b"ff" {
return Err(TraceParentError::InvalidVersion);
}
if bytes.len() > TRACEPARENT_LENGTH && (version == b"00" || bytes[TRACEPARENT_LENGTH] != b'-') {
return Err(TraceParentError::InvalidFormat);
}
if !is_lower_hex(trace_id) || trace_id.iter().all(|byte| *byte == b'0') {
return Err(TraceParentError::InvalidTraceId);
}
if !is_lower_hex(span_id) || span_id.iter().all(|byte| *byte == b'0') {
return Err(TraceParentError::InvalidSpanId);
}
if !is_lower_hex(flags) {
return Err(TraceParentError::InvalidFlags);
}
Ok(())
}
fn is_lower_hex(bytes: &[u8]) -> bool {
bytes
.iter()
.all(|byte| byte.is_ascii_digit() || matches!(byte, b'a'..=b'f'))
}
fn parse_hex_byte(bytes: &[u8]) -> Option<u8> {
if bytes.len() != 2 || !is_lower_hex(bytes) {
return None;
}
let high = *bytes.first()?;
let low = *bytes.get(1)?;
Some(hex_value(high)? << 4 | hex_value(low)?)
}
fn hex_value(byte: u8) -> Option<u8> {
match byte {
b'0'..=b'9' => Some(byte - b'0'),
b'a'..=b'f' => Some(byte - b'a' + 10),
_ => None,
}
}