use std::{collections::BTreeMap, fmt as std_fmt};
use serde::{Deserialize, Deserializer, Serialize};
use super::{
error::ObservabilityError,
schema::{event_names, metric_outcomes, trace_fields},
};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize)]
#[non_exhaustive]
pub struct TraceFieldName(String);
impl TraceFieldName {
pub fn new(value: impl Into<String>) -> Result<Self, ObservabilityError> {
let value = value.into().trim().to_owned();
validate_trace_field_name(&value)?;
Ok(Self(value))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self) -> String {
self.0
}
}
impl std_fmt::Display for TraceFieldName {
fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
formatter.write_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for TraceFieldName {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
Self::new(String::deserialize(deserializer)?).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Default, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct TraceFields(Vec<(TraceFieldName, String)>);
impl std_fmt::Debug for TraceFields {
fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
formatter
.debug_struct("TraceFields")
.field("field_count", &self.0.len())
.finish_non_exhaustive()
}
}
impl TraceFields {
pub fn new(
fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Result<Self, ObservabilityError> {
let mut normalized = BTreeMap::<TraceFieldName, String>::new();
for (key, value) in fields {
let value = value.into();
let key = TraceFieldName::new(key)?;
if !value.trim().is_empty() {
normalized.insert(key, value);
}
}
Ok(Self(normalized.into_iter().collect()))
}
#[must_use]
pub fn from_lossy(
fields: impl IntoIterator<Item = (impl Into<String>, impl Into<String>)>,
) -> Self {
let mut normalized = BTreeMap::<TraceFieldName, String>::new();
for (key, value) in fields {
let value = value.into();
if !value.trim().is_empty()
&& let Ok(key) = TraceFieldName::new(key)
{
normalized.insert(key, value);
}
}
Self(normalized.into_iter().collect())
}
pub fn single(
key: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, ObservabilityError> {
Self::new([(key, value)])
}
#[must_use]
pub fn with(mut self, key: &'static str, value: impl Into<String>) -> Self {
if let Ok(key) = TraceFieldName::new(key) {
self.insert(key, value.into());
}
self
}
pub fn try_with(
mut self,
key: impl Into<String>,
value: impl Into<String>,
) -> Result<Self, ObservabilityError> {
let key = TraceFieldName::new(key)?;
self.insert(key, value.into());
Ok(self)
}
#[must_use]
pub fn request_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::REQUEST_ID, value)
}
#[must_use]
pub fn trace_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::TRACE_ID, value)
}
#[must_use]
pub fn actor_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::ACTOR_ID, value)
}
#[must_use]
pub fn user_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::USER_ID, value)
}
#[must_use]
pub fn client_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::CLIENT_ID, value)
}
#[must_use]
pub fn source_ip(self, value: impl Into<String>) -> Self {
self.with(trace_fields::SOURCE_IP, value)
}
#[must_use]
pub fn operation(self, value: impl Into<String>) -> Self {
self.with(trace_fields::OPERATION, value)
}
#[must_use]
pub fn outcome(self, value: impl Into<String>) -> Self {
self.with(trace_fields::OUTCOME, value)
}
#[must_use]
pub fn reason_code(self, value: impl Into<String>) -> Self {
self.with(trace_fields::REASON_CODE, value)
}
#[must_use]
pub fn subject_id(self, value: impl Into<String>) -> Self {
self.with(trace_fields::SUBJECT_ID, value)
}
#[must_use]
pub fn subject_kind(self, value: impl Into<String>) -> Self {
self.with(trace_fields::SUBJECT_KIND, value)
}
#[must_use]
pub fn method(self, value: impl Into<String>) -> Self {
self.with(trace_fields::METHOD, value)
}
#[must_use]
pub fn route(self, value: impl Into<String>) -> Self {
self.with(trace_fields::ROUTE, value)
}
#[must_use]
pub fn path(self, value: impl Into<String>) -> Self {
self.with(trace_fields::PATH, value)
}
#[must_use]
pub fn error_kind(self, value: impl Into<String>) -> Self {
self.with(trace_fields::ERROR_KIND, value)
}
#[must_use]
pub fn error_code(self, value: impl Into<String>) -> Self {
self.with(trace_fields::ERROR_CODE, value)
}
#[must_use]
pub fn worker(self, value: impl Into<String>) -> Self {
self.with(trace_fields::WORKER, value)
}
#[must_use]
pub fn job(self, value: impl Into<String>) -> Self {
self.with(trace_fields::JOB, value)
}
#[must_use]
pub fn latency_ms(self, value: impl Into<String>) -> Self {
self.with(trace_fields::LATENCY_MS, value)
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&str> {
self.0
.iter()
.find(|(name, _)| name.as_str() == key)
.map(|(_, value)| value.as_str())
}
#[must_use]
pub fn as_slice(&self) -> &[(TraceFieldName, String)] {
&self.0
}
#[must_use]
pub fn to_btree_map(&self) -> BTreeMap<String, String> {
self.0
.iter()
.map(|(name, value)| (name.as_str().to_owned(), value.clone()))
.collect()
}
#[must_use]
pub fn into_vec(self) -> Vec<(String, String)> {
self.0
.into_iter()
.map(|(name, value)| (name.into_string(), value))
.collect()
}
fn insert(&mut self, key: TraceFieldName, value: String) {
if value.trim().is_empty() {
return;
}
match self.0.binary_search_by(|(name, _)| name.cmp(&key)) {
Ok(index) => self.0[index].1 = value,
Err(index) => self.0.insert(index, (key, value)),
}
}
fn from_valid_fields(fields: impl IntoIterator<Item = (TraceFieldName, String)>) -> Self {
let mut normalized = BTreeMap::<TraceFieldName, String>::new();
for (key, value) in fields {
if !value.trim().is_empty() {
normalized.insert(key, value);
}
}
Self(normalized.into_iter().collect())
}
}
impl<'de> Deserialize<'de> for TraceFields {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let fields = Vec::<(TraceFieldName, String)>::deserialize(deserializer)?;
Ok(Self::from_valid_fields(fields))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventKind {
Http,
Worker,
Audit,
Security,
Domain,
}
impl EventKind {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Http => "http",
Self::Worker => "worker",
Self::Audit => "audit",
Self::Security => "security",
Self::Domain => "domain",
}
}
}
impl std_fmt::Display for EventKind {
fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum EventOutcome {
Success,
Failure,
Denied,
Skipped,
Retry,
}
impl EventOutcome {
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Success => metric_outcomes::SUCCESS,
Self::Failure => metric_outcomes::FAILURE,
Self::Denied => metric_outcomes::DENIED,
Self::Skipped => "skipped",
Self::Retry => "retry",
}
}
}
impl std_fmt::Display for EventOutcome {
fn fmt(&self, formatter: &mut std_fmt::Formatter<'_>) -> std_fmt::Result {
formatter.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct StructuredEvent {
name: String,
kind: EventKind,
fields: TraceFields,
}
impl<'de> Deserialize<'de> for StructuredEvent {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
#[derive(Deserialize)]
struct StructuredEventWire {
name: String,
kind: EventKind,
#[serde(default)]
fields: TraceFields,
}
let wire = StructuredEventWire::deserialize(deserializer)?;
Ok(Self::new(wire.name, wire.kind)
.map_err(serde::de::Error::custom)?
.with_fields(wire.fields))
}
}
impl StructuredEvent {
pub fn new(name: impl Into<String>, kind: EventKind) -> Result<Self, ObservabilityError> {
let name = name.into().trim().to_owned();
validate_event_name(&name)?;
Ok(Self::from_valid_parts(name, kind))
}
fn from_valid_parts(name: String, kind: EventKind) -> Self {
Self {
name,
kind,
fields: TraceFields::default(),
}
}
#[must_use]
pub fn http_request() -> Self {
Self::from_valid_parts(event_names::HTTP_REQUEST.to_owned(), EventKind::Http)
}
#[must_use]
pub fn worker_tick(worker: impl Into<String>) -> Self {
Self::from_valid_parts(event_names::WORKER_TICK.to_owned(), EventKind::Worker)
.with_fields(TraceFields::default().worker(worker))
}
#[must_use]
pub fn security_decision() -> Self {
Self::from_valid_parts(
event_names::SECURITY_DECISION.to_owned(),
EventKind::Security,
)
}
#[must_use]
pub fn audit_event() -> Self {
Self::from_valid_parts(event_names::AUDIT_EVENT.to_owned(), EventKind::Audit)
}
#[must_use]
pub fn with_fields(mut self, fields: TraceFields) -> Self {
self.fields = fields;
self
}
#[must_use]
pub fn merge_fields(mut self, fields: TraceFields) -> Self {
for (key, value) in fields.0 {
self.fields.insert(key, value);
}
self
}
#[must_use]
pub fn outcome(mut self, outcome: EventOutcome) -> Self {
self.fields = self.fields.outcome(outcome.as_str());
self
}
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
#[must_use]
pub const fn kind(&self) -> EventKind {
self.kind
}
#[must_use]
pub const fn fields(&self) -> &TraceFields {
&self.fields
}
#[must_use]
pub fn trace_fields(&self) -> TraceFields {
self.fields
.clone()
.with(trace_fields::EVENT_NAME, self.name.clone())
.with(trace_fields::EVENT_KIND, self.kind.as_str())
}
#[must_use]
pub fn into_trace_fields(self) -> TraceFields {
self.fields
.with(trace_fields::EVENT_NAME, self.name)
.with(trace_fields::EVENT_KIND, self.kind.as_str())
}
#[must_use]
pub fn to_btree_map(&self) -> BTreeMap<String, String> {
self.trace_fields().to_btree_map()
}
}
fn validate_trace_field_name(value: &str) -> Result<(), ObservabilityError> {
if value.is_empty()
|| !value
.bytes()
.all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
{
return Err(ObservabilityError::InvalidTraceFieldName);
}
Ok(())
}
fn validate_event_name(value: &str) -> Result<(), ObservabilityError> {
if value.is_empty()
|| !value.bytes().all(|byte| {
byte.is_ascii_lowercase()
|| byte.is_ascii_digit()
|| matches!(byte, b'-' | b'_' | b'.' | b':')
})
{
return Err(ObservabilityError::InvalidEventName);
}
Ok(())
}