Skip to main content

toolkit/api/
openapi_registry.rs

1// Updated: 2026-04-28 by Constructor Tech
2//! `OpenAPI` registry for schema and operation management
3//!
4//! This gear provides a standalone `OpenAPI` registry that collects operation specs
5//! and schemas, and builds a complete `OpenAPI` document from them.
6
7use anyhow::Result;
8use arc_swap::ArcSwap;
9use dashmap::DashMap;
10use std::collections::{BTreeMap, HashSet};
11use std::sync::Arc;
12use utoipa::openapi::{
13    OpenApi, OpenApiBuilder, Ref, RefOr, Required,
14    content::ContentBuilder,
15    header::HeaderBuilder,
16    info::InfoBuilder,
17    path::{
18        HttpMethod, OperationBuilder as UOperationBuilder, ParameterBuilder, ParameterIn,
19        PathItemBuilder, PathsBuilder,
20    },
21    request_body::RequestBodyBuilder,
22    response::{Response, ResponsesBuilder},
23    schema::{ArrayBuilder, ComponentsBuilder, ObjectBuilder, Schema, SchemaFormat, SchemaType},
24    security::{ApiKey, ApiKeyValue, HttpAuthScheme, HttpBuilder, SecurityScheme},
25    server::Server,
26};
27
28use crate::api::operation_builder;
29use toolkit_canonical_errors::problem;
30use toolkit_contract::StreamFraming;
31
32/// Name of the `OpenAPI` apiKey scheme for platform operations, using
33/// [`toolkit_security::constants::INTERNAL_TOKEN_HEADER`].
34pub const INTERNAL_TOKEN_SECURITY_SCHEME: &str = "internalToken";
35
36/// Type alias for schema collections used in API operations.
37type SchemaCollection = Vec<(String, RefOr<Schema>)>;
38
39/// `OpenAPI` document metadata (title, version, description)
40#[derive(Debug, Clone)]
41pub struct OpenApiInfo {
42    pub title: String,
43    pub version: String,
44    pub description: Option<String>,
45    pub servers: Vec<String>,
46}
47
48impl Default for OpenApiInfo {
49    fn default() -> Self {
50        Self {
51            title: "API Documentation".to_owned(),
52            version: "0.1.0".to_owned(),
53            description: None,
54            servers: Vec::new(),
55        }
56    }
57}
58
59/// `OpenAPI` registry trait for operation and schema registration
60pub trait OpenApiRegistry: Send + Sync {
61    /// Register an API operation specification
62    fn register_operation(&self, spec: &operation_builder::OperationSpec);
63
64    /// Ensure schema for a type (including transitive dependencies) is registered
65    /// under components and return the canonical component name for `$ref`.
66    /// This is a type-erased version for dyn compatibility.
67    fn ensure_schema_raw(&self, name: &str, schemas: SchemaCollection) -> String;
68
69    /// Downcast support for accessing the concrete implementation if needed.
70    fn as_any(&self) -> &dyn std::any::Any;
71}
72
73/// Helper function to call `ensure_schema` with proper type information
74///
75/// # Panics
76/// Panics if `T` is a `Vec<_>`. utoipa names every `Vec<_>` `Vec`, so
77/// registering one as a component would collide with every other list
78/// response; use
79/// [`OperationBuilder::json_array_response_with_schema`](crate::api::operation_builder::OperationBuilder::json_array_response_with_schema)
80/// instead. Also panics if `T`'s name is already registered with a different
81/// definition (see `ensure_schema_raw`).
82pub fn ensure_schema<T: utoipa::ToSchema + utoipa::PartialSchema + 'static>(
83    registry: &dyn OpenApiRegistry,
84) -> String {
85    use utoipa::PartialSchema;
86
87    // 1) Canonical component name for T as seen by utoipa
88    let root_name = T::name().to_string();
89
90    // utoipa's default `ToSchema::name()` drops generic arguments, so every
91    // `Vec<_>` collapses to the single name `Vec` and distinct list responses
92    // clobber each other (or, since M-14, panic on collision). `Vec` is a std
93    // type, so `#[schema(as = "...")]` cannot rescue it — the caller has to use
94    // the array-aware builder instead. Guard only this one name: a legitimate
95    // user DTO could plausibly be called `Option`, `Page`, or `Map`.
96    assert!(
97        root_name != "Vec",
98        "ensure_schema::<Vec<_>>() would register the component name `Vec`, which every other \
99         Vec<T> also resolves to. Use `OperationBuilder::json_array_response_with_schema::<Item>()` \
100         to emit an inline array with only the item type named."
101    );
102
103    // 2) Always insert T's own schema first (actual object, not a ref)
104    //    This avoids self-referential components.
105    let mut collected: SchemaCollection = vec![(root_name.clone(), <T as PartialSchema>::schema())];
106
107    // 3) Collect and append all referenced schemas (dependencies) of T
108    T::schemas(&mut collected);
109
110    // 4) Pass to registry for insertion
111    registry.ensure_schema_raw(&root_name, collected)
112}
113
114/// Build the `x-*` vendor extensions for one operation.
115fn operation_vendor_extensions(
116    spec: &operation_builder::OperationSpec,
117) -> utoipa::openapi::extensions::Extensions {
118    let mut ext = utoipa::openapi::extensions::Extensions::default();
119
120    // Pagination
121    if let Some(pagination) = spec.vendor_extensions.x_odata_filter.as_ref()
122        && let Ok(value) = serde_json::to_value(pagination)
123    {
124        ext.insert("x-odata-filter".to_owned(), value);
125    }
126    if let Some(pagination) = spec.vendor_extensions.x_odata_orderby.as_ref()
127        && let Ok(value) = serde_json::to_value(pagination)
128    {
129        ext.insert("x-odata-orderby".to_owned(), value);
130    }
131
132    // GatewayProvider selects proxy routes via this extension (key shared with toolkit-gateway).
133    // The edge strips platform tokens, so platform routes stay unexposed.
134    if spec.exposed && spec.auth != operation_builder::RouteAuth::Platform {
135        ext.insert(
136            "x-toolkit-visibility".to_owned(),
137            serde_json::Value::String("exposed".to_owned()),
138        );
139    }
140
141    // Per-route request deadline, readable by edge gateways that proxy this
142    // route (key shared with toolkit-gateway). `Inherit` emits nothing so the
143    // document stays quiet for the common case.
144    match spec.request_timeout {
145        operation_builder::RouteTimeout::Inherit => {}
146        operation_builder::RouteTimeout::Disabled => {
147            ext.insert(
148                "x-toolkit-request-timeout".to_owned(),
149                serde_json::Value::String("none".to_owned()),
150            );
151        }
152        operation_builder::RouteTimeout::Custom(timeout) => {
153            ext.insert(
154                "x-toolkit-request-timeout".to_owned(),
155                serde_json::Value::String(humantime::format_duration(timeout).to_string()),
156            );
157        }
158    }
159
160    // Throttling zone bindings. The contract layer only knows zone
161    // *names*; the API gateway enriches these operations with the
162    // zones' numeric limits (`x-rate-limit-rps` / `x-rate-limit-burst`)
163    // when it builds the final document, using the zone name emitted
164    // here as the join key.
165    if let Some(throttling) = spec.throttling.as_ref() {
166        if let Some(zone) = throttling.rate_limit_zone.as_ref() {
167            ext.insert(
168                "x-throttling-rate-limit-zone".to_owned(),
169                serde_json::Value::String(zone.clone()),
170            );
171        }
172        if let Some(zone) = throttling.in_flight_limit_zone.as_ref() {
173            ext.insert(
174                "x-throttling-in-flight-limit-zone".to_owned(),
175                serde_json::Value::String(zone.clone()),
176            );
177        }
178    }
179
180    ext
181}
182
183/// Build a scalar parameter schema, preserving its format and minimum.
184///
185/// `format` is the token as the document carries it. `SchemaFormat::Custom`
186/// serializes it verbatim, which is what a `KnownFormat` serializes to as well
187/// — `"int64"` here and `SchemaFormat::KnownFormat(KnownFormat::Int64)` build
188/// the same document — so a declaration site states the token and takes no
189/// `utoipa` dependency for it.
190fn param_schema_object(
191    schema_type: SchemaType,
192    format: Option<&str>,
193    minimum: Option<f64>,
194) -> utoipa::openapi::schema::Object {
195    ObjectBuilder::new()
196        .schema_type(schema_type)
197        .format(format.map(|format| SchemaFormat::Custom(format.to_owned())))
198        .minimum(minimum)
199        .build()
200}
201
202/// Implementation of `OpenAPI` registry with lock-free data structures
203pub struct OpenApiRegistryImpl {
204    /// Store operation specs keyed by "METHOD:path"
205    pub operation_specs: DashMap<String, operation_builder::OperationSpec>,
206    /// Store schema components using arc-swap for lock-free reads
207    /// `BTreeMap` ensures deterministic ordering of schemas in the `OpenAPI` document
208    pub components_registry: ArcSwap<BTreeMap<String, RefOr<Schema>>>,
209}
210
211impl OpenApiRegistryImpl {
212    /// Create a new empty registry
213    #[must_use]
214    pub fn new() -> Self {
215        Self {
216            operation_specs: DashMap::new(),
217            components_registry: ArcSwap::from_pointee(BTreeMap::new()),
218        }
219    }
220
221    /// Build `OpenAPI` specification from registered operations and components.
222    ///
223    /// # Arguments
224    /// * `info` - `OpenAPI` document metadata (title, version, description)
225    ///
226    /// # Errors
227    /// Returns an error if the `OpenAPI` specification cannot be built.
228    #[allow(unknown_lints, de0205_operation_builder)]
229    pub fn build_openapi(&self, info: &OpenApiInfo) -> Result<OpenApi> {
230        use http::Method;
231
232        // Log operation count for visibility
233        let op_count = self.operation_specs.len();
234        tracing::info!("Building OpenAPI: found {op_count} registered operations");
235
236        // 1) Paths
237        let mut paths = PathsBuilder::new();
238
239        for spec in self.operation_specs.iter().map(|e| e.value().clone()) {
240            let mut op = UOperationBuilder::new()
241                .operation_id(spec.operation_id.clone().or(Some(spec.handler_id.clone())))
242                .summary(spec.summary.clone())
243                .description(spec.description.clone());
244
245            for tag in &spec.tags {
246                op = op.tag(tag.clone());
247            }
248
249            let ext = operation_vendor_extensions(&spec);
250            if !ext.is_empty() {
251                op = op.extensions(Some(ext));
252            }
253
254            // Parameters
255            for p in &spec.params {
256                op = op.parameter(build_parameter(p));
257            }
258
259            // Request body
260            if let Some(rb) = &spec.request_body {
261                let content = build_request_body_content(&rb.schema);
262                let mut rbld = RequestBodyBuilder::new()
263                    .description(rb.description.clone())
264                    .content(rb.content_type.to_owned(), content);
265                if rb.required {
266                    rbld = rbld.required(Some(Required::True));
267                }
268                op = op.request_body(Some(rbld.build()));
269            }
270
271            // Responses
272            let mut responses_by_status = BTreeMap::<u16, Response>::new();
273            for r in &spec.responses {
274                let response = responses_by_status
275                    .entry(r.status)
276                    .or_insert_with(|| Response::new(&r.description));
277                // Preserve the historical last-declaration-wins behavior for
278                // the status-level description while merging media types.
279                response.description.clone_from(&r.description);
280
281                // Body-less response (e.g. 204 No Content) is signalled by an
282                // empty `content_type`. Emit just `description` — attaching a
283                // `content` block would make code-generators expect a body.
284                if !r.content_type.is_empty() {
285                    // Streaming media types are json-like here too: their
286                    // declared schema is the *item* type, so it must render as
287                    // a `$ref` rather than as an opaque string blob. Derived
288                    // from `StreamFraming` rather than hard-coded, so a new
289                    // framing variant is covered automatically instead of
290                    // silently falling through to the opaque-string branch.
291                    let is_json_like = r.content_type == "application/json"
292                        || r.content_type == problem::APPLICATION_PROBLEM_JSON
293                        || StreamFraming::is_stream_media_type(r.content_type);
294                    let content = if is_json_like {
295                        // Manually build content to preserve the correct content type.
296                        ContentBuilder::new()
297                            .schema(Some(build_response_schema(r.schema.as_ref())))
298                            .build()
299                    } else {
300                        let schema = Schema::Object(
301                            ObjectBuilder::new()
302                                .schema_type(SchemaType::Type(
303                                    utoipa::openapi::schema::Type::String,
304                                ))
305                                .format(Some(SchemaFormat::Custom(r.content_type.into())))
306                                .build(),
307                        );
308                        ContentBuilder::new().schema(Some(schema)).build()
309                    };
310                    response.content.insert(r.content_type.to_owned(), content);
311                }
312
313                for header in &r.headers {
314                    let schema_type = match header.header_type {
315                        operation_builder::ResponseHeaderType::String => {
316                            SchemaType::Type(utoipa::openapi::schema::Type::String)
317                        }
318                        operation_builder::ResponseHeaderType::Integer => {
319                            SchemaType::Type(utoipa::openapi::schema::Type::Integer)
320                        }
321                        operation_builder::ResponseHeaderType::Boolean => {
322                            SchemaType::Type(utoipa::openapi::schema::Type::Boolean)
323                        }
324                    };
325                    let declared = HeaderBuilder::new()
326                        .description(header.description.clone())
327                        .schema(ObjectBuilder::new().schema_type(schema_type).build())
328                        .build();
329                    response.headers.insert(header.name.clone(), declared);
330                }
331            }
332            let responses = ResponsesBuilder::new().responses_from_iter(
333                responses_by_status
334                    .into_iter()
335                    .map(|(status, response)| (status.to_string(), response)),
336            );
337            op = op.responses(responses.build());
338
339            // Platform operations require internalToken, not bearerAuth.
340            let scheme = match spec.auth {
341                operation_builder::RouteAuth::Platform => Some(INTERNAL_TOKEN_SECURITY_SCHEME),
342                operation_builder::RouteAuth::Authenticated => Some("bearerAuth"),
343                operation_builder::RouteAuth::Anonymous => None,
344            };
345            if let Some(scheme) = scheme {
346                op = op.security(utoipa::openapi::security::SecurityRequirement::new(
347                    scheme,
348                    Vec::<String>::new(),
349                ));
350            }
351
352            let method = match spec.method {
353                Method::POST => HttpMethod::Post,
354                Method::PUT => HttpMethod::Put,
355                Method::DELETE => HttpMethod::Delete,
356                Method::PATCH => HttpMethod::Patch,
357                // GET and any other method default to Get
358                _ => HttpMethod::Get,
359            };
360
361            let item = PathItemBuilder::new().operation(method, op.build()).build();
362            // Convert Axum-style path to OpenAPI-style path
363            let openapi_path = operation_builder::axum_to_openapi_path(&spec.path);
364            paths = paths.path(openapi_path, item);
365        }
366
367        // 2) Components (from our registry)
368        let reg = self.components_registry.load();
369        let mut components = ComponentsBuilder::new();
370        for (name, schema) in reg.iter() {
371            components = components.schema(name.clone(), schema.clone());
372        }
373
374        // Add bearer auth security scheme
375        components = components.security_scheme(
376            "bearerAuth",
377            SecurityScheme::Http(
378                HttpBuilder::new()
379                    .scheme(HttpAuthScheme::Bearer)
380                    .bearer_format("JWT")
381                    .build(),
382            ),
383        );
384
385        // Platform-plane internal token, required by platform operations
386        components = components.security_scheme(
387            INTERNAL_TOKEN_SECURITY_SCHEME,
388            SecurityScheme::ApiKey(ApiKey::Header(ApiKeyValue::with_description(
389                toolkit_security::constants::INTERNAL_TOKEN_HEADER,
390                "Platform-plane workload credential, validated by the receiving listener",
391            ))),
392        );
393
394        // 3) Info & final OpenAPI doc
395        let openapi_info = InfoBuilder::new()
396            .title(&info.title)
397            .version(&info.version)
398            .description(info.description.clone())
399            .build();
400
401        let servers = (!info.servers.is_empty()).then(|| {
402            info.servers
403                .iter()
404                .cloned()
405                .map(Server::new)
406                .collect::<Vec<_>>()
407        });
408
409        let mut openapi = OpenApiBuilder::new()
410            .info(openapi_info)
411            .servers(servers)
412            .paths(paths.build())
413            .components(Some(components.build()))
414            .build();
415
416        // Document-level vendor extension: this spec is generated from Rust
417        // contract traits + `schemars`/`utoipa` schemas, which cover a deliberate
418        // subset of REST (ADR-0002). It is the MINIMUM conformance contract —
419        // remote services may expose strictly more, never less. Downstream
420        // directory validators key their superset semantics off this marker.
421        let mut ext = utoipa::openapi::extensions::Extensions::default();
422        ext.insert(
423            "x-toolkit-spec-scope".to_owned(),
424            serde_json::json!("minimum-conformance"),
425        );
426        openapi.extensions = Some(ext);
427
428        warn_dangling_refs_in_openapi(&openapi);
429
430        Ok(openapi)
431    }
432}
433
434impl Default for OpenApiRegistryImpl {
435    fn default() -> Self {
436        Self::new()
437    }
438}
439
440impl OpenApiRegistry for OpenApiRegistryImpl {
441    fn register_operation(&self, spec: &operation_builder::OperationSpec) {
442        let operation_key = format!("{}:{}", spec.method.as_str(), spec.path);
443        // Normalize platform visibility at registration; warn once instead of on each document
444        // build.
445        let mut spec = std::borrow::Cow::Borrowed(spec);
446        if spec.exposed && spec.auth == operation_builder::RouteAuth::Platform {
447            tracing::warn!(
448                method = %spec.method,
449                path = %spec.path,
450                "a platform-authenticated operation is declared exposed; it is not exposed"
451            );
452            spec.to_mut().exposed = false;
453        }
454        let spec = spec.as_ref();
455        // Surface duplicate (method, path) registrations — e.g. a generated
456        // `register_<trait>_routes()` colliding with a hand-written route, or two
457        // SDKs registering the same path (M-13). Silently overwriting the earlier
458        // operation's OpenAPI spec is a hard-to-diagnose drift; the axum router
459        // itself will also panic on the duplicate route at bind time.
460        if let Some(prev) = self
461            .operation_specs
462            .insert(operation_key.clone(), spec.clone())
463            && prev.handler_id != spec.handler_id
464        {
465            tracing::warn!(
466                operation_key = %operation_key,
467                previous_handler = %prev.handler_id,
468                new_handler = %spec.handler_id,
469                "duplicate OpenAPI operation registration; the earlier operation spec was \
470                 overwritten - generated and manual routes must not share a (method, path)"
471            );
472        }
473
474        tracing::debug!(
475            handler_id = %spec.handler_id,
476            method = %spec.method.as_str(),
477            path = %spec.path,
478            summary = %spec.summary.as_deref().unwrap_or("No summary"),
479            operation_key = %operation_key,
480            "Registered API operation in registry"
481        );
482    }
483
484    fn ensure_schema_raw(&self, root_name: &str, schemas: SchemaCollection) -> String {
485        // Snapshot & copy-on-write
486        let current = self.components_registry.load();
487        let mut reg = (**current).clone();
488
489        for (name, schema) in schemas {
490            // Conflict policy: identical → no-op; different → HARD ERROR. Two
491            // distinct types resolving to the same schema name (utoipa uses the
492            // bare type ident by default) would otherwise silently clobber each
493            // other in `components.schemas`, producing a spec where one type
494            // masquerades under another's name — a hard-to-diagnose wire
495            // mismatch. Fail fast at registration instead.
496            if let Some(existing) = reg.get(&name) {
497                let a = serde_json::to_value(existing).ok();
498                let b = serde_json::to_value(&schema).ok();
499                if a == b {
500                    continue; // Skip identical schemas
501                }
502                panic!(
503                    "OpenAPI schema name collision: `{name}` is registered with two different \
504                     definitions. Two distinct types share the same schema name — rename one, or \
505                     give it a distinct `#[schema(as = \"...\")]` alias. For a `Vec<T>` response \
506                     use `OperationBuilder::json_array_response_with_schema::<T>()`, which emits \
507                     an inline array instead of registering a component named `Vec`. \
508                     existing={}, new={}",
509                    a.map(|v| truncate_json(&v)).unwrap_or_default(),
510                    b.map(|v| truncate_json(&v)).unwrap_or_default(),
511                );
512            }
513            reg.insert(name, schema);
514        }
515
516        self.components_registry.store(Arc::new(reg));
517        root_name.to_owned()
518    }
519
520    fn as_any(&self) -> &dyn std::any::Any {
521        self
522    }
523}
524
525/// Render a JSON value to a compact, length-bounded string for diagnostics.
526/// Bounded by character count (char-boundary safe) rather than bytes.
527fn truncate_json(v: &serde_json::Value) -> String {
528    const MAX: usize = 200;
529    let s = v.to_string();
530    if s.chars().count() > MAX {
531        let mut out: String = s.chars().take(MAX).collect();
532        out.push('\u{2026}');
533        out
534    } else {
535        s
536    }
537}
538
539/// One `ParamSpec` as the document's parameter object.
540fn build_parameter(p: &operation_builder::ParamSpec) -> utoipa::openapi::path::Parameter {
541    let in_ = match p.location {
542        operation_builder::ParamLocation::Path => ParameterIn::Path,
543        operation_builder::ParamLocation::Query => ParameterIn::Query,
544        operation_builder::ParamLocation::Header => ParameterIn::Header,
545        operation_builder::ParamLocation::Cookie => ParameterIn::Cookie,
546    };
547    let required = if matches!(p.location, operation_builder::ParamLocation::Path) || p.required {
548        Required::True
549    } else {
550        Required::False
551    };
552
553    let schema_type = match p.param_type.as_str() {
554        "integer" => SchemaType::Type(utoipa::openapi::schema::Type::Integer),
555        "number" => SchemaType::Type(utoipa::openapi::schema::Type::Number),
556        "boolean" => SchemaType::Type(utoipa::openapi::schema::Type::Boolean),
557        _ => SchemaType::Type(utoipa::openapi::schema::Type::String),
558    };
559    let mut item_object = param_schema_object(schema_type, p.format.as_deref(), p.minimum);
560    // A closed set of values stays a string in the document; the `enum` is
561    // what tells a generated client which ones it may send.
562    if !p.enum_values.is_empty() {
563        item_object = ObjectBuilder::from(item_object)
564            .enum_values(Some(p.enum_values.clone()))
565            .build();
566    }
567
568    let mut builder = ParameterBuilder::new()
569        .name(&p.name)
570        .parameter_in(in_)
571        .required(required)
572        .description(p.description.clone());
573
574    if p.array {
575        // `style: form, explode: true` is the repeated-key encoding
576        // (`?tag=a&tag=b`). Spelling it out matters: the OpenAPI default for a
577        // query array is `form` with `explode: true`, but generators differ on
578        // whether they assume it, and the wire format has to be unambiguous
579        // for a client written against this spec to interoperate.
580        builder = builder
581            .style(Some(utoipa::openapi::path::ParameterStyle::Form))
582            .explode(Some(true))
583            .schema(Some(Schema::Array(
584                utoipa::openapi::schema::ArrayBuilder::new()
585                    .items(item_object)
586                    .build(),
587            )));
588    } else {
589        builder = builder.schema(Some(Schema::Object(item_object)));
590    }
591
592    builder.build()
593}
594
595/// Build the `OpenAPI` content object for a request body schema variant.
596fn build_request_body_content(
597    schema: &operation_builder::RequestBodySchema,
598) -> utoipa::openapi::content::Content {
599    match schema {
600        operation_builder::RequestBodySchema::Ref { schema_name } => ContentBuilder::new()
601            .schema(Some(RefOr::Ref(Ref::from_schema_name(schema_name.clone()))))
602            .build(),
603        operation_builder::RequestBodySchema::MultipartFile { field_name } => {
604            // Build multipart/form-data schema with a single binary file field
605            // type: object
606            // properties:
607            //   {field_name}: { type: string, format: binary }
608            // required: [ field_name ]
609            let file_schema = Schema::Object(
610                ObjectBuilder::new()
611                    .schema_type(SchemaType::Type(utoipa::openapi::schema::Type::String))
612                    .format(Some(SchemaFormat::Custom("binary".into())))
613                    .build(),
614            );
615            let obj = ObjectBuilder::new()
616                .property(field_name.clone(), file_schema)
617                .required(field_name.clone());
618            ContentBuilder::new()
619                .schema(Some(Schema::Object(obj.build())))
620                .build()
621        }
622        operation_builder::RequestBodySchema::Binary => {
623            // Represent raw binary body as type string, format binary.
624            // This is used for application/octet-stream and similar raw binary content.
625            let schema = Schema::Object(
626                ObjectBuilder::new()
627                    .schema_type(SchemaType::Type(utoipa::openapi::schema::Type::String))
628                    .format(Some(SchemaFormat::Custom("binary".into())))
629                    .build(),
630            );
631            ContentBuilder::new().schema(Some(schema)).build()
632        }
633        operation_builder::RequestBodySchema::InlineObject => {
634            // Preserve previous behavior for inline object bodies
635            ContentBuilder::new()
636                .schema(Some(Schema::Object(ObjectBuilder::new().build())))
637                .build()
638        }
639    }
640}
641
642/// Build the response body schema for a [`operation_builder::ResponseSchema`].
643///
644/// `None` — a JSON response with no declared schema — yields a free-form
645/// object, preserving the previous behaviour.
646fn build_response_schema(schema: Option<&operation_builder::ResponseSchema>) -> RefOr<Schema> {
647    match schema {
648        Some(operation_builder::ResponseSchema::Ref { schema_name }) => {
649            RefOr::Ref(Ref::from_schema_name(schema_name.clone()))
650        }
651        // Top-level arrays are emitted INLINE, with only the item type
652        // registered as a named component. Naming the array itself would use
653        // utoipa's `Vec` (generics are stripped from `ToSchema::name()`), so
654        // every list endpoint in the process would fight over one component.
655        Some(operation_builder::ResponseSchema::Array { items_schema_name }) => {
656            RefOr::T(Schema::Array(
657                ArrayBuilder::new()
658                    .items(RefOr::Ref(Ref::from_schema_name(items_schema_name.clone())))
659                    .build(),
660            ))
661        }
662        None => RefOr::T(Schema::Object(ObjectBuilder::new().build())),
663    }
664}
665
666/// Walk the finalized `OpenAPI` document and warn about dangling `$ref` targets.
667///
668/// Scans the entire document (operations, request bodies, responses, and schemas)
669/// so that `$ref`s emitted outside `components.schemas` are also caught.
670fn warn_dangling_refs_in_openapi(openapi: &OpenApi) {
671    for ref_name in &collect_all_dangling_refs_in_openapi(openapi) {
672        tracing::warn!(
673            schema = %ref_name,
674            "Dangling $ref: schema '{}' is referenced but not registered. \
675             Add an explicit `ensure_schema::<T>(registry)` call.",
676            ref_name,
677        );
678    }
679}
680
681/// Serialize the full `OpenAPI` document to JSON, collect every
682/// `#/components/schemas/{name}` reference, and return those not defined
683/// in `components.schemas`.
684fn collect_all_dangling_refs_in_openapi(openapi: &OpenApi) -> Vec<String> {
685    let value = match serde_json::to_value(openapi) {
686        Ok(v) => v,
687        Err(err) => {
688            tracing::debug!(error = %err, "Failed to serialize OpenAPI doc for dangling $ref check");
689            return Vec::new();
690        }
691    };
692
693    let mut all_refs = HashSet::new();
694    collect_refs_from_json(&value, &mut all_refs);
695
696    // Defined schema names live under components.schemas keys
697    let defined: HashSet<&str> = value
698        .pointer("/components/schemas")
699        .and_then(|v| v.as_object())
700        .map(|obj| obj.keys().map(String::as_str).collect())
701        .unwrap_or_default();
702
703    all_refs
704        .into_iter()
705        .filter(|name| !defined.contains(name.as_str()))
706        .collect()
707}
708
709/// Recursively extract `#/components/schemas/{name}` targets from a JSON value.
710fn collect_refs_from_json(value: &serde_json::Value, refs: &mut HashSet<String>) {
711    match value {
712        serde_json::Value::Object(map) => {
713            if let Some(serde_json::Value::String(ref_str)) = map.get("$ref")
714                && let Some(name) = ref_str.strip_prefix("#/components/schemas/")
715            {
716                refs.insert(name.to_owned());
717            }
718            for v in map.values() {
719                collect_refs_from_json(v, refs);
720            }
721        }
722        serde_json::Value::Array(arr) => {
723            for v in arr {
724                collect_refs_from_json(v, refs);
725            }
726        }
727        _ => {}
728    }
729}
730
731#[cfg(test)]
732#[cfg_attr(coverage_nightly, coverage(off))]
733mod tests {
734    use super::*;
735    use crate::api::operation_builder::{
736        OperationSpec, ParamSpec, ResponseHeaderSpec, ResponseHeaderType, ResponseSchema,
737        ResponseSpec, RouteTimeout, VendorExtensions,
738    };
739    use http::Method;
740
741    /// Minimal `OperationSpec` carrying a single 200 response with `schema`.
742    fn spec_with_response(
743        path: &str,
744        handler: &str,
745        schema: Option<ResponseSchema>,
746    ) -> OperationSpec {
747        OperationSpec {
748            method: Method::GET,
749            path: path.to_owned(),
750            operation_id: Some(handler.to_owned()),
751            summary: None,
752            description: None,
753            tags: vec![],
754            params: vec![],
755            request_body: None,
756            responses: vec![ResponseSpec {
757                status: 200,
758                content_type: "application/json",
759                description: "OK".to_owned(),
760                schema,
761                headers: vec![],
762            }],
763            handler_id: handler.to_owned(),
764            auth: operation_builder::RouteAuth::Anonymous,
765            exposed: false,
766            throttling: None,
767            allowed_request_content_types: None,
768            vendor_extensions: VendorExtensions::default(),
769            license_requirement: None,
770            request_timeout: RouteTimeout::Inherit,
771        }
772    }
773
774    /// The 200 response schema for `path`, as JSON.
775    fn response_schema_json(doc: &serde_json::Value, path: &str) -> serde_json::Value {
776        doc["paths"][path]["get"]["responses"]["200"]["content"]["application/json"]["schema"]
777            .clone()
778    }
779
780    fn test_info() -> OpenApiInfo {
781        OpenApiInfo {
782            title: "T".to_owned(),
783            version: "1".to_owned(),
784            description: None,
785            servers: Vec::new(),
786        }
787    }
788
789    #[test]
790    fn throttling_zone_names_are_emitted_as_vendor_extensions() {
791        use crate::api::operation_builder::ThrottlingSpec;
792
793        let registry = OpenApiRegistryImpl::new();
794        let mut spec = spec_with_response("/throttled", "throttled_op", None);
795        spec.throttling = Some(ThrottlingSpec {
796            rate_limit_zone: Some("rl_zone".to_owned()),
797            in_flight_limit_zone: Some("ifl_zone".to_owned()),
798            require_security_context: false,
799            dry_run: false,
800        });
801        registry.register_operation(&spec);
802        // An operation without throttling must not carry the extensions.
803        registry.register_operation(&spec_with_response("/plain", "plain_op", None));
804
805        let doc = registry.build_openapi(&test_info()).unwrap();
806        let json = serde_json::to_value(&doc).unwrap();
807
808        let throttled = &json["paths"]["/throttled"]["get"];
809        assert_eq!(
810            throttled["x-throttling-rate-limit-zone"],
811            serde_json::json!("rl_zone")
812        );
813        assert_eq!(
814            throttled["x-throttling-in-flight-limit-zone"],
815            serde_json::json!("ifl_zone")
816        );
817
818        let plain = &json["paths"]["/plain"]["get"];
819        assert!(plain.get("x-throttling-rate-limit-zone").is_none());
820        assert!(plain.get("x-throttling-in-flight-limit-zone").is_none());
821    }
822
823    #[test]
824    fn request_timeout_is_emitted_as_a_vendor_extension() {
825        use std::time::Duration;
826
827        let registry = OpenApiRegistryImpl::new();
828
829        let mut custom = spec_with_response("/custom", "custom_op", None);
830        custom.request_timeout = RouteTimeout::Custom(Duration::from_secs(60));
831        registry.register_operation(&custom);
832
833        let mut disabled = spec_with_response("/stream", "stream_op", None);
834        disabled.request_timeout = RouteTimeout::Disabled;
835        registry.register_operation(&disabled);
836
837        registry.register_operation(&spec_with_response("/inherit", "inherit_op", None));
838
839        let doc = registry.build_openapi(&test_info()).expect("build OpenAPI");
840        let json = serde_json::to_value(&doc).expect("serialize OpenAPI");
841
842        // `Custom` emits humantime's normalised form (`60s` renders as `"1m"`),
843        // pinned so a formatting change can't silently shift the wire contract
844        // toolkit-gateway's `parse_request_timeout` reads.
845        let emitted = json["paths"]["/custom"]["get"]["x-toolkit-request-timeout"]
846            .as_str()
847            .expect("a Custom timeout emits a string");
848        assert_eq!(emitted, "1m");
849        assert_eq!(
850            humantime::parse_duration(emitted).expect("the emitted string is valid humantime"),
851            Duration::from_secs(60)
852        );
853
854        assert_eq!(
855            json["paths"]["/stream"]["get"]["x-toolkit-request-timeout"],
856            serde_json::json!("none"),
857        );
858
859        // `Inherit` (the default) stays quiet so the common case is unchanged.
860        assert!(
861            json["paths"]["/inherit"]["get"]
862                .get("x-toolkit-request-timeout")
863                .is_none(),
864        );
865    }
866
867    #[test]
868    fn test_registry_creation() {
869        let registry = OpenApiRegistryImpl::new();
870        assert_eq!(registry.operation_specs.len(), 0);
871        assert_eq!(registry.components_registry.load().len(), 0);
872    }
873
874    #[test]
875    fn parameter_formats_are_preserved_in_scalar_and_array_schemas() {
876        use serde_json::json;
877
878        // `int64` is a format `utoipa` knows and `resource-version` is not:
879        // both reach the document as the token the declaration spelled, which
880        // is what lets `ParamSpec::format` be a plain string.
881        for (format, param_type, expected) in [
882            (
883                Some("int64"),
884                "integer",
885                json!({"type": "integer", "format": "int64", "minimum": 1}),
886            ),
887            (
888                Some("resource-version"),
889                "integer",
890                json!({"type": "integer", "format": "resource-version", "minimum": 1}),
891            ),
892            (None, "integer", json!({"type": "integer", "minimum": 1})),
893        ] {
894            for array in [false, true] {
895                let registry = OpenApiRegistryImpl::new();
896                let mut spec = spec_with_response("/test", "get_test", None);
897                let mut param = ParamSpec::query("version")
898                    .required(true)
899                    .param_type(param_type)
900                    .array(array)
901                    .minimum(1.0);
902                if let Some(format) = format {
903                    param = param.format(format);
904                }
905                spec.params.push(param);
906                registry.register_operation(&spec);
907                let doc = registry.build_openapi(&test_info()).expect("build OpenAPI");
908                let json = serde_json::to_value(doc).expect("serialize OpenAPI");
909                let schema = &json["paths"]["/test"]["get"]["parameters"][0]["schema"];
910                let expected_schema = if array {
911                    json!({"type": "array", "items": expected})
912                } else {
913                    expected.clone()
914                };
915                assert_eq!(schema, &expected_schema, "format={format:?}, array={array}");
916            }
917        }
918    }
919
920    #[test]
921    fn test_register_operation() {
922        let registry = OpenApiRegistryImpl::new();
923        let spec = OperationSpec {
924            method: Method::GET,
925            path: "/test".to_owned(),
926            operation_id: Some("test_op".to_owned()),
927            summary: Some("Test operation".to_owned()),
928            description: None,
929            tags: vec![],
930            params: vec![],
931            request_body: None,
932            responses: vec![ResponseSpec {
933                status: 200,
934                content_type: "application/json",
935                description: "Success".to_owned(),
936                schema: None,
937                headers: vec![],
938            }],
939            handler_id: "get_test".to_owned(),
940            auth: operation_builder::RouteAuth::Anonymous,
941            exposed: false,
942            throttling: None,
943            allowed_request_content_types: None,
944            vendor_extensions: VendorExtensions::default(),
945            license_requirement: None,
946            request_timeout: RouteTimeout::Inherit,
947        };
948
949        registry.register_operation(&spec);
950        assert_eq!(registry.operation_specs.len(), 1);
951    }
952
953    #[test]
954    fn response_headers_are_emitted_with_their_declared_types() {
955        let registry = OpenApiRegistryImpl::new();
956        let mut spec = spec_with_response("/submit", "submit", None);
957        spec.responses[0].headers = vec![
958            ResponseHeaderSpec::new(
959                "Location",
960                "Operation resource URI",
961                ResponseHeaderType::String,
962            ),
963            ResponseHeaderSpec::new(
964                "Retry-After",
965                "Retry delay in seconds",
966                ResponseHeaderType::Integer,
967            ),
968            ResponseHeaderSpec::new(
969                "Idempotency-Replayed",
970                "Whether this is a replay",
971                ResponseHeaderType::Boolean,
972            ),
973        ];
974        registry.register_operation(&spec);
975
976        let doc = registry.build_openapi(&test_info()).unwrap();
977        let json = serde_json::to_value(doc).unwrap();
978        let headers = &json["paths"]["/submit"]["get"]["responses"]["200"]["headers"];
979        assert_eq!(headers["Location"]["schema"]["type"], "string");
980        assert_eq!(headers["Location"]["description"], "Operation resource URI");
981        assert_eq!(headers["Retry-After"]["schema"]["type"], "integer");
982        assert_eq!(headers["Idempotency-Replayed"]["schema"]["type"], "boolean");
983    }
984
985    #[test]
986    fn response_content_types_with_the_same_status_are_combined() {
987        let registry = OpenApiRegistryImpl::new();
988        let mut spec = spec_with_response("/document", "document", None);
989        spec.responses[0].content_type = "text/plain";
990        spec.responses[0].description = "Plain document".to_owned();
991        spec.responses[0].headers = vec![ResponseHeaderSpec::new(
992            "X-Plain-Document",
993            "Whether plain text is available",
994            ResponseHeaderType::Boolean,
995        )];
996        spec.responses.push(
997            ResponseSpec::new(
998                http::StatusCode::OK.as_u16(),
999                "text/html",
1000                "HTML document",
1001                None,
1002            )
1003            .with_headers([ResponseHeaderSpec::new(
1004                "X-HTML-Document",
1005                "Whether HTML is available",
1006                ResponseHeaderType::Boolean,
1007            )]),
1008        );
1009        registry.register_operation(&spec);
1010
1011        let doc = registry.build_openapi(&test_info()).unwrap();
1012        let json = serde_json::to_value(doc).unwrap();
1013        let response = &json["paths"]["/document"]["get"]["responses"]["200"];
1014        assert_eq!(response["description"], "HTML document");
1015        assert_eq!(
1016            response["content"]["text/plain"]["schema"]["format"],
1017            "text/plain"
1018        );
1019        assert_eq!(
1020            response["content"]["text/html"]["schema"]["format"],
1021            "text/html"
1022        );
1023        assert_eq!(
1024            response["headers"]["X-Plain-Document"]["schema"]["type"],
1025            "boolean"
1026        );
1027        assert_eq!(
1028            response["headers"]["X-HTML-Document"]["schema"]["type"],
1029            "boolean"
1030        );
1031    }
1032
1033    #[test]
1034    fn bodyless_response_can_declare_headers_without_content() {
1035        let registry = OpenApiRegistryImpl::new();
1036        let mut spec = spec_with_response("/jobs", "jobs", None);
1037        spec.responses[0].content_type = "";
1038        spec.responses[0].schema = None;
1039        spec.responses[0].headers = vec![ResponseHeaderSpec::without_description(
1040            "Retry-After",
1041            ResponseHeaderType::Integer,
1042        )];
1043        registry.register_operation(&spec);
1044
1045        let doc = registry.build_openapi(&test_info()).unwrap();
1046        let json = serde_json::to_value(doc).unwrap();
1047        let response = &json["paths"]["/jobs"]["get"]["responses"]["200"];
1048        assert!(response.get("content").is_none());
1049        assert_eq!(
1050            response["headers"]["Retry-After"]["schema"]["type"],
1051            "integer"
1052        );
1053        assert!(
1054            response["headers"]["Retry-After"]
1055                .get("description")
1056                .is_none()
1057        );
1058    }
1059
1060    #[test]
1061    fn test_build_empty_openapi() {
1062        let registry = OpenApiRegistryImpl::new();
1063        let info = OpenApiInfo {
1064            title: "Test API".to_owned(),
1065            version: "1.0.0".to_owned(),
1066            description: Some("Test API Description".to_owned()),
1067            servers: Vec::new(),
1068        };
1069        let doc = registry.build_openapi(&info).unwrap();
1070        let json = serde_json::to_value(&doc).unwrap();
1071
1072        // Verify it's valid OpenAPI document structure
1073        assert!(json.get("openapi").is_some());
1074        assert!(json.get("info").is_some());
1075        assert!(json.get("paths").is_some());
1076
1077        // Verify info section
1078        let openapi_info = json.get("info").unwrap();
1079        assert_eq!(openapi_info.get("title").unwrap(), "Test API");
1080        assert_eq!(openapi_info.get("version").unwrap(), "1.0.0");
1081        assert_eq!(
1082            openapi_info.get("description").unwrap(),
1083            "Test API Description"
1084        );
1085    }
1086
1087    #[test]
1088    fn test_build_openapi_with_operation() {
1089        let registry = OpenApiRegistryImpl::new();
1090        let spec = OperationSpec {
1091            method: Method::GET,
1092            path: "/users/{id}".to_owned(),
1093            operation_id: Some("get_user".to_owned()),
1094            summary: Some("Get user by ID".to_owned()),
1095            description: Some("Retrieves a user by their ID".to_owned()),
1096            tags: vec!["users".to_owned()],
1097            params: vec![ParamSpec::path("id").description("User ID")],
1098            request_body: None,
1099            responses: vec![ResponseSpec {
1100                status: 200,
1101                content_type: "application/json",
1102                description: "User found".to_owned(),
1103                schema: None,
1104                headers: vec![],
1105            }],
1106            handler_id: "get_users_id".to_owned(),
1107            auth: operation_builder::RouteAuth::Anonymous,
1108            exposed: false,
1109            throttling: None,
1110            allowed_request_content_types: None,
1111            vendor_extensions: VendorExtensions::default(),
1112            license_requirement: None,
1113            request_timeout: RouteTimeout::Inherit,
1114        };
1115
1116        registry.register_operation(&spec);
1117        let info = OpenApiInfo::default();
1118        let doc = registry.build_openapi(&info).unwrap();
1119        let json = serde_json::to_value(&doc).unwrap();
1120
1121        // Verify path exists
1122        let paths = json.get("paths").unwrap();
1123        assert!(paths.get("/users/{id}").is_some());
1124
1125        // Verify operation details
1126        let get_op = paths.get("/users/{id}").unwrap().get("get").unwrap();
1127        assert_eq!(get_op.get("operationId").unwrap(), "get_user");
1128        assert_eq!(get_op.get("summary").unwrap(), "Get user by ID");
1129    }
1130
1131    #[test]
1132    fn test_ensure_schema_raw() {
1133        let registry = OpenApiRegistryImpl::new();
1134        let schema = Schema::Object(ObjectBuilder::new().build());
1135        let schemas = vec![("TestSchema".to_owned(), RefOr::T(schema))];
1136
1137        let name = registry.ensure_schema_raw("TestSchema", schemas);
1138        assert_eq!(name, "TestSchema");
1139        assert_eq!(registry.components_registry.load().len(), 1);
1140    }
1141
1142    #[test]
1143    fn test_build_openapi_with_binary_request() {
1144        use crate::api::operation_builder::RequestBodySchema;
1145
1146        let registry = OpenApiRegistryImpl::new();
1147        let spec = OperationSpec {
1148            method: Method::POST,
1149            path: "/files/v1/upload".to_owned(),
1150            operation_id: Some("upload_file".to_owned()),
1151            summary: Some("Upload a file".to_owned()),
1152            description: Some("Upload raw binary file".to_owned()),
1153            tags: vec!["upload".to_owned()],
1154            params: vec![],
1155            request_body: Some(crate::api::operation_builder::RequestBodySpec {
1156                content_type: "application/octet-stream",
1157                description: Some("Raw file bytes".to_owned()),
1158                schema: RequestBodySchema::Binary,
1159                required: true,
1160            }),
1161            responses: vec![ResponseSpec {
1162                status: 200,
1163                content_type: "application/json",
1164                description: "Upload successful".to_owned(),
1165                schema: None,
1166                headers: vec![],
1167            }],
1168            handler_id: "post_upload".to_owned(),
1169            auth: operation_builder::RouteAuth::Anonymous,
1170            exposed: false,
1171            throttling: None,
1172            allowed_request_content_types: Some(vec!["application/octet-stream"]),
1173            vendor_extensions: VendorExtensions::default(),
1174            license_requirement: None,
1175            request_timeout: RouteTimeout::Inherit,
1176        };
1177
1178        registry.register_operation(&spec);
1179        let info = OpenApiInfo::default();
1180        let doc = registry.build_openapi(&info).unwrap();
1181        let json = serde_json::to_value(&doc).unwrap();
1182
1183        // Verify path exists
1184        let paths = json.get("paths").unwrap();
1185        assert!(paths.get("/files/v1/upload").is_some());
1186
1187        // Verify request body has application/octet-stream with binary schema
1188        let post_op = paths.get("/files/v1/upload").unwrap().get("post").unwrap();
1189        let request_body = post_op.get("requestBody").unwrap();
1190        let content = request_body.get("content").unwrap();
1191        let octet_stream = content
1192            .get("application/octet-stream")
1193            .expect("application/octet-stream content type should exist");
1194
1195        // Verify schema is type: string, format: binary
1196        let schema = octet_stream.get("schema").unwrap();
1197        assert_eq!(schema.get("type").unwrap(), "string");
1198        assert_eq!(schema.get("format").unwrap(), "binary");
1199
1200        // Verify required flag
1201        assert_eq!(request_body.get("required").unwrap(), true);
1202    }
1203
1204    #[test]
1205    fn test_build_openapi_with_pagination() {
1206        let registry = OpenApiRegistryImpl::new();
1207
1208        let mut filter: operation_builder::ODataPagination<
1209            std::collections::BTreeMap<String, Vec<String>>,
1210        > = operation_builder::ODataPagination::default();
1211        filter.allowed_fields.insert(
1212            "name".to_owned(),
1213            vec!["eq", "ne", "contains", "startswith", "endswith", "in"]
1214                .into_iter()
1215                .map(String::from)
1216                .collect(),
1217        );
1218        filter.allowed_fields.insert(
1219            "age".to_owned(),
1220            vec!["eq", "ne", "gt", "ge", "lt", "le", "in"]
1221                .into_iter()
1222                .map(String::from)
1223                .collect(),
1224        );
1225
1226        let mut order_by: operation_builder::ODataPagination<Vec<String>> =
1227            operation_builder::ODataPagination::default();
1228        order_by.allowed_fields.push("name asc".to_owned());
1229        order_by.allowed_fields.push("name desc".to_owned());
1230        order_by.allowed_fields.push("age asc".to_owned());
1231        order_by.allowed_fields.push("age desc".to_owned());
1232
1233        let mut spec = OperationSpec {
1234            method: Method::GET,
1235            path: "/test".to_owned(),
1236            operation_id: Some("test_op".to_owned()),
1237            summary: Some("Test".to_owned()),
1238            description: None,
1239            tags: vec![],
1240            params: vec![],
1241            request_body: None,
1242            responses: vec![ResponseSpec {
1243                status: 200,
1244                content_type: "application/json",
1245                description: "OK".to_owned(),
1246                schema: None,
1247                headers: vec![],
1248            }],
1249            handler_id: "get_test".to_owned(),
1250            auth: operation_builder::RouteAuth::Anonymous,
1251            exposed: false,
1252            throttling: None,
1253            allowed_request_content_types: None,
1254            vendor_extensions: VendorExtensions::default(),
1255            license_requirement: None,
1256            request_timeout: RouteTimeout::Inherit,
1257        };
1258        spec.vendor_extensions.x_odata_filter = Some(filter);
1259        spec.vendor_extensions.x_odata_orderby = Some(order_by);
1260
1261        registry.register_operation(&spec);
1262        let info = OpenApiInfo::default();
1263        let doc = registry.build_openapi(&info).unwrap();
1264        let json = serde_json::to_value(&doc).unwrap();
1265
1266        let paths = json.get("paths").unwrap();
1267        let op = paths.get("/test").unwrap().get("get").unwrap();
1268
1269        let filter_ext = op
1270            .get("x-odata-filter")
1271            .expect("x-odata-filter should be present");
1272
1273        let allowed_fields = filter_ext.get("allowedFields").unwrap();
1274        assert!(allowed_fields.get("name").is_some());
1275        assert!(allowed_fields.get("age").is_some());
1276
1277        let order_ext = op
1278            .get("x-odata-orderby")
1279            .expect("x-odata-orderby should be present");
1280
1281        let allowed_order = order_ext.get("allowedFields").unwrap().as_array().unwrap();
1282        assert!(allowed_order.iter().any(|v| v.as_str() == Some("name asc")));
1283        assert!(allowed_order.iter().any(|v| v.as_str() == Some("age desc")));
1284    }
1285
1286    #[test]
1287    fn platform_operations_require_the_internal_token_scheme() {
1288        let registry = OpenApiRegistryImpl::new();
1289        let mut spec = OperationSpec {
1290            method: Method::POST,
1291            path: "/tr/v1/entities".to_owned(),
1292            operation_id: Some("register".to_owned()),
1293            summary: None,
1294            description: None,
1295            tags: vec![],
1296            params: vec![],
1297            request_body: None,
1298            responses: vec![ResponseSpec {
1299                status: 202,
1300                content_type: "application/json",
1301                description: "Accepted".to_owned(),
1302                schema: None,
1303                headers: vec![],
1304            }],
1305            handler_id: "register".to_owned(),
1306            auth: operation_builder::RouteAuth::Platform,
1307            exposed: false,
1308            throttling: None,
1309            allowed_request_content_types: None,
1310            vendor_extensions: VendorExtensions::default(),
1311            license_requirement: None,
1312            request_timeout: RouteTimeout::Inherit,
1313        };
1314        registry.register_operation(&spec);
1315        spec.method = Method::GET;
1316        spec.handler_id = "read".to_owned();
1317        spec.operation_id = Some("read".to_owned());
1318        spec.auth = operation_builder::RouteAuth::Authenticated;
1319        registry.register_operation(&spec);
1320
1321        let json =
1322            serde_json::to_value(registry.build_openapi(&OpenApiInfo::default()).unwrap()).unwrap();
1323        let item = &json["paths"]["/tr/v1/entities"];
1324        assert_eq!(
1325            item["post"]["security"],
1326            serde_json::json!([{ "internalToken": [] }]),
1327            "platform"
1328        );
1329        assert_eq!(
1330            item["get"]["security"],
1331            serde_json::json!([{ "bearerAuth": [] }]),
1332            "tenant-authenticated"
1333        );
1334        let scheme = &json["components"]["securitySchemes"]["internalToken"];
1335        assert_eq!(scheme["type"], "apiKey");
1336        assert_eq!(scheme["in"], "header");
1337        assert_eq!(scheme["name"], "x-toolkit-internal-token");
1338    }
1339
1340    #[test]
1341    fn test_public_operation_emits_visibility_extension() {
1342        let registry = OpenApiRegistryImpl::new();
1343        let public = OperationSpec {
1344            method: Method::GET,
1345            path: "/calc/v1/ping".to_owned(),
1346            operation_id: Some("ping".to_owned()),
1347            summary: Some("Ping".to_owned()),
1348            description: None,
1349            tags: vec![],
1350            params: vec![],
1351            request_body: None,
1352            responses: vec![ResponseSpec {
1353                status: 200,
1354                content_type: "application/json",
1355                description: "OK".to_owned(),
1356                schema: None,
1357                headers: vec![],
1358            }],
1359            handler_id: "get_ping".to_owned(),
1360            auth: operation_builder::RouteAuth::Anonymous,
1361            exposed: true,
1362            throttling: None,
1363            allowed_request_content_types: None,
1364            vendor_extensions: VendorExtensions::default(),
1365            license_requirement: None,
1366            request_timeout: RouteTimeout::Inherit,
1367        };
1368        // A second, internal operation must NOT carry the extension.
1369        let mut internal = public.clone();
1370        internal.path = "/calc/v1/internal".to_owned();
1371        internal.handler_id = "get_internal".to_owned();
1372        internal.operation_id = Some("internal".to_owned());
1373        internal.exposed = false;
1374
1375        registry.register_operation(&public);
1376        registry.register_operation(&internal);
1377        let doc = registry.build_openapi(&OpenApiInfo::default()).unwrap();
1378        let json = serde_json::to_value(&doc).unwrap();
1379        let paths = json.get("paths").unwrap();
1380
1381        let public_op = paths.get("/calc/v1/ping").unwrap().get("get").unwrap();
1382        assert_eq!(
1383            public_op
1384                .get("x-toolkit-visibility")
1385                .and_then(|v| v.as_str()),
1386            Some("exposed"),
1387            "public operation must advertise the gateway visibility extension"
1388        );
1389
1390        let internal_op = paths.get("/calc/v1/internal").unwrap().get("get").unwrap();
1391        assert!(
1392            internal_op.get("x-toolkit-visibility").is_none(),
1393            "non-public operation must not carry the visibility extension"
1394        );
1395    }
1396
1397    #[test]
1398    fn a_platform_operation_declared_exposed_is_not_exposed() {
1399        let registry = OpenApiRegistryImpl::new();
1400        let platform = OperationSpec {
1401            method: Method::POST,
1402            path: "/calc/v1/platform".to_owned(),
1403            operation_id: Some("platform".to_owned()),
1404            summary: None,
1405            description: None,
1406            tags: vec![],
1407            params: vec![],
1408            request_body: None,
1409            responses: vec![ResponseSpec {
1410                status: 200,
1411                content_type: "application/json",
1412                description: "OK".to_owned(),
1413                schema: None,
1414                headers: vec![],
1415            }],
1416            handler_id: "post_platform".to_owned(),
1417            auth: operation_builder::RouteAuth::Platform,
1418            exposed: true,
1419            throttling: None,
1420            allowed_request_content_types: None,
1421            vendor_extensions: VendorExtensions::default(),
1422            license_requirement: None,
1423            request_timeout: RouteTimeout::Inherit,
1424        };
1425
1426        registry.register_operation(&platform);
1427        let doc = registry.build_openapi(&OpenApiInfo::default()).unwrap();
1428        let json = serde_json::to_value(&doc).unwrap();
1429        let op = &json["paths"]["/calc/v1/platform"]["post"];
1430
1431        assert!(
1432            op.get("x-toolkit-visibility").is_none(),
1433            "no host may publish a platform operation"
1434        );
1435        assert_eq!(op["security"], serde_json::json!([{ "internalToken": [] }]));
1436        let stored = registry
1437            .operation_specs
1438            .get("POST:/calc/v1/platform")
1439            .expect("registered");
1440        assert!(
1441            !stored.exposed,
1442            "stored unexposed, so every host reads it so"
1443        );
1444    }
1445
1446    /// Helper: build a minimal `OpenAPI` doc with the given component schemas.
1447    fn build_test_openapi(schemas: BTreeMap<String, RefOr<Schema>>) -> OpenApi {
1448        let mut components = ComponentsBuilder::new();
1449        for (name, schema) in schemas {
1450            components = components.schema(name, schema);
1451        }
1452        OpenApiBuilder::new()
1453            .components(Some(components.build()))
1454            .build()
1455    }
1456
1457    #[test]
1458    fn test_dangling_refs_detects_missing_in_components() {
1459        let mut schemas: BTreeMap<String, RefOr<Schema>> = BTreeMap::new();
1460        // Register "Foo" with a $ref to "Bar" which is NOT registered
1461        let foo_schema = serde_json::from_value::<Schema>(serde_json::json!({
1462            "type": "object",
1463            "properties": {
1464                "bar": { "$ref": "#/components/schemas/Bar" }
1465            }
1466        }))
1467        .unwrap();
1468        schemas.insert("Foo".to_owned(), RefOr::T(foo_schema));
1469
1470        let openapi = build_test_openapi(schemas);
1471        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
1472        assert_eq!(dangling, vec!["Bar".to_owned()]);
1473    }
1474
1475    #[test]
1476    fn test_dangling_refs_no_false_positives() {
1477        let mut schemas: BTreeMap<String, RefOr<Schema>> = BTreeMap::new();
1478        // Register "Bar"
1479        let bar_schema = Schema::Object(ObjectBuilder::new().build());
1480        schemas.insert("Bar".to_owned(), RefOr::T(bar_schema));
1481
1482        // Register "Foo" referencing "Bar"
1483        let foo_schema = serde_json::from_value::<Schema>(serde_json::json!({
1484            "type": "object",
1485            "properties": {
1486                "bar": { "$ref": "#/components/schemas/Bar" }
1487            }
1488        }))
1489        .unwrap();
1490        schemas.insert("Foo".to_owned(), RefOr::T(foo_schema));
1491
1492        let openapi = build_test_openapi(schemas);
1493        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
1494        assert!(
1495            dangling.is_empty(),
1496            "Expected no dangling refs but got: {dangling:?}"
1497        );
1498    }
1499
1500    #[test]
1501    fn test_dangling_refs_detects_missing_in_operations() {
1502        // Build an OpenAPI doc with a response $ref to "MissingDto" but no
1503        // matching component schema — simulates the scenario CodeRabbit flagged.
1504        let openapi_json = serde_json::json!({
1505            "openapi": "3.1.0",
1506            "info": { "title": "test", "version": "0.1.0" },
1507            "paths": {
1508                "/items": {
1509                    "get": {
1510                        "responses": {
1511                            "200": {
1512                                "description": "OK",
1513                                "content": {
1514                                    "application/json": {
1515                                        "schema": { "$ref": "#/components/schemas/MissingDto" }
1516                                    }
1517                                }
1518                            }
1519                        }
1520                    }
1521                }
1522            },
1523            "components": {
1524                "schemas": {}
1525            }
1526        });
1527        let openapi: OpenApi = serde_json::from_value(openapi_json).unwrap();
1528        let dangling = collect_all_dangling_refs_in_openapi(&openapi);
1529        assert_eq!(dangling, vec!["MissingDto".to_owned()]);
1530    }
1531
1532    // --- array responses -------------------------------------------------
1533    //
1534    // A top-level array must be emitted inline, referencing the item type,
1535    // and must NOT create a component of its own. utoipa names every `Vec<T>`
1536    // `Vec`, so a named array component makes all list endpoints collide.
1537
1538    #[test]
1539    fn array_response_emits_inline_array_referencing_item() {
1540        let registry = OpenApiRegistryImpl::new();
1541        registry.register_operation(&spec_with_response(
1542            "/gears",
1543            "list_gears",
1544            Some(ResponseSchema::Array {
1545                items_schema_name: "GearDto".to_owned(),
1546            }),
1547        ));
1548
1549        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
1550        let schema = response_schema_json(&doc, "/gears");
1551
1552        assert_eq!(schema["type"], "array");
1553        assert_eq!(schema["items"]["$ref"], "#/components/schemas/GearDto");
1554        // The array itself is not a component.
1555        assert!(schema.get("$ref").is_none());
1556        assert!(doc["components"]["schemas"].get("Vec").is_none());
1557    }
1558
1559    #[test]
1560    fn ref_response_still_emits_plain_ref() {
1561        let registry = OpenApiRegistryImpl::new();
1562        registry.register_operation(&spec_with_response(
1563            "/gear",
1564            "get_gear",
1565            Some(ResponseSchema::Ref {
1566                schema_name: "GearDto".to_owned(),
1567            }),
1568        ));
1569
1570        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
1571        let schema = response_schema_json(&doc, "/gear");
1572
1573        assert_eq!(schema["$ref"], "#/components/schemas/GearDto");
1574        assert!(schema.get("type").is_none());
1575    }
1576
1577    /// `OperationBuilder::multipart_json` declares the *item* schema under the
1578    /// bare `multipart/mixed` media-type key: no `boundary=` parameter (that is
1579    /// generated per response at runtime, so it is not a property of the
1580    /// operation), and a `$ref` rather than the opaque string blob a
1581    /// non-json-like media type would render as.
1582    #[test]
1583    fn multipart_mixed_response_emits_the_item_ref_under_a_bare_media_type() {
1584        let registry = OpenApiRegistryImpl::new();
1585        let mut spec = spec_with_response(
1586            "/events",
1587            "stream_events",
1588            Some(ResponseSchema::Ref {
1589                schema_name: "FrameDto".to_owned(),
1590            }),
1591        );
1592        spec.responses[0].content_type = "multipart/mixed";
1593        registry.register_operation(&spec);
1594
1595        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
1596        let content = &doc["paths"]["/events"]["get"]["responses"]["200"]["content"];
1597
1598        assert_eq!(
1599            content["multipart/mixed"]["schema"]["$ref"],
1600            "#/components/schemas/FrameDto"
1601        );
1602        // The runtime boundary must not leak into the spec's media-type key.
1603        assert_eq!(
1604            content.as_object().map(|o| o.keys().collect::<Vec<_>>()),
1605            Some(vec![&"multipart/mixed".to_owned()])
1606        );
1607        // Not rendered as a string with a custom format — that is what a
1608        // non-json-like media type would produce, and it would lose the item
1609        // schema entirely.
1610        assert!(content["multipart/mixed"]["schema"].get("format").is_none());
1611    }
1612
1613    #[test]
1614    fn schemaless_json_response_still_emits_free_form_object() {
1615        let registry = OpenApiRegistryImpl::new();
1616        registry.register_operation(&spec_with_response("/any", "any_op", None));
1617
1618        let doc = serde_json::to_value(registry.build_openapi(&test_info()).unwrap()).unwrap();
1619        let schema = response_schema_json(&doc, "/any");
1620
1621        assert!(schema.get("$ref").is_none());
1622        assert_ne!(schema["type"], "array");
1623    }
1624
1625    /// The regression this whole change exists for: two list endpoints
1626    /// returning different item types used to both register a component named
1627    /// `Vec`, silently clobbering each other (and, after M-14, panicking).
1628    #[test]
1629    fn two_distinct_array_responses_do_not_collide() {
1630        #[derive(utoipa::ToSchema)]
1631        #[allow(dead_code)]
1632        struct AlphaDto {
1633            alpha: String,
1634        }
1635        #[derive(utoipa::ToSchema)]
1636        #[allow(dead_code)]
1637        struct BetaDto {
1638            beta: i32,
1639        }
1640
1641        let registry = OpenApiRegistryImpl::new();
1642        // Registering the ITEM types is what the array builder method does.
1643        let a = ensure_schema::<AlphaDto>(&registry);
1644        let b = ensure_schema::<BetaDto>(&registry);
1645        assert_eq!((a.as_str(), b.as_str()), ("AlphaDto", "BetaDto"));
1646
1647        registry.register_operation(&spec_with_response(
1648            "/alphas",
1649            "list_alphas",
1650            Some(ResponseSchema::Array {
1651                items_schema_name: a,
1652            }),
1653        ));
1654        registry.register_operation(&spec_with_response(
1655            "/betas",
1656            "list_betas",
1657            Some(ResponseSchema::Array {
1658                items_schema_name: b,
1659            }),
1660        ));
1661
1662        let openapi = registry.build_openapi(&test_info()).unwrap();
1663        assert!(
1664            collect_all_dangling_refs_in_openapi(&openapi).is_empty(),
1665            "array item refs must point at registered components"
1666        );
1667
1668        let doc = serde_json::to_value(&openapi).unwrap();
1669        let schemas = &doc["components"]["schemas"];
1670        assert!(schemas.get("AlphaDto").is_some());
1671        assert!(schemas.get("BetaDto").is_some());
1672        assert!(schemas.get("Vec").is_none());
1673        assert_eq!(
1674            response_schema_json(&doc, "/alphas")["items"]["$ref"],
1675            "#/components/schemas/AlphaDto"
1676        );
1677        assert_eq!(
1678            response_schema_json(&doc, "/betas")["items"]["$ref"],
1679            "#/components/schemas/BetaDto"
1680        );
1681    }
1682
1683    #[test]
1684    #[should_panic(expected = "would register the component name `Vec`")]
1685    fn ensure_schema_rejects_vec_directly() {
1686        #[derive(utoipa::ToSchema)]
1687        #[allow(dead_code)]
1688        struct ItemDto {
1689            x: u8,
1690        }
1691        let registry = OpenApiRegistryImpl::new();
1692        let _ = ensure_schema::<Vec<ItemDto>>(&registry);
1693    }
1694
1695    #[test]
1696    #[should_panic(expected = "OpenAPI schema name collision")]
1697    fn ensure_schema_raw_panics_on_conflicting_definition() {
1698        let registry = OpenApiRegistryImpl::new();
1699        registry.ensure_schema_raw(
1700            "Dup",
1701            vec![("Dup".to_owned(), RefOr::Ref(Ref::from_schema_name("First")))],
1702        );
1703        registry.ensure_schema_raw(
1704            "Dup",
1705            vec![(
1706                "Dup".to_owned(),
1707                RefOr::Ref(Ref::from_schema_name("Second")),
1708            )],
1709        );
1710    }
1711
1712    #[test]
1713    fn ensure_schema_raw_allows_identical_reregistration() {
1714        let registry = OpenApiRegistryImpl::new();
1715        let entry = || {
1716            vec![(
1717                "Same".to_owned(),
1718                RefOr::Ref(Ref::from_schema_name("Target")),
1719            )]
1720        };
1721        registry.ensure_schema_raw("Same", entry());
1722        registry.ensure_schema_raw("Same", entry());
1723        assert_eq!(registry.components_registry.load().len(), 1);
1724    }
1725}