use std::{
collections::{BTreeMap, HashSet},
fmt,
};
use axum::{
Extension, Router,
handler::Handler,
http::Method,
routing::{MethodFilter, MethodRouter, on},
};
use thiserror::Error;
use utoipa::openapi::{
OpenApi, Server,
path::{Parameter, ParameterIn, PathItem},
security::SecurityRequirement,
};
use crate::{
http::{EndpointContract, EndpointContractRegistry, HttpMiddlewareError, HttpMiddlewareStack},
pagination::PageLimits,
result::{ClassifyError, ErrorKind},
};
use super::{
OpenApiContractError, annotate_contracts,
contracts::{operations, operations_mut},
cursor_pagination_parameters, offset_pagination_parameters, validate_contracts,
};
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiRouteError {
#[error(transparent)]
InvalidContracts(#[from] OpenApiContractError),
#[error(transparent)]
InvalidMiddleware(#[from] HttpMiddlewareError),
#[error("invalid OpenAPI route document: {reason}")]
InvalidDocument {
reason: &'static str,
},
#[error("OpenAPI operation {method} {path} is already registered")]
DuplicateOperation {
method: &'static str,
path: String,
},
#[error(
"OpenAPI operation ID {operation_id} is already registered; set #[utoipa::path(operation_id = \"...\")] to distinguish handlers"
)]
DuplicateOperationId {
operation_id: String,
},
#[error("conflicting OpenAPI {kind} component {name}")]
ConflictingComponent {
kind: &'static str,
name: String,
},
#[error("conflicting OpenAPI {field} for path {path}")]
ConflictingPathMetadata {
field: &'static str,
path: String,
},
#[error("pagination is already configured for this route")]
PaginationAlreadyConfigured,
}
impl ClassifyError for OpenApiRouteError {
fn error_kind(&self) -> ErrorKind {
match self {
Self::InvalidContracts(error) => error.error_kind(),
Self::InvalidMiddleware(error) => error.error_kind(),
_ => ErrorKind::Validation,
}
}
fn error_code(&self) -> crate::result::ErrorCode {
crate::result::ErrorCode::internal(match self {
Self::InvalidContracts(_) => "openapi_invalid_route_contracts",
Self::InvalidMiddleware(_) => "openapi_invalid_route_middleware",
Self::InvalidDocument { .. } => "openapi_invalid_route_document",
Self::DuplicateOperation { .. } => "openapi_duplicate_operation",
Self::DuplicateOperationId { .. } => "openapi_duplicate_operation_id",
Self::ConflictingComponent { .. } => "openapi_conflicting_component",
Self::ConflictingPathMetadata { .. } => "openapi_conflicting_path_metadata",
Self::PaginationAlreadyConfigured => "openapi_pagination_already_configured",
})
}
}
#[must_use]
pub struct OpenApiRoute<S = (), P: Copy + 'static = &'static str> {
router: MethodRouter<S>,
document: OpenApi,
path: String,
pagination_configured: bool,
contracts: Vec<EndpointContract<P>>,
}
impl<S, P: Copy + 'static> fmt::Debug for OpenApiRoute<S, P> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("OpenApiRoute")
.field("path", &self.path)
.finish_non_exhaustive()
}
}
impl<S: Clone + Send + Sync + 'static> OpenApiRoute<S> {
pub fn from_handler<H, T>(handler: H, mut document: OpenApi) -> Result<Self, OpenApiRouteError>
where
H: Handler<T, S>,
T: 'static,
{
if document.paths.paths.len() != 1 {
return Err(OpenApiRouteError::InvalidDocument {
reason: "a handler must describe exactly one path",
});
}
let servers = document.servers.take();
let security = document.security.take();
let (path, item) =
document
.paths
.paths
.iter_mut()
.next()
.ok_or(OpenApiRouteError::InvalidDocument {
reason: "missing handler path",
})?;
if !path.starts_with('/') {
return Err(OpenApiRouteError::InvalidDocument {
reason: "handler paths must start with /",
});
}
let mut filter: Option<MethodFilter> = None;
for (method, operation) in operations(item) {
if operation.is_some() {
let method = Method::from_bytes(method.as_bytes()).map_err(|_| {
OpenApiRouteError::InvalidDocument {
reason: "invalid HTTP method",
}
})?;
let next = MethodFilter::try_from(method).map_err(|_| {
OpenApiRouteError::InvalidDocument {
reason: "unsupported HTTP method",
}
})?;
filter = Some(filter.map_or(next, |filter| filter.or(next)));
}
}
let filter = filter.ok_or(OpenApiRouteError::InvalidDocument {
reason: "a handler must describe at least one operation",
})?;
normalize_operation_inheritance(item, servers, security)?;
Ok(Self {
path: path.clone(),
router: on(filter, handler),
document,
pagination_configured: false,
contracts: Vec::new(),
})
}
pub fn with_contract<P: Copy + 'static>(
self,
contract: EndpointContract<P>,
) -> Result<OpenApiRoute<S, P>, OpenApiRouteError> {
self.with_contracts([contract])
}
pub fn with_contracts<P: Copy + 'static>(
self,
contracts: impl IntoIterator<Item = EndpointContract<P>>,
) -> Result<OpenApiRoute<S, P>, OpenApiRouteError> {
if !self.contracts.is_empty() {
return Err(OpenApiRouteError::InvalidDocument {
reason: "contracts are already configured for this handler",
});
}
let contracts: Vec<_> = contracts.into_iter().collect();
validate_contracts(&self.document, &EndpointContractRegistry::new(&contracts))?;
Ok(OpenApiRoute {
router: self.router,
document: self.document,
path: self.path,
pagination_configured: self.pagination_configured,
contracts,
})
}
}
impl<S: Clone + Send + Sync + 'static, P: Copy + 'static> OpenApiRoute<S, P> {
pub fn with_cursor_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
self.with_pagination(limits, cursor_pagination_parameters(limits))
}
pub fn with_offset_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
self.with_pagination(limits, offset_pagination_parameters(limits))
}
fn with_pagination(
mut self,
limits: PageLimits,
parameters: Vec<Parameter>,
) -> Result<Self, OpenApiRouteError> {
if self.pagination_configured {
return Err(OpenApiRouteError::PaginationAlreadyConfigured);
}
for item in self.document.paths.paths.values_mut() {
for operation in operations_mut(item) {
let target = operation.parameters.get_or_insert_default();
for parameter in ¶meters {
if let Some(existing) = target
.iter_mut()
.find(|existing| same_parameter(existing, parameter))
{
existing.schema = parameter.schema.clone();
existing.required = parameter.required.clone();
} else {
target.push(parameter.clone());
}
}
}
}
self.router = self.router.layer(Extension(limits));
self.pagination_configured = true;
Ok(self)
}
}
#[must_use]
pub struct OpenApiRouter<S = (), P: Copy + 'static = &'static str> {
router: Router<S>,
document: OpenApi,
contracts: Vec<EndpointContract<P>>,
}
impl<S, P: Copy + 'static> fmt::Debug for OpenApiRouter<S, P> {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("OpenApiRouter")
.field("paths", &self.document.paths.paths.len())
.finish_non_exhaustive()
}
}
impl<S: Clone + Send + Sync + 'static, P: Copy + 'static> OpenApiRouter<S, P> {
pub fn new(document: OpenApi) -> Result<Self, OpenApiRouteError> {
if !document.paths.paths.is_empty() {
return Err(OpenApiRouteError::InvalidDocument {
reason: "register paths through route! instead of the base document",
});
}
Ok(Self {
router: Router::new(),
document,
contracts: Vec::new(),
})
}
pub fn route(mut self, mut route: OpenApiRoute<S, P>) -> Result<Self, OpenApiRouteError> {
for (path, item) in &mut route.document.paths.paths {
if let Some(existing) = self.document.paths.paths.get_mut(path) {
for (method, operation) in operations(item) {
if operation.is_some()
&& operations(existing)
.iter()
.any(|(other, operation)| *other == method && operation.is_some())
{
return Err(OpenApiRouteError::DuplicateOperation {
method,
path: path.clone(),
});
}
}
merge_path_metadata(path, "summary", &mut existing.summary, item.summary.take())?;
merge_path_metadata(
path,
"description",
&mut existing.description,
item.description.take(),
)?;
if let Some(incoming) = item.extensions.take() {
let target = existing.extensions.get_or_insert_default();
if incoming.iter().any(|(key, value)| {
target.get(key).is_some_and(|existing| existing != value)
}) {
return Err(OpenApiRouteError::ConflictingPathMetadata {
field: "extensions",
path: path.clone(),
});
}
target.merge(incoming);
}
}
}
let mut operation_ids = HashSet::new();
for operation_id in self
.document
.paths
.paths
.values()
.chain(route.document.paths.paths.values())
.flat_map(operations)
.filter_map(|(_, operation)| operation?.operation_id.as_deref())
{
if !operation_ids.insert(operation_id) {
return Err(OpenApiRouteError::DuplicateOperationId {
operation_id: operation_id.to_owned(),
});
}
}
if let (Some(existing), Some(incoming)) =
(&self.document.components, &route.document.components)
{
check_components("schema", &existing.schemas, &incoming.schemas)?;
check_components("response", &existing.responses, &incoming.responses)?;
check_components(
"security scheme",
&existing.security_schemes,
&incoming.security_schemes,
)?;
}
self.router = self.router.route(&route.path, route.router);
self.document.merge(route.document);
self.contracts.extend(route.contracts);
Ok(self)
}
#[must_use]
pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
EndpointContractRegistry::new(&self.contracts)
}
pub fn into_parts_with_stack(
self,
stack: HttpMiddlewareStack,
permission_to_string: impl Fn(P) -> String,
) -> Result<(Router<S>, OpenApi), OpenApiRouteError> {
stack.validate_endpoint_contracts(&self.contracts())?;
let document = annotate_contracts(
self.document,
&EndpointContractRegistry::new(&self.contracts),
permission_to_string,
)?;
Ok((stack.apply(self.router), document))
}
pub fn into_parts(self) -> (Router<S>, OpenApi, Vec<EndpointContract<P>>) {
(self.router, self.document, self.contracts)
}
}
fn normalize_operation_inheritance(
item: &mut PathItem,
document_servers: Option<Vec<Server>>,
document_security: Option<Vec<SecurityRequirement>>,
) -> Result<(), OpenApiRouteError> {
let parameters = item.parameters.take().unwrap_or_default();
validate_unique_parameters(¶meters)?;
let servers = item.servers.take().or(document_servers);
for operation in operations_mut(item) {
validate_unique_parameters(operation.parameters.as_deref().unwrap_or_default())?;
if operation.servers.is_none() {
operation.servers = servers.clone();
}
if operation.security.is_none() {
operation.security = document_security.clone();
}
if !parameters.is_empty() {
let target = operation.parameters.get_or_insert_default();
for parameter in ¶meters {
if !target
.iter()
.any(|existing| same_parameter(existing, parameter))
{
target.push(parameter.clone());
}
}
}
}
Ok(())
}
fn validate_unique_parameters(parameters: &[Parameter]) -> Result<(), OpenApiRouteError> {
if parameters.iter().enumerate().any(|(index, parameter)| {
parameters[..index]
.iter()
.any(|other| same_parameter(parameter, other))
}) {
return Err(OpenApiRouteError::InvalidDocument {
reason: "parameters must be unique by name and location",
});
}
Ok(())
}
fn same_parameter(left: &Parameter, right: &Parameter) -> bool {
left.parameter_in == right.parameter_in
&& if left.parameter_in == ParameterIn::Header {
left.name.eq_ignore_ascii_case(&right.name)
} else {
left.name == right.name
}
}
fn merge_path_metadata<T: PartialEq>(
path: &str,
field: &'static str,
existing: &mut Option<T>,
incoming: Option<T>,
) -> Result<(), OpenApiRouteError> {
if let Some(value) = incoming {
if existing.as_ref().is_some_and(|existing| *existing != value) {
return Err(OpenApiRouteError::ConflictingPathMetadata {
field,
path: path.to_owned(),
});
}
*existing = Some(value);
}
Ok(())
}
fn check_components<T: PartialEq>(
kind: &'static str,
existing: &BTreeMap<String, T>,
incoming: &BTreeMap<String, T>,
) -> Result<(), OpenApiRouteError> {
for (name, value) in incoming {
if existing.get(name).is_some_and(|existing| existing != value) {
return Err(OpenApiRouteError::ConflictingComponent {
kind,
name: name.clone(),
});
}
}
Ok(())
}
#[macro_export]
macro_rules! openapi_route {
($handler:path $(,)?) => {{
use $crate::http::openapi::utoipa;
#[derive(utoipa::OpenApi)]
#[openapi(paths($handler))]
struct RouteDocument;
$crate::http::openapi::OpenApiRoute::from_handler(
$handler,
<RouteDocument as utoipa::OpenApi>::openapi(),
)
}};
}