footing 0.1.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
//! Resource descriptors, probe results, reports, and summaries.

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

use serde::{Deserialize, Serialize};

use super::error::{ResourceDescriptorError, 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 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;
/// 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, 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.
    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.
    pub id: String,
    /// Human-readable resource name.
    pub name: String,
    /// Infrastructure category of the resource.
    pub kind: ResourceKind,
    /// Whether a failure blocks service readiness.
    pub criticality: ResourceCriticality,
    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
    /// Bounded metadata attached to the resource.
    pub 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)?;
        self.labels.insert(key, value);
        Ok(self)
    }

    pub(super) fn validate(&self) -> Result<(), ResourceDescriptorError> {
        normalize_resource_id(&self.id)?;
        normalize_resource_name(&self.name)?;
        for (key, value) in &self.labels {
            normalize_resource_label_key(key)?;
            normalize_resource_label_value(key, value)?;
        }
        Ok(())
    }
}

#[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.
    pub resource: ResourceDescriptor,
    /// Health status returned by the probe.
    pub status: ResourceStatus,
    /// Short operator-facing result summary.
    pub summary: String,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Additional diagnostic observations.
    pub details: Vec<String>,
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    /// Suggested recovery actions.
    pub 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.
    #[must_use]
    pub fn with_detail(mut self, detail: impl Into<String>) -> Self {
        if let Some(detail) = normalize_optional_message(detail) {
            self.details.push(detail);
        }
        self
    }

    /// Adds one operator-facing remediation hint.
    #[must_use]
    pub fn with_remediation(mut self, remediation: impl Into<String>) -> Self {
        if let Some(remediation) = normalize_optional_message(remediation) {
            self.remediations.push(remediation);
        }
        self
    }

    /// 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 = ResourceDescriptorError;

    fn try_from(value: ResourceDiagnosticWire) -> Result<Self, Self::Error> {
        value.resource.validate()?;
        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.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(try_from = "ResourceDiagnosticsReportWire")]
#[non_exhaustive]
pub struct ResourceDiagnosticsReport {
    /// Service instance represented by this report.
    pub service_name: String,
    /// Aggregate status derived from all resources.
    pub status: ResourceStatus,
    /// Counts grouped by status and readiness impact.
    pub summary: ResourceDiagnosticsSummary,
    /// Individual resource results.
    pub 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)
            .map_err(|_| ResourceRegistryError::InvalidServiceName)?;
        for (index, diagnostic) in resources.iter().enumerate() {
            diagnostic
                .resource
                .validate()
                .map_err(|source| ResourceRegistryError::InvalidDescriptor { index, source })?;
        }
        let status = aggregate_status(&resources);
        let summary = ResourceDiagnosticsSummary::from_diagnostics(&resources);
        Ok(Self {
            service_name,
            status,
            summary,
            resources,
        })
    }

    /// Returns true when no required resource is unhealthy.
    #[must_use]
    pub fn ready(&self) -> bool {
        self.resources
            .iter()
            .all(|diagnostic| !diagnostic.readiness_blocking())
    }

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

#[derive(Deserialize)]
struct ResourceDiagnosticsReportWire {
    service_name: String,
    #[serde(default, rename = "status")]
    _status: Option<ResourceStatus>,
    #[serde(default, rename = "summary")]
    _summary: Option<ResourceDiagnosticsSummary>,
    #[serde(default)]
    resources: Vec<ResourceDiagnostic>,
}

impl TryFrom<ResourceDiagnosticsReportWire> for ResourceDiagnosticsReport {
    type Error = ResourceRegistryError;

    fn try_from(value: ResourceDiagnosticsReportWire) -> Result<Self, Self::Error> {
        Self::new(value.service_name, value.resources)
    }
}

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

impl ResourceDiagnosticsSummary {
    #[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| diagnostic.status == ResourceStatus::Unhealthy)
    {
        return ResourceStatus::Degraded;
    }
    if resources
        .iter()
        .any(|diagnostic| diagnostic.status == 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 valid_identifier(&value) {
        Ok(value)
    } else {
        Err(ResourceRegistryError::InvalidServiceName)
    }
}

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 {
    let mut value = value
        .into()
        .trim()
        .chars()
        .filter(|character| !character.is_control())
        .collect::<String>();
    if value.is_empty() {
        fallback.to_owned()
    } else {
        truncate_resource_message(&mut value);
        value
    }
}

fn normalize_optional_message(value: impl Into<String>) -> Option<String> {
    let mut value = value
        .into()
        .trim()
        .chars()
        .filter(|character| !character.is_control())
        .collect::<String>();
    if value.is_empty() {
        return None;
    }
    truncate_resource_message(&mut value);
    Some(value)
}

fn truncate_resource_message(value: &mut String) {
    if value.len() <= MAX_RESOURCE_MESSAGE_LENGTH {
        return;
    }

    value.truncate(MAX_RESOURCE_MESSAGE_LENGTH);
    while !value.is_char_boundary(value.len()) {
        value.pop();
    }
}