footing 0.1.21

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
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;

    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;

    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;

    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;

    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;

    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;

    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;
    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));
}

#[test]
fn registry_rejects_invalid_probe_timeouts() {
    for timeout in [Duration::ZERO, Duration::MAX] {
        assert!(matches!(
            registry().with_probe_timeout(timeout),
            Err(ResourceRegistryError::InvalidProbeTimeout)
        ));
    }
}

#[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()
    );
}