Skip to main content

endpoint_libs/model/
api_document.rs

1//! Shared plumbing for emitting API description documents (OpenAPI 3.1,
2//! AsyncAPI 3.0) from the endpoint model.
3//!
4//! This module deliberately contains no OpenAPI- or AsyncAPI-specific shapes.
5//! It provides the three things both emitters need and neither should
6//! reimplement:
7//!
8//! 1. [`SchemaComponents`] — every referenced struct/enum collected once, at
9//!    document scope rather than per-endpoint.
10//! 2. [`relocate_refs`] — moving `#/$defs/X` to wherever a given document format
11//!    wants its shared definitions.
12//! 3. [`apply_meta`] — the `meta` passthrough, which is the sanctioned way to
13//!    get per-field and per-endpoint annotations into a document without
14//!    growing the model.
15//!
16//! It lives in endpoint-libs rather than endpointgen because a server needs the
17//! same registry walk at startup to answer MCP requests, and a future OpenRPC
18//! emitter would need it a third time.
19//!
20//! **The RON definitions are the source of truth.** Nothing here parses a
21//! document; these are outputs only.
22
23use alloc::collections::BTreeMap;
24use alloc::format;
25use alloc::string::String;
26use alloc::vec::Vec;
27
28#[cfg(not(any(feature = "std", feature = "std-deps")))]
29use crate::eyre::{self, Result, bail};
30#[cfg(any(feature = "std", feature = "std-deps"))]
31use eyre::{self, Result, bail};
32
33use serde_json::{Map, Value};
34
35use crate::model::endpoint::EndpointSchema;
36use crate::model::json_schema::{TypeRegistry, fields_to_object_schema};
37use crate::model::types::MetaMap;
38
39/// Where a document format keeps its shared schema definitions.
40///
41/// JSON Schema puts them in `#/$defs`; both OpenAPI 3.1 and AsyncAPI 3.0 want
42/// `#/components/schemas`.
43pub const COMPONENTS_SCHEMAS_PREFIX: &str = "#/components/schemas/";
44
45/// The `$defs` prefix that [`crate::model::Type::to_json_schema`] emits.
46const DEFS_PREFIX: &str = "#/$defs/";
47
48/// Every struct and enum referenced by a set of endpoints, emitted once.
49///
50/// [`crate::model::Type::to_json_schema`] already produces JSON Schema 2020-12,
51/// and OpenAPI 3.1 is a superset of it, so these values drop into a document
52/// essentially verbatim. The only work is hoisting them to document scope:
53/// `to_mcp_input_schema`/`to_mcp_output_schema` deliberately build a *fresh*
54/// `defs` map per endpoint so each MCP tool schema is self-contained, which is
55/// exactly wrong for a document where operations should share `$ref`s.
56///
57/// Refs in [`SchemaComponents::schemas`] and in the per-endpoint schemas
58/// returned by [`SchemaComponents::request_schema`] /
59/// [`SchemaComponents::response_schema`] are already relocated to
60/// [`COMPONENTS_SCHEMAS_PREFIX`] — callers do not need to call
61/// [`relocate_refs`] themselves.
62#[derive(Debug, Default, Clone, PartialEq, Eq)]
63pub struct SchemaComponents {
64    /// Definition name → schema, e.g. `"User"` → `{ "type": "object", ... }`.
65    pub schemas: BTreeMap<String, Value>,
66}
67
68impl SchemaComponents {
69    /// Walks `endpoints`, collecting every referenced definition exactly once.
70    ///
71    /// Fails if any `StructRef`/`EnumRef`/`StructTable` is missing from
72    /// `registry` — a document with dangling `$ref`s is worse than no document,
73    /// because validators accept it and generators emit broken clients.
74    pub fn collect(endpoints: &[EndpointSchema], registry: &TypeRegistry) -> Result<Self> {
75        let mut defs = BTreeMap::new();
76
77        for endpoint in endpoints {
78            // Build and discard the object schemas; the point is the side
79            // effect on the shared `defs` map.
80            fields_to_object_schema(&endpoint.parameters, registry, &mut defs)
81                .map_err(|e| eyre::eyre!("endpoint {}: parameters: {e}", endpoint.name))?;
82            fields_to_object_schema(&endpoint.returns, registry, &mut defs)
83                .map_err(|e| eyre::eyre!("endpoint {}: returns: {e}", endpoint.name))?;
84
85            if let Some(stream) = &endpoint.stream_response {
86                stream
87                    .to_json_schema(registry, &mut defs)
88                    .map_err(|e| eyre::eyre!("endpoint {}: stream_response: {e}", endpoint.name))?;
89            }
90
91            for error in &endpoint.errors {
92                fields_to_object_schema(&error.fields, registry, &mut defs).map_err(|e| {
93                    eyre::eyre!("endpoint {}: error {}: {e}", endpoint.name, error.name)
94                })?;
95            }
96        }
97
98        for schema in defs.values_mut() {
99            relocate_refs(schema, COMPONENTS_SCHEMAS_PREFIX);
100        }
101
102        Ok(Self { schemas: defs })
103    }
104
105    /// Object schema over an endpoint's `parameters`, with refs pointing at
106    /// [`Self::schemas`]. Non-`Optional` parameters land in `required`.
107    pub fn request_schema(
108        &self,
109        endpoint: &EndpointSchema,
110        registry: &TypeRegistry,
111    ) -> Result<Value> {
112        self.object_schema(
113            &endpoint.parameters,
114            registry,
115            &format!("endpoint {} parameters", endpoint.name),
116        )
117    }
118
119    /// Object schema over an endpoint's `returns`. See [`Self::request_schema`].
120    pub fn response_schema(
121        &self,
122        endpoint: &EndpointSchema,
123        registry: &TypeRegistry,
124    ) -> Result<Value> {
125        self.object_schema(
126            &endpoint.returns,
127            registry,
128            &format!("endpoint {} returns", endpoint.name),
129        )
130    }
131
132    /// Builds an object schema whose `$ref`s point into the shared components.
133    ///
134    /// The throwaway `defs` map here is not a leak: every definition it would
135    /// collect is already in [`Self::schemas`], because `collect` walked the
136    /// same fields. Only the returned root object is used.
137    fn object_schema(
138        &self,
139        fields: &[crate::model::types::Field],
140        registry: &TypeRegistry,
141        context: &str,
142    ) -> Result<Value> {
143        let mut throwaway = BTreeMap::new();
144        let mut schema = fields_to_object_schema(fields, registry, &mut throwaway)?;
145        relocate_refs(&mut schema, COMPONENTS_SCHEMAS_PREFIX);
146        apply_field_meta(&mut schema, fields, context)?;
147        Ok(schema)
148    }
149}
150
151/// Applies each field's `meta` to its property in an object schema.
152///
153/// Deliberately done here rather than inside `fields_to_object_schema`: that
154/// helper also builds MCP tool schemas, and those must stay byte-identical.
155/// Field annotations are a document concern.
156///
157/// A field whose schema is a bare `$ref` is a hard error rather than a silent
158/// no-op: sibling keys next to a `$ref` are ignored by most JSON Schema 2020-12
159/// tooling, so emitting them would produce a document that looks annotated and
160/// is not. Annotate the referenced definition instead.
161fn apply_field_meta(
162    schema: &mut Value,
163    fields: &[crate::model::types::Field],
164    context: &str,
165) -> Result<()> {
166    #[cfg(not(feature = "std"))]
167    use crate::convert_case::{Case, Casing};
168    #[cfg(feature = "std")]
169    use convert_case::{Case, Casing};
170
171    for field in fields {
172        if field.meta.is_empty() {
173            continue;
174        }
175        let key = field.name.to_case(Case::Camel);
176        let Some(property) = schema.get_mut("properties").and_then(|p| p.get_mut(&key)) else {
177            continue;
178        };
179        if property.get("$ref").is_some() {
180            bail!(
181                "{context}: field `{}` carries meta but its schema is a bare $ref; \
182                 annotate the referenced definition instead — sibling keys next to \
183                 $ref are ignored by JSON Schema 2020-12 tooling",
184                field.name
185            );
186        }
187        apply_meta(
188            property,
189            &field.meta,
190            &format!("{context}: field `{}`", field.name),
191        )?;
192    }
193    Ok(())
194}
195
196/// Rewrites `#/$defs/X` to `{prefix}X` throughout `value`, in place.
197///
198/// Recurses through objects and arrays, and only touches string values under a
199/// `$ref` key — a `description` that happens to mention `#/$defs/` is left
200/// alone. Refs that do not start with `#/$defs/` (absolute URLs, refs already
201/// relocated) are untouched, which makes this idempotent.
202///
203/// Termination: this walks the finished `Value` tree, not the type graph.
204/// `to_json_schema` reserves a `$defs` slot before recursing into struct
205/// fields, so recursive types produce a finite tree containing a `$ref` back to
206/// themselves, not an infinite one.
207pub fn relocate_refs(value: &mut Value, prefix: &str) {
208    match value {
209        Value::Object(map) => {
210            if let Some(Value::String(target)) = map.get_mut("$ref")
211                && let Some(name) = target.strip_prefix(DEFS_PREFIX)
212            {
213                *target = format!("{prefix}{name}");
214            }
215            for child in map.values_mut() {
216                relocate_refs(child, prefix);
217            }
218        }
219        Value::Array(items) => {
220            for item in items {
221                relocate_refs(item, prefix);
222            }
223        }
224        _ => {}
225    }
226}
227
228/// Non-`x-` `meta` keys that map onto a schema or operation object verbatim.
229///
230/// Everything else without an `x-` prefix is rejected: a typo'd `exmaple` that
231/// silently vanishes is how these documents rot, and the failure is invisible
232/// until someone reads the generated spec and believes it.
233const RECOGNISED_META_KEYS: &[&str] = &[
234    // Annotation keywords
235    "example",
236    "examples",
237    "deprecated",
238    "tags",
239    // JSON Schema constraint keywords
240    "minimum",
241    "maximum",
242    "minLength",
243    "maxLength",
244    "pattern",
245    "enum",
246];
247
248/// Copies `meta` onto `target`, which must be a JSON object.
249///
250/// - Keys starting with `x-` are copied verbatim (both formats allow arbitrary
251///   specification extensions).
252/// - Keys in [`RECOGNISED_META_KEYS`] are copied verbatim.
253/// - Anything else is a hard error naming `context`, so a mistake surfaces at
254///   generation time rather than as a quietly missing field.
255///
256/// Existing keys on `target` are overwritten: `meta` is an explicit author
257/// annotation and should win over an inferred default.
258pub fn apply_meta(target: &mut Value, meta: &MetaMap, context: &str) -> Result<()> {
259    if meta.is_empty() {
260        return Ok(());
261    }
262
263    let Value::Object(map) = target else {
264        bail!("{context}: cannot apply meta to a non-object JSON value");
265    };
266
267    for (key, value) in &meta.0 {
268        if key.starts_with("x-") || RECOGNISED_META_KEYS.contains(&key.as_str()) {
269            map.insert(key.clone(), value.clone());
270            continue;
271        }
272        bail!(
273            "{context}: unrecognised meta key `{key}`. Prefix it with `x-` to emit it as a \
274             specification extension, or use one of the mapped keys: {}",
275            RECOGNISED_META_KEYS.join(", ")
276        );
277    }
278
279    Ok(())
280}
281
282/// Collects every `$ref` target string in `value`.
283///
284/// Used by emitter tests to prove that a finished document has no dangling
285/// references and no surviving `$defs`.
286pub fn collect_refs(value: &Value, out: &mut Vec<String>) {
287    match value {
288        Value::Object(map) => {
289            if let Some(Value::String(target)) = map.get("$ref") {
290                out.push(target.clone());
291            }
292            for child in map.values() {
293                collect_refs(child, out);
294            }
295        }
296        Value::Array(items) => {
297            for item in items {
298                collect_refs(item, out);
299            }
300        }
301        _ => {}
302    }
303}
304
305/// Object schema over a `Vec<Field>` with refs already relocated.
306///
307/// Convenience for emitters building envelope payloads (error objects, message
308/// wrappers) that are not an endpoint's own parameters or returns.
309pub fn object_schema_for_fields(
310    fields: &[crate::model::types::Field],
311    registry: &TypeRegistry,
312) -> Result<Value> {
313    let mut defs = BTreeMap::new();
314    let mut schema = fields_to_object_schema(fields, registry, &mut defs)?;
315    relocate_refs(&mut schema, COMPONENTS_SCHEMAS_PREFIX);
316    Ok(schema)
317}
318
319/// Builds a JSON object from `(key, value)` pairs, skipping `None` values.
320///
321/// Emitters assemble a lot of optional fields; this keeps that readable without
322/// a builder type.
323pub fn json_object(entries: impl IntoIterator<Item = (String, Option<Value>)>) -> Value {
324    let mut map = Map::new();
325    for (key, value) in entries {
326        if let Some(value) = value {
327            map.insert(key, value);
328        }
329    }
330    Value::Object(map)
331}
332
333#[cfg(test)]
334mod tests {
335    use super::*;
336    use crate::model::types::{EnumVariant, Field, Type};
337    use serde_json::json;
338
339    fn registry_with(types: &[Type]) -> TypeRegistry {
340        let mut registry = TypeRegistry::new();
341        registry.add_all(types.iter());
342        registry
343    }
344
345    fn user_struct() -> Type {
346        Type::struct_(
347            "User",
348            vec![
349                Field::new("id", Type::Int64),
350                Field::new("name", Type::String),
351            ],
352        )
353    }
354
355    /// A struct that contains itself, to prove the rewrite terminates.
356    fn recursive_node() -> Type {
357        Type::struct_(
358            "Node",
359            vec![
360                Field::new("value", Type::String),
361                Field::new(
362                    "children",
363                    Type::Vec(Box::new(Type::StructRef("Node".into()))),
364                ),
365            ],
366        )
367    }
368
369    #[test]
370    fn relocate_refs_rewrites_nested_and_array_positions() {
371        let mut value = json!({
372            "type": "object",
373            "properties": {
374                "items": {
375                    "type": "array",
376                    "items": { "anyOf": [ { "$ref": "#/$defs/User" }, { "type": "null" } ] }
377                }
378            }
379        });
380
381        relocate_refs(&mut value, COMPONENTS_SCHEMAS_PREFIX);
382
383        let target = &value["properties"]["items"]["items"]["anyOf"][0]["$ref"];
384        assert_eq!(target, "#/components/schemas/User");
385    }
386
387    #[test]
388    fn relocate_refs_leaves_non_defs_refs_and_is_idempotent() {
389        let mut value = json!({
390            "a": { "$ref": "#/components/schemas/Already" },
391            "b": { "$ref": "https://example.com/schema.json" },
392            "c": { "$ref": "#/$defs/Moves" },
393        });
394
395        relocate_refs(&mut value, COMPONENTS_SCHEMAS_PREFIX);
396        let once = value.clone();
397        relocate_refs(&mut value, COMPONENTS_SCHEMAS_PREFIX);
398
399        assert_eq!(value, once, "relocation must be idempotent");
400        assert_eq!(value["a"]["$ref"], "#/components/schemas/Already");
401        assert_eq!(value["b"]["$ref"], "https://example.com/schema.json");
402        assert_eq!(value["c"]["$ref"], "#/components/schemas/Moves");
403    }
404
405    #[test]
406    fn relocate_refs_ignores_ref_like_strings_outside_ref_keys() {
407        let mut value = json!({ "description": "see #/$defs/User for details" });
408        relocate_refs(&mut value, COMPONENTS_SCHEMAS_PREFIX);
409        assert_eq!(value["description"], "see #/$defs/User for details");
410    }
411
412    #[test]
413    fn collect_shares_definitions_across_endpoints() {
414        let registry = registry_with(&[user_struct()]);
415        let endpoints = vec![
416            EndpointSchema::new(
417                "GetUser",
418                1,
419                vec![Field::new("id", Type::Int64)],
420                vec![Field::new("user", Type::StructRef("User".into()))],
421            ),
422            EndpointSchema::new(
423                "ListUsers",
424                2,
425                vec![],
426                vec![Field::new(
427                    "users",
428                    Type::Vec(Box::new(Type::StructRef("User".into()))),
429                )],
430            ),
431        ];
432
433        let components = SchemaComponents::collect(&endpoints, &registry).unwrap();
434
435        // One shared definition, not one per endpoint.
436        assert_eq!(components.schemas.keys().collect::<Vec<_>>(), vec!["User"]);
437    }
438
439    #[test]
440    fn collect_relocates_refs_inside_components() {
441        let registry = registry_with(&[recursive_node()]);
442        let endpoints = vec![EndpointSchema::new(
443            "GetTree",
444            1,
445            vec![],
446            vec![Field::new("root", Type::StructRef("Node".into()))],
447        )];
448
449        let components = SchemaComponents::collect(&endpoints, &registry).unwrap();
450
451        let mut refs = vec![];
452        for schema in components.schemas.values() {
453            collect_refs(schema, &mut refs);
454        }
455        assert!(!refs.is_empty(), "recursive struct should self-reference");
456        for target in &refs {
457            assert!(
458                target.starts_with(COMPONENTS_SCHEMAS_PREFIX),
459                "ref {target} was not relocated"
460            );
461        }
462    }
463
464    #[test]
465    fn collect_terminates_on_recursive_structs() {
466        let registry = registry_with(&[recursive_node()]);
467        let endpoints = vec![EndpointSchema::new(
468            "GetTree",
469            1,
470            vec![],
471            vec![Field::new("root", Type::StructRef("Node".into()))],
472        )];
473
474        // The assertion is that this returns at all.
475        let components = SchemaComponents::collect(&endpoints, &registry).unwrap();
476        assert!(components.schemas.contains_key("Node"));
477    }
478
479    #[test]
480    fn collect_resolves_enum_refs() {
481        let role = Type::Enum {
482            name: "UserRole".into(),
483            variants: vec![
484                EnumVariant::new_with_description("Admin", "Platform admin".to_string(), 0),
485                EnumVariant::new_with_description("User", "Regular user".to_string(), 1),
486            ],
487        };
488        let registry = registry_with(&[role]);
489        let endpoints = vec![EndpointSchema::new(
490            "GetRole",
491            1,
492            vec![],
493            vec![Field::new(
494                "role",
495                Type::EnumRef {
496                    name: "UserRole".into(),
497                    prefixed_name: false,
498                },
499            )],
500        )];
501
502        let components = SchemaComponents::collect(&endpoints, &registry).unwrap();
503        assert!(
504            components.schemas.contains_key("UserRole"),
505            "got {:?}",
506            components.schemas.keys().collect::<Vec<_>>()
507        );
508    }
509
510    #[test]
511    fn collect_reports_the_endpoint_for_a_dangling_ref() {
512        let registry = TypeRegistry::new();
513        let endpoints = vec![EndpointSchema::new(
514            "GetGhost",
515            1,
516            vec![],
517            vec![Field::new("ghost", Type::StructRef("Missing".into()))],
518        )];
519
520        let err = SchemaComponents::collect(&endpoints, &registry)
521            .unwrap_err()
522            .to_string();
523        assert!(err.contains("GetGhost"), "{err}");
524        assert!(err.contains("Missing"), "{err}");
525    }
526
527    #[test]
528    fn request_and_response_schemas_reference_shared_components() {
529        let registry = registry_with(&[user_struct()]);
530        let endpoint = EndpointSchema::new(
531            "GetUser",
532            1,
533            vec![Field::new("id", Type::Int64)],
534            vec![Field::new("user", Type::StructRef("User".into()))],
535        );
536        let components =
537            SchemaComponents::collect(std::slice::from_ref(&endpoint), &registry).unwrap();
538
539        let response = components.response_schema(&endpoint, &registry).unwrap();
540
541        let mut refs = vec![];
542        collect_refs(&response, &mut refs);
543        assert_eq!(refs, vec!["#/components/schemas/User"]);
544
545        let request = components.request_schema(&endpoint, &registry).unwrap();
546        assert_eq!(request["required"], json!(["id"]));
547    }
548
549    #[test]
550    fn optional_fields_are_not_required() {
551        let registry = TypeRegistry::new();
552        let endpoint = EndpointSchema::new(
553            "Search",
554            1,
555            vec![
556                Field::new("query", Type::String),
557                Field::new("cursor", Type::Optional(Box::new(Type::String))),
558            ],
559            vec![],
560        );
561        let components =
562            SchemaComponents::collect(std::slice::from_ref(&endpoint), &registry).unwrap();
563
564        let request = components.request_schema(&endpoint, &registry).unwrap();
565        assert_eq!(request["required"], json!(["query"]));
566        assert!(request["properties"]["cursor"].is_object());
567    }
568
569    #[test]
570    fn apply_meta_copies_extensions_and_recognised_keys() {
571        let mut target = json!({ "type": "string" });
572        let mut meta = MetaMap::default();
573        meta.insert("x-internal-id", json!(42));
574        meta.insert("example", json!("hello"));
575        meta.insert("deprecated", json!(true));
576
577        apply_meta(&mut target, &meta, "Endpoint Foo").unwrap();
578
579        assert_eq!(target["x-internal-id"], 42);
580        assert_eq!(target["example"], "hello");
581        assert_eq!(target["deprecated"], true);
582        assert_eq!(target["type"], "string");
583    }
584
585    #[test]
586    fn apply_meta_rejects_unrecognised_keys_with_context() {
587        let mut target = json!({ "type": "string" });
588        let mut meta = MetaMap::default();
589        // A plausible typo of `example`.
590        meta.insert("exmaple", json!("hello"));
591
592        let err = apply_meta(&mut target, &meta, "endpoint GetUser field id")
593            .unwrap_err()
594            .to_string();
595
596        assert!(err.contains("endpoint GetUser field id"), "{err}");
597        assert!(err.contains("exmaple"), "{err}");
598        // The message should tell the author how to fix it.
599        assert!(err.contains("x-"), "{err}");
600    }
601
602    #[test]
603    fn field_meta_lands_on_the_property() {
604        let registry = TypeRegistry::new();
605        let mut field = Field::new("cursor", Type::String);
606        field.meta.insert("example", json!("abc123"));
607        field.meta.insert("x-opaque", json!(true));
608
609        let endpoint = EndpointSchema::new("Search", 1, vec![field], vec![]);
610        let components =
611            SchemaComponents::collect(std::slice::from_ref(&endpoint), &registry).unwrap();
612
613        let request = components.request_schema(&endpoint, &registry).unwrap();
614        assert_eq!(request["properties"]["cursor"]["example"], "abc123");
615        assert_eq!(request["properties"]["cursor"]["x-opaque"], true);
616    }
617
618    #[test]
619    fn field_meta_on_a_bare_ref_is_rejected() {
620        // Sibling keys next to $ref are ignored by tooling; failing loudly beats
621        // emitting a document that looks annotated but isn't.
622        let registry = registry_with(&[user_struct()]);
623        let mut field = Field::new("user", Type::StructRef("User".into()));
624        field.meta.insert("example", json!({ "id": 1 }));
625
626        let endpoint = EndpointSchema::new("GetUser", 1, vec![], vec![field]);
627        let components =
628            SchemaComponents::collect(std::slice::from_ref(&endpoint), &registry).unwrap();
629
630        let err = components
631            .response_schema(&endpoint, &registry)
632            .unwrap_err()
633            .to_string();
634        assert!(err.contains("GetUser"), "{err}");
635        assert!(err.contains("user"), "{err}");
636        assert!(err.contains("$ref"), "{err}");
637    }
638
639    #[test]
640    fn apply_meta_is_a_noop_when_empty() {
641        let mut target = json!({ "type": "string" });
642        let before = target.clone();
643        apply_meta(&mut target, &MetaMap::default(), "ctx").unwrap();
644        assert_eq!(target, before);
645    }
646
647    #[test]
648    fn mcp_schemas_stay_self_contained() {
649        // The document emitters share definitions; MCP tool schemas must not.
650        // Consumers rely on each tool schema standing alone, so this guards
651        // against a future refactor "unifying" the two paths.
652        let registry = registry_with(&[user_struct()]);
653        let endpoint = EndpointSchema::new(
654            "GetUser",
655            1,
656            vec![],
657            vec![Field::new("user", Type::StructRef("User".into()))],
658        );
659
660        let mcp = endpoint.to_mcp_output_schema(&registry).unwrap();
661
662        assert!(
663            mcp.get("$defs").is_some(),
664            "MCP output schema must carry its own $defs"
665        );
666        let mut refs = vec![];
667        collect_refs(&mcp, &mut refs);
668        assert!(
669            refs.iter().all(|r| r.starts_with("#/$defs/")),
670            "MCP schemas must keep $defs refs, got {refs:?}"
671        );
672    }
673}