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