use axum::http::Method;
use super::model::route_segment_matches;
use super::{
EndpointAuth, EndpointContract, EndpointContractDocument, EndpointContractReconciliationError,
EndpointContractSnapshot, EndpointContractValidationError, EndpointIdempotency, EndpointMethod,
EndpointPathPattern, EndpointRateLimit, EndpointRouteRegistration,
};
const MAX_ENDPOINT_RATE_LIMIT_LABEL_LENGTH: usize = 64;
#[derive(Debug, Clone, Copy)]
pub struct EndpointContractRegistry<'a, P: Copy + 'static = &'static str> {
endpoints: &'a [EndpointContract<P>],
}
impl<'a, P: Copy + 'static> EndpointContractRegistry<'a, P> {
#[must_use]
pub const fn new(endpoints: &'a [EndpointContract<P>]) -> Self {
Self { endpoints }
}
#[must_use]
pub const fn endpoints(&self) -> &'a [EndpointContract<P>] {
self.endpoints
}
#[must_use]
pub fn find(&self, method: &Method, path: &str) -> Option<&'a EndpointContract<P>> {
self.endpoints
.iter()
.find(|contract| contract.matches(method, path))
}
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(())
}
pub fn reconcile_routes(
&self,
routes: &[EndpointRouteRegistration],
) -> Result<ReconciledEndpointContracts, EndpointContractReconciliationError> {
self.validate()
.map_err(EndpointContractReconciliationError::InvalidContracts)?;
for (index, route) in routes.iter().copied().enumerate() {
for (other_index, other) in routes.iter().copied().enumerate().skip(index + 1) {
if route == other {
return Err(EndpointContractReconciliationError::DuplicateRegistration {
first_index: index,
second_index: other_index,
method: route.method(),
path: route.path().as_str(),
});
}
}
if !self.endpoints.iter().any(|endpoint| {
endpoint.method() == route.method() && endpoint.path() == route.path()
}) {
return Err(EndpointContractReconciliationError::RouteWithoutContract {
method: route.method(),
path: route.path().as_str(),
});
}
}
for endpoint in self.endpoints {
if !routes
.iter()
.copied()
.any(|route| endpoint.method() == route.method() && endpoint.path() == route.path())
{
return Err(EndpointContractReconciliationError::ContractWithoutRoute {
method: endpoint.method(),
path: endpoint.path().as_str(),
});
}
}
Ok(ReconciledEndpointContracts {
endpoints: self
.endpoints
.iter()
.map(|endpoint| ReconciledEndpointPolicy {
method: endpoint.method(),
path: endpoint.path(),
auth: endpoint.auth(),
idempotency: endpoint.idempotency(),
rate_limit: endpoint.rate_limit(),
})
.collect(),
})
}
#[must_use]
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]
pub fn snapshot(
&self,
permission_to_string: impl Fn(P) -> String + Copy,
) -> EndpointContractSnapshot {
EndpointContractSnapshot::from_contracts(self.endpoints, permission_to_string)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct ReconciledEndpointContracts {
endpoints: Vec<ReconciledEndpointPolicy>,
}
impl ReconciledEndpointContracts {
#[must_use]
pub fn len(&self) -> usize {
self.endpoints.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.endpoints.is_empty()
}
pub(crate) fn policies(&self) -> &[ReconciledEndpointPolicy] {
&self.endpoints
}
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct ReconciledEndpointPolicy {
pub(crate) method: EndpointMethod,
pub(crate) path: EndpointPathPattern,
pub(crate) auth: EndpointAuth,
pub(crate) idempotency: EndpointIdempotency,
pub(crate) rate_limit: EndpointRateLimit,
}
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 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'_')
}