use axum::{extract::MatchedPath, http::Method};
use super::{
EndpointAuth, EndpointContract, EndpointContractDocument, EndpointContractSnapshot,
EndpointContractValidationError, EndpointMethod, EndpointPathPattern,
};
#[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: &MatchedPath) -> Option<&'a EndpointContract<P>> {
let method = EndpointMethod::try_from(method).ok()?;
let find = |method| {
self.endpoints.iter().find(|contract| {
contract.method() == method && contract.path().as_str() == path.as_str()
})
};
find(method).or_else(|| {
(method == EndpointMethod::Head)
.then(|| find(EndpointMethod::Get))
.flatten()
})
}
pub fn validate(&self) -> Result<(), EndpointContractValidationError> {
for (index, endpoint) in self.endpoints.iter().enumerate() {
Self::new(&self.endpoints[..index]).validate_addition(endpoint)?;
}
Ok(())
}
pub(super) fn validate_addition(
&self,
endpoint: &EndpointContract<P>,
) -> Result<(), EndpointContractValidationError> {
validate_endpoint(self.endpoints.len(), endpoint)?;
for (index, other) in self.endpoints.iter().enumerate() {
if endpoint.method() == other.method()
&& endpoint.path().as_str() == other.path().as_str()
{
return Err(EndpointContractValidationError::DuplicateRoute {
first_index: index,
second_index: self.endpoints.len(),
method: endpoint.method(),
path: endpoint.path().as_str(),
});
}
}
Ok(())
}
#[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)
}
}
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 !crate::http::is_valid_route_path(path)
|| path
.split('/')
.any(|segment| segment.starts_with([':', '*']))
|| 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 Some(mode) = endpoint.permissions().empty_requirement_mode() {
return Err(EndpointContractValidationError::EmptyPermissions { index, mode });
}
if endpoint.auth() == EndpointAuth::Public && !endpoint.permissions().is_none() {
return Err(EndpointContractValidationError::PublicEndpointRequiresPermissions { index });
}
Ok(())
}
fn valid_template_path(path: &str) -> bool {
path.split('/').all(|segment| {
if let Some(parameter) = segment
.strip_prefix('{')
.and_then(|segment| segment.strip_suffix('}'))
{
!parameter.is_empty()
&& parameter
.bytes()
.all(|byte| byte.is_ascii_alphanumeric() || byte == b'_')
} else {
!segment.contains(['{', '}'])
}
})
}