footing 0.4.2

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
use std::{borrow::Cow, error::Error, fmt};

/// Thread-safe boxed error used at generic service boundaries.
pub type BoxError = Box<dyn std::error::Error + Send + Sync + 'static>;
/// Convenience result type using [`BoxError`] by default.
pub type Result<T, E = BoxError> = std::result::Result<T, E>;

/// Default error code.
pub const DEFAULT_ERROR_CODE: &str = "unknown_error";
/// Maximum supported error code length.
pub const MAX_ERROR_CODE_LENGTH: usize = 128;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Classification of error.
pub enum ErrorKind {
    /// Indicates validation.
    Validation,
    /// Indicates authentication.
    Authentication,
    /// Indicates authorization.
    Authorization,
    /// Indicates not found.
    NotFound,
    /// Indicates conflict.
    Conflict,
    /// Indicates rate limit.
    RateLimit,
    /// Indicates timeout.
    Timeout,
    /// Indicates dependency.
    Dependency,
    /// Indicates unavailable.
    Unavailable,
    /// Indicates internal.
    Internal,
}

impl ErrorKind {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Validation => "validation",
            Self::Authentication => "authentication",
            Self::Authorization => "authorization",
            Self::NotFound => "not_found",
            Self::Conflict => "conflict",
            Self::RateLimit => "rate_limit",
            Self::Timeout => "timeout",
            Self::Dependency => "dependency",
            Self::Unavailable => "unavailable",
            Self::Internal => "internal",
        }
    }

    #[must_use]
    /// Returns the retryable.
    pub const fn retryable(self) -> bool {
        matches!(
            self,
            Self::RateLimit | Self::Timeout | Self::Dependency | Self::Unavailable
        )
    }

    #[must_use]
    /// Returns the client fault.
    pub const fn client_fault(self) -> bool {
        matches!(
            self,
            Self::Validation
                | Self::Authentication
                | Self::Authorization
                | Self::NotFound
                | Self::Conflict
                | Self::RateLimit
        )
    }
}

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

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
/// Validated stable identifier used to classify an error.
pub struct ErrorCode(Cow<'static, str>);

impl ErrorCode {
    /// Attempts to create and validate an error code.
    pub fn try_new(value: impl Into<String>) -> std::result::Result<Self, ErrorCodeError> {
        let value = value.into().trim().to_owned();
        validate_error_code(&value)?;
        Ok(Self(Cow::Owned(value)))
    }

    /// Creates a value from parts.
    pub fn from_parts(
        parts: impl IntoIterator<Item = impl AsRef<str>>,
    ) -> std::result::Result<Self, ErrorCodeError> {
        let mut code = String::new();
        for part in parts {
            let part = part.as_ref().trim();
            if part.is_empty() {
                return Err(ErrorCodeError::Empty);
            }
            if !code.is_empty() {
                code.push('_');
            }
            code.push_str(part);
        }
        Self::try_new(code)
    }

    pub(crate) const fn internal(value: &'static str) -> Self {
        Self(Cow::Borrowed(value))
    }

    #[must_use]
    /// Returns the generic code for errors that intentionally have no finer classification.
    pub const fn unknown() -> Self {
        Self(Cow::Borrowed(DEFAULT_ERROR_CODE))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        &self.0
    }

    #[must_use]
    /// Consumes this value and returns string.
    pub fn into_string(self) -> String {
        self.0.into_owned()
    }
}

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

impl PartialEq<&str> for ErrorCode {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Errors that can occur while handling error code.
pub enum ErrorCodeError {
    /// Indicates empty.
    Empty,
    /// The value exceeds the supported length.
    TooLong {
        #[doc = "The configured upper bound."]
        max: usize,
    },
    /// The characters is invalid.
    InvalidCharacters,
}

impl fmt::Display for ErrorCodeError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Empty => formatter.write_str("error code must not be empty"),
            Self::TooLong { max } => {
                write!(
                    formatter,
                    "error code must be less than or equal to {max} bytes"
                )
            }
            Self::InvalidCharacters => {
                formatter.write_str("error code contains unsupported characters")
            }
        }
    }
}

impl Error for ErrorCodeError {}

impl ClassifyError for ErrorCodeError {
    fn error_kind(&self) -> ErrorKind {
        ErrorKind::Validation
    }

    fn error_code(&self) -> ErrorCode {
        ErrorCode::internal(match self {
            Self::Empty => "error_code_empty",
            Self::TooLong { .. } => "error_code_too_long",
            Self::InvalidCharacters => "error_code_invalid_characters",
        })
    }
}

#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Represents error descriptor.
pub struct ErrorDescriptor {
    kind: ErrorKind,
    code: ErrorCode,
    message: String,
    retryable: bool,
    visibility: ErrorVisibility,
}

impl fmt::Debug for ErrorDescriptor {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter
            .debug_struct("ErrorDescriptor")
            .field("kind", &self.kind)
            .field("code", &self.code)
            .field("message", &"[REDACTED]")
            .field("retryable", &self.retryable)
            .field("visibility", &self.visibility)
            .finish()
    }
}

impl ErrorDescriptor {
    #[must_use]
    /// Creates a new instance.
    pub fn new(kind: ErrorKind, code: ErrorCode, message: impl Into<String>) -> Self {
        Self {
            kind,
            code,
            message: normalize_error_message(kind, message),
            retryable: kind.retryable(),
            visibility: ErrorVisibility::default_for_kind(kind),
        }
    }

    /// Attempts to create a descriptor from a dynamic error code.
    pub fn try_new(
        kind: ErrorKind,
        code: impl Into<String>,
        message: impl Into<String>,
    ) -> std::result::Result<Self, ErrorCodeError> {
        Ok(Self::new(kind, ErrorCode::try_new(code)?, message))
    }

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

    #[must_use]
    /// Returns the code.
    pub fn code(&self) -> &ErrorCode {
        &self.code
    }

    #[must_use]
    /// Returns the message.
    pub fn message(&self) -> &str {
        &self.message
    }

    #[must_use]
    /// Returns the retryable.
    pub const fn retryable(&self) -> bool {
        self.retryable
    }

    #[must_use]
    /// Returns the visibility.
    pub const fn visibility(&self) -> ErrorVisibility {
        self.visibility
    }

    #[must_use]
    /// Returns the public message.
    pub fn public_message(&self) -> &str {
        if self.visibility.exposes_message() {
            self.message()
        } else {
            generic_error_message(self.kind)
        }
    }

    #[must_use]
    /// Configures retryable and returns the updated value.
    pub const fn with_retryable(mut self, retryable: bool) -> Self {
        self.retryable = retryable;
        self
    }

    #[must_use]
    /// Configures visibility and returns the updated value.
    pub const fn with_visibility(mut self, visibility: ErrorVisibility) -> Self {
        self.visibility = visibility;
        self
    }

    #[must_use]
    /// Configures public message and returns the updated value.
    pub const fn with_public_message(self) -> Self {
        self.with_visibility(ErrorVisibility::Public)
    }

    #[must_use]
    /// Configures private message and returns the updated value.
    pub const fn with_private_message(self) -> Self {
        self.with_visibility(ErrorVisibility::Private)
    }
}

fn normalize_error_message(kind: ErrorKind, message: impl Into<String>) -> String {
    let message = message.into().trim().to_owned();
    if message.is_empty() {
        generic_error_message(kind).to_owned()
    } else {
        message
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported error visibility values.
pub enum ErrorVisibility {
    /// Indicates public.
    Public,
    /// Indicates private.
    Private,
}

impl ErrorVisibility {
    #[must_use]
    /// Creates default for kind.
    pub const fn default_for_kind(kind: ErrorKind) -> Self {
        if kind.client_fault() {
            Self::Public
        } else {
            Self::Private
        }
    }

    #[must_use]
    /// Returns the exposes message.
    pub const fn exposes_message(self) -> bool {
        matches!(self, Self::Public)
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported error log level values.
pub enum ErrorLogLevel {
    /// Indicates debug.
    Debug,
    /// Indicates info.
    Info,
    /// Indicates warn.
    Warn,
    /// Indicates error.
    Error,
}

#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
/// Decision produced by error boundary.
pub struct ErrorBoundaryDecision {
    descriptor: ErrorDescriptor,
    alert: bool,
}

impl ErrorBoundaryDecision {
    #[must_use]
    /// Returns the descriptor.
    pub const fn descriptor(&self) -> &ErrorDescriptor {
        &self.descriptor
    }

    #[must_use]
    /// Returns the log level.
    pub const fn log_level(&self) -> ErrorLogLevel {
        log_level_for_kind(self.descriptor.kind())
    }

    #[must_use]
    /// Returns the alert.
    pub const fn alert(&self) -> bool {
        self.alert
    }

    #[must_use]
    /// Returns the public message.
    pub fn public_message(&self) -> &str {
        self.descriptor.public_message()
    }

    #[must_use]
    /// Consumes this value and returns descriptor.
    pub fn into_descriptor(self) -> ErrorDescriptor {
        self.descriptor
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
/// Policy controlling error boundary.
pub struct ErrorBoundaryPolicy {
    expose_server_error_messages: bool,
    alert_internal_errors: bool,
}

impl Default for ErrorBoundaryPolicy {
    fn default() -> Self {
        Self::new()
    }
}

impl ErrorBoundaryPolicy {
    #[must_use]
    /// Creates a new instance.
    pub const fn new() -> Self {
        Self {
            expose_server_error_messages: false,
            alert_internal_errors: true,
        }
    }

    #[must_use]
    /// Creates cli.
    pub const fn cli() -> Self {
        Self {
            expose_server_error_messages: true,
            alert_internal_errors: false,
        }
    }

    #[must_use]
    /// Creates trusted internal.
    pub const fn trusted_internal() -> Self {
        Self {
            expose_server_error_messages: true,
            alert_internal_errors: true,
        }
    }

    #[must_use]
    /// Returns the exposes server error messages.
    pub const fn exposes_server_error_messages(self) -> bool {
        self.expose_server_error_messages
    }

    #[must_use]
    /// Returns the alerts internal errors.
    pub const fn alerts_internal_errors(self) -> bool {
        self.alert_internal_errors
    }

    #[must_use]
    /// Controls whether server error messages are exposed.
    ///
    /// Client error visibility is preserved, including explicitly private messages.
    pub const fn with_server_error_messages(mut self, expose: bool) -> Self {
        self.expose_server_error_messages = expose;
        self
    }

    #[must_use]
    /// Configures internal error alerts and returns the updated value.
    pub const fn with_internal_error_alerts(mut self, alert: bool) -> Self {
        self.alert_internal_errors = alert;
        self
    }

    #[must_use]
    /// Determines the value.
    pub fn decide<E>(&self, error: &E) -> ErrorBoundaryDecision
    where
        E: ClassifyError + ?Sized,
    {
        self.decide_descriptor(error.error_descriptor())
    }

    #[must_use]
    /// Determines descriptor.
    pub fn decide_descriptor(&self, descriptor: ErrorDescriptor) -> ErrorBoundaryDecision {
        let kind = descriptor.kind();
        let descriptor = if self.expose_server_error_messages && !kind.client_fault() {
            descriptor.with_public_message()
        } else {
            descriptor
        };
        ErrorBoundaryDecision {
            descriptor,
            alert: self.alert_internal_errors && matches!(kind, ErrorKind::Internal),
        }
    }
}

#[must_use]
/// Returns the generic public message for an error kind.
pub const fn generic_error_message(kind: ErrorKind) -> &'static str {
    match kind {
        ErrorKind::Validation => "request validation failed",
        ErrorKind::Authentication => "authentication is required",
        ErrorKind::Authorization => "permission is denied",
        ErrorKind::NotFound => "resource was not found",
        ErrorKind::Conflict => "resource conflict",
        ErrorKind::RateLimit => "too many requests",
        ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => {
            "service is unavailable"
        }
        ErrorKind::Internal => "internal server error",
    }
}

const fn log_level_for_kind(kind: ErrorKind) -> ErrorLogLevel {
    match kind {
        ErrorKind::Validation
        | ErrorKind::Authentication
        | ErrorKind::Authorization
        | ErrorKind::NotFound
        | ErrorKind::Conflict => ErrorLogLevel::Info,
        ErrorKind::RateLimit => ErrorLogLevel::Debug,
        ErrorKind::Timeout | ErrorKind::Dependency | ErrorKind::Unavailable => ErrorLogLevel::Warn,
        ErrorKind::Internal => ErrorLogLevel::Error,
    }
}

/// Provides stable classification and public metadata for an error.
pub trait ClassifyError: fmt::Display {
    /// Returns the error kind.
    fn error_kind(&self) -> ErrorKind;

    /// Returns the stable machine-readable error code.
    fn error_code(&self) -> ErrorCode;

    /// Returns the error descriptor.
    fn error_descriptor(&self) -> ErrorDescriptor {
        ErrorDescriptor::new(self.error_kind(), self.error_code(), self.to_string())
    }
}

impl ClassifyError for ErrorDescriptor {
    fn error_kind(&self) -> ErrorKind {
        self.kind
    }

    fn error_code(&self) -> ErrorCode {
        self.code.clone()
    }

    fn error_descriptor(&self) -> ErrorDescriptor {
        self.clone()
    }
}

fn validate_error_code(value: &str) -> std::result::Result<(), ErrorCodeError> {
    if value.is_empty() {
        return Err(ErrorCodeError::Empty);
    }
    if value.len() > MAX_ERROR_CODE_LENGTH {
        return Err(ErrorCodeError::TooLong {
            max: MAX_ERROR_CODE_LENGTH,
        });
    }
    if !value
        .bytes()
        .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
    {
        return Err(ErrorCodeError::InvalidCharacters);
    }
    Ok(())
}