footing 0.1.0

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
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
use std::{borrow::Cow, collections::BTreeMap, fmt};

use axum::http::Method;
use serde::{Deserialize, Serialize};
use thiserror::Error;

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

const MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH: usize = 64;

/// 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> {
        if method == Method::DELETE {
            Ok(Self::Delete)
        } else if method == Method::GET {
            Ok(Self::Get)
        } else if method == Method::HEAD {
            Ok(Self::Head)
        } else if method == Method::OPTIONS {
            Ok(Self::Options)
        } else if method == Method::PATCH {
            Ok(Self::Patch)
        } else if method == Method::POST {
            Ok(Self::Post)
        } else if method == Method::PUT {
            Ok(Self::Put)
        } else {
            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) -> Cow<'static, str> {
        Cow::Borrowed("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 {
    /// 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::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,
}

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))
    }

    #[must_use]
    /// Returns the document.
    pub fn document(self, permission_to_string: impl Fn(P) -> String) -> EndpointContractDocument {
        EndpointContractDocument {
            method: self.method.as_str().to_owned(),
            path: self.path.as_str().to_owned(),
            path_kind: match self.path {
                EndpointPathPattern::Exact(_) => "exact",
                EndpointPathPattern::Template(_) => "template",
            }
            .to_owned(),
            auth: self.auth.as_str().to_owned(),
            permissions: document_permissions(self.permissions, permission_to_string),
            risk: self.risk.as_str().to_owned(),
            idempotency: self.idempotency.as_str().to_owned(),
            pagination: self.pagination.as_str().to_owned(),
            rate_limit: self.rate_limit.as_str().to_owned(),
            audit: self.audit.as_str().to_owned(),
        }
    }
}

#[derive(Debug, Clone, Copy)]
/// Registry for endpoint contract.
pub struct EndpointContractRegistry<'a, P: Copy + 'static = &'static str> {
    endpoints: &'a [EndpointContract<P>],
}

impl<'a, P: Copy + 'static> EndpointContractRegistry<'a, P> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(endpoints: &'a [EndpointContract<P>]) -> Self {
        Self { endpoints }
    }

    #[must_use]
    /// Returns the endpoints.
    pub const fn endpoints(&self) -> &'a [EndpointContract<P>] {
        self.endpoints
    }

    #[must_use]
    /// Returns the find.
    pub fn find(&self, method: &Method, path: &str) -> Option<&'a EndpointContract<P>> {
        self.endpoints
            .iter()
            .find(|contract| contract.matches(method, path))
    }

    /// Validates this value.
    pub fn validate(&self) -> Result<(), EndpointContractValidationError> {
        for (index, endpoint) in self.endpoints.iter().enumerate() {
            validate_endpoint(index, endpoint)?;
            for (other_index, other) in self.endpoints.iter().enumerate().skip(index + 1) {
                if endpoint.method == other.method && endpoint.path == other.path {
                    return Err(EndpointContractValidationError::DuplicateRoute {
                        first_index: index,
                        second_index: other_index,
                        method: endpoint.method,
                        path: endpoint.path.as_str(),
                    });
                }
            }
        }
        Ok(())
    }

    #[must_use]
    /// Returns the documents.
    pub fn documents(
        &self,
        permission_to_string: impl Fn(P) -> String + Copy,
    ) -> Vec<EndpointContractDocument> {
        self.endpoints
            .iter()
            .map(|endpoint| endpoint.document(permission_to_string))
            .collect()
    }

    #[must_use]
    /// Returns an immutable snapshot.
    pub fn snapshot(
        &self,
        permission_to_string: impl Fn(P) -> String + Copy,
    ) -> EndpointContractSnapshot {
        EndpointContractSnapshot::from_contracts(self.endpoints, permission_to_string)
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
/// Represents endpoint contract document.
pub struct EndpointContractDocument {
    /// The pub value.
    pub method: String,
    /// The pub value.
    pub path: String,
    /// The pub value.
    pub path_kind: String,
    /// The pub value.
    pub auth: String,
    /// The pub value.
    pub permissions: EndpointPermissionsDocument,
    /// The pub value.
    pub risk: String,
    /// The pub value.
    pub idempotency: String,
    /// The pub value.
    pub pagination: String,
    /// The pub value.
    pub rate_limit: String,
    /// The pub value.
    pub audit: String,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
/// Represents endpoint permissions document.
pub struct EndpointPermissionsDocument {
    /// The pub value.
    pub mode: String,
    /// The pub value.
    pub values: Vec<String>,
}

/// Deterministic route-contract snapshot for tooling and startup diagnostics.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshot {
    /// The pub value.
    pub schema_version: u32,
    /// The pub value.
    pub summary: EndpointContractSnapshotSummary,
    /// The pub value.
    pub endpoints: Vec<EndpointContractDocument>,
}

impl EndpointContractSnapshot {
    /// Schema version.
    pub const SCHEMA_VERSION: u32 = 1;

    #[must_use]
    /// Creates a new instance.
    pub fn new(endpoints: Vec<EndpointContractDocument>) -> Self {
        Self {
            schema_version: Self::SCHEMA_VERSION,
            summary: EndpointContractSnapshotSummary::from_documents(&endpoints),
            endpoints,
        }
    }

    #[must_use]
    /// Creates a value from contracts.
    pub fn from_contracts<P: Copy + 'static>(
        endpoints: &[EndpointContract<P>],
        permission_to_string: impl Fn(P) -> String + Copy,
    ) -> Self {
        Self {
            schema_version: Self::SCHEMA_VERSION,
            summary: EndpointContractSnapshotSummary::from_contracts(endpoints),
            endpoints: endpoints
                .iter()
                .map(|endpoint| endpoint.document(permission_to_string))
                .collect(),
        }
    }

    /// Converts this value to pretty JSON.
    pub fn to_pretty_json(&self) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(self)
    }
}

/// Aggregated endpoint contract counts.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct EndpointContractSnapshotSummary {
    /// The pub value.
    pub total: usize,
    /// The pub value.
    pub by_auth: BTreeMap<String, usize>,
    /// The pub value.
    pub by_risk: BTreeMap<String, usize>,
    /// The pub value.
    pub by_audit: BTreeMap<String, usize>,
    /// The pub value.
    pub by_rate_limit: BTreeMap<String, usize>,
    /// The pub value.
    pub permissioned: usize,
    /// The pub value.
    pub paginated: usize,
    /// The pub value.
    pub idempotency_required: usize,
}

impl EndpointContractSnapshotSummary {
    #[must_use]
    /// Creates a value from contracts.
    pub fn from_contracts<P: Copy + 'static>(endpoints: &[EndpointContract<P>]) -> Self {
        let mut summary = Self::new(endpoints.len());

        for endpoint in endpoints {
            increment(&mut summary.by_auth, endpoint.auth.as_str());
            increment(&mut summary.by_risk, endpoint.risk.as_str());
            increment(&mut summary.by_audit, endpoint.audit.as_str());
            increment(&mut summary.by_rate_limit, endpoint.rate_limit.as_str());
            if !endpoint.permissions.is_public() {
                summary.permissioned += 1;
            }
            if endpoint.pagination != EndpointPagination::None {
                summary.paginated += 1;
            }
            if endpoint.idempotency == EndpointIdempotency::Required {
                summary.idempotency_required += 1;
            }
        }

        summary
    }

    #[must_use]
    /// Creates a value from documents.
    pub fn from_documents(endpoints: &[EndpointContractDocument]) -> Self {
        let mut summary = Self::new(endpoints.len());

        for endpoint in endpoints {
            increment(&mut summary.by_auth, &endpoint.auth);
            increment(&mut summary.by_risk, &endpoint.risk);
            increment(&mut summary.by_audit, &endpoint.audit);
            increment(&mut summary.by_rate_limit, &endpoint.rate_limit);
            if endpoint.permissions.mode != "public" {
                summary.permissioned += 1;
            }
            if endpoint.pagination != "none" {
                summary.paginated += 1;
            }
            if endpoint.idempotency == "required" {
                summary.idempotency_required += 1;
            }
        }

        summary
    }

    fn new(total: usize) -> Self {
        Self {
            total,
            by_auth: BTreeMap::new(),
            by_risk: BTreeMap::new(),
            by_audit: BTreeMap::new(),
            by_rate_limit: BTreeMap::new(),
            permissioned: 0,
            paginated: 0,
            idempotency_required: 0,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, Error)]
#[non_exhaustive]
/// Errors that can occur while handling endpoint contract validation.
pub enum EndpointContractValidationError {
    #[error("endpoint contract at index {index} has an empty path")]
    /// The path is empty.
    EmptyPath {
        #[doc = "The zero-based item index."]
        index: usize,
    },
    #[error("endpoint contract at index {index} path must start with '/'")]
    /// Indicates relative path.
    RelativePath {
        #[doc = "The zero-based item index."]
        index: usize,
        #[doc = "The affected path."]
        path: &'static str,
    },
    #[error("endpoint contract at index {index} has an invalid path: {path:?}")]
    /// The path is invalid.
    InvalidPath {
        #[doc = "The zero-based item index."]
        index: usize,
        #[doc = "The affected path."]
        path: &'static str,
    },
    #[error("endpoint contract at index {index} has an invalid template segment")]
    /// The template is invalid.
    InvalidTemplate {
        #[doc = "The zero-based item index."]
        index: usize,
        #[doc = "The affected path."]
        path: &'static str,
    },
    #[error("endpoint contract at index {index} has an invalid custom rate limit label: {value:?}")]
    /// The rate limit label is invalid.
    InvalidRateLimitLabel {
        #[doc = "The zero-based item index."]
        index: usize,
        #[doc = "The offending value."]
        value: &'static str,
    },
    #[error("endpoint contract at index {index} has empty {mode} permissions")]
    /// The permissions is empty.
    EmptyPermissions {
        #[doc = "The zero-based item index."]
        index: usize,
        #[doc = "The configured mode."]
        mode: &'static str,
    },
    #[error("public endpoint contract at index {index} must not require permissions")]
    /// Indicates public endpoint requires permissions.
    PublicEndpointRequiresPermissions {
        #[doc = "The zero-based item index."]
        index: usize,
    },
    #[error("private endpoint contract at index {index} must require permissions")]
    /// Indicates private endpoint without permissions.
    PrivateEndpointWithoutPermissions {
        #[doc = "The zero-based item index."]
        index: usize,
    },
    #[error(
        "duplicate endpoint contract {method} {path} at indexes {first_index} and {second_index}"
    )]
    /// A duplicate route was encountered.
    DuplicateRoute {
        /// The first index value.
        first_index: usize,
        /// The second index value.
        second_index: usize,
        /// The method value.
        method: EndpointMethod,
        /// The affected path.
        path: &'static str,
    },
}

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

    fn error_code(&self) -> Cow<'static, str> {
        Cow::Borrowed(match self {
            Self::EmptyPath { .. } => "endpoint_contract_empty_path",
            Self::RelativePath { .. } => "endpoint_contract_relative_path",
            Self::InvalidPath { .. } => "endpoint_contract_invalid_path",
            Self::InvalidTemplate { .. } => "endpoint_contract_invalid_template",
            Self::InvalidRateLimitLabel { .. } => "endpoint_contract_invalid_rate_limit_label",
            Self::EmptyPermissions { .. } => "endpoint_contract_empty_permissions",
            Self::PublicEndpointRequiresPermissions { .. } => {
                "endpoint_contract_public_requires_permissions"
            }
            Self::PrivateEndpointWithoutPermissions { .. } => {
                "endpoint_contract_private_without_permissions"
            }
            Self::DuplicateRoute { .. } => "endpoint_contract_duplicate_route",
        })
    }
}

fn validate_endpoint<P: Copy + 'static>(
    index: usize,
    endpoint: &EndpointContract<P>,
) -> Result<(), EndpointContractValidationError> {
    let path = endpoint.path.as_str();
    if path.is_empty() {
        return Err(EndpointContractValidationError::EmptyPath { index });
    }
    if !path.starts_with('/') {
        return Err(EndpointContractValidationError::RelativePath { index, path });
    }
    if !valid_contract_path(path)
        || matches!(endpoint.path, EndpointPathPattern::Exact(_)) && path.contains(['{', '}'])
    {
        return Err(EndpointContractValidationError::InvalidPath { index, path });
    }
    if matches!(endpoint.path, EndpointPathPattern::Template(_)) && !valid_template_path(path) {
        return Err(EndpointContractValidationError::InvalidTemplate { index, path });
    }
    if let EndpointRateLimit::Custom(value) = endpoint.rate_limit
        && !valid_rate_limit_label(value)
    {
        return Err(EndpointContractValidationError::InvalidRateLimitLabel { index, value });
    }
    if let Some(mode) = endpoint.permissions.empty_requirement_mode() {
        return Err(EndpointContractValidationError::EmptyPermissions { index, mode });
    }
    if endpoint.auth == EndpointAuth::Public && !endpoint.permissions.is_public() {
        return Err(EndpointContractValidationError::PublicEndpointRequiresPermissions { index });
    }
    if endpoint.auth.requires_identity() && endpoint.permissions.is_public() {
        return Err(EndpointContractValidationError::PrivateEndpointWithoutPermissions { index });
    }
    Ok(())
}

fn document_permissions<P: Copy + 'static>(
    permissions: EndpointPermissions<P>,
    permission_to_string: impl Fn(P) -> String,
) -> EndpointPermissionsDocument {
    match permissions {
        EndpointPermissions::Public => EndpointPermissionsDocument {
            mode: "public".to_owned(),
            values: Vec::new(),
        },
        EndpointPermissions::One(permission) => EndpointPermissionsDocument {
            mode: "one".to_owned(),
            values: vec![permission_to_string(permission)],
        },
        EndpointPermissions::Any(permissions) => EndpointPermissionsDocument {
            mode: "any".to_owned(),
            values: permissions
                .iter()
                .copied()
                .map(permission_to_string)
                .collect(),
        },
        EndpointPermissions::All(permissions) => EndpointPermissionsDocument {
            mode: "all".to_owned(),
            values: permissions
                .iter()
                .copied()
                .map(permission_to_string)
                .collect(),
        },
    }
}

fn increment(values: &mut BTreeMap<String, usize>, key: &str) {
    *values.entry(key.to_owned()).or_default() += 1;
}

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,
        }
    }
}

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
}

fn valid_contract_path(path: &str) -> bool {
    path.is_ascii()
        && !path.bytes().any(|byte| {
            byte.is_ascii_control()
                || byte.is_ascii_whitespace()
                || matches!(byte, b'?' | b'#' | b'\\')
        })
}

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

    path.split('/').all(|segment| {
        !segment.is_empty()
            && if segment.starts_with('{') || segment.ends_with('}') {
                route_segment_matches(segment, "value")
            } else {
                !segment.contains(['{', '}'])
            }
    })
}

fn valid_rate_limit_label(value: &str) -> bool {
    !value.is_empty()
        && value.len() <= MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH
        && value
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'_')
}

#[cfg(test)]
mod tests {
    use axum::http::Method;

    use super::{
        EndpointAudit, EndpointAuth, EndpointContract, EndpointContractRegistry,
        EndpointContractSnapshot, EndpointMethod, EndpointPathPattern, EndpointPermissions,
        EndpointRateLimit, EndpointRisk,
    };
    use crate::result::{ClassifyError, ErrorKind};

    #[test]
    fn endpoint_contract_matches_exact_and_template_paths() {
        let exact: EndpointContract = EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        );
        let template: EndpointContract = EndpointContract::new(
            EndpointMethod::Delete,
            EndpointPathPattern::Template("/api/users/{id}"),
        );

        assert!(exact.matches(&Method::GET, "/api/users"));
        assert!(!exact.matches(&Method::GET, "/api/users/123"));
        assert!(template.matches(&Method::DELETE, "/api/users/123"));
        assert!(!template.matches(&Method::DELETE, "/api/users/123/sessions"));
    }

    #[test]
    fn unsupported_endpoint_method_is_classified_as_validation() {
        let error = EndpointMethod::try_from(&Method::TRACE)
            .expect_err("TRACE should not be contractable")
            .error_descriptor();

        assert_eq!(error.kind(), ErrorKind::Validation);
        assert_eq!(error.code().as_str(), "endpoint_method_unsupported");
    }

    #[test]
    fn endpoint_permissions_support_common_policy_modes() {
        let one = EndpointPermissions::one("users:read");
        let any = EndpointPermissions::any(&["users:read", "users:write"]);
        let all = EndpointPermissions::all(&["users:read", "users:write"]);

        assert!(one.is_granted_by(|permission| permission == "users:read"));
        assert!(any.is_granted_by(|permission| permission == "users:write"));
        assert!(!all.is_granted_by(|permission| permission == "users:write"));
        assert!(all.contains("users:read"));
        assert!(!EndpointPermissions::<&str>::all(&[]).is_granted_by(|_| true));
    }

    #[test]
    fn registry_validates_duplicate_routes_and_private_permissions() {
        let endpoints = [
            EndpointContract::new(
                EndpointMethod::Get,
                EndpointPathPattern::Exact("/api/users"),
            )
            .with_auth(EndpointAuth::Admin)
            .with_permissions(EndpointPermissions::one("users:read"))
            .with_risk(EndpointRisk::Low),
            EndpointContract::new(
                EndpointMethod::Post,
                EndpointPathPattern::Exact("/api/users"),
            )
            .with_auth(EndpointAuth::Admin)
            .with_permissions(EndpointPermissions::one("users:write"))
            .with_risk(EndpointRisk::Medium),
        ];

        let registry = EndpointContractRegistry::new(&endpoints);
        registry.validate().expect("contracts should be valid");
        assert!(registry.find(&Method::POST, "/api/users").is_some());
    }

    #[test]
    fn registry_rejects_empty_permission_sets() {
        let endpoints = [EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::<&str>::all(&[]))];
        let registry = EndpointContractRegistry::new(&endpoints);
        let error = registry
            .validate()
            .expect_err("empty all permissions should be invalid");

        assert!(matches!(
            error,
            super::EndpointContractValidationError::EmptyPermissions { mode: "all", .. }
        ));
    }

    #[test]
    fn registry_rejects_invalid_path_patterns() {
        let endpoints = [EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users?active=true"),
        )];
        let registry = EndpointContractRegistry::<&str>::new(&endpoints);

        let error = registry
            .validate()
            .expect_err("query strings do not belong in route contracts");

        assert!(matches!(
            error,
            super::EndpointContractValidationError::InvalidPath { .. }
        ));
    }

    #[test]
    fn registry_rejects_template_syntax_in_exact_paths() {
        let endpoints = [EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users/{id}"),
        )];
        let registry = EndpointContractRegistry::<&str>::new(&endpoints);

        let error = registry
            .validate()
            .expect_err("template segments must use EndpointPathPattern::Template");

        assert!(matches!(
            error,
            super::EndpointContractValidationError::InvalidPath { .. }
        ));
    }

    #[test]
    fn registry_rejects_invalid_custom_rate_limit_labels() {
        let endpoints = [EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_rate_limit(EndpointRateLimit::Custom("User Reads"))];
        let registry = EndpointContractRegistry::<&str>::new(&endpoints);

        let error = registry
            .validate()
            .expect_err("custom rate limit labels must be stable metric labels");

        assert!(matches!(
            error,
            super::EndpointContractValidationError::InvalidRateLimitLabel { .. }
        ));
    }

    #[test]
    fn registry_exports_stable_contract_documents() {
        let endpoints = [EndpointContract::new(
            EndpointMethod::Get,
            EndpointPathPattern::Exact("/api/users"),
        )
        .with_auth(EndpointAuth::Admin)
        .with_permissions(EndpointPermissions::one("users:read"))
        .with_risk(EndpointRisk::Low)];
        let registry = EndpointContractRegistry::new(&endpoints);

        let documents = registry.documents(str::to_owned);

        assert_eq!(documents.len(), 1);
        assert_eq!(documents[0].method, "GET");
        assert_eq!(documents[0].path, "/api/users");
        assert_eq!(documents[0].auth, "admin");
        assert_eq!(documents[0].permissions.mode, "one");
        assert_eq!(documents[0].permissions.values, ["users:read"]);
    }

    #[test]
    fn registry_exports_stable_contract_snapshot() {
        let endpoints = [
            EndpointContract::new(
                EndpointMethod::Get,
                EndpointPathPattern::Exact("/api/users"),
            )
            .with_auth(EndpointAuth::Admin)
            .with_permissions(EndpointPermissions::one("users:read"))
            .with_risk(EndpointRisk::Low)
            .with_rate_limit(EndpointRateLimit::Read)
            .with_audit(EndpointAudit::Optional),
            EndpointContract::new(
                EndpointMethod::Delete,
                EndpointPathPattern::Template("/api/users/{id}"),
            )
            .with_auth(EndpointAuth::Admin)
            .with_permissions(EndpointPermissions::one("users:delete"))
            .with_risk(EndpointRisk::High)
            .with_rate_limit(EndpointRateLimit::Write)
            .with_audit(EndpointAudit::Required),
        ];
        let registry = EndpointContractRegistry::new(&endpoints);

        let snapshot = registry.snapshot(str::to_owned);

        assert_eq!(
            snapshot.schema_version,
            EndpointContractSnapshot::SCHEMA_VERSION
        );
        assert_eq!(snapshot.summary.total, 2);
        assert_eq!(snapshot.summary.permissioned, 2);
        assert_eq!(snapshot.summary.by_auth["admin"], 2);
        assert_eq!(snapshot.summary.by_risk["high"], 1);
        assert_eq!(snapshot.summary.by_audit["required"], 1);
        assert!(
            snapshot
                .to_pretty_json()
                .expect("json")
                .contains("\"endpoints\"")
        );
    }
}