use serde_json::json;
use super::{
EventKind, EventOutcome, HealthCheck, HealthReport, HealthState, LogTimeZone,
MAX_HEALTH_MESSAGE_LENGTH, MAX_METRIC_LABEL_KEY_LENGTH, MAX_METRIC_LABEL_VALUE_LENGTH,
MAX_METRIC_LABELS, MAX_METRIC_NAME_LENGTH, MetricKind, MetricLabels, MetricRegistry,
MetricRegistryLimits, MetricSample, MetricsError, MetricsSnapshot, ObservabilityError,
StructuredEvent, TraceContext, TraceFieldName, TraceFields, TracingConfig, encode_openmetrics,
env_filter_from, event_names, metric_outcomes, trace_fields,
};
use crate::result::{ClassifyError, ErrorKind};
#[test]
fn invalid_metric_names_and_labels_cannot_silently_merge_series() {
let registry = MetricRegistry::new();
registry
.increment_counter("jobs_a", 2, MetricLabels::default())
.unwrap();
for name in [
"jobs-a", "jobs.a", " jobs_a", "jobs_a ", "1jobs", "_jobs", "任务",
] {
assert_eq!(
registry.increment_counter(name, 1, MetricLabels::default()),
Err(MetricsError::InvalidName)
);
assert!(
serde_json::from_value::<MetricSample>(json!({
"name": name, "kind": "counter", "value": 1.0,
}))
.is_err()
);
}
assert_eq!(registry.snapshot().unwrap().samples()[0].value(), 2.0);
for key in ["user-id", "user.id", " user_id", "1user"] {
assert_eq!(
MetricLabels::new([(key, "first"), ("user_id", "second")]),
Err(MetricsError::InvalidLabelKey)
);
}
assert_eq!(
MetricLabels::new([("user_id", "first"), ("user_id", "second")]),
Err(MetricsError::DuplicateLabelKey)
);
assert!(serde_json::from_value::<MetricLabels>(json!([["zone", "a"], ["zone", "b"]])).is_err());
}
#[test]
fn metric_snapshots_reject_duplicate_and_conflicting_families_in_both_orders() {
let jobs = MetricSample::counter("jobs", 1).unwrap();
for (other, error) in [
(jobs.clone(), MetricsError::DuplicateSeries),
(
MetricSample::counter("jobs_total", 2).unwrap(),
MetricsError::MetricNameConflict,
),
(
MetricSample::gauge("jobs", 2.0).unwrap(),
MetricsError::MetricTypeConflict,
),
(
MetricSample::gauge("jobs_total", 2.0).unwrap(),
MetricsError::MetricNameConflict,
),
] {
for samples in [
vec![jobs.clone(), other.clone()],
vec![other.clone(), jobs.clone()],
] {
let wire = json!({"samples": samples});
assert_eq!(MetricsSnapshot::new(samples), Err(error));
assert!(serde_json::from_value::<MetricsSnapshot>(wire).is_err());
}
}
let histogram = MetricSample::histogram("latency", 1, 0.5, vec![(1.0, 1)]).unwrap();
for suffix in ["sum", "count", "bucket", "created"] {
let gauge = MetricSample::gauge(format!("latency_{suffix}"), 1.0).unwrap();
assert_eq!(
MetricsSnapshot::new(vec![histogram.clone(), gauge]),
Err(MetricsError::MetricNameConflict)
);
}
let labeled = jobs.clone().with_label("queue", "ready").unwrap();
assert!(MetricsSnapshot::new(vec![jobs, labeled]).is_ok());
}
#[test]
fn histogram_buckets_are_cumulative_and_preserved_in_snapshots_and_export() {
let registry = MetricRegistry::new()
.with_histogram_buckets("latency", vec![0.1, 0.5, 1.0])
.unwrap();
for value in [0.0, 0.1, 0.25, 0.5, 2.0] {
registry
.observe_histogram(
"latency",
value,
MetricLabels::single("route", "/jobs").unwrap(),
)
.unwrap();
}
let snapshot = registry.snapshot().unwrap();
let sample = &snapshot.samples()[0];
assert_eq!(sample.count(), Some(5));
assert_eq!(sample.value(), 2.85);
assert_eq!(sample.buckets(), &[(0.1, 2), (0.5, 4), (1.0, 4)]);
assert_eq!(
serde_json::from_value::<MetricsSnapshot>(serde_json::to_value(&snapshot).unwrap())
.unwrap(),
snapshot
);
let output = encode_openmetrics(&snapshot);
for (bound, count) in [("0.1", 2), ("0.5", 4), ("1", 4), ("+Inf", 5)] {
assert!(output.contains(&format!(
"latency_bucket{{route=\"/jobs\",le=\"{bound}\"}} {count}\n"
)));
}
assert!(matches!(
registry.with_histogram_buckets("latency", vec![1.0]),
Err(MetricsError::HistogramAlreadyObserved)
));
}
#[test]
fn histograms_reject_invalid_bounds_counts_and_non_histogram_metadata() {
for bounds in [
vec![],
vec![1.0, 1.0],
vec![2.0, 1.0],
vec![f64::NAN],
vec![f64::INFINITY],
vec![-1.0],
(0..=super::MAX_HISTOGRAM_BUCKETS)
.map(|i| i as f64)
.collect(),
] {
assert!(matches!(
MetricRegistry::new().with_histogram_buckets("latency", bounds),
Err(MetricsError::InvalidHistogramBuckets)
));
}
for buckets in [vec![(1.0, 3)], vec![(1.0, 2), (2.0, 1)]] {
assert!(matches!(
MetricSample::histogram("latency", 2, 1.0, buckets),
Err(MetricsError::InvalidHistogram)
));
}
for wire in [
json!({"name":"latency", "kind":"histogram", "value":1.0, "count":0, "buckets":[[1.0,0]]}),
json!({"name":"latency", "kind":"histogram", "value":1.0, "count":2, "buckets":[[1.0,2],[2.0,1]]}),
json!({"name":"latency", "kind":"histogram", "value":1.0, "buckets":[[1.0,1]]}),
json!({"name":"jobs", "kind":"counter", "value":1.0, "count":1}),
json!({"name":"jobs", "kind":"gauge", "value":1.0, "buckets":[[1.0,1]]}),
] {
assert!(serde_json::from_value::<MetricSample>(wire).is_err());
}
}
#[test]
fn default_histogram_bounds_are_used_and_rejected_updates_are_atomic() {
let registry = MetricRegistry::new();
registry
.observe_histogram("latency", f64::MAX, MetricLabels::default())
.unwrap();
let before = registry.snapshot().unwrap();
assert_eq!(
before.samples()[0]
.buckets()
.iter()
.map(|(bound, _)| *bound)
.collect::<Vec<_>>(),
super::DEFAULT_HISTOGRAM_BUCKETS
);
assert!(
registry
.observe_histogram("latency", f64::MAX, MetricLabels::default())
.is_err()
);
assert_eq!(registry.snapshot().unwrap(), before);
}
#[test]
fn metric_sample_updates_existing_labels_at_capacity() {
let labels =
MetricLabels::new((0..MAX_METRIC_LABELS).map(|index| (format!("key_{index}"), "old")))
.unwrap();
let sample = MetricSample::counter("jobs_total", 1)
.unwrap()
.with_labels(labels)
.unwrap();
let updated = sample.clone().with_label("key_0", "new").unwrap();
assert_eq!(updated.labels().len(), MAX_METRIC_LABELS);
assert!(updated.labels().contains(&("key_0".into(), "new".into())));
assert!(matches!(
sample.clone().with_label("extra", "new"),
Err(MetricsError::TooManyLabels { .. })
));
assert_eq!(
sample.clone().with_label("key_0", "bad\nvalue"),
Err(MetricsError::InvalidLabelValue)
);
assert_eq!(sample.clone().with_label("extra", "").unwrap(), sample);
let removed = sample.with_label("key_0", "").unwrap();
assert_eq!(removed.labels().len(), MAX_METRIC_LABELS - 1);
assert!(!removed.labels().iter().any(|(name, _)| name == "key_0"));
}
#[test]
fn empty_metric_labels_share_one_series_and_release_the_same_capacity() {
let empty = MetricLabels::single("zone", "").unwrap();
assert_eq!(empty, MetricLabels::default());
let registry = MetricRegistry::with_limits(MetricRegistryLimits::new(1, 1).unwrap());
registry
.increment_counter("jobs", 2, empty.clone())
.unwrap();
registry
.increment_counter("jobs", 3, MetricLabels::default())
.unwrap();
let before = registry.snapshot().unwrap();
assert_eq!(before.samples().len(), 1);
assert_eq!(before.samples()[0].value(), 5.0);
assert_eq!(
encode_openmetrics(&before),
"# TYPE jobs counter\njobs_total 5\n# EOF\n"
);
let sample = MetricSample::counter("jobs", 1).unwrap();
assert_eq!(
registry.replace_families(
["jobs"],
[sample.clone(), sample.with_label("zone", "").unwrap()],
),
Err(MetricsError::DuplicateSeries)
);
assert_eq!(registry.snapshot().unwrap(), before);
assert!(registry.remove_series("jobs", empty).unwrap());
registry
.set_gauge("other", 1.0, MetricLabels::default())
.unwrap();
}
#[test]
fn empty_metric_labels_are_canonical_in_builders_and_deserialization() {
let pairs = [("zone", ""), ("region", "east")];
let expected = MetricLabels::single("region", "east").unwrap();
assert_eq!(MetricLabels::new(pairs).unwrap(), expected);
assert_eq!(MetricLabels::from_lossy(pairs), expected);
assert_eq!(
serde_json::from_value::<MetricLabels>(json!(pairs)).unwrap(),
expected
);
let sample = MetricSample::gauge("load", 1.0)
.unwrap()
.with_label("zone", "old")
.unwrap()
.with_label("zone", "")
.unwrap()
.with_label("region", "east")
.unwrap();
assert_eq!(sample.labels(), expected.as_slice());
let decoded: MetricSample = serde_json::from_value(json!({
"name": "load", "kind": "gauge", "value": 1.0, "labels": pairs
}))
.unwrap();
assert_eq!(decoded, sample);
}
#[test]
fn metric_labels_reject_prometheus_reserved_and_invalid_names() {
for name in ["__name__", "__address__", " __private ", "--private"] {
assert_eq!(
MetricLabels::single(name, "value"),
Err(MetricsError::InvalidLabelKey)
);
assert!(MetricLabels::from_lossy([(name, "value")]).is_empty());
assert!(serde_json::from_value::<MetricLabels>(json!([[name, "value"]])).is_err());
let sample = MetricSample::gauge("load", 1.0).unwrap();
assert_eq!(
sample.with_label(name, "value"),
Err(MetricsError::InvalidLabelKey)
);
}
assert!(MetricLabels::single("_private", "value").is_ok());
}
#[test]
fn metric_snapshots_round_trip_binary_samples() {
for snapshot in [
MetricsSnapshot::default(),
MetricsSnapshot::new(vec![
MetricSample::counter("jobs_total", 2)
.unwrap()
.with_label("queue", "pending")
.unwrap(),
MetricSample::gauge("temperature", -1.0).unwrap(),
MetricSample::histogram("latency", 3, 0.5, vec![(1.0, 3)]).unwrap(),
])
.unwrap(),
] {
let bytes = postcard::to_allocvec(&snapshot).unwrap();
assert_eq!(
postcard::from_bytes::<MetricsSnapshot>(&bytes).unwrap(),
snapshot
);
for sample in snapshot.samples() {
let bytes = postcard::to_allocvec(sample).unwrap();
assert_eq!(
&postcard::from_bytes::<MetricSample>(&bytes).unwrap(),
sample
);
let json = serde_json::to_value(sample).unwrap();
assert_eq!(json.get("count").is_some(), sample.count().is_some());
}
}
}
#[test]
fn counter_names_must_leave_a_nonempty_exported_family() {
let registry = MetricRegistry::new();
registry
.increment_counter("jobs_total", 1, MetricLabels::default())
.unwrap();
let before = registry.snapshot().unwrap();
for name in ["_total", " _total ", ".total"] {
assert_eq!(
MetricSample::counter(name, 1),
Err(MetricsError::InvalidName)
);
assert_eq!(
MetricSample::new(name, MetricKind::Counter, 1.0),
Err(MetricsError::InvalidName)
);
assert_eq!(
registry.increment_counter(name, 1, MetricLabels::default()),
Err(MetricsError::InvalidName)
);
assert!(
serde_json::from_value::<MetricSample>(json!({
"name": name, "kind": "counter", "value": 1.0
}))
.is_err()
);
}
assert_eq!(registry.snapshot().unwrap(), before);
for name in ["jobs_total", "total", "jobs"] {
assert!(MetricSample::counter(name, 1).is_ok());
}
}
#[test]
fn metric_snapshots_round_trip_objects() {
for snapshot in [
MetricsSnapshot::default(),
MetricsSnapshot::new(vec![
MetricSample::counter("jobs_total", 2)
.unwrap()
.with_label("queue", "a")
.unwrap(),
MetricSample::histogram("latency", 2, 0.5, vec![(1.0, 2)]).unwrap(),
])
.unwrap(),
] {
let wire = serde_json::to_value(&snapshot).unwrap();
assert_eq!(
serde_json::from_value::<MetricsSnapshot>(wire.clone()).unwrap(),
snapshot
);
}
}
#[test]
fn histogram_validation_covers_registry_builders_and_serde() {
let registry = MetricRegistry::new();
registry
.observe_histogram("latency", 1.0, MetricLabels::default())
.unwrap();
let before = registry.snapshot().unwrap();
assert_eq!(
registry.observe_histogram("latency", -1.0, MetricLabels::default()),
Err(MetricsError::NegativeValue)
);
let labels = MetricLabels::single("le", "1").unwrap();
assert_eq!(
registry.observe_histogram("latency", 1.0, labels.clone()),
Err(MetricsError::ReservedHistogramLabel)
);
assert_eq!(registry.snapshot().unwrap(), before);
assert!(matches!(
MetricSample::histogram("latency", 1, -1.0, vec![(1.0, 1)]),
Err(MetricsError::NegativeValue)
));
let sample = MetricSample::histogram("latency", 1, 1.0, vec![(1.0, 1)]).unwrap();
assert!(matches!(
sample.clone().with_labels(labels.clone()),
Err(MetricsError::ReservedHistogramLabel)
));
assert!(matches!(
sample.clone().with_label("le", "1"),
Err(MetricsError::ReservedHistogramLabel)
));
for wire in [
json!({"name":"latency", "kind":"histogram", "value":-1.0, "count":1}),
json!({"name":"latency", "kind":"histogram", "value":1.0, "count":1, "labels":[["le","1"]]}),
] {
assert!(serde_json::from_value::<MetricSample>(wire).is_err());
}
registry
.set_gauge(
"temperature",
-1.0,
MetricLabels::single("le", "1").unwrap(),
)
.unwrap();
assert!(MetricSample::gauge("temperature", -1.0).is_ok());
}
#[test]
fn builds_default_filter_from_service_name() {
let filter = env_filter_from(&TracingConfig::new("example_service"), None)
.expect("filter should be valid");
assert_eq!(filter.to_string(), "tower_http=info,info");
}
#[test]
fn rejects_invalid_service_name() {
let result = env_filter_from(&TracingConfig::new("bad service"), None);
assert!(matches!(
result,
Err(ObservabilityError::InvalidServiceName)
));
}
#[test]
fn observability_errors_have_stable_classification() {
let service_name = ObservabilityError::InvalidServiceName.error_descriptor();
let event_name = StructuredEvent::new("Bad Event", EventKind::Domain)
.expect_err("event name should be invalid")
.error_descriptor();
assert_eq!(service_name.kind(), ErrorKind::Validation);
assert_eq!(service_name.code().as_str(), "tracing_service_name_invalid");
assert_eq!(event_name.kind(), ErrorKind::Validation);
assert_eq!(event_name.code().as_str(), "event_name_invalid");
}
#[test]
fn env_filter_overrides_config_filter() {
let filter = env_filter_from(
&TracingConfig::new("example_service").with_env_filter("=bad"),
Some("example_service=debug".to_owned()),
)
.expect("environment filter should override config filter");
assert_eq!(filter.to_string(), "example_service=debug");
}
#[test]
fn tracing_config_defaults_to_utc_timestamps() {
let config = TracingConfig::new("example_service");
assert_eq!(config.time_zone(), LogTimeZone::Utc);
assert_eq!(
config.with_time_zone(LogTimeZone::Local).time_zone(),
LogTimeZone::Local
);
assert_eq!(LogTimeZone::Utc.as_str(), "utc");
assert_eq!(LogTimeZone::Local.as_str(), "local");
}
#[test]
fn rejects_invalid_explicit_filter_without_env_override() {
let result = env_filter_from(
&TracingConfig::new("example_service").with_env_filter("=bad"),
None,
);
let error = result.expect_err("invalid filter should fail");
assert!(matches!(&error, ObservabilityError::InvalidFilter(_)));
assert!(!format!("{error:?}").contains("=bad"));
}
#[test]
fn rejects_invalid_env_filter() {
let result = env_filter_from(
&TracingConfig::new("example_service"),
Some("=bad".to_owned()),
);
assert!(matches!(result, Err(ObservabilityError::InvalidFilter(_))));
}
#[test]
fn health_report_aggregates_checks() {
let report = HealthReport::new(
"example_service",
vec![
HealthCheck::serving("database").expect("health check should be valid"),
HealthCheck::unavailable("mail", "smtp unavailable")
.expect("health check should be valid"),
],
)
.expect("health report should be valid");
assert_eq!(report.state(), HealthState::Unavailable);
assert_eq!(report.checks().len(), 2);
assert!(HealthCheck::serving(" ").is_err());
assert!(HealthReport::serving("bad service").is_err());
assert!(!format!("{report:?}").contains("smtp unavailable"));
let degraded = HealthReport::new(
"example_service",
vec![
HealthCheck::serving("database").expect("health check should be valid"),
HealthCheck::new("cache", HealthState::Degraded).expect("health check should be valid"),
],
)
.expect("health report should be valid");
assert_eq!(degraded.state(), HealthState::Degraded);
assert_eq!(
HealthReport::serving("example_service")
.expect("health report should be valid")
.state(),
HealthState::Serving
);
}
#[test]
fn health_deserialization_uses_same_validation_and_recomputes_state() {
assert!(
serde_json::from_value::<HealthCheck>(json!({
"name": "bad service",
"state": "serving"
}))
.is_err()
);
let report: HealthReport = serde_json::from_value(json!({
"service": "example_service",
"state": "serving",
"checks": [
{ "name": "database", "state": "unavailable", "message": "down" }
]
}))
.expect("valid health report should deserialize");
assert_eq!(report.state(), HealthState::Unavailable);
}
#[test]
fn health_reports_round_trip_every_state_in_json_and_binary_formats() {
for state in [
HealthState::Serving,
HealthState::Degraded,
HealthState::Unavailable,
] {
for check in [
HealthCheck::new("database", state).unwrap(),
HealthCheck::new("database", state)
.unwrap()
.with_message("状态说明"),
] {
let report = HealthReport::new("service", vec![check]).unwrap();
let bytes = postcard::to_allocvec(&report).unwrap();
assert_eq!(
postcard::from_bytes::<HealthReport>(&bytes).unwrap(),
report
);
let json = serde_json::to_value(&report).unwrap();
assert_eq!(
serde_json::from_value::<HealthReport>(json).unwrap(),
report
);
}
}
let empty = HealthReport::serving("service").unwrap();
let bytes = postcard::to_allocvec(&empty).unwrap();
assert_eq!(postcard::from_bytes::<HealthReport>(&bytes).unwrap(), empty);
}
#[test]
fn health_messages_are_sanitized_and_bounded() {
let check = HealthCheck::unavailable(
"database",
format!(
" database\n\t unavailable\0 {}",
"界".repeat(MAX_HEALTH_MESSAGE_LENGTH)
),
)
.expect("health check should validate");
let message = check.message().expect("non-empty message should remain");
assert!(message.len() <= MAX_HEALTH_MESSAGE_LENGTH);
assert!(!message.chars().any(char::is_control));
assert!(message.starts_with("database unavailable "));
assert_eq!(
HealthCheck::serving("database")
.expect("health check should validate")
.with_message(" \n\t ")
.message(),
None
);
let deserialized: HealthCheck = serde_json::from_value(json!({
"name": "database",
"state": "unavailable",
"message": "line one\nline two"
}))
.expect("health check should deserialize");
assert_eq!(deserialized.message(), Some("line one line two"));
}
#[cfg(feature = "diagnostics")]
#[test]
fn diagnostics_reports_have_one_canonical_health_conversion() {
use crate::diagnostics::{
ResourceDescriptor, ResourceDiagnostic, ResourceDiagnosticsReport, ResourceKind,
};
let required = ResourceDescriptor::required("database", "Database", ResourceKind::Database)
.expect("descriptor should validate");
let optional = ResourceDescriptor::optional("smtp", "SMTP", ResourceKind::Messaging)
.expect("descriptor should validate");
let report = ResourceDiagnosticsReport::new(
"example_service",
vec![
ResourceDiagnostic::unhealthy(required, "database unavailable"),
ResourceDiagnostic::unknown(optional, "smtp not checked"),
],
)
.expect("report should validate");
let health = HealthReport::from(&report);
assert_eq!(health.service(), "example_service");
assert_eq!(health.state(), HealthState::Unavailable);
assert_eq!(health.checks()[0].state(), HealthState::Unavailable);
assert_eq!(health.checks()[1].state(), HealthState::Degraded);
assert_eq!(health.checks()[0].message(), Some("database unavailable"));
}
#[test]
fn trace_fields_keep_standard_names_and_drop_empty_values() {
let fields = TraceFields::default()
.request_id("req_01")
.request_id("req_02")
.actor_id("usr_01")
.route("/api/users")
.latency_ms("12")
.try_with("empty", " ")
.expect("trace field should be valid");
assert_eq!(fields.get(trace_fields::REQUEST_ID), Some("req_02"));
assert_eq!(fields.get(trace_fields::ACTOR_ID), Some("usr_01"));
assert_eq!(fields.get(trace_fields::ROUTE), Some("/api/users"));
assert_eq!(fields.get(trace_fields::LATENCY_MS), Some("12"));
assert_eq!(fields.get("empty"), None);
assert!(fields.clone().try_with("RequestId", "bad").is_err());
assert!(TraceFieldName::new("RequestId").is_err());
assert!(TraceFields::new([("RequestId", "bad")]).is_err());
assert_eq!(
TraceFields::from_lossy([("RequestId", "bad"), ("request_id", "req_01")])
.get(trace_fields::REQUEST_ID),
Some("req_01")
);
assert!(!format!("{fields:?}").contains("usr_01"));
assert!(!format!("{fields:?}").contains("/api/users"));
}
#[test]
fn trace_field_updates_preserve_order_and_last_nonblank_value() {
let updates = [
("z", "first"),
("a", "second"),
("z", "last"),
("m", "middle"),
("a", " "),
];
let fields = updates
.into_iter()
.fold(TraceFields::default(), |fields, (key, value)| {
fields.with(key, value)
});
assert_eq!(fields, TraceFields::new(updates).unwrap());
assert_eq!(
serde_json::to_value(&fields).unwrap(),
json!([["a", "second"], ["m", "middle"], ["z", "last"]])
);
assert_eq!(fields.clone().with("Invalid", "ignored"), fields);
assert!(fields.clone().try_with("Invalid", "").is_err());
assert_eq!(
fields.try_with(" m ", "updated").unwrap().get("m"),
Some("updated")
);
}
#[test]
fn structured_event_fields_can_be_merged_or_replaced() {
let event = StructuredEvent::worker_tick("mail")
.merge_fields(TraceFields::single("attempt", "1").unwrap())
.merge_fields(TraceFields::new([("attempt", "2"), ("outcome", "success")]).unwrap());
assert_eq!(event.fields().get("worker"), Some("mail"));
assert_eq!(event.fields().get("attempt"), Some("2"));
let replacement = TraceFields::single("request_id", "req_01").unwrap();
assert_eq!(
event.with_fields(replacement.clone()).fields(),
&replacement
);
}
#[test]
fn trace_deserialization_uses_same_validation() {
assert!(serde_json::from_value::<TraceFieldName>(json!("RequestId")).is_err());
assert!(serde_json::from_value::<TraceFields>(json!([["RequestId", "bad"]])).is_err());
assert!(
serde_json::from_value::<StructuredEvent>(json!({
"name": "Bad Event",
"kind": "domain",
"fields": []
}))
.is_err()
);
let event: StructuredEvent = serde_json::from_value(json!({
"name": "user.created",
"kind": "domain",
"fields": [["request_id", "req_01"], ["request_id", "req_02"], ["trace_id", ""]]
}))
.expect("valid structured event should deserialize");
assert_eq!(event.name(), "user.created");
assert_eq!(event.fields().get(trace_fields::REQUEST_ID), Some("req_02"));
assert_eq!(event.fields().get(trace_fields::TRACE_ID), None);
}
#[test]
fn trace_context_normalizes_optional_ids() {
let context = TraceContext::new(
Some(" trace_01 ".to_owned()),
Some("bad/span".to_owned()),
Some("req_01".to_owned()),
);
assert_eq!(context.trace_id(), Some("trace_01"));
assert_eq!(context.span_id(), None);
assert_eq!(context.request_id(), Some("req_01"));
assert!(!context.is_empty());
let context: TraceContext = serde_json::from_value(json!({
"trace_id": "trace.01",
"span_id": "span 01",
"request_id": "req:01"
}))
.expect("trace context should deserialize");
assert_eq!(context.trace_id(), Some("trace.01"));
assert_eq!(context.span_id(), None);
assert_eq!(context.request_id(), Some("req:01"));
}
#[test]
fn structured_events_use_stable_names_and_fields() {
let event = StructuredEvent::http_request()
.with_fields(
TraceFields::default()
.request_id("req_01")
.method("GET")
.route("/health"),
)
.outcome(EventOutcome::Success);
assert_eq!(event.name(), event_names::HTTP_REQUEST);
assert_eq!(event.kind(), EventKind::Http);
assert_eq!(event.fields().get(trace_fields::REQUEST_ID), Some("req_01"));
assert_eq!(
event.trace_fields().get(trace_fields::EVENT_NAME),
Some(event_names::HTTP_REQUEST)
);
assert_eq!(
event.fields().get(trace_fields::OUTCOME),
Some(metric_outcomes::SUCCESS)
);
assert_eq!(
event.to_btree_map().get(trace_fields::EVENT_KIND),
Some(&"http".to_owned())
);
assert!(StructuredEvent::new("Bad Event", EventKind::Domain).is_err());
}
#[test]
fn metrics_snapshot_keeps_labels() {
let snapshot = MetricsSnapshot::new(vec![
MetricSample::counter("worker_ticks_total", 3)
.expect("metric sample should build")
.with_label("worker_name", "mail")
.unwrap(),
])
.unwrap();
assert_eq!(snapshot.samples()[0].name(), "worker_ticks_total");
assert_eq!(snapshot.samples()[0].kind(), MetricKind::Counter);
assert_eq!(
snapshot.samples()[0].labels()[0],
("worker_name".into(), "mail".into())
);
assert_eq!(
MetricLabels::new([("worker_name", "mail")])
.expect("metric labels should build")
.get("worker_name"),
Some("mail")
);
assert_eq!(
MetricLabels::new([("z", "1"), ("a", "2")])
.expect("metric labels should build")
.to_btree_map()
.keys()
.cloned()
.collect::<Vec<_>>(),
vec!["a".to_owned(), "z".to_owned()]
);
assert!(MetricLabels::new([(" ", "bad")]).is_err());
assert!(MetricLabels::from_lossy([(" ", "bad")]).is_empty());
let labels =
MetricLabels::single("account", "private-account-id").expect("metric labels should build");
assert!(!format!("{labels:?}").contains("private-account-id"));
let private_label = "private-snapshot-label";
let snapshot = MetricsSnapshot::new(vec![
MetricSample::counter("private_total", 1)
.expect("metric sample should build")
.with_label("account", private_label)
.unwrap(),
])
.unwrap();
assert!(!format!("{snapshot:?}").contains(private_label));
}
#[test]
fn metrics_deserialization_uses_same_validation() {
assert!(serde_json::from_value::<MetricLabels>(json!([[" ", "bad"]])).is_err());
assert!(
serde_json::from_value::<MetricSample>(json!({
"name": " ",
"kind": "counter",
"value": 1.0,
"labels": []
}))
.is_err()
);
let sample: MetricSample = serde_json::from_value(json!({
"name": "worker_ticks_total",
"kind": "counter",
"value": 1.0,
"labels": [["worker_name", "mail"]]
}))
.expect("valid metric sample should deserialize");
assert_eq!(sample.name(), "worker_ticks_total");
assert_eq!(
sample.labels(),
[("worker_name".to_owned(), "mail".to_owned())]
);
let snapshot: MetricsSnapshot = serde_json::from_value(json!({"samples": [
{
"name": "http_requests_total",
"kind": "counter",
"value": 2.0,
"labels": [["method", "GET"]]
}
]}))
.expect("valid metrics snapshot should deserialize");
assert_eq!(snapshot.samples().len(), 1);
}
#[test]
fn metrics_registry_rejects_non_finite_values() {
let registry = MetricRegistry::new();
assert!(matches!(
registry.set_gauge("memory", f64::NAN, MetricLabels::default()),
Err(MetricsError::InvalidValue)
));
assert!(matches!(
registry.observe_histogram("latency", f64::INFINITY, MetricLabels::default()),
Err(MetricsError::InvalidValue)
));
assert!(matches!(
MetricSample::gauge("temperature", f64::NAN),
Err(MetricsError::InvalidValue)
));
assert!(matches!(
registry.increment_counter(" ", 1, MetricLabels::default()),
Err(MetricsError::InvalidName)
));
}
#[test]
fn metric_names_and_labels_have_hard_input_bounds() {
assert!(matches!(
MetricSample::counter("x".repeat(MAX_METRIC_NAME_LENGTH + 1), 1),
Err(MetricsError::NameTooLong { .. })
));
assert!(matches!(
MetricLabels::single("x".repeat(MAX_METRIC_LABEL_KEY_LENGTH + 1), "value"),
Err(MetricsError::LabelKeyTooLong { .. })
));
assert!(matches!(
MetricLabels::single("key", "x".repeat(MAX_METRIC_LABEL_VALUE_LENGTH + 1)),
Err(MetricsError::LabelValueTooLong { .. })
));
assert!(matches!(
MetricLabels::single("key", "line one\nline two"),
Err(MetricsError::InvalidLabelValue)
));
assert!(matches!(
MetricLabels::new((0..=MAX_METRIC_LABELS).map(|index| (format!("key_{index}"), "value"))),
Err(MetricsError::TooManyLabels { .. })
));
let lossy = MetricLabels::from_lossy(
(0..=MAX_METRIC_LABELS).map(|index| (format!("key_{index}"), "value")),
);
assert_eq!(lossy.as_slice().len(), MAX_METRIC_LABELS);
}
#[test]
fn metrics_registry_enforces_total_and_per_metric_series_limits() {
assert!(MetricRegistryLimits::new(0, 0).is_err());
assert!(MetricRegistryLimits::new(2, 3).is_err());
let limits = MetricRegistryLimits::new(3, 2).expect("limits should validate");
let registry = MetricRegistry::with_limits(limits);
for account in ["one", "two"] {
registry
.increment_counter(
"requests_total",
1,
MetricLabels::single("account", account).expect("label should validate"),
)
.expect("series within the per-metric limit should be retained");
}
assert!(matches!(
registry.increment_counter(
"requests_total",
1,
MetricLabels::single("account", "three").expect("label should validate")
),
Err(MetricsError::MetricSeriesLimitExceeded { max: 2 })
));
registry
.set_gauge("workers", 1.0, MetricLabels::default())
.expect("third total series should be retained");
assert!(matches!(
registry.set_gauge("queue_depth", 1.0, MetricLabels::default()),
Err(MetricsError::RegistrySeriesLimitExceeded { max: 3 })
));
registry
.increment_counter(
"requests_total",
2,
MetricLabels::single("account", "one").expect("label should validate"),
)
.expect("updates to retained series must continue at the limit");
let snapshot = registry.snapshot().expect("snapshot should build");
assert_eq!(snapshot.samples().len(), 3);
assert_eq!(registry.limits(), limits);
}
#[test]
fn metrics_registry_rejects_aggregate_overflow_without_poisoning_snapshot() {
let registry = MetricRegistry::new();
registry
.observe_histogram("latency", f64::MAX, MetricLabels::default())
.expect("first finite observation should be accepted");
assert!(matches!(
registry.observe_histogram("latency", f64::MAX, MetricLabels::default()),
Err(MetricsError::InvalidValue)
));
let snapshot = registry
.snapshot()
.expect("rejected overflow must not poison the registry");
assert_eq!(snapshot.samples().len(), 1);
assert_eq!(snapshot.samples()[0].value(), f64::MAX);
assert_eq!(snapshot.samples()[0].count(), Some(1));
}
#[test]
fn metrics_errors_have_stable_classification() {
let descriptor = MetricsError::InvalidValue.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(descriptor.code().as_str(), "metric_value_invalid");
let descriptor = MetricsError::InvalidName.error_descriptor();
assert_eq!(descriptor.kind(), ErrorKind::Validation);
assert_eq!(descriptor.code().as_str(), "metric_name_invalid");
}
#[test]
fn metrics_registry_accumulates_and_encodes_openmetrics() {
let registry = MetricRegistry::new();
registry
.increment_counter(
"http_requests_total",
2,
MetricLabels::new([("method", "GET"), ("status", "200")])
.expect("metric labels should build"),
)
.expect("counter should update");
registry
.observe_histogram(
"http_request_duration_seconds",
0.25,
MetricLabels::single("route", "/health").expect("metric label should build"),
)
.expect("histogram should update");
let encoded = encode_openmetrics(®istry.snapshot().expect("snapshot should build"));
assert!(encoded.contains("# TYPE http_requests counter"));
assert_eq!(encoded.matches("# TYPE http_requests counter").count(), 1);
assert!(encoded.contains("method=\"GET\""));
assert!(encoded.contains("http_request_duration_seconds_sum"));
assert!(encoded.contains("http_request_duration_seconds_count"));
}
#[test]
fn registry_rejects_type_conflicts_without_mutating_existing_samples() {
for reverse in [false, true] {
let registry = MetricRegistry::new();
let register = |kind| match kind {
MetricKind::Counter => {
registry.increment_counter("jobs_total", 2, MetricLabels::default())
}
_ => registry.set_gauge("jobs_total", 3.0, MetricLabels::default()),
};
let (first, second) = if reverse {
(MetricKind::Gauge, MetricKind::Counter)
} else {
(MetricKind::Counter, MetricKind::Gauge)
};
register(first).unwrap();
let before = registry.snapshot().unwrap();
assert_eq!(register(second), Err(MetricsError::MetricTypeConflict));
assert_eq!(registry.snapshot().unwrap().samples(), before.samples());
}
}
#[test]
fn registry_reserves_family_and_generated_sample_names_in_both_orders() {
for kind in [MetricKind::Histogram, MetricKind::Counter] {
let suffixes: &[&str] = if kind == MetricKind::Histogram {
&["_sum", "_count", "_bucket", "_created"]
} else {
&["_total", "_created"]
};
for suffix in suffixes {
for reverse in [false, true] {
let registry = MetricRegistry::new();
let derived = format!("work{suffix}");
let register_family = || {
if kind == MetricKind::Histogram {
registry.observe_histogram("work", 0.5, MetricLabels::default())
} else {
registry.increment_counter("work", 1, MetricLabels::default())
}
};
let register_gauge = || registry.set_gauge(&derived, 1.0, MetricLabels::default());
let conflict = if reverse {
register_gauge().unwrap();
register_family()
} else {
register_family().unwrap();
register_gauge()
};
assert_eq!(conflict, Err(MetricsError::MetricNameConflict));
assert_eq!(registry.snapshot().unwrap().samples().len(), 1);
}
}
}
}
#[test]
fn registry_allows_multiple_label_sets_and_rejects_counter_aliases() {
let registry = MetricRegistry::new();
registry
.increment_counter("jobs_total", 1, MetricLabels::single("queue", "a").unwrap())
.unwrap();
registry
.increment_counter("jobs_total", 2, MetricLabels::single("queue", "b").unwrap())
.unwrap();
assert_eq!(
registry.increment_counter("jobs", 1, MetricLabels::default()),
Err(MetricsError::MetricNameConflict)
);
assert_eq!(registry.snapshot().unwrap().samples().len(), 2);
}
#[test]
fn metric_encoders_match_protocol_fixtures() {
let snapshot = MetricsSnapshot::new(vec![
MetricSample::counter("jobs_total", 2)
.unwrap()
.with_label("queue", "a")
.unwrap(),
MetricSample::histogram("latency", 0, 0.0, vec![(1.0, 0)])
.unwrap()
.with_label("route", "/empty")
.unwrap(),
MetricSample::gauge("queue_depth", 4.0).unwrap(),
MetricSample::counter("jobs_total", 3)
.unwrap()
.with_label("queue", "b")
.unwrap(),
MetricSample::counter("retries", 1).unwrap(),
MetricSample::histogram("latency", 2, 0.75, vec![(1.0, 2)])
.unwrap()
.with_label("route", "/jobs")
.unwrap(),
])
.unwrap();
assert_eq!(
encode_openmetrics(&snapshot),
include_str!("fixtures/openmetrics.txt")
);
assert_eq!(
super::encode_prometheus(&snapshot),
include_str!("fixtures/prometheus.txt")
);
}