footing 0.5.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
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
use std::{borrow::Cow, fmt};

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

use crate::http::{IdempotencyRequestPolicy, RateLimitRequestPolicy};
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, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// A borrowed or owned endpoint path, retaining its literal/template distinction.
///
/// Use [`Self::exact`] and [`Self::template`] in constant contracts. Runtime paths
/// can use `EndpointPathPattern::Exact(path.into())` or `Template(path.into())`.
/// Owning mounted paths lets routers compose without leaking strings.
pub enum EndpointPathPattern {
    /// A literal absolute path without captures.
    Exact(Cow<'static, str>),
    /// An absolute path with optional whole-segment captures such as `{user_id}`.
    /// Capture names contain ASCII letters, digits or underscores. Empty path
    /// segments and trailing slashes are preserved; catch-all and mixed literal
    /// capture segments are not supported.
    Template(Cow<'static, str>),
}

impl EndpointPathPattern {
    /// Creates a borrowed literal path, including in constant contracts.
    #[must_use]
    pub const fn exact(path: &'static str) -> Self {
        Self::Exact(Cow::Borrowed(path))
    }

    /// Creates a borrowed template path, including in constant contracts.
    #[must_use]
    pub const fn template(path: &'static str) -> Self {
        Self::Template(Cow::Borrowed(path))
    }

    #[must_use]
    /// Returns this value as str.
    pub fn as_str(&self) -> &str {
        match self {
            Self::Exact(path) | Self::Template(path) => 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> {
    /// No additional permission check; authentication is specified by [`EndpointAuth`].
    None,
    /// Indicates one.
    One(P),
    /// Indicates any.
    Any(&'static [P]),
    /// Indicates all.
    All(&'static [P]),
}

impl<P: Copy + 'static> EndpointPermissions<P> {
    #[must_use]
    /// Returns whether no additional permission check is required.
    pub const fn is_none(self) -> bool {
        matches!(self, Self::None)
    }

    #[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::None => 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::None | 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::None => 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 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 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]
/// Reusable application policies, independent of an endpoint's route and pagination.
///
/// Idempotency and rate limiting use the same policy types as the middleware.
/// Defaults describe a public, low-risk endpoint with permissions, auditing,
/// idempotency and rate limiting disabled, matching
/// [`crate::http::HttpMiddlewareConfig::standard`]. Enable rate limiting explicitly
/// in both the policy and middleware when required. These are declarations;
/// constructing a policy does not install authentication or permission checks.
/// Validate contracts against the middleware when assembling routes.
pub struct EndpointPolicy<P: Copy + 'static = &'static str> {
    auth: EndpointAuth,
    permissions: EndpointPermissions<P>,
    risk: EndpointRisk,
    idempotency: IdempotencyRequestPolicy,
    rate_limit: RateLimitRequestPolicy,
    audit: EndpointAudit,
}

impl<P: Copy + 'static> Default for EndpointPolicy<P> {
    fn default() -> Self {
        EndpointPolicy::new().with_permissions(EndpointPermissions::None)
    }
}

impl EndpointPolicy {
    #[must_use]
    /// Creates the default policy without needing a permission-type annotation.
    ///
    /// String permissions are the initial type. [`Self::with_permissions`] infers
    /// a custom type from its argument. This constructor also works in constants.
    pub const fn new() -> Self {
        Self {
            auth: EndpointAuth::Public,
            permissions: EndpointPermissions::None,
            risk: EndpointRisk::Low,
            idempotency: IdempotencyRequestPolicy::Disabled,
            rate_limit: RateLimitRequestPolicy::Disabled,
            audit: EndpointAudit::None,
        }
    }
}

impl<P: Copy + 'static> EndpointPolicy<P> {
    #[must_use]
    /// Declares the identity category required by the endpoint.
    pub const fn with_auth(mut self, auth: EndpointAuth) -> Self {
        self.auth = auth;
        self
    }

    #[must_use]
    /// Declares the permissions the application must enforce after authentication.
    /// The returned policy adopts their type and preserves all other settings.
    ///
    /// ```rust
    /// use footing::http::{EndpointAuth, EndpointPermissions, EndpointPolicy};
    ///
    /// #[derive(Clone, Copy)]
    /// enum Permission { Read }
    ///
    /// let policy = EndpointPolicy::new()
    ///     .with_auth(EndpointAuth::Authenticated)
    ///     .with_permissions(EndpointPermissions::One(Permission::Read));
    /// ```
    pub const fn with_permissions<Q: Copy + 'static>(
        self,
        permissions: EndpointPermissions<Q>,
    ) -> EndpointPolicy<Q> {
        EndpointPolicy {
            auth: self.auth,
            permissions,
            risk: self.risk,
            idempotency: self.idempotency,
            rate_limit: self.rate_limit,
            audit: self.audit,
        }
    }

    #[must_use]
    /// Sets the endpoint's operational risk classification.
    pub const fn with_risk(mut self, risk: EndpointRisk) -> Self {
        self.risk = risk;
        self
    }

    #[must_use]
    /// Declares the idempotency policy the middleware must apply to this endpoint.
    pub const fn with_idempotency(mut self, idempotency: IdempotencyRequestPolicy) -> Self {
        self.idempotency = idempotency;
        self
    }

    #[must_use]
    /// Declares whether the middleware must rate-limit this endpoint.
    /// `Disabled` explicitly exempts it from rate limiting.
    pub const fn with_rate_limit(mut self, rate_limit: RateLimitRequestPolicy) -> Self {
        self.rate_limit = rate_limit;
        self
    }

    #[must_use]
    /// Declares the endpoint's audit requirement.
    pub const fn with_audit(mut self, audit: EndpointAudit) -> Self {
        self.audit = audit;
        self
    }

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

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

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

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

    /// Returns whether rate limiting is required.
    #[must_use]
    pub const fn rate_limit(&self) -> RateLimitRequestPolicy {
        self.rate_limit
    }

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

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// A route, its pagination mode and the application policies enforced around it.
///
/// Use this directly with [`super::EndpointRouter`] or standalone contract
/// registries. Documented routes derive identity and pagination automatically;
/// configure their application policies with [`EndpointPolicy`]. Contracts can
/// own paths produced by module nesting.
pub struct EndpointContract<P: Copy + 'static = &'static str> {
    method: EndpointMethod,
    path: EndpointPathPattern,
    policy: EndpointPolicy<P>,
    pagination: EndpointPagination,
}

impl EndpointContract {
    #[must_use]
    /// Describes an endpoint with [`EndpointPolicy::new`] and no pagination.
    ///
    /// The default contract matches [`crate::http::HttpMiddlewareConfig::standard`]
    /// and needs no permission-type annotation. [`Self::with_policy`] and
    /// [`Self::with_permissions`] infer custom permission types from their arguments.
    /// Creating a contract does not install middleware; validate its policies when
    /// assembling routes.
    pub const fn new(method: EndpointMethod, path: EndpointPathPattern) -> Self {
        Self::from_policy(method, path, EndpointPolicy::new())
    }
}

impl<P: Copy + 'static> EndpointContract<P> {
    /// Combines a route and policy, including in constant permission tables.
    ///
    /// The permission type is inferred from `policy`. Both borrowed and owned
    /// paths are accepted; constant declarations use a borrowed path.
    /// Pagination defaults to [`EndpointPagination::None`].
    ///
    /// ```rust
    /// use footing::http::{EndpointAuth, EndpointContract, EndpointMethod,
    ///     EndpointPathPattern, EndpointPermissions, EndpointPolicy};
    ///
    /// #[derive(Clone, Copy)]
    /// enum Permission { UsersRead }
    ///
    /// const READ: EndpointPolicy<Permission> = EndpointPolicy::new()
    ///     .with_auth(EndpointAuth::Authenticated)
    ///     .with_permissions(EndpointPermissions::One(Permission::UsersRead));
    /// static ROUTES: &[EndpointContract<Permission>] = &[
    ///     EndpointContract::from_policy(
    ///         EndpointMethod::Get, EndpointPathPattern::exact("/users"), READ,
    ///     ),
    /// ];
    /// ```
    #[must_use]
    pub const fn from_policy(
        method: EndpointMethod,
        path: EndpointPathPattern,
        policy: EndpointPolicy<P>,
    ) -> Self {
        Self {
            method,
            path,
            policy,
            pagination: EndpointPagination::None,
        }
    }

    /// Replaces all application policies, preserving the route and pagination.
    /// The returned contract adopts the supplied policy's permission type.
    /// Use [`Self::from_policy`] when declaring a constant contract.
    #[must_use]
    pub fn with_policy<Q: Copy + 'static>(self, policy: EndpointPolicy<Q>) -> EndpointContract<Q> {
        EndpointContract {
            method: self.method,
            path: self.path,
            policy,
            pagination: self.pagination,
        }
    }

    /// Declares the identity category required by the endpoint.
    #[must_use]
    pub const fn with_auth(mut self, auth: EndpointAuth) -> Self {
        self.policy = self.policy.with_auth(auth);
        self
    }

    /// Declares the permissions the application must enforce after authentication.
    /// The returned contract adopts their type, preserving its route and other policies.
    /// For constants, set permissions on an [`EndpointPolicy`] and use [`Self::from_policy`].
    #[must_use]
    pub fn with_permissions<Q: Copy + 'static>(
        self,
        permissions: EndpointPermissions<Q>,
    ) -> EndpointContract<Q> {
        let policy = self.policy.with_permissions(permissions);
        self.with_policy(policy)
    }

    /// Sets the endpoint's operational risk classification.
    #[must_use]
    pub const fn with_risk(mut self, risk: EndpointRisk) -> Self {
        self.policy = self.policy.with_risk(risk);
        self
    }

    /// Declares the idempotency policy the middleware must apply to this endpoint.
    #[must_use]
    pub const fn with_idempotency(mut self, idempotency: IdempotencyRequestPolicy) -> Self {
        self.policy = self.policy.with_idempotency(idempotency);
        self
    }

    /// Declares the handler's pagination mode for manual contract registration.
    #[must_use]
    pub const fn with_pagination(mut self, pagination: EndpointPagination) -> Self {
        self.pagination = pagination;
        self
    }

    /// Declares whether the middleware must rate-limit this endpoint.
    /// `Disabled` explicitly exempts it from rate limiting.
    #[must_use]
    pub const fn with_rate_limit(mut self, rate_limit: RateLimitRequestPolicy) -> Self {
        self.policy = self.policy.with_rate_limit(rate_limit);
        self
    }

    /// Declares the endpoint's audit requirement.
    #[must_use]
    pub const fn with_audit(mut self, audit: EndpointAudit) -> Self {
        self.policy = self.policy.with_audit(audit);
        self
    }

    /// Returns the application policies for reuse on other endpoints.
    #[must_use]
    pub const fn policy(&self) -> EndpointPolicy<P> {
        self.policy
    }

    #[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
    }

    #[cfg(feature = "openapi")]
    pub(crate) fn set_path(&mut self, path: String) {
        self.path = match &self.path {
            EndpointPathPattern::Exact(_) => EndpointPathPattern::Exact(path.into()),
            EndpointPathPattern::Template(_) => EndpointPathPattern::Template(path.into()),
        };
    }

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

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

    #[must_use]
    /// Returns whether access requires more than an authenticated identity.
    ///
    /// Identity categories (`User`, `Client`, `Admin`, `Service`) and explicit
    /// permissions must be checked before replaying an idempotent response.
    pub const fn requires_authorization(&self) -> bool {
        !matches!(
            self.auth(),
            EndpointAuth::Public | EndpointAuth::Authenticated
        ) || !self.permissions().is_none()
    }

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

    #[must_use]
    /// Returns the idempotency.
    pub const fn idempotency(&self) -> IdempotencyRequestPolicy {
        self.policy.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) -> RateLimitRequestPolicy {
        self.policy.rate_limit()
    }

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