footing 0.1.6

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
use std::fmt;

use axum::http::Method;
use thiserror::Error;

use crate::result::{ClassifyError, ErrorKind};

/// HTTP method used by endpoint contracts.
///
/// The type is intentionally small and copyable so route contracts can be kept
/// in static slices without pulling a full OpenAPI model into application code.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum EndpointMethod {
    /// Indicates delete.
    Delete,
    /// Indicates get.
    Get,
    /// Indicates head.
    Head,
    /// Indicates options.
    Options,
    /// Indicates patch.
    Patch,
    /// Indicates post.
    Post,
    /// Indicates put.
    Put,
}

impl EndpointMethod {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Delete => "DELETE",
            Self::Get => "GET",
            Self::Head => "HEAD",
            Self::Options => "OPTIONS",
            Self::Patch => "PATCH",
            Self::Post => "POST",
            Self::Put => "PUT",
        }
    }

    #[must_use]
    /// Returns whether this value is safe.
    pub const fn is_safe(self) -> bool {
        matches!(self, Self::Get | Self::Head | Self::Options)
    }
}

impl TryFrom<&Method> for EndpointMethod {
    type Error = EndpointMethodError;

    fn try_from(method: &Method) -> Result<Self, Self::Error> {
        match method.as_str() {
            "DELETE" => Ok(Self::Delete),
            "GET" => Ok(Self::Get),
            "HEAD" => Ok(Self::Head),
            "OPTIONS" => Ok(Self::Options),
            "PATCH" => Ok(Self::Patch),
            "POST" => Ok(Self::Post),
            "PUT" => Ok(Self::Put),
            _ => Err(EndpointMethodError),
        }
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Error)]
#[error("HTTP method is not supported by endpoint contracts")]
/// Errors that can occur while handling endpoint method.
pub struct EndpointMethodError;

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

    fn error_code(&self) -> crate::result::ErrorCode {
        crate::result::ErrorCode::internal("endpoint_method_unsupported")
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint path pattern values.
pub enum EndpointPathPattern {
    /// Indicates exact.
    Exact(&'static str),
    /// Indicates template.
    Template(&'static str),
}

impl EndpointPathPattern {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Exact(path) | Self::Template(path) => path,
        }
    }

    #[must_use]
    /// Returns whether this value matches the value.
    pub fn matches(self, path: &str) -> bool {
        match self {
            Self::Exact(expected) => path == expected,
            Self::Template(template) => route_template_matches(template, path),
        }
    }
}

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint auth values.
pub enum EndpointAuth {
    /// Indicates public.
    Public,
    /// Indicates authenticated.
    Authenticated,
    /// Indicates user.
    User,
    /// Indicates client.
    Client,
    /// Indicates admin.
    Admin,
    /// Indicates service.
    Service,
}

impl EndpointAuth {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Public => "public",
            Self::Authenticated => "authenticated",
            Self::User => "user",
            Self::Client => "client",
            Self::Admin => "admin",
            Self::Service => "service",
        }
    }

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

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint permissions values.
pub enum EndpointPermissions<P: Copy + 'static = &'static str> {
    /// Indicates public.
    Public,
    /// Indicates one.
    One(P),
    /// Indicates any.
    Any(&'static [P]),
    /// Indicates all.
    All(&'static [P]),
}

impl<P: Copy + 'static> EndpointPermissions<P> {
    #[must_use]
    /// Creates public.
    pub const fn public() -> Self {
        Self::Public
    }

    #[must_use]
    /// Creates one.
    pub const fn one(permission: P) -> Self {
        Self::One(permission)
    }

    #[must_use]
    /// Creates any.
    pub const fn any(permissions: &'static [P]) -> Self {
        Self::Any(permissions)
    }

    #[must_use]
    /// Creates all.
    pub const fn all(permissions: &'static [P]) -> Self {
        Self::All(permissions)
    }

    #[must_use]
    /// Returns whether this value is public.
    pub const fn is_public(self) -> bool {
        matches!(self, Self::Public)
    }

    #[must_use]
    /// Returns whether this value is granted by.
    pub fn is_granted_by(self, mut has_permission: impl FnMut(P) -> bool) -> bool {
        match self {
            Self::Public => true,
            Self::One(permission) => has_permission(permission),
            Self::Any(permissions) => permissions.iter().copied().any(has_permission),
            Self::All(permissions) => {
                !permissions.is_empty() && permissions.iter().copied().all(has_permission)
            }
        }
    }

    #[must_use]
    /// Returns the empty requirement mode.
    pub fn empty_requirement_mode(self) -> Option<&'static str> {
        match self {
            Self::Any([]) => Some("any"),
            Self::All([]) => Some("all"),
            Self::Public | Self::One(_) | Self::Any(_) | Self::All(_) => None,
        }
    }
}

impl<P: Copy + Eq + 'static> EndpointPermissions<P> {
    #[must_use]
    /// Returns whether this value contains the value.
    pub fn contains(self, permission: P) -> bool {
        match self {
            Self::Public => false,
            Self::One(expected) => expected == permission,
            Self::Any(permissions) | Self::All(permissions) => permissions.contains(&permission),
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint risk values.
pub enum EndpointRisk {
    /// Indicates low.
    Low,
    /// Indicates medium.
    Medium,
    /// Indicates high.
    High,
    /// Indicates critical.
    Critical,
}

impl EndpointRisk {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Low => "low",
            Self::Medium => "medium",
            Self::High => "high",
            Self::Critical => "critical",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint idempotency values.
pub enum EndpointIdempotency {
    /// Indicates not applicable.
    NotApplicable,
    /// Indicates optional.
    Optional,
    /// Indicates required.
    Required,
}

impl EndpointIdempotency {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::NotApplicable => "not_applicable",
            Self::Optional => "optional",
            Self::Required => "required",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint pagination values.
pub enum EndpointPagination {
    /// Indicates none.
    None,
    /// Indicates offset.
    Offset,
    /// Indicates cursor.
    Cursor,
}

impl EndpointPagination {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Offset => "offset",
            Self::Cursor => "cursor",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint rate limit values.
pub enum EndpointRateLimit {
    /// The route is explicitly exempt from rate limiting.
    Exempt,
    /// Indicates default.
    Default,
    /// Indicates read.
    Read,
    /// Indicates write.
    Write,
    /// Indicates authentication.
    Authentication,
    /// Indicates sensitive.
    Sensitive,
    /// Indicates custom.
    Custom(&'static str),
}

impl EndpointRateLimit {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::Exempt => "exempt",
            Self::Default => "default",
            Self::Read => "read",
            Self::Write => "write",
            Self::Authentication => "authentication",
            Self::Sensitive => "sensitive",
            Self::Custom(value) => value,
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Enumerates the supported endpoint audit values.
pub enum EndpointAudit {
    /// Indicates none.
    None,
    /// Indicates optional.
    Optional,
    /// Indicates required.
    Required,
}

impl EndpointAudit {
    #[must_use]
    /// Returns this value as str.
    pub const fn as_str(self) -> &'static str {
        match self {
            Self::None => "none",
            Self::Optional => "optional",
            Self::Required => "required",
        }
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Represents endpoint contract.
pub struct EndpointContract<P: Copy + 'static = &'static str> {
    method: EndpointMethod,
    path: EndpointPathPattern,
    auth: EndpointAuth,
    permissions: EndpointPermissions<P>,
    risk: EndpointRisk,
    idempotency: EndpointIdempotency,
    pagination: EndpointPagination,
    rate_limit: EndpointRateLimit,
    audit: EndpointAudit,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// One route explicitly registered alongside an Axum router.
///
/// Axum does not expose a stable route-enumeration API, so applications use
/// this value as the auditable registration input to contract reconciliation.
pub struct EndpointRouteRegistration {
    method: EndpointMethod,
    path: EndpointPathPattern,
}

impl EndpointRouteRegistration {
    #[must_use]
    /// Creates a route registration using the same pattern passed to Axum.
    pub const fn new(method: EndpointMethod, path: EndpointPathPattern) -> Self {
        Self { method, path }
    }

    #[must_use]
    /// Returns the registered HTTP method.
    pub const fn method(self) -> EndpointMethod {
        self.method
    }

    #[must_use]
    /// Returns the registered route path.
    pub const fn path(self) -> EndpointPathPattern {
        self.path
    }
}

impl<P: Copy + 'static> EndpointContract<P> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(method: EndpointMethod, path: EndpointPathPattern) -> Self {
        Self {
            method,
            path,
            auth: EndpointAuth::Public,
            permissions: EndpointPermissions::Public,
            risk: EndpointRisk::Low,
            idempotency: EndpointIdempotency::NotApplicable,
            pagination: EndpointPagination::None,
            rate_limit: EndpointRateLimit::Default,
            audit: EndpointAudit::None,
        }
    }

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

    #[must_use]
    /// Configures permissions and returns the updated value.
    pub const fn with_permissions(mut self, permissions: EndpointPermissions<P>) -> Self {
        self.permissions = permissions;
        self
    }

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

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

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

    #[must_use]
    /// Configures rate limit and returns the updated value.
    pub const fn with_rate_limit(mut self, rate_limit: EndpointRateLimit) -> Self {
        self.rate_limit = rate_limit;
        self
    }

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

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

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

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

    #[must_use]
    /// Returns the permissions.
    pub const fn permissions(&self) -> EndpointPermissions<P> {
        self.permissions
    }

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

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

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

    #[must_use]
    /// Returns the rate limit.
    pub const fn rate_limit(&self) -> EndpointRateLimit {
        self.rate_limit
    }

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

    #[must_use]
    /// Returns whether this value matches the value.
    pub fn matches(self, method: &Method, path: &str) -> bool {
        EndpointMethod::try_from(method)
            .is_ok_and(|method| self.method == method && self.path.matches(path))
    }
}

fn route_template_matches(template: &str, path: &str) -> bool {
    let Some(template) = template.strip_prefix('/') else {
        return false;
    };
    let Some(path) = path.strip_prefix('/') else {
        return false;
    };

    let mut template_segments = template.split('/');
    let mut path_segments = path.split('/');
    loop {
        match (template_segments.next(), path_segments.next()) {
            (None, None) => return true,
            (Some(template_segment), Some(path_segment))
                if route_segment_matches(template_segment, path_segment) => {}
            _ => return false,
        }
    }
}

pub(super) fn route_segment_matches(template_segment: &str, path_segment: &str) -> bool {
    if path_segment.is_empty() {
        return false;
    }
    if let Some(parameter) = template_segment
        .strip_prefix('{')
        .and_then(|segment| segment.strip_suffix('}'))
    {
        return !parameter.is_empty()
            && parameter
                .bytes()
                .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_');
    }

    template_segment == path_segment
}