use std::{
collections::{BTreeMap, HashSet},
fmt,
};
use axum::{
Router,
handler::Handler,
routing::{MethodFilter, MethodRouter, on},
};
use serde::Serialize;
use thiserror::Error;
use utoipa::openapi::{
Components, Content, Header, OpenApi, RefOr, Response, Schema, Server,
encoding::Encoding,
extensions::Extensions,
path::{Callback, Operation, Parameter, ParameterIn, PathItem},
request_body::RequestBody,
schema::{AdditionalProperties, ArrayItems},
security::SecurityRequirement,
};
use crate::{
http::{
EndpointContract, EndpointContractRegistry, EndpointMethod, EndpointPagination,
EndpointPathPattern, EndpointPolicy,
},
result::{ClassifyError, ErrorKind},
};
use super::{
OpenApiContractError,
contracts::{operations, operations_mut, resolve_parameter, validate_supported_path_item},
validate_contracts,
};
#[cfg(feature = "pagination")]
use super::{cursor_pagination_parameters, offset_pagination_parameters};
#[cfg(feature = "http-stack")]
use crate::http::{HttpMiddlewareError, HttpMiddlewareStack};
#[cfg(feature = "pagination")]
use crate::pagination::PageLimits;
#[cfg(feature = "pagination")]
use axum::Extension;
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiRouteError {
#[error(transparent)]
InvalidContracts(#[from] OpenApiContractError),
#[error(transparent)]
#[cfg(feature = "http-stack")]
InvalidMiddleware(#[from] HttpMiddlewareError),
#[error("invalid OpenAPI route document: {reason}")]
InvalidDocument {
reason: &'static str,
},
#[error(
"OpenAPI mount prefix must be a non-root literal path without trailing slash, captures, encoding, or dot segments"
)]
InvalidPrefix,
#[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("conflicting OpenAPI document {field}")]
ConflictingDocumentMetadata {
field: &'static str,
},
#[error("conflicting OpenAPI tag {name}")]
ConflictingTag {
name: 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(),
#[cfg(feature = "http-stack")]
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",
#[cfg(feature = "http-stack")]
Self::InvalidMiddleware(_) => "openapi_invalid_route_middleware",
Self::InvalidDocument { .. } => "openapi_invalid_route_document",
Self::InvalidPrefix => "openapi_invalid_mount_prefix",
Self::DuplicateOperation { .. } => "openapi_duplicate_operation",
Self::DuplicateOperationId { .. } => "openapi_duplicate_operation_id",
Self::ConflictingComponent { .. } => "openapi_conflicting_component",
Self::ConflictingPathMetadata { .. } => "openapi_conflicting_path_metadata",
Self::ConflictingDocumentMetadata { .. } => "openapi_conflicting_document_metadata",
Self::ConflictingTag { .. } => "openapi_conflicting_tag",
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: EndpointPagination,
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,
{
validate_references(&document, ReferencePolicy::Incoming)?;
let servers = document.servers.take();
let security = document.security.take();
inherit_document_defaults(&mut document, servers.as_deref(), security.as_deref());
let mut paths = document.paths.paths.iter_mut();
let (Some((path, item)), None) = (paths.next(), paths.next()) else {
return Err(OpenApiRouteError::InvalidDocument {
reason: "a handler must describe exactly one path",
});
};
if !path.starts_with('/') {
return Err(OpenApiRouteError::InvalidDocument {
reason: "handler paths must start with /",
});
}
validate_supported_path_item(item)
.map_err(|reason| OpenApiRouteError::InvalidDocument { reason })?;
let filter = [
(&item.get, MethodFilter::GET),
(&item.put, MethodFilter::PUT),
(&item.post, MethodFilter::POST),
(&item.delete, MethodFilter::DELETE),
(&item.options, MethodFilter::OPTIONS),
(&item.head, MethodFilter::HEAD),
(&item.patch, MethodFilter::PATCH),
(&item.trace, MethodFilter::TRACE),
]
.into_iter()
.filter_map(|(operation, method)| operation.is_some().then_some(method))
.reduce(MethodFilter::or)
.ok_or(OpenApiRouteError::InvalidDocument {
reason: "a handler must describe at least one operation",
})?;
normalize_operation_parameters(item, document.components.as_ref())?;
Ok(Self {
path: path.clone(),
router: on(filter, handler),
document,
pagination: EndpointPagination::None,
contracts: Vec::new(),
})
}
pub fn with_contract<P: Copy + 'static>(
self,
mut policy_for: impl FnMut(EndpointMethod) -> EndpointPolicy<P>,
) -> Result<OpenApiRoute<S, P>, OpenApiRouteError> {
if !self.contracts.is_empty() {
return Err(OpenApiRouteError::InvalidDocument {
reason: "contracts are already configured for this handler",
});
}
let mut contracts = Vec::new();
for (path, item) in &self.document.paths.paths {
let pattern = if path.contains('{') {
EndpointPathPattern::Template(path.clone().into())
} else {
EndpointPathPattern::Exact(path.clone().into())
};
for (method, operation) in operations(item) {
if operation.is_none() {
continue;
}
let method = match method {
"GET" => EndpointMethod::Get,
"PUT" => EndpointMethod::Put,
"POST" => EndpointMethod::Post,
"DELETE" => EndpointMethod::Delete,
"OPTIONS" => EndpointMethod::Options,
"HEAD" => EndpointMethod::Head,
"PATCH" => EndpointMethod::Patch,
_ => {
return Err(OpenApiContractError::UnsupportedPathItem {
path: path.clone(),
reason: "HTTP method is not supported by endpoint contracts",
}
.into());
}
};
let contract = EndpointContract::new(method, pattern.clone())
.with_policy(policy_for(method))
.with_pagination(self.pagination);
contracts.push(contract);
}
}
validate_contracts(&self.document, &EndpointContractRegistry::new(&contracts))?;
Ok(OpenApiRoute {
router: self.router,
document: self.document,
path: self.path,
pagination: self.pagination,
contracts,
})
}
}
impl<S: Clone + Send + Sync + 'static, P: Copy + 'static> OpenApiRoute<S, P> {
#[cfg(feature = "pagination")]
#[cfg_attr(docsrs, doc(cfg(feature = "pagination")))]
pub fn with_cursor_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
self.with_pagination(
limits,
EndpointPagination::Cursor,
cursor_pagination_parameters(limits),
)
}
#[cfg(feature = "pagination")]
#[cfg_attr(docsrs, doc(cfg(feature = "pagination")))]
pub fn with_offset_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
self.with_pagination(
limits,
EndpointPagination::Offset,
offset_pagination_parameters(limits),
)
}
#[cfg(feature = "pagination")]
fn with_pagination(
mut self,
limits: PageLimits,
pagination: EndpointPagination,
parameters: Vec<Parameter>,
) -> Result<Self, OpenApiRouteError> {
if self.pagination != EndpointPagination::None {
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()
.filter_map(|existing| match existing {
RefOr::T(parameter) => Some(parameter),
RefOr::Ref(_) => None,
})
.find(|existing| same_parameter(existing, parameter))
{
existing.schema = parameter.schema.clone();
existing.content.clear();
existing.required = parameter.required.clone();
} else {
target.push(parameter.clone().into());
}
}
}
}
self.contracts = self
.contracts
.into_iter()
.map(|contract| contract.with_pagination(pagination))
.collect();
if !self.contracts.is_empty() {
validate_contracts(
&self.document,
&EndpointContractRegistry::new(&self.contracts),
)?;
}
self.router = self.router.layer(Extension(limits));
self.pagination = pagination;
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",
});
}
validate_references(&document, ReferencePolicy::Base)?;
validate_operation_ids(&document)?;
Ok(Self {
router: Router::new(),
document,
contracts: Vec::new(),
})
}
pub fn route(mut self, mut route: OpenApiRoute<S, P>) -> Result<Self, OpenApiRouteError> {
let (servers, security) = document_defaults(&self.document);
inherit_reusable_defaults(&mut self.document, Some(&servers), Some(&security));
inherit_reusable_defaults(&mut route.document, Some(&servers), Some(&security));
merge_route_documents(&mut self.document, route.document)?;
self.router = self.router.route(&route.path, route.router);
self.contracts.extend(route.contracts);
Ok(self)
}
pub fn merge(mut self, mut other: Self) -> Result<Self, OpenApiRouteError> {
validate_references(&other.document, ReferencePolicy::Incoming)?;
let (servers, security) = document_defaults(&self.document);
inherit_reusable_defaults(&mut self.document, Some(&servers), Some(&security));
let servers = other
.document
.servers
.take()
.unwrap_or_else(default_servers);
let security = other.document.security.take().unwrap_or_default();
inherit_document_defaults(&mut other.document, Some(&servers), Some(&security));
merge_route_documents(&mut self.document, other.document)?;
self.router = self.router.merge(other.router);
self.contracts.extend(other.contracts);
Ok(self)
}
pub fn nest(self, prefix: &str, mut module: Self) -> Result<Self, OpenApiRouteError> {
if !crate::http::is_valid_route_path(prefix)
|| prefix.contains(['{', '}', '*', '%'])
|| prefix[1..].split('/').any(|segment| {
segment.is_empty() || matches!(segment, "." | "..") || segment.starts_with(':')
})
{
return Err(OpenApiRouteError::InvalidPrefix);
}
validate_references(&module.document, ReferencePolicy::Nested)?;
let mut paths = BTreeMap::new();
for (path, mut item) in module.document.paths.paths {
let mounted = mounted_path(prefix, &path);
for operation in operations_mut(&mut item) {
if let Some(metadata) = operation
.extensions
.as_mut()
.and_then(|extensions| extensions.get_mut(super::CONTRACT_EXTENSION))
{
let Some(contract_path) = metadata.pointer_mut("/contract/path") else {
return Err(OpenApiRouteError::InvalidDocument {
reason: "nested footing contract metadata must contain its original path",
});
};
if contract_path.as_str() != Some(path.as_str()) {
return Err(OpenApiRouteError::InvalidDocument {
reason: "nested footing contract metadata differs from its original path",
});
}
*contract_path = serde_json::Value::String(mounted.clone());
}
}
paths.insert(mounted, item);
}
module.document.paths.paths = paths;
for contract in &mut module.contracts {
contract.set_path(mounted_path(prefix, contract.path().as_str()));
}
module.router = Router::new().nest(prefix, module.router);
self.merge(module)
}
pub fn with_api_fallbacks(mut self) -> Self {
self.router = self
.router
.fallback(crate::http::route_not_found)
.method_not_allowed_fallback(crate::http::method_not_allowed);
self
}
#[must_use]
pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
EndpointContractRegistry::new(&self.contracts)
}
#[cfg(feature = "http-stack")]
#[cfg_attr(docsrs, doc(cfg(feature = "http-stack")))]
pub fn into_parts_with_stack(
self,
stack: HttpMiddlewareStack,
) -> Result<(Router<S>, OpenApi), OpenApiRouteError> {
stack.validate_endpoint_contracts(&self.contracts())?;
validate_contracts(&self.document, &self.contracts())?;
Ok((stack.apply(self.router), self.document))
}
pub fn into_parts(self) -> (Router<S>, OpenApi, Vec<EndpointContract<P>>) {
(self.router, self.document, self.contracts)
}
}
fn mounted_path(prefix: &str, path: &str) -> String {
if path == "/" {
prefix.to_owned()
} else {
format!("{prefix}{path}")
}
}
#[derive(Clone, Copy)]
enum ReferencePolicy {
Base,
Incoming,
Nested,
}
fn validate_references(
document: &OpenApi,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
if let Some(components) = &document.components {
for schema in components.schemas.values() {
validate_schema_reference(schema, policy)?;
}
for response in components.responses.values() {
validate_response_references(response, policy)?;
}
for parameter in components.parameters.values() {
validate_parameter_references(parameter, policy)?;
}
for body in components.request_bodies.values() {
validate_body_references(body, policy)?;
}
for header in components.headers.values() {
validate_header_references(header, policy)?;
}
for content in components.media_types.values() {
validate_content_references(content, policy)?;
}
for example in components.examples.values() {
validate_reference_object(example, policy)?;
}
for scheme in components.security_schemes.values() {
validate_reference_object(scheme, policy)?;
}
for link in components.links.values() {
validate_link_references(link, policy)?;
}
for callback in components.callbacks.values() {
validate_callback_references(callback, policy)?;
}
for item in components.path_items.values() {
validate_path_item_references(item, policy)?;
}
}
for item in document.paths.paths.values().chain(
document
.webhooks
.iter()
.flat_map(|webhooks| webhooks.paths.values()),
) {
validate_path_item_references(item, policy)?;
}
Ok(())
}
fn validate_path_item_references(
item: &PathItem,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
if let Some(reference) = &item.ref_path {
validate_reference(reference, policy)?;
}
for parameter in item.parameters.iter().flatten() {
validate_parameter_references(parameter, policy)?;
}
for operation in all_operations(item) {
for parameter in operation.parameters.iter().flatten() {
validate_parameter_references(parameter, policy)?;
}
if let Some(body) = &operation.request_body {
validate_body_references(body, policy)?;
}
for response in operation.responses.responses.values() {
validate_response_references(response, policy)?;
}
for callback in operation.callbacks.values() {
validate_callback_references(callback, policy)?;
}
}
Ok(())
}
fn validate_parameter_references(
parameter: &RefOr<Parameter>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(parameter) = parameter else {
return validate_reference_object(parameter, policy);
};
for schema in parameter.schema.iter() {
validate_schema_reference(schema, policy)?;
}
for content in parameter.content.values() {
validate_content_references(content, policy)?;
}
Ok(())
}
fn validate_body_references(
body: &RefOr<RequestBody>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(body) = body else {
return validate_reference_object(body, policy);
};
for content in body.content.values() {
validate_content_references(content, policy)?;
}
Ok(())
}
fn validate_callback_references(
callback: &RefOr<Callback>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(callback) = callback else {
return validate_reference_object(callback, policy);
};
for item in callback.values() {
match item {
RefOr::Ref(reference) => validate_reference(&reference.ref_location, policy)?,
RefOr::T(item) => validate_path_item_references(item, policy)?,
}
}
Ok(())
}
fn validate_response_references(
response: &RefOr<Response>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(response) = response else {
return validate_reference_object(response, policy);
};
for header in response.headers.values() {
validate_header_references(header, policy)?;
}
for content in response.content.values() {
validate_content_references(content, policy)?;
}
for link in response.links.values() {
validate_link_references(link, policy)?;
}
Ok(())
}
fn validate_link_references(
link: &RefOr<utoipa::openapi::link::Link>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
match link {
RefOr::Ref(reference) => validate_reference(&reference.ref_location, policy),
RefOr::T(link) => validate_reference(&link.operation_ref, policy),
}
}
fn validate_header_references(
header: &RefOr<Header>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(header) = header else {
return validate_reference_object(header, policy);
};
for schema in header.schema.iter() {
validate_schema_reference(schema, policy)?;
}
for content in header.content.values() {
validate_content_references(content, policy)?;
}
for example in header.examples.values() {
validate_reference_object(example, policy)?;
}
Ok(())
}
fn validate_content_references(
content: &RefOr<Content>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let RefOr::T(content) = content else {
return validate_reference_object(content, policy);
};
for schema in content.schema.iter().chain(&content.item_schema) {
validate_schema_reference(schema, policy)?;
}
for example in content.examples.values() {
validate_reference_object(example, policy)?;
}
for encoding in content
.encoding
.values()
.chain(&content.prefix_encoding)
.chain(content.item_encoding.as_deref())
{
validate_encoding_references(encoding, policy)?;
}
Ok(())
}
fn validate_encoding_references(
encoding: &Encoding,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
for header in encoding.headers.values() {
validate_header_references(header, policy)?;
}
for nested in encoding
.encoding
.values()
.chain(&encoding.prefix_encoding)
.chain(encoding.item_encoding.as_deref())
{
validate_encoding_references(nested, policy)?;
}
Ok(())
}
fn validate_reference_object<T>(
value: &RefOr<T>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
if let RefOr::Ref(reference) = value {
validate_reference(&reference.ref_location, policy)?;
}
Ok(())
}
fn validate_schema_reference(
schema: &RefOr<Schema>,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
match schema {
RefOr::Ref(reference) => validate_reference(&reference.ref_location, policy),
RefOr::T(schema) => validate_schema_references(schema, policy),
}
}
fn validate_schema_references(
schema: &Schema,
policy: ReferencePolicy,
) -> Result<(), OpenApiRouteError> {
let (items, discriminator) = match schema {
Schema::Object(object) => {
if let Some(schema) = &object.content_schema {
validate_schema_reference(schema, policy)?;
}
for property in object.properties.values() {
validate_schema_reference(property, policy)?;
}
if let Some(AdditionalProperties::RefOr(schema)) =
object.additional_properties.as_deref()
{
validate_schema_reference(schema, policy)?;
}
if let Some(schema) = &object.property_names {
validate_schema_references(schema, policy)?;
}
return Ok(());
}
Schema::Array(array) => {
if let Some(schema) = &array.content_schema {
validate_schema_reference(schema, policy)?;
}
if let ArrayItems::RefOrSchema(schema) = &array.items {
validate_schema_reference(schema, policy)?;
}
for schema in &array.prefix_items {
validate_schema_references(schema, policy)?;
}
return Ok(());
}
Schema::OneOf(schema) => (&schema.items, &schema.discriminator),
Schema::AllOf(schema) => (&schema.items, &schema.discriminator),
Schema::AnyOf(schema) => (&schema.items, &schema.discriminator),
_ => {
return Err(OpenApiRouteError::InvalidDocument {
reason: "unsupported schema variant for reference validation",
});
}
};
for schema in items {
validate_schema_reference(schema, policy)?;
}
if let Some(discriminator) = discriminator {
for reference in discriminator.mapping.values() {
validate_reference(reference, policy)?;
}
}
Ok(())
}
fn validate_reference(reference: &str, policy: ReferencePolicy) -> Result<(), OpenApiRouteError> {
let Some(fragment) = reference.strip_prefix('#') else {
return Ok(());
};
let Ok(pointer) = percent_encoding::percent_decode_str(fragment).decode_utf8() else {
return Ok(());
};
let mut segments = pointer.split('/');
if segments.next() != Some("") {
return Ok(());
}
let root = segments.next();
if matches!(policy, ReferencePolicy::Nested) && root == Some("paths") {
return Err(OpenApiRouteError::InvalidDocument {
reason: "nested modules cannot reference local paths; use operation IDs or component references",
});
}
if matches!(policy, ReferencePolicy::Incoming)
&& matches!(root, Some("info" | "tags" | "servers" | "security"))
{
return Err(OpenApiRouteError::InvalidDocument {
reason: "incoming documents cannot reference root info, tags, servers or security; use component references",
});
}
if root == Some("paths") && segments.next().is_some() {
let managed = match segments.next() {
Some("parameters" | "servers") => true,
Some("get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace") => {
segments.next() == Some("parameters")
}
_ => false,
};
if managed {
return Err(OpenApiRouteError::InvalidDocument {
reason: "registered paths cannot be referenced through path parameters, path servers or operation parameters; use component references",
});
}
}
Ok(())
}
fn merge_route_documents(
document: &mut OpenApi,
mut incoming: OpenApi,
) -> Result<(), OpenApiRouteError> {
merge_document_metadata(document, &mut incoming)?;
for (path, item) in &mut incoming.paths.paths {
if let Some(existing) = document.paths.paths.get_mut(path) {
for ((method, operation), (_, existing)) in
operations(item).into_iter().zip(operations(existing))
{
if operation.is_some() && existing.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);
}
}
}
if let Some(mut incoming) = incoming.components.take() {
let existing = document.components.get_or_insert_default();
macro_rules! merge {
($kind:literal, $field:ident) => {
check_components($kind, &existing.$field, &incoming.$field)?;
existing.$field.append(&mut incoming.$field);
};
}
merge!("schema", schemas);
merge!("response", responses);
merge!("parameter", parameters);
merge!("example", examples);
merge!("request body", request_bodies);
merge!("header", headers);
merge!("link", links);
merge!("callback", callbacks);
merge!("path item", path_items);
merge!("media type", media_types);
merge!("security scheme", security_schemes);
merge_extensions(
&mut existing.extensions,
incoming.extensions,
"components.extensions",
)?;
}
document.merge(incoming);
validate_operation_ids(document)
}
fn all_operations(item: &PathItem) -> impl Iterator<Item = &Operation> {
operations(item)
.into_iter()
.filter_map(|(_, operation)| operation)
.chain(item.query.iter())
.chain(item.additional_operations.values())
}
fn validate_operation_ids(document: &OpenApi) -> Result<(), OpenApiRouteError> {
let mut ids = HashSet::new();
for item in document
.paths
.paths
.values()
.chain(
document
.webhooks
.iter()
.flat_map(|webhooks| webhooks.paths.values()),
)
.chain(
document
.components
.iter()
.flat_map(|components| components.path_items.values()),
)
{
validate_path_operation_ids(item, &mut ids)?;
}
for callback in document
.components
.iter()
.flat_map(|components| components.callbacks.values())
{
validate_callback_operation_ids(callback, &mut ids)?;
}
Ok(())
}
fn validate_path_operation_ids<'a>(
item: &'a PathItem,
ids: &mut HashSet<&'a str>,
) -> Result<(), OpenApiRouteError> {
for operation in all_operations(item) {
if let Some(id) = operation.operation_id.as_deref()
&& !ids.insert(id)
{
return Err(OpenApiRouteError::DuplicateOperationId {
operation_id: id.to_owned(),
});
}
for callback in operation.callbacks.values() {
validate_callback_operation_ids(callback, ids)?;
}
}
Ok(())
}
fn validate_callback_operation_ids<'a>(
callback: &'a RefOr<Callback>,
ids: &mut HashSet<&'a str>,
) -> Result<(), OpenApiRouteError> {
if let RefOr::T(callback) = callback {
for item in callback.values() {
if let RefOr::T(item) = item {
validate_path_operation_ids(item, ids)?;
}
}
}
Ok(())
}
fn validate_document_context(
document: &OpenApi,
incoming: &OpenApi,
) -> Result<(), OpenApiRouteError> {
if document.openapi != incoming.openapi {
return Err(OpenApiRouteError::ConflictingDocumentMetadata { field: "openapi" });
}
if document.schema != incoming.schema {
return Err(OpenApiRouteError::ConflictingDocumentMetadata { field: "$schema" });
}
const OAS_DIALECT: &str = "https://spec.openapis.org/oas/3.1/dialect/base";
if document
.json_schema_dialect
.as_deref()
.unwrap_or(OAS_DIALECT)
!= incoming
.json_schema_dialect
.as_deref()
.unwrap_or(OAS_DIALECT)
{
return Err(OpenApiRouteError::ConflictingDocumentMetadata {
field: "jsonSchemaDialect",
});
}
if document.self_uri != incoming.self_uri {
return Err(OpenApiRouteError::ConflictingDocumentMetadata { field: "$self" });
}
Ok(())
}
fn merge_document_metadata(
document: &mut OpenApi,
incoming: &mut OpenApi,
) -> Result<(), OpenApiRouteError> {
validate_document_context(document, incoming)?;
if let Some(mut webhooks) = incoming.webhooks.take() {
let target = document.webhooks.get_or_insert_default();
check_components("webhook", &target.paths, &webhooks.paths)?;
target.paths.append(&mut webhooks.paths);
merge_extensions(
&mut target.extensions,
webhooks.extensions,
"webhooks.extensions",
)?;
}
if let Some(external_docs) = incoming.external_docs.take() {
if document
.external_docs
.as_ref()
.is_some_and(|existing| !same_definition(existing, &external_docs))
{
return Err(OpenApiRouteError::ConflictingDocumentMetadata {
field: "externalDocs",
});
}
document.external_docs = Some(external_docs);
}
{
let mut tags = BTreeMap::new();
for tag in document
.tags
.iter()
.flatten()
.chain(incoming.tags.iter().flatten())
{
if tags
.insert(&tag.name, tag)
.is_some_and(|existing| !same_definition(existing, tag))
{
return Err(OpenApiRouteError::ConflictingTag {
name: tag.name.clone(),
});
}
}
}
if let Some(tags) = incoming.tags.take() {
let target = document.tags.get_or_insert_default();
for tag in tags {
if !target.iter().any(|existing| existing.name == tag.name) {
target.push(tag);
}
}
}
merge_extensions(
&mut document.extensions,
incoming.extensions.take(),
"extensions",
)?;
merge_extensions(
&mut document.paths.extensions,
incoming.paths.extensions.take(),
"paths.extensions",
)?;
if let Some(components) = incoming.components.as_mut() {
merge_extensions(
&mut document.components.get_or_insert_default().extensions,
components.extensions.take(),
"components.extensions",
)?;
}
Ok(())
}
fn merge_extensions(
existing: &mut Option<Extensions>,
incoming: Option<Extensions>,
field: &'static str,
) -> Result<(), OpenApiRouteError> {
if let Some(incoming) = incoming {
let target = existing.get_or_insert_default();
if incoming
.iter()
.any(|(key, value)| target.get(key).is_some_and(|existing| existing != value))
{
return Err(OpenApiRouteError::ConflictingDocumentMetadata { field });
}
target.merge(incoming);
}
Ok(())
}
fn normalize_operation_parameters(
item: &mut PathItem,
components: Option<&Components>,
) -> Result<(), OpenApiRouteError> {
let normalize = |parameters: Option<Vec<RefOr<Parameter>>>| {
parameters
.unwrap_or_default()
.iter()
.map(|parameter| {
resolve_parameter(parameter, components)
.map(std::borrow::Cow::into_owned)
.map(RefOr::T)
.map_err(|reason| OpenApiRouteError::InvalidDocument { reason })
})
.collect::<Result<Vec<_>, _>>()
};
let parameters = normalize(item.parameters.take())?;
validate_unique_parameters(¶meters)?;
item.servers = None;
for operation in operations_mut(item) {
if operation.parameters.is_some() {
operation.parameters = Some(normalize(operation.parameters.take())?);
}
validate_unique_parameters(operation.parameters.as_deref().unwrap_or_default())?;
if !parameters.is_empty() {
let target = operation.parameters.get_or_insert_default();
for parameter in ¶meters {
if !target
.iter()
.any(|existing| same_parameter_ref(existing, parameter))
{
target.push(parameter.clone());
}
}
}
}
Ok(())
}
fn default_servers() -> Vec<Server> {
vec![Server::new("/")]
}
fn document_defaults(document: &OpenApi) -> (Vec<Server>, Vec<SecurityRequirement>) {
(
document.servers.clone().unwrap_or_else(default_servers),
document.security.clone().unwrap_or_default(),
)
}
fn inherit_document_defaults(
document: &mut OpenApi,
document_servers: Option<&[Server]>,
document_security: Option<&[SecurityRequirement]>,
) {
for item in document.paths.paths.values_mut() {
inherit_operation_defaults(item, document_servers, document_security);
}
inherit_reusable_defaults(document, document_servers, document_security);
}
fn inherit_reusable_defaults(
document: &mut OpenApi,
document_servers: Option<&[Server]>,
document_security: Option<&[SecurityRequirement]>,
) {
for item in document
.webhooks
.iter_mut()
.flat_map(|webhooks| webhooks.paths.values_mut())
.chain(
document
.components
.iter_mut()
.flat_map(|components| components.path_items.values_mut()),
)
{
inherit_operation_defaults(item, document_servers, document_security);
}
for callback in document
.components
.iter_mut()
.flat_map(|components| components.callbacks.values_mut())
{
inherit_callback_defaults(callback, document_servers, document_security);
}
}
fn inherit_operation_defaults(
item: &mut PathItem,
document_servers: Option<&[Server]>,
document_security: Option<&[SecurityRequirement]>,
) {
let servers = item
.servers
.as_deref()
.or(document_servers)
.map(<[_]>::to_vec);
for operation in operations_mut(item) {
if operation.servers.is_none() {
operation.servers = servers.clone();
}
if operation.security.is_none() {
operation.security = document_security.map(<[_]>::to_vec);
}
for callback in operation.callbacks.values_mut() {
inherit_callback_defaults(callback, document_servers, document_security);
}
}
}
fn inherit_callback_defaults(
callback: &mut RefOr<Callback>,
document_servers: Option<&[Server]>,
document_security: Option<&[SecurityRequirement]>,
) {
if let RefOr::T(callback) = callback {
for item in callback.values_mut() {
if let RefOr::T(item) = item {
inherit_operation_defaults(item, document_servers, document_security);
}
}
}
}
fn validate_unique_parameters(parameters: &[RefOr<Parameter>]) -> Result<(), OpenApiRouteError> {
if parameters.iter().enumerate().any(|(index, parameter)| {
parameters[..index]
.iter()
.any(|other| same_parameter_ref(parameter, other))
}) {
return Err(OpenApiRouteError::InvalidDocument {
reason: "parameters must be unique by name and location",
});
}
Ok(())
}
fn same_parameter_ref(left: &RefOr<Parameter>, right: &RefOr<Parameter>) -> bool {
match (left, right) {
(RefOr::T(left), RefOr::T(right)) => same_parameter(left, right),
_ => false,
}
}
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 same_definition<T: PartialEq + Serialize>(left: &T, right: &T) -> bool {
left == right
|| matches!((serde_json::to_value(left), serde_json::to_value(right)),
(Ok(left), Ok(right)) if left == right)
}
fn check_components<T: PartialEq + Serialize>(
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| !same_definition(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(),
)
}};
}