use std::time::Duration;
use super::*;
use crate::result::BoxError;
fn registry() -> ResourceRegistry {
ResourceRegistry::new("example_service").expect("static service name is valid")
}
fn required(id: &str, name: &str, kind: ResourceKind) -> ResourceDescriptor {
ResourceDescriptor::required(id, name, kind).expect("static descriptor is valid")
}
fn optional(id: &str, name: &str, kind: ResourceKind) -> ResourceDescriptor {
ResourceDescriptor::optional(id, name, kind).expect("static descriptor is valid")
}
#[test]
fn diagnostics_round_trip_json_and_binary_with_empty_and_populated_fields() {
fn round_trip<
T: serde::Serialize + serde::de::DeserializeOwned + PartialEq + std::fmt::Debug,
>(
value: &T,
) {
let json = serde_json::to_vec(value).unwrap();
assert_eq!(&serde_json::from_slice::<T>(&json).unwrap(), value);
let binary = postcard::to_allocvec(value).unwrap();
assert_eq!(&postcard::from_bytes::<T>(&binary).unwrap(), value);
}
round_trip(&ResourceDiagnosticsReport::new("test", vec![]).unwrap());
for populated in [false, true] {
let mut descriptor = required("database", "Database", ResourceKind::Database);
if populated {
descriptor = descriptor.with_label("role", "primary").unwrap();
}
round_trip(&descriptor);
for status in [
ResourceStatus::Healthy,
ResourceStatus::Degraded,
ResourceStatus::Unhealthy,
ResourceStatus::Unknown,
] {
let mut diagnostic =
ResourceDiagnostic::new(descriptor.clone(), status, "probe result");
if populated {
diagnostic = diagnostic
.with_detail("details")
.unwrap()
.with_remediation("retry")
.unwrap();
}
round_trip(&diagnostic);
round_trip(&ResourceDiagnosticsReport::new("test", vec![diagnostic]).unwrap());
}
}
}
#[tokio::test]
async fn registry_runs_static_probes_and_rolls_up_status() {
let registry = registry()
.with_probe(static_resource_probe(
required("contracts", "HTTP Contracts", ResourceKind::Configuration),
ResourceDiagnostic::healthy,
"contracts are valid",
))
.expect("first probe should register")
.with_probe(static_resource_probe(
optional("smtp", "SMTP", ResourceKind::Messaging),
ResourceDiagnostic::degraded,
"SMTP is not configured",
))
.expect("second probe should register");
let report = registry.run().await.expect("diagnostics should run");
assert!(report.ready());
assert_eq!(report.status(), ResourceStatus::Degraded);
assert_eq!(report.summary().total(), 2);
assert_eq!(report.summary().healthy(), 1);
assert_eq!(report.summary().degraded(), 1);
}
#[tokio::test]
async fn registry_runs_closure_probes_with_captured_state() {
let expected_schema_version = 1;
let registry = registry()
.with_probe(resource_probe(
required("contracts", "HTTP Contracts", ResourceKind::Http),
move |resource| async move {
Ok(ResourceDiagnostic::healthy(resource, "contracts are valid")
.with_detail(format!("schema_version={expected_schema_version}"))
.expect("static detail should validate"))
},
))
.expect("probe should register");
let report = registry.run().await.expect("diagnostics should run");
assert!(report.ready());
assert_eq!(report.status(), ResourceStatus::Healthy);
assert_eq!(
report.resources()[0].details(),
["schema_version=1".to_owned()]
);
}
#[tokio::test]
async fn required_unhealthy_resource_blocks_readiness() {
let registry = registry()
.with_probe(static_resource_probe(
required("oidc-key", "OIDC Key", ResourceKind::Cryptography),
ResourceDiagnostic::unhealthy,
"signing key is missing",
))
.expect("probe should register");
let report = registry.run().await.expect("diagnostics should run");
assert!(!report.ready());
assert_eq!(report.status(), ResourceStatus::Unhealthy);
assert_eq!(report.summary().readiness_blocking(), 1);
assert_eq!(report.readiness_blockers()[0].resource().id(), "oidc-key");
}
#[tokio::test]
async fn required_unknown_resource_blocks_readiness() {
let registry = registry()
.with_probe(static_resource_probe(
required("database", "Database", ResourceKind::Database),
ResourceDiagnostic::unknown,
"database health was not checked",
))
.expect("probe should register");
let report = registry.run().await.expect("diagnostics should run");
assert!(!report.ready());
assert_eq!(report.status(), ResourceStatus::Unknown);
assert_eq!(report.summary().readiness_blocking(), 1);
}
#[tokio::test]
async fn registry_rejects_duplicate_resource_ids() {
let descriptor = required("config", "Configuration", ResourceKind::Configuration);
let registry = registry()
.with_probe(static_resource_probe(
descriptor.clone(),
ResourceDiagnostic::healthy,
"ok",
))
.expect("first probe should register")
.with_probe(static_resource_probe(
descriptor,
ResourceDiagnostic::healthy,
"ok",
));
assert!(matches!(
registry,
Err(ResourceRegistryError::DuplicateResourceId { .. })
));
}
#[tokio::test]
async fn registry_rejects_empty_service_name() {
assert!(matches!(
ResourceRegistry::new(" "),
Err(ResourceRegistryError::InvalidServiceName)
));
}
#[tokio::test]
async fn registry_anchors_probe_results_to_registered_descriptor() {
let registry = registry()
.with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
|_| async move {
Ok(ResourceDiagnostic::healthy(
optional("other", "Other", ResourceKind::Other),
"database is reachable",
))
},
))
.expect("probe should register");
let report = registry.run().await.expect("diagnostics should run");
assert_eq!(report.resources()[0].resource().id(), "database");
assert_eq!(report.resources()[0].resource().name(), "Database");
assert_eq!(
report.resources()[0].resource().criticality(),
ResourceCriticality::Required
);
assert_eq!(report.resources()[0].summary(), "database is reachable");
}
#[tokio::test]
async fn registry_bounds_each_probe_and_reports_timeout() {
let registry = registry()
.with_probe_timeout(Duration::from_millis(1))
.expect("positive timeout should validate")
.with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
|_| async move { std::future::pending::<Result<ResourceDiagnostic, BoxError>>().await },
))
.expect("probe should register");
let report = registry
.run()
.await
.expect("timeout should become a diagnostic");
assert!(!report.ready());
assert_eq!(report.resources()[0].summary(), "resource probe timed out");
assert!(report.resources()[0].details().is_empty());
}
#[tokio::test]
async fn registry_does_not_copy_probe_errors_into_serialized_reports() {
let private_detail = "private-probe-error";
let registry = registry()
.with_probe(resource_probe(
required("database", "Database", ResourceKind::Database),
move |_| async move {
Err::<ResourceDiagnostic, BoxError>(Box::new(std::io::Error::other(private_detail)))
},
))
.expect("probe should register");
let report = registry
.run()
.await
.expect("failure should become a diagnostic");
let wire = serde_json::to_string(&report).expect("report should serialize");
assert_eq!(report.resources()[0].summary(), "resource probe failed");
assert!(report.resources()[0].details().is_empty());
assert!(!wire.contains(private_detail));
}
#[tokio::test]
async fn registry_rejects_zero_probe_timeout() {
let error = registry()
.with_probe_timeout(Duration::ZERO)
.expect_err("zero timeout should fail validation");
assert_eq!(
error.to_string(),
"resource diagnostic probe timeout must be greater than zero"
);
}
#[test]
fn descriptor_construction_and_deserialization_share_validation() {
assert!(matches!(
ResourceDescriptor::required("", "Database", ResourceKind::Database),
Err(ResourceDescriptorError::EmptyId)
));
assert!(matches!(
ResourceDescriptor::required("bad id", "Database", ResourceKind::Database),
Err(ResourceDescriptorError::InvalidId)
));
assert!(matches!(
required("database", "Database", ResourceKind::Database).with_label("", "true"),
Err(ResourceDescriptorError::EmptyLabelKey)
));
assert!(
serde_json::from_value::<ResourceDescriptor>(serde_json::json!({
"id": "",
"name": "Database",
"kind": "database",
"criticality": "required"
}))
.is_err()
);
}
#[test]
fn diagnostic_debug_redacts_labels_and_operator_messages_without_changing_wire_data() {
let label = "private-resource-label";
let summary = "private-resource-summary";
let detail = "private-resource-detail";
let remediation = "private-resource-remediation";
let descriptor = required("database", "Database", ResourceKind::Database)
.with_label("endpoint", label)
.expect("resource label should validate");
let diagnostic = ResourceDiagnostic::unhealthy(descriptor, summary)
.with_detail(detail)
.expect("detail should validate")
.with_remediation(remediation)
.expect("remediation should validate");
let output = format!("{diagnostic:?}");
assert!(output.contains("label_count"));
for sensitive in [label, summary, detail, remediation] {
assert!(!output.contains(sensitive));
}
let wire = serde_json::to_value(&diagnostic).expect("diagnostic should serialize");
assert_eq!(wire["resource"]["labels"]["endpoint"], label);
assert_eq!(wire["summary"], summary);
assert_eq!(wire["details"][0], detail);
assert_eq!(wire["remediations"][0], remediation);
}
#[test]
fn report_deserialization_recomputes_status_and_summary() {
let value = serde_json::json!({
"service_name": "example_service",
"status": "healthy",
"summary": {
"total": 0,
"healthy": 0,
"degraded": 0,
"unhealthy": 0,
"unknown": 0,
"readiness_blocking": 0
},
"resources": [{
"resource": {
"id": "database",
"name": "Database",
"kind": "database",
"criticality": "required"
},
"status": "unhealthy",
"summary": "database is unavailable"
}]
});
let report: ResourceDiagnosticsReport =
serde_json::from_value(value).expect("report JSON should deserialize");
assert_eq!(report.status(), ResourceStatus::Unhealthy);
assert_eq!(report.summary().total(), 1);
assert_eq!(report.summary().readiness_blocking(), 1);
}
#[test]
fn descriptor_labels_are_bounded_for_builders_and_serde() {
let mut descriptor = required("database", "Database", ResourceKind::Database);
for index in 0..MAX_RESOURCE_LABELS {
descriptor = descriptor
.with_label(format!("label_{index}"), "value")
.expect("label within the bound should validate");
}
descriptor = descriptor
.with_label("label_0", "updated")
.expect("updating an existing label should not increase cardinality");
assert_eq!(descriptor.labels().len(), MAX_RESOURCE_LABELS);
assert_eq!(
descriptor.labels().get("label_0").map(String::as_str),
Some("updated")
);
assert!(matches!(
descriptor.with_label("one_more", "value"),
Err(ResourceDescriptorError::TooManyLabels { .. })
));
let labels = (0..=MAX_RESOURCE_LABELS)
.map(|index| {
(
format!("label_{index}"),
serde_json::Value::String("value".to_owned()),
)
})
.collect::<serde_json::Map<_, _>>();
assert!(
serde_json::from_value::<ResourceDescriptor>(serde_json::json!({
"id": "database",
"name": "Database",
"kind": "database",
"criticality": "required",
"labels": labels
}))
.is_err()
);
}
#[test]
fn diagnostic_messages_and_collections_are_bounded() {
let mut diagnostic = ResourceDiagnostic::unhealthy(
required("database", "Database", ResourceKind::Database),
format!(
" unavailable\n{} ",
"界".repeat(MAX_RESOURCE_MESSAGE_LENGTH)
),
);
assert!(diagnostic.summary().len() <= MAX_RESOURCE_MESSAGE_LENGTH);
assert!(!diagnostic.summary().chars().any(char::is_control));
for _ in 0..MAX_RESOURCE_DIAGNOSTIC_DETAILS {
diagnostic = diagnostic
.with_detail("bounded detail")
.expect("detail within the bound should validate");
}
assert!(matches!(
diagnostic.clone().with_detail("one more"),
Err(ResourceDiagnosticError::TooManyDetails { .. })
));
assert!(
diagnostic
.clone()
.with_detail(" \n\t ")
.expect("an empty normalized detail is a no-op")
.details()
.len()
== MAX_RESOURCE_DIAGNOSTIC_DETAILS
);
for _ in 0..MAX_RESOURCE_DIAGNOSTIC_REMEDIATIONS {
diagnostic = diagnostic
.with_remediation("bounded remediation")
.expect("remediation within the bound should validate");
}
assert!(matches!(
diagnostic.with_remediation("one more"),
Err(ResourceDiagnosticError::TooManyRemediations { .. })
));
}
#[test]
fn report_rejects_duplicate_and_excess_resources() {
let descriptor = required("database", "Database", ResourceKind::Database);
let duplicate = ResourceDiagnosticsReport::new(
"example_service",
vec![
ResourceDiagnostic::healthy(descriptor.clone(), "ok"),
ResourceDiagnostic::healthy(descriptor, "ok"),
],
);
assert!(matches!(
duplicate,
Err(ResourceRegistryError::DuplicateResourceId { .. })
));
let resources = (0..=MAX_RESOURCE_REPORT_RESOURCES)
.map(|index| {
ResourceDiagnostic::healthy(
required(
&format!("resource_{index}"),
&format!("Resource {index}"),
ResourceKind::Other,
),
"ok",
)
})
.collect();
assert!(matches!(
ResourceDiagnosticsReport::new("example_service", resources),
Err(ResourceRegistryError::TooManyResources { .. })
));
assert!(matches!(
ResourceDiagnosticsReport::new(
"x".repeat(MAX_DIAGNOSTICS_SERVICE_NAME_LENGTH + 1),
Vec::new()
),
Err(ResourceRegistryError::ServiceNameTooLong { .. })
));
}
#[test]
fn diagnostic_deserialization_enforces_collection_bounds() {
let details = vec!["detail"; MAX_RESOURCE_DIAGNOSTIC_DETAILS + 1];
assert!(
serde_json::from_value::<ResourceDiagnostic>(serde_json::json!({
"resource": {
"id": "database",
"name": "Database",
"kind": "database",
"criticality": "required"
},
"status": "unhealthy",
"summary": "down",
"details": details
}))
.is_err()
);
}