footing 0.6.3

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
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
//! Resource descriptors, probe results, reports, and summaries.

use std::{collections::BTreeMap, fmt, time::Duration};

use serde::{Deserialize, Deserializer, Serialize};

use super::error::{ResourceDescriptorError, ResourceDiagnosticError, ResourceRegistryError};

/// Maximum supported resource identifier length.
pub const MAX_RESOURCE_ID_LENGTH: usize = 128;
/// Maximum supported resource name length.
pub const MAX_RESOURCE_NAME_LENGTH: usize = 128;
/// Maximum supported diagnostics service name length.
pub const MAX_DIAGNOSTICS_SERVICE_NAME_LENGTH: usize = 128;
/// Maximum number of labels on one resource descriptor.
pub const MAX_RESOURCE_LABELS: usize = 32;
/// Maximum supported resource label key length.
pub const MAX_RESOURCE_LABEL_KEY_LENGTH: usize = 64;
/// Maximum supported resource label value length.
pub const MAX_RESOURCE_LABEL_VALUE_LENGTH: usize = 256;
/// Maximum supported resource message length.
pub const MAX_RESOURCE_MESSAGE_LENGTH: usize = 1024;
/// Maximum number of detail messages on one resource diagnostic.
pub const MAX_RESOURCE_DIAGNOSTIC_DETAILS: usize = 32;
/// Maximum number of remediation hints on one resource diagnostic.
pub const MAX_RESOURCE_DIAGNOSTIC_REMEDIATIONS: usize = 16;
/// Maximum number of resources in one registry or diagnostics report.
pub const MAX_RESOURCE_REPORT_RESOURCES: usize = 256;
/// Default maximum time allowed for one resource probe.
pub const DEFAULT_RESOURCE_PROBE_TIMEOUT: Duration = Duration::from_secs(5);

/// Stable category for a probed resource.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceKind {
    /// Indicates configuration.
    Configuration,
    /// Indicates database.
    Database,
    /// Indicates filesystem.
    Filesystem,
    /// Indicates cryptography.
    Cryptography,
    /// Indicates HTTP.
    Http,
    /// Indicates LDAP.
    Ldap,
    /// Indicates messaging.
    Messaging,
    /// Indicates worker.
    Worker,
    /// Indicates external.
    External,
    /// A value not covered by another variant.
    Other,
}

impl ResourceKind {
    /// Returns the stable wire/log representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Configuration => "configuration",
            Self::Database => "database",
            Self::Filesystem => "filesystem",
            Self::Cryptography => "cryptography",
            Self::Http => "http",
            Self::Ldap => "ldap",
            Self::Messaging => "messaging",
            Self::Worker => "worker",
            Self::External => "external",
            Self::Other => "other",
        }
    }
}

impl fmt::Display for ResourceKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Whether a resource should block startup/readiness.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceCriticality {
    /// Indicates required.
    Required,
    /// Indicates optional.
    Optional,
}

impl ResourceCriticality {
    /// Returns true when an unhealthy resource should make the process not
    /// ready.
    #[must_use]
    pub const fn required(self) -> bool {
        matches!(self, Self::Required)
    }

    /// Returns the stable wire/log representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Required => "required",
            Self::Optional => "optional",
        }
    }
}

impl fmt::Display for ResourceCriticality {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Probe status for one resource.
#[derive(
    Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize,
)]
#[non_exhaustive]
#[serde(rename_all = "snake_case")]
pub enum ResourceStatus {
    /// The component is healthy.
    Healthy,
    /// The component is degraded.
    Degraded,
    /// The component is unhealthy.
    Unhealthy,
    /// The value is unknown.
    #[default]
    Unknown,
}

impl ResourceStatus {
    /// Returns true when the resource can safely serve production traffic.
    #[must_use]
    pub const fn healthy(self) -> bool {
        matches!(self, Self::Healthy)
    }

    /// Returns true when the resource is in a known non-ready state.
    #[must_use]
    pub const fn unhealthy(self) -> bool {
        matches!(self, Self::Unhealthy)
    }

    /// Returns true when the resource is usable but needs operator attention.
    #[must_use]
    pub const fn degraded(self) -> bool {
        matches!(self, Self::Degraded)
    }

    /// Returns the stable wire/log representation.
    #[must_use]
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Healthy => "healthy",
            Self::Degraded => "degraded",
            Self::Unhealthy => "unhealthy",
            Self::Unknown => "unknown",
        }
    }
}

impl fmt::Display for ResourceStatus {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(self.as_str())
    }
}

/// Resource identity and static metadata.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDescriptorWire")]
#[non_exhaustive]
pub struct ResourceDescriptor {
    /// Stable identifier used to correlate probe results.
    id: String,
    /// Human-readable resource name.
    name: String,
    /// Infrastructure category of the resource.
    kind: ResourceKind,
    /// Whether a failure blocks service readiness.
    criticality: ResourceCriticality,
    /// Bounded metadata attached to the resource.
    labels: BTreeMap<String, String>,
}

impl fmt::Debug for ResourceDescriptor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResourceDescriptor")
            .field("id", &self.id)
            .field("name", &self.name)
            .field("kind", &self.kind)
            .field("criticality", &self.criticality)
            .field("label_count", &self.labels.len())
            .finish()
    }
}

impl ResourceDescriptor {
    /// Creates a required resource descriptor.
    pub fn required(
        id: impl Into<String>,
        name: impl Into<String>,
        kind: ResourceKind,
    ) -> Result<Self, ResourceDescriptorError> {
        Self::new(id, name, kind, ResourceCriticality::Required)
    }

    /// Creates an optional resource descriptor.
    pub fn optional(
        id: impl Into<String>,
        name: impl Into<String>,
        kind: ResourceKind,
    ) -> Result<Self, ResourceDescriptorError> {
        Self::new(id, name, kind, ResourceCriticality::Optional)
    }

    /// Creates a resource descriptor with explicit criticality.
    pub fn new(
        id: impl Into<String>,
        name: impl Into<String>,
        kind: ResourceKind,
        criticality: ResourceCriticality,
    ) -> Result<Self, ResourceDescriptorError> {
        Ok(Self {
            id: normalize_resource_id(id)?,
            name: normalize_resource_name(name)?,
            kind,
            criticality,
            labels: BTreeMap::new(),
        })
    }

    /// Adds a stable string label.
    pub fn with_label(
        mut self,
        key: impl Into<String>,
        value: impl Into<String>,
    ) -> Result<Self, ResourceDescriptorError> {
        let key = normalize_resource_label_key(key)?;
        let value = normalize_resource_label_value(&key, value)?;
        if !self.labels.contains_key(&key) && self.labels.len() >= MAX_RESOURCE_LABELS {
            return Err(ResourceDescriptorError::TooManyLabels {
                max: MAX_RESOURCE_LABELS,
            });
        }
        self.labels.insert(key, value);
        Ok(self)
    }

    /// Returns the stable resource identifier.
    #[must_use]
    pub fn id(&self) -> &str {
        &self.id
    }

    /// Returns the human-readable resource name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Returns the resource kind.
    #[must_use]
    pub const fn kind(&self) -> ResourceKind {
        self.kind
    }

    /// Returns the resource criticality.
    #[must_use]
    pub const fn criticality(&self) -> ResourceCriticality {
        self.criticality
    }

    /// Returns the bounded resource labels.
    #[must_use]
    pub fn labels(&self) -> &BTreeMap<String, String> {
        &self.labels
    }
}

#[derive(Deserialize)]
struct ResourceDescriptorWire {
    id: String,
    name: String,
    kind: ResourceKind,
    criticality: ResourceCriticality,
    #[serde(default)]
    labels: BTreeMap<String, String>,
}

impl TryFrom<ResourceDescriptorWire> for ResourceDescriptor {
    type Error = ResourceDescriptorError;

    fn try_from(value: ResourceDescriptorWire) -> Result<Self, Self::Error> {
        let mut descriptor = Self::new(value.id, value.name, value.kind, value.criticality)?;
        for (key, value) in value.labels {
            descriptor = descriptor.with_label(key, value)?;
        }
        Ok(descriptor)
    }
}

/// Result of probing one resource.
#[derive(Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDiagnosticWire")]
#[non_exhaustive]
pub struct ResourceDiagnostic {
    /// Resource that was probed.
    resource: ResourceDescriptor,
    /// Health status returned by the probe.
    status: ResourceStatus,
    /// Short operator-facing result summary.
    summary: String,
    /// Additional diagnostic observations.
    details: Vec<String>,
    /// Suggested recovery actions.
    remediations: Vec<String>,
}

impl fmt::Debug for ResourceDiagnostic {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ResourceDiagnostic")
            .field("resource", &self.resource)
            .field("status", &self.status)
            .field("summary", &"[REDACTED]")
            .field("detail_count", &self.details.len())
            .field("remediation_count", &self.remediations.len())
            .finish()
    }
}

impl ResourceDiagnostic {
    /// Creates a healthy diagnostic.
    #[must_use]
    pub fn healthy(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
        Self::new(resource, ResourceStatus::Healthy, summary)
    }

    /// Creates a degraded diagnostic.
    #[must_use]
    pub fn degraded(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
        Self::new(resource, ResourceStatus::Degraded, summary)
    }

    /// Creates an unhealthy diagnostic.
    #[must_use]
    pub fn unhealthy(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
        Self::new(resource, ResourceStatus::Unhealthy, summary)
    }

    /// Creates an unknown diagnostic.
    #[must_use]
    pub fn unknown(resource: ResourceDescriptor, summary: impl Into<String>) -> Self {
        Self::new(resource, ResourceStatus::Unknown, summary)
    }

    /// Creates a diagnostic with explicit status.
    #[must_use]
    pub fn new(
        resource: ResourceDescriptor,
        status: ResourceStatus,
        summary: impl Into<String>,
    ) -> Self {
        Self {
            resource,
            status,
            summary: normalize_message(summary, "resource diagnostic completed"),
            details: Vec::new(),
            remediations: Vec::new(),
        }
    }

    /// Adds one operator-facing detail.
    pub fn with_detail(
        mut self,
        detail: impl Into<String>,
    ) -> Result<Self, ResourceDiagnosticError> {
        if let Some(detail) = normalize_optional_message(detail) {
            if self.details.len() >= MAX_RESOURCE_DIAGNOSTIC_DETAILS {
                return Err(ResourceDiagnosticError::TooManyDetails {
                    max: MAX_RESOURCE_DIAGNOSTIC_DETAILS,
                });
            }
            self.details.push(detail);
        }
        Ok(self)
    }

    /// Adds one operator-facing remediation hint.
    pub fn with_remediation(
        mut self,
        remediation: impl Into<String>,
    ) -> Result<Self, ResourceDiagnosticError> {
        if let Some(remediation) = normalize_optional_message(remediation) {
            if self.remediations.len() >= MAX_RESOURCE_DIAGNOSTIC_REMEDIATIONS {
                return Err(ResourceDiagnosticError::TooManyRemediations {
                    max: MAX_RESOURCE_DIAGNOSTIC_REMEDIATIONS,
                });
            }
            self.remediations.push(remediation);
        }
        Ok(self)
    }

    /// Returns the resource that was probed.
    #[must_use]
    pub const fn resource(&self) -> &ResourceDescriptor {
        &self.resource
    }

    /// Returns the probe status.
    #[must_use]
    pub const fn status(&self) -> ResourceStatus {
        self.status
    }

    /// Returns the bounded operator-facing summary.
    #[must_use]
    pub fn summary(&self) -> &str {
        &self.summary
    }

    /// Returns the bounded diagnostic details.
    #[must_use]
    pub fn details(&self) -> &[String] {
        &self.details
    }

    /// Returns the bounded remediation hints.
    #[must_use]
    pub fn remediations(&self) -> &[String] {
        &self.remediations
    }

    /// Returns true when this diagnostic blocks readiness.
    #[must_use]
    pub const fn readiness_blocking(&self) -> bool {
        self.resource.criticality.required()
            && matches!(
                self.status,
                ResourceStatus::Unhealthy | ResourceStatus::Unknown
            )
    }
}

#[derive(Deserialize)]
struct ResourceDiagnosticWire {
    resource: ResourceDescriptor,
    status: ResourceStatus,
    summary: String,
    #[serde(default)]
    details: Vec<String>,
    #[serde(default)]
    remediations: Vec<String>,
}

impl TryFrom<ResourceDiagnosticWire> for ResourceDiagnostic {
    type Error = ResourceDiagnosticError;

    fn try_from(value: ResourceDiagnosticWire) -> Result<Self, Self::Error> {
        let mut diagnostic = ResourceDiagnostic::new(value.resource, value.status, value.summary);
        for detail in value.details {
            diagnostic = diagnostic.with_detail(detail)?;
        }
        for remediation in value.remediations {
            diagnostic = diagnostic.with_remediation(remediation)?;
        }
        Ok(diagnostic)
    }
}

/// Aggregate diagnostics for one service process.
///
/// Deserialization requires `status`, `summary`, and `resources`, and rejects
/// aggregates that disagree with the resource results. Use [`Self::new`] to
/// compute a report from resources; an explicitly empty list is valid and ready.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[non_exhaustive]
pub struct ResourceDiagnosticsReport {
    /// Service instance represented by this report.
    service_name: String,
    /// Aggregate status derived from all resources.
    status: ResourceStatus,
    /// Counts grouped by status and readiness impact.
    summary: ResourceDiagnosticsSummary,
    /// Individual resource results.
    resources: Vec<ResourceDiagnostic>,
}

impl ResourceDiagnosticsReport {
    /// Creates a report and computes the aggregate status.
    pub fn new(
        service_name: impl Into<String>,
        resources: Vec<ResourceDiagnostic>,
    ) -> Result<Self, ResourceRegistryError> {
        let service_name = normalize_diagnostics_service_name(service_name)?;
        if resources.len() > MAX_RESOURCE_REPORT_RESOURCES {
            return Err(ResourceRegistryError::TooManyResources {
                max: MAX_RESOURCE_REPORT_RESOURCES,
            });
        }
        let mut seen = BTreeMap::new();
        for (index, diagnostic) in resources.iter().enumerate() {
            let resource_id = diagnostic.resource().id();
            if let Some(first_index) = seen.insert(resource_id, index) {
                return Err(ResourceRegistryError::DuplicateResourceId {
                    id: resource_id.to_owned(),
                    first_index,
                    second_index: index,
                });
            }
        }
        Ok(Self::from_validated(service_name, resources))
    }

    /// The caller has validated the service name, resource limit and unique IDs.
    pub(super) fn from_validated(service_name: String, resources: Vec<ResourceDiagnostic>) -> Self {
        Self {
            service_name,
            status: aggregate_status(&resources),
            summary: ResourceDiagnosticsSummary::from_diagnostics(&resources),
            resources,
        }
    }

    /// Returns true when no required resource is unhealthy or unknown.
    #[must_use]
    pub fn ready(&self) -> bool {
        self.summary.readiness_blocking == 0
    }

    /// Returns required resources whose status is unhealthy or unknown.
    #[must_use]
    pub fn readiness_blockers(&self) -> Vec<&ResourceDiagnostic> {
        self.resources
            .iter()
            .filter(|diagnostic| diagnostic.readiness_blocking())
            .collect()
    }

    /// Returns the service represented by this report.
    #[must_use]
    pub fn service_name(&self) -> &str {
        &self.service_name
    }

    /// Returns the derived aggregate status.
    #[must_use]
    pub const fn status(&self) -> ResourceStatus {
        self.status
    }

    /// Returns the derived status counts.
    #[must_use]
    pub const fn summary(&self) -> &ResourceDiagnosticsSummary {
        &self.summary
    }

    /// Returns the bounded resource diagnostics in registry order.
    #[must_use]
    pub fn resources(&self) -> &[ResourceDiagnostic] {
        &self.resources
    }
}

#[derive(Deserialize)]
struct ResourceDiagnosticsReportWire {
    service_name: String,
    status: ResourceStatus,
    summary: ResourceDiagnosticsSummaryWire,
    resources: Vec<ResourceDiagnostic>,
}

// Read the serialized field types even in non-self-describing formats. The
// counts are validated against the resources before the report is returned.
#[derive(Deserialize)]
struct ResourceDiagnosticsSummaryWire {
    total: usize,
    healthy: usize,
    degraded: usize,
    unhealthy: usize,
    unknown: usize,
    readiness_blocking: usize,
}

impl<'de> Deserialize<'de> for ResourceDiagnosticsReport {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = ResourceDiagnosticsReportWire::deserialize(deserializer)?;
        let report =
            Self::new(wire.service_name, wire.resources).map_err(serde::de::Error::custom)?;
        if wire.status != report.status {
            return Err(serde::de::Error::custom(
                "diagnostics report status must match its resources",
            ));
        }
        let actual = wire.summary;
        let expected = &report.summary;
        if actual.total != expected.total
            || actual.healthy != expected.healthy
            || actual.degraded != expected.degraded
            || actual.unhealthy != expected.unhealthy
            || actual.unknown != expected.unknown
            || actual.readiness_blocking != expected.readiness_blocking
        {
            return Err(serde::de::Error::custom(
                "diagnostics report summary must match its resources",
            ));
        }
        Ok(report)
    }
}

/// Status counts for a diagnostics report.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize)]
#[non_exhaustive]
pub struct ResourceDiagnosticsSummary {
    /// Total number of resources in the report.
    total: usize,
    /// Number of healthy resources.
    healthy: usize,
    /// Number of degraded resources.
    degraded: usize,
    /// Number of unhealthy resources.
    unhealthy: usize,
    /// Number of resources whose status is unknown.
    unknown: usize,
    /// Number of required resources currently blocking readiness.
    readiness_blocking: usize,
}

impl ResourceDiagnosticsSummary {
    /// Returns the total number of resources.
    #[must_use]
    pub const fn total(&self) -> usize {
        self.total
    }

    /// Returns the number of healthy resources.
    #[must_use]
    pub const fn healthy(&self) -> usize {
        self.healthy
    }

    /// Returns the number of degraded resources.
    #[must_use]
    pub const fn degraded(&self) -> usize {
        self.degraded
    }

    /// Returns the number of unhealthy resources.
    #[must_use]
    pub const fn unhealthy(&self) -> usize {
        self.unhealthy
    }

    /// Returns the number of resources with unknown status.
    #[must_use]
    pub const fn unknown(&self) -> usize {
        self.unknown
    }

    /// Returns the number of resources blocking readiness.
    #[must_use]
    pub const fn readiness_blocking(&self) -> usize {
        self.readiness_blocking
    }

    #[must_use]
    fn from_diagnostics(resources: &[ResourceDiagnostic]) -> Self {
        let mut summary = Self {
            total: resources.len(),
            ..Self::default()
        };
        for diagnostic in resources {
            match diagnostic.status() {
                ResourceStatus::Healthy => summary.healthy += 1,
                ResourceStatus::Degraded => summary.degraded += 1,
                ResourceStatus::Unhealthy => summary.unhealthy += 1,
                ResourceStatus::Unknown => summary.unknown += 1,
            }
            if diagnostic.readiness_blocking() {
                summary.readiness_blocking += 1;
            }
        }
        summary
    }
}

fn aggregate_status(resources: &[ResourceDiagnostic]) -> ResourceStatus {
    if resources.iter().any(|diagnostic| {
        diagnostic.resource.criticality.required() && diagnostic.status == ResourceStatus::Unhealthy
    }) {
        return ResourceStatus::Unhealthy;
    }
    if resources
        .iter()
        .any(|diagnostic| diagnostic.status == ResourceStatus::Unknown)
    {
        return ResourceStatus::Unknown;
    }
    if resources.iter().any(|diagnostic| {
        matches!(
            diagnostic.status,
            ResourceStatus::Unhealthy | ResourceStatus::Degraded
        )
    }) {
        return ResourceStatus::Degraded;
    }
    ResourceStatus::Healthy
}

pub(super) fn normalize_diagnostics_service_name(
    value: impl Into<String>,
) -> Result<String, ResourceRegistryError> {
    let value = value.into().trim().to_owned();
    if value.len() > MAX_DIAGNOSTICS_SERVICE_NAME_LENGTH {
        return Err(ResourceRegistryError::ServiceNameTooLong {
            max: MAX_DIAGNOSTICS_SERVICE_NAME_LENGTH,
        });
    }
    if !valid_identifier(&value) {
        return Err(ResourceRegistryError::InvalidServiceName);
    }
    Ok(value)
}

fn normalize_resource_id(value: impl Into<String>) -> Result<String, ResourceDescriptorError> {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        return Err(ResourceDescriptorError::EmptyId);
    }
    if value.len() > MAX_RESOURCE_ID_LENGTH {
        return Err(ResourceDescriptorError::IdTooLong {
            max: MAX_RESOURCE_ID_LENGTH,
        });
    }
    if !valid_identifier(&value) {
        return Err(ResourceDescriptorError::InvalidId);
    }
    Ok(value)
}

fn normalize_resource_name(value: impl Into<String>) -> Result<String, ResourceDescriptorError> {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        return Err(ResourceDescriptorError::EmptyName);
    }
    if value.len() > MAX_RESOURCE_NAME_LENGTH {
        return Err(ResourceDescriptorError::NameTooLong {
            max: MAX_RESOURCE_NAME_LENGTH,
        });
    }
    if value.chars().any(char::is_control) {
        return Err(ResourceDescriptorError::InvalidName);
    }
    Ok(value)
}

fn normalize_resource_label_key(
    value: impl Into<String>,
) -> Result<String, ResourceDescriptorError> {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        return Err(ResourceDescriptorError::EmptyLabelKey);
    }
    if value.len() > MAX_RESOURCE_LABEL_KEY_LENGTH {
        return Err(ResourceDescriptorError::LabelKeyTooLong {
            max: MAX_RESOURCE_LABEL_KEY_LENGTH,
        });
    }
    if !valid_identifier(&value) {
        return Err(ResourceDescriptorError::InvalidLabelKey);
    }
    Ok(value)
}

fn normalize_resource_label_value(
    key: &str,
    value: impl Into<String>,
) -> Result<String, ResourceDescriptorError> {
    let value = value.into().trim().to_owned();
    if value.is_empty() {
        return Err(ResourceDescriptorError::EmptyLabelValue {
            key: key.to_owned(),
        });
    }
    if value.len() > MAX_RESOURCE_LABEL_VALUE_LENGTH {
        return Err(ResourceDescriptorError::LabelValueTooLong {
            key: key.to_owned(),
            max: MAX_RESOURCE_LABEL_VALUE_LENGTH,
        });
    }
    if value.chars().any(char::is_control) {
        return Err(ResourceDescriptorError::InvalidLabelValue {
            key: key.to_owned(),
        });
    }
    Ok(value)
}

fn valid_identifier(value: &str) -> bool {
    !value.is_empty()
        && value
            .bytes()
            .all(|byte| byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'_' | b'.' | b':'))
}

fn normalize_message(value: impl Into<String>, fallback: &str) -> String {
    normalize_optional_message(value).unwrap_or_else(|| fallback.to_owned())
}

fn normalize_optional_message(value: impl Into<String>) -> Option<String> {
    crate::text::normalize_message(value, MAX_RESOURCE_MESSAGE_LENGTH)
}