footing 0.1.22

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

/// Invalid or conflicting documented route registration.
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum OpenApiRouteError {
    /// Attached endpoint contracts disagree with the documented operations.
    #[error(transparent)]
    InvalidContracts(#[from] OpenApiContractError),
    /// Middleware configuration disagrees with a registered contract.
    #[error(transparent)]
    InvalidMiddleware(#[from] HttpMiddlewareError),
    /// The document does not describe the expected route set.
    #[error("invalid OpenAPI route document: {reason}")]
    InvalidDocument {
        /// Description of the violated registration requirement.
        reason: &'static str,
    },
    /// Registering an operation twice would overwrite its documentation.
    #[error("OpenAPI operation {method} {path} is already registered")]
    DuplicateOperation {
        /// Duplicated HTTP method.
        method: &'static str,
        /// Duplicated path.
        path: String,
    },
    /// Operations must use distinct identifiers across the complete document.
    #[error(
        "OpenAPI operation ID {operation_id} is already registered; set #[utoipa::path(operation_id = \"...\")] to distinguish handlers"
    )]
    DuplicateOperationId {
        /// Duplicated identifier that must be disambiguated.
        operation_id: String,
    },
    /// Two routes assign different definitions to the same component name.
    #[error("conflicting OpenAPI {kind} component {name}")]
    ConflictingComponent {
        /// Kind of component.
        kind: &'static str,
        /// Component name that must be disambiguated.
        name: String,
    },
    /// Routes disagree on metadata shared by all operations at a path.
    #[error("conflicting OpenAPI {field} for path {path}")]
    ConflictingPathMetadata {
        /// Shared metadata field.
        field: &'static str,
        /// Path whose metadata conflicts.
        path: String,
    },
    /// Multiple pagination layers could override each other at runtime.
    #[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",
        })
    }
}

/// An Axum handler and its generated operation metadata.
///
/// Construct with [`super::route!`] so the handler, methods, paths and schemas
/// come from the same `utoipa::path` annotation. Axum's normal route-pattern
/// validation applies when the route is registered.
#[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> {
    /// Associates a handler with its generated single-path document.
    ///
    /// Document-level security and servers apply only to this handler's
    /// operations. Explicit operation values take precedence; path-level
    /// servers also override document-level servers.
    ///
    /// Prefer [`super::route!`], which supplies the matching document automatically.
    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(),
        })
    }

    /// Attaches the contract to this handler, checking its method, path and
    /// documented parameters. Configure pagination before attaching contracts.
    pub fn with_contract<P: Copy + 'static>(
        self,
        contract: EndpointContract<P>,
    ) -> Result<OpenApiRoute<S, P>, OpenApiRouteError> {
        self.with_contracts([contract])
    }

    /// Attaches one contract per documented operation for a multi-method handler.
    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> {
    /// Installs cursor pagination limits and updates the documented parameters.
    ///
    /// This replaces pagination schemas/defaults while retaining unrelated query
    /// parameters and existing descriptions. Use this instead of installing an
    /// independent `Extension<PageLimits>` on a documented route.
    pub fn with_cursor_pagination(self, limits: PageLimits) -> Result<Self, OpenApiRouteError> {
        self.with_pagination(limits, cursor_pagination_parameters(limits))
    }

    /// Installs offset pagination limits and updates the documented parameters.
    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 &parameters {
                    // The route configuration owns the wire constraints. Keep user
                    // descriptions and unrelated metadata when overriding defaults.
                    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)
    }
}

/// Registers Axum routes and OpenAPI operations together.
///
/// Start with a document containing API metadata and reusable components, then
/// add handlers with [`super::route!`]. Attach contracts with
/// [`OpenApiRoute::with_contract`] and finish with [`Self::into_parts_with_stack`]
/// to validate the registered routes against footing's middleware policies.
/// [`Self::into_parts`] preserves the native types and contracts for applications
/// that manage their own middleware. State and documentation routes can then be
/// installed on the resulting Axum router.
#[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> {
    /// Starts with metadata/components, rejecting paths without registered handlers.
    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(),
        })
    }

    /// Registers the generated methods/path and merges their schemas.
    ///
    /// Path parameters and servers retain their per-operation inheritance.
    /// Conflicting operations, components or shared path metadata return errors.
    /// Operation IDs must be unique; use `#[utoipa::path(operation_id = "...")]`
    /// to distinguish handlers with the same name in different modules.
    /// Invalid or ambiguous route patterns follow Axum's startup panic behavior.
    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)
    }

    /// Returns the contracts attached to the registered handlers.
    #[must_use]
    pub fn contracts(&self) -> EndpointContractRegistry<'_, P> {
        EndpointContractRegistry::new(&self.contracts)
    }

    /// Validates complete contract coverage and runtime policies, annotates the
    /// document, and applies the stack to these registered routes.
    ///
    /// Authorization remains the application's responsibility. Use final
    /// application paths when middleware policies match paths; nesting the
    /// finished router requires reviewing those policies.
    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))
    }

    /// Returns the native router, document and attached contracts for applications
    /// that manage middleware themselves. Runtime policies are not validated;
    /// prefer [`Self::into_parts_with_stack`] when using footing's stack.
    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(&parameters)?;
    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 &parameters {
                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(())
}

/// Collects a handler's route and schemas from its `utoipa::path` annotation.
///
/// Returns `Result<OpenApiRoute<S>, OpenApiRouteError>`. Qualified handler paths
/// are supported. No separate `get(handler)` or `#[openapi(paths(handler))]`
/// registration is needed.
#[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(),
        )
    }};
}