From 64948b8c81dcac77a97544855348a14e7f01fb44 Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 14:11:16 +0900 Subject: [PATCH 1/7] fix(macro): request-only types keep their name; typed codec fields in request views A type whose request view differs gets a separate `{Name}Input` only when its response view is also used. When request bodies reach `{Name}Input` but nothing outside the request side reaches `{Name}`, the request view takes over `{Name}` and every `$ref` follows (generic `Tree_i32.Input` alike), so request-only DTOs keep their names and no orphan response view is emitted. Fields read by a custom serde function (`deserialize_with` / `with`) are documented from their Rust type (or `value_type`) in request views instead of an untyped `{}`; a `deserialize_with` alone no longer splits the views. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_request-view-naming.json | 1 + README.md | 6 +- SKILL.md | 4 +- .../[...name]/concept.concept-2.mdx | 6 +- .../app/documentation/[...name]/migration.mdx | 2 + crates/vespera_macro/src/openapi_generator.rs | 5 +- .../openapi_generator/component_schemas.rs | 146 ++++++++- ...request_only_portfolio_update_request.snap | 21 ++ .../src/openapi_generator/tests_accuracy.rs | 17 +- .../openapi_generator/tests_request_only.rs | 304 ++++++++++++++++++ ...est_shapes_custom_deserializer_option.snap | 25 +- ...ath__tests__path_wire_override_fields.snap | 3 +- ...ry__tests__query_wire_override_fields.snap | 3 +- ...lity__enum_views_tuple_variant_fields.snap | 2 +- ...ty__enum_views_variant_codec_untagged.snap | 3 +- .../src/parser/schema/request_view.rs | 34 +- .../src/parser/schema/request_view/tests.rs | 7 +- ...field_deserialize_with_on_deserialize.snap | 3 +- .../parser/schema/struct_schema/flatten.rs | 5 +- ...e_fidelity__struct_views_tuple_codecs.snap | 4 +- ...ide__wire_override_field_with_unknown.snap | 21 +- ...rride__wire_override_transparent_with.snap | 4 +- .../src/parser/schema/wire_override.rs | 24 +- crates/vespera_macro/src/router_codegen.rs | 3 +- .../src/router_codegen/export.rs | 3 +- examples/axum-example/openapi.json | 191 +---------- ...ecs__codecs_component_EventTimesInput.snap | 9 +- .../snapshots/integration_test__openapi.snap | 192 +---------- 28 files changed, 620 insertions(+), 428 deletions(-) create mode 100644 .changepacks/changepack_log_request-view-naming.json create mode 100644 crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_request_only__request_only_portfolio_update_request.snap create mode 100644 crates/vespera_macro/src/openapi_generator/tests_request_only.rs diff --git a/.changepacks/changepack_log_request-view-naming.json b/.changepacks/changepack_log_request-view-naming.json new file mode 100644 index 000000000..31154c475 --- /dev/null +++ b/.changepacks/changepack_log_request-view-naming.json @@ -0,0 +1 @@ +{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro request views: a type whose request view differs but that only request bodies reach (no response, directly or through another type) keeps its own component name — {Name} is its request view and no {Name}Input or orphan response view is emitted (0.8.0 renamed request-only DTOs to {Name}Input); types read and returned keep {Name} + {Name}Input (collision names {Name}Input2, ... unchanged). Fields read by a custom serde function (deserialize_with / with) are documented from their Rust type (or #[schema(value_type)]) in request views instead of an untyped {} — Option> is a nullable T — and a deserialize_with alone no longer creates a {Name}Input; with / serialize_with still document {} in responses.","date":"2026-11-17T00:00:00.000Z"} diff --git a/README.md b/README.md index 20293bdc6..4a23f782b 100644 --- a/README.md +++ b/README.md @@ -222,7 +222,9 @@ one-sided `skip_deserializing` / `skip_serializing`, or `rename(deserialize = "..")` — request bodies reference a separate `{Name}Input` component (defaulted fields optional, `skip_deserializing` fields absent, deserialize names), FastAPI-style, while responses keep -`{Name}`. Types whose two views are identical get no extra component. +`{Name}`. Types whose two views are identical get no extra component, and a +type that is only read (no response reaches it) keeps its own name: `{Name}` +is then its request view and no `{Name}Input` is emitted. `#[schema(name = "X")]` yields `XInput`; if that name is already taken the first free `XInput2`, `XInput3`, … is used. @@ -250,7 +252,7 @@ pub struct Rgb { pub r: u8, pub g: u8, pub b: u8 } | Attribute | Documented as | |---|---| | field `#[schema(value_type = T)]` | `T`'s schema (constraints such as `minimum` still apply) | -| field `#[serde(with / serialize_with / deserialize_with)]` without `value_type` | `{}` (any value) with a description saying the shape is unknown — never the Rust type. One-sided `serialize_with` / `deserialize_with` only affects that direction (`{Name}Input` for requests); an `Option` read by a custom deserializer is `required` in requests, as in serde | +| field `#[serde(with / serialize_with / deserialize_with)]` without `value_type` | responses (`with` / `serialize_with`): `{}` (any value) with a description saying the shape is unknown; requests: the field's Rust type, like any other field (add `value_type` when the function reads another shape). An `Option` read by a custom deserializer is `required` in requests, as in serde | | container `#[serde(into = "T")]` | responses use `T`; requests keep the fields (`{Name}Input`) | | container `#[serde(from = "T")]` / `try_from` | requests use `T` (`{Name}Input`); responses keep the fields | | container `#[schema(value_type = T)]` | `T` in both directions (wins over `into` / `from`) | diff --git a/SKILL.md b/SKILL.md index c306404e5..72fe77e19 100644 --- a/SKILL.md +++ b/SKILL.md @@ -253,7 +253,7 @@ pub async fn reindex() {} | `url::Url` | `string` + `format: uri` | | | `serde_json::Value`, SeaORM `Json` / `JsonValue` | `{}` | Any JSON value (a `Json` with a type argument is axum's wrapper) | | field `#[schema(value_type = T)]` | `T`'s schema | Use with `#[serde(with = ..)]` etc. | -| field `#[serde(with / serialize_with / deserialize_with)]` without `value_type` | `{}` + description note | Shape unknown; per direction for one-sided keys | +| field `#[serde(with / serialize_with / deserialize_with)]` without `value_type` | responses: `{}` + description note; requests: the Rust type | Response shape unknown (`with` / `serialize_with`); request views document the field's type | | container `#[serde(into = "T")]` / `from` / `try_from` | `T` for responses / requests | Other direction keeps the fields (`{Name}Input`); container `#[schema(value_type = T)]` = both | | `std::time::Duration` | `object` `{secs, nanos}` | serde's std shape; other qualified `Duration`s → `{}` | | `()` | empty response | `200` without `content` (use `status = 204` for No Content) | @@ -646,7 +646,7 @@ vespera::schema_type!(Schema from Model, name = "MemoSchema"); **Required Logic:** `required` follows nullability (`Option`) and what serde writes: `skip_serializing` / `skip_serializing_if` fields are not required in the response view. -**Request views (`{Name}Input`):** when serde reads a type differently than it writes it (`#[serde(default)]` on a field or the container, one-sided `skip_deserializing` / `skip_serializing`, `rename(deserialize = ..)` / `rename_all(deserialize = ..)` differing from the serialize side, a container `into` / `from` / `try_from` documented through a different type per direction, a one-sided `serialize_with` / `deserialize_with`, an `Option` read by a custom deserializer (required in requests), or a field type that itself has an input view), request bodies (`Json` / `Form` / `TypedMultipart`) reference an extra `{Name}Input` component: defaulted fields are optional, `skip_deserializing` fields are absent, keys use the deserialize name. `{Name}` stays the response view. Nothing extra is emitted when both views are identical or no request body uses the type. `#[schema(name = "X")]` gives `XInput`; if that name is taken, `XInput2`, `XInput3`, …. +**Request views (`{Name}Input`):** when serde reads a type differently than it writes it (`#[serde(default)]` on a field or the container, one-sided `skip_deserializing` / `skip_serializing`, `rename(deserialize = ..)` / `rename_all(deserialize = ..)` differing from the serialize side, a container `into` / `from` / `try_from` documented through a different type per direction, a `with` / `serialize_with` (response shape unknown, request typed), an `Option` read by a custom deserializer (required in requests), or a field type that itself has an input view), request bodies (`Json` / `Form` / `TypedMultipart`) reference an extra `{Name}Input` component: defaulted fields are optional, `skip_deserializing` fields are absent, keys use the deserialize name. `{Name}` stays the response view. Nothing extra is emitted when both views are identical or no request body uses the type; a type only request bodies reach (no response, directly or transitively) keeps its name — `{Name}` is then its request view, no `{Name}Input`. `#[schema(name = "X")]` gives `XInput`; if that name is taken, `XInput2`, `XInput3`, …. ### Same-File Relation Adapters diff --git a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx index 2b1a2fbbe..3dced523e 100644 --- a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx +++ b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx @@ -78,7 +78,7 @@ pub struct Rgb { pub r: u8, pub g: u8, pub b: u8 } Field `#[serde(with / serialize_with / deserialize_with)]` without `value_type` - `{}` (any value) with a description. A one-sided key only affects its direction + Responses (`with` / `serialize_with`): `{}` (any value) with a description. Requests: the field's Rust type, like any other field (add `value_type` when the custom function reads another shape) Container `#[serde(into = "T")]` @@ -99,7 +99,7 @@ An `Option` field read by a custom deserializer is `required` in request bodies, ## Request Views (`{Name}Input`) -serde can read a type differently than it writes it. When that happens, `Json` / `Form` / `TypedMultipart` request bodies reference an extra `{Name}Input` component, FastAPI-style, while responses keep using `{Name}`: +serde can read a type differently than it writes it. When that happens and the type is both read and returned, `Json` / `Form` / `TypedMultipart` request bodies reference an extra `{Name}Input` component, FastAPI-style, while responses keep using `{Name}`: ```rust #[derive(Serialize, Deserialize, vespera::Schema)] @@ -114,7 +114,7 @@ pub struct Settings { A type gets an input view when it has `#[serde(default)]` on a field or the container, one-sided `skip_deserializing` / `skip_serializing`, a `rename(deserialize = "..")` / `rename_all(deserialize = "..")` that differs from the serialize side, a container `from` / `try_from`, or a field whose type has its own input view. In `{Name}Input` defaulted fields are not `required`, `skip_deserializing` fields are absent and keys use the deserialize names. -No `Input` component is emitted when both views are identical or no request body uses the type. `#[schema(name = "X")]` gives `XInput`; when a type already owns that name, the first free `XInput2`, `XInput3`, … is used. Types generated by `schema_type!` derive `Schema` too, so they follow the same rule. +No `Input` component is emitted when both views are identical or no request body uses the type. A type that is only read — used by request bodies (directly or through another request-only type) but reached by no response — keeps its own name: `{Name}` is its request view and no `{Name}Input` is emitted. In `CreateOrder { items: Vec }` used only as a request body, both `CreateOrder` and `LineItem` are request views; once a response also returns `LineItem`, it gets `LineItem` + `LineItemInput` and `CreateOrder.items` references `LineItemInput`. `#[schema(name = "X")]` gives `XInput`; when a type already owns that name, the first free `XInput2`, `XInput3`, … is used. Types generated by `schema_type!` derive `Schema` too, so they follow the same rule. ## Type Mapping diff --git a/apps/landing/src/app/documentation/[...name]/migration.mdx b/apps/landing/src/app/documentation/[...name]/migration.mdx index 7421533ba..7a3aaaa74 100644 --- a/apps/landing/src/app/documentation/[...name]/migration.mdx +++ b/apps/landing/src/app/documentation/[...name]/migration.mdx @@ -35,6 +35,8 @@ These change the generated document without any code change: - **`Form` on `GET` / `HEAD`** is documented as query parameters (axum reads the query string there), not as a request body. - **`TypedHeader`** header names come from `T` — the wire name for known `headers::*` types, otherwise `T` in kebab-case (`XRequestId` → `x-request-id`) — instead of the argument binding; `TypedHeader(_)` is no longer dropped. - **`#[serde(default)]` fields stay `required` in response schemas**; only the `{Name}Input` request view makes them optional. +- **Request-only types keep their name (0.8.1).** A type whose request view differs but that no response returns (directly or through another type) is emitted once, as its request view, under `{Name}` — 0.8.0 emitted an unused `{Name}` plus `{Name}Input`. Clients generated from 0.8.0 that use `PortfolioUpdateRequestInput`-style names go back to `PortfolioUpdateRequest`. Types used on both sides keep `{Name}` + `{Name}Input`. +- **`deserialize_with` / `with` fields are typed in request views (0.8.1)**: documented from the Rust type (or `#[schema(value_type = T)]`) instead of an untyped `{}`; `Option>` is a nullable `T`. A `deserialize_with` alone no longer creates a `{Name}Input`; `with` / `serialize_with` still document `{}` in responses. - **Type mappings:** naive date-times / times (`NaiveDateTime`, `PrimitiveDateTime`, sea-orm `DateTime`, `NaiveTime`, `time::Time`) no longer carry the offset-requiring `date-time` / `time` format; unit structs are `{type: null}`; `Option<()>` is a single `null` type; `u8`–`u64` get `minimum: 0` (and `u8` / `u16` / `u32` a `maximum`); unknown types and unresolved generic parameters are `{}` (any) instead of `{type: object}`; user `Schema` types named like builtins (`Date`, `Decimal`, `Uuid`, …) keep their `$ref`. - **Enums:** concrete generic enums (`ApiResponse>`) are inlined with their type arguments; `serde_repr` enums are `{type: integer, enum: [...]}`; enum `{Name}Input` views follow the deserialize side; an internally tagged newtype variant over a closed or map payload merges the tag into the payload object. - **`cfg`-gated route modules and handlers** that `#[route]` never registered are mounted under the same `#[cfg]` instead of being dropped (they stay out of the document); a bare handler argument named like a path segment no longer adds a duplicate path parameter. diff --git a/crates/vespera_macro/src/openapi_generator.rs b/crates/vespera_macro/src/openapi_generator.rs index cd17cf2df..85bcdd25e 100644 --- a/crates/vespera_macro/src/openapi_generator.rs +++ b/crates/vespera_macro/src/openapi_generator.rs @@ -21,6 +21,8 @@ mod route_claims; mod tests_accuracy; #[cfg(test)] mod tests_parser_views; +#[cfg(test)] +mod tests_request_only; use component_schemas::{ build_file_cache, build_schema_lookups, build_struct_file_index, parse_component_schemas, @@ -145,7 +147,7 @@ pub fn try_generate_openapi_doc_with_metadata( } }; stage("component schemas"); - let (paths, all_tags) = build_path_items( + let (mut paths, all_tags) = build_path_items( metadata, &known_schema_names, &struct_definitions, @@ -158,6 +160,7 @@ pub fn try_generate_openapi_doc_with_metadata( crate::parser::schema::request_view::install(std::sync::Arc::default()); install_stored_defaults(std::sync::Arc::default()); component_schemas::prune_unreferenced_inputs(&mut schemas, &paths, &input_names); + component_schemas::collapse_request_only_inputs(&mut schemas, &mut paths, &input_names)?; component_schemas::reject_internally_tagged_in_document(&schemas, &paths)?; let security_config = security_config.unwrap_or_default(); let tags = build_tags(all_tags, security_config.tag_descriptions.as_ref()); diff --git a/crates/vespera_macro/src/openapi_generator/component_schemas.rs b/crates/vespera_macro/src/openapi_generator/component_schemas.rs index 1875753ed..48c3cde3c 100644 --- a/crates/vespera_macro/src/openapi_generator/component_schemas.rs +++ b/crates/vespera_macro/src/openapi_generator/component_schemas.rs @@ -112,13 +112,102 @@ pub(super) fn prune_unreferenced_inputs( if !schemas.keys().any(|name| prunable(name)) { return; } - // Every component reachable from a request body. - let mut pending: Vec = Vec::new(); - for item in paths.values() { - // Serialization of these plain data types cannot fail. - let value = serde_json::to_value(item).unwrap_or_default(); - collect_path_item_request_refs(&value, &mut pending); + let reached = reach(schemas, path_refs(paths).request); + schemas.retain(|name, _| !prunable(name) || reached.contains(name)); +} + +/// Give a request-only type its own name back: when a request body reaches +/// a type's `{Name}Input` but nothing outside the request side reaches its +/// `{Name}` (the response view), the request view takes over `{Name}` and +/// every `{Name}Input` `$ref` (of `paths` and `schemas`) points at it, so no +/// orphan response view is left behind. `Tree_i32.Input` → `Tree_i32` +/// alike. A type also returned keeps both components. +/// +/// The response side is everything a path reaches outside its request +/// parameters / bodies, plus every component the request side does not +/// reach (an unused type stays documented, with what it references) — not +/// the `{Name}` views being replaced, which only their own (also replaced) +/// views reference: `CreateOrder { items: Vec }` used only as a +/// request body gives `CreateOrder` and `LineItem`. +/// +/// Runs after [`prune_unreferenced_inputs`] (every remaining input is +/// reached by a request). +pub(super) fn collapse_request_only_inputs( + schemas: &mut BTreeMap, + paths: &mut BTreeMap, + input_names: &request_view::InputNames, +) -> syn::Result<()> { + // Input component → the component whose request view it is. + let mut inputs: BTreeMap<&str, &str> = input_names + .iter() + .filter(|(component, input)| { + schemas.contains_key(component.as_str()) && schemas.contains_key(input.as_str()) + }) + .map(|(component, input)| (input.as_str(), component.as_str())) + .collect(); + for name in schemas.keys() { + if let Some(component) = name.strip_suffix(".Input") { + inputs.insert(name, component); + } + } + if inputs.is_empty() { + return Ok(()); + } + let refs = path_refs(paths); + let request = reach(schemas, refs.request); + let views: BTreeSet<&str> = inputs.values().copied().collect(); + let mut roots = refs.other; + roots.extend( + schemas + .keys() + .filter(|name| { + !request.contains(*name) + && !views.contains(name.as_str()) + && !inputs.contains_key(name.as_str()) + }) + .cloned(), + ); + let response = reach(schemas, roots); + let renames: BTreeMap = inputs + .into_iter() + .filter(|(_, component)| !response.contains(*component)) + .map(|(input, component)| (input.to_string(), component.to_string())) + .collect(); + if renames.is_empty() { + return Ok(()); } + for (input, component) in &renames { + if let Some(schema) = schemas.remove(input) { + schemas.insert(component.clone(), schema); + } + } + // A plain-data round-trip (cannot fail). + let rename = |value: serde_json::Result| { + value.map(|mut value| { + crate::router_codegen::rewrite_schema_refs(&mut value, &renames); + value + }) + }; + let rebuild_error = |error: serde_json::Error| { + syn::Error::new( + proc_macro2::Span::call_site(), + format!("vespera: failed to rename request-only input components: {error}"), + ) + }; + *schemas = rename(serde_json::to_value(&*schemas)) + .and_then(serde_json::from_value) + .map_err(rebuild_error)?; + *paths = rename(serde_json::to_value(&*paths)) + .and_then(serde_json::from_value) + .map_err(rebuild_error)?; + Ok(()) +} + +/// Every component reachable from `pending` (its `$ref`s, transitively). +fn reach( + schemas: &BTreeMap, + mut pending: Vec, +) -> BTreeSet { let mut reached: BTreeSet = BTreeSet::new(); while let Some(name) = pending.pop() { if let Some(schema) = schemas.get(&name) @@ -128,7 +217,28 @@ pub(super) fn prune_unreferenced_inputs( collect_component_refs(&value, &mut pending); } } - schemas.retain(|name, _| !prunable(name) || reached.contains(name)); + reached +} + +/// The component `$ref`s of `paths`, split by side. +struct PathRefs { + /// Request parameters and bodies (see [`collect_path_item_refs`]). + request: Vec, + /// Everything else (responses, callbacks, ...). + other: Vec, +} + +fn path_refs(paths: &BTreeMap) -> PathRefs { + let mut refs = PathRefs { + request: Vec::new(), + other: Vec::new(), + }; + for item in paths.values() { + // Serialization of these plain data types cannot fail. + let value = serde_json::to_value(item).unwrap_or_default(); + collect_path_item_refs(&value, &mut refs); + } + refs } /// Component names of every `$ref` inside `value`. @@ -155,24 +265,28 @@ fn collect_component_refs(value: &serde_json::Value, out: &mut Vec) { } } -/// Request-side `$ref`s of one serialized path item: the path-level -/// `parameters`, and each operation's `parameters` and `requestBody` (both -/// deserialized). Only operation-level keys count: a response schema with a -/// property named `parameters` or `requestBody` is not a request. -fn collect_path_item_request_refs(item: &serde_json::Value, out: &mut Vec) { +/// The `$ref`s of one serialized path item, split into [`PathRefs`]: the +/// request side is the path-level `parameters`, and each operation's +/// `parameters` and `requestBody` (both deserialized). Only operation-level +/// keys count: a response schema with a property named `parameters` or +/// `requestBody` is not a request. +fn collect_path_item_refs(item: &serde_json::Value, refs: &mut PathRefs) { const METHODS: [&str; 8] = [ "get", "put", "post", "delete", "options", "head", "patch", "trace", ]; for (key, child) in item.as_object().into_iter().flatten() { if key == "parameters" { - collect_component_refs(child, out); + collect_component_refs(child, &mut refs.request); } else if METHODS.contains(&key.as_str()) && let Some(operation) = child.as_object() { for (op_key, op_child) in operation { - if op_key == "parameters" || op_key == "requestBody" { - collect_component_refs(op_child, out); - } + let out = if op_key == "parameters" || op_key == "requestBody" { + &mut refs.request + } else { + &mut refs.other + }; + collect_component_refs(op_child, out); } } } diff --git a/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_request_only__request_only_portfolio_update_request.snap b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_request_only__request_only_portfolio_update_request.snap new file mode 100644 index 000000000..163465b9d --- /dev/null +++ b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_request_only__request_only_portfolio_update_request.snap @@ -0,0 +1,21 @@ +--- +source: crates/vespera_macro/src/openapi_generator/tests_request_only.rs +expression: "serde_json::to_string_pretty(request).unwrap()" +--- +{ + "properties": { + "productionEndDate": { + "default": null, + "format": "date", + "type": [ + "string", + "null" + ] + }, + "title": { + "default": "", + "type": "string" + } + }, + "type": "object" +} diff --git a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs index e33414c6d..89be784e3 100644 --- a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs +++ b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs @@ -307,8 +307,10 @@ fn input_names_skip_unparsable_definitions() { /// Inputs no request body reaches emit no `Input` component (`Out`). A /// field-level `default` makes the request view differ: serde always writes -/// the field, so the response keeps it required while `OptInput` does not -/// (and `Holder` follows transitively). +/// the field, so the response keeps it required while the request view does +/// not (and `Holder` follows transitively). `Holder` / `Opt` are only read +/// (no response returns them), so their request views keep the plain names +/// instead of an orphan response view plus `HolderInput` / `OptInput`. #[test] fn identical_or_unused_request_views_emit_nothing() { let mut metadata = CollectedMetadata::new(); @@ -345,9 +347,16 @@ fn identical_or_unused_request_views_emit_nothing() { .unwrap() .keys() .collect(); + assert_eq!(names, ["Holder", "Opt", "Out", "Same"]); + let json = serde_json::to_value(&doc).unwrap(); assert_eq!( - names, - ["Holder", "HolderInput", "Opt", "OptInput", "Out", "Same"] + json["paths"]["/holder"]["post"]["requestBody"]["content"]["application/json"]["schema"], + serde_json::json!({"$ref": "#/components/schemas/Holder"}) + ); + // `Opt` is the request view: the defaulted field is optional. + assert_eq!( + json["components"]["schemas"]["Opt"]["required"], + serde_json::Value::Null ); } diff --git a/crates/vespera_macro/src/openapi_generator/tests_request_only.rs b/crates/vespera_macro/src/openapi_generator/tests_request_only.rs new file mode 100644 index 000000000..cfd0cf5ea --- /dev/null +++ b/crates/vespera_macro/src/openapi_generator/tests_request_only.rs @@ -0,0 +1,304 @@ +//! Request-only types keep their component name: a type whose request view +//! differs gets a separate `{Name}Input` only when its response view is used +//! too (see `component_schemas::collapse_request_only_inputs`). + +use serde_json::{Value, json}; + +use super::tests_accuracy::{generate, post, schema, stored_post}; +use crate::metadata::CollectedMetadata; + +/// The document for `structs` and one POST route per `(path, fn, sig)`, as +/// JSON. +fn doc_for(structs: &[(&str, &str)], routes: &[(&str, &str, &str)]) -> Value { + let mut metadata = CollectedMetadata::new(); + for (name, definition) in structs { + metadata.structs.push(schema(name, definition)); + } + let mut storage = Vec::new(); + for (path, fn_name, sig) in routes { + metadata.routes.push(post(path, fn_name)); + storage.push(stored_post(fn_name, sig)); + } + serde_json::to_value(generate(&metadata, &storage)).unwrap() +} + +fn component_names(doc: &Value) -> Vec<&str> { + doc["components"]["schemas"] + .as_object() + .unwrap() + .keys() + .map(String::as_str) + .collect() +} + +fn request_ref<'a>(doc: &'a Value, path: &str) -> &'a Value { + &doc["paths"][path]["post"]["requestBody"]["content"]["application/json"]["schema"] +} + +fn schema_ref(name: &str) -> Value { + json!({"$ref": format!("#/components/schemas/{name}")}) +} + +const PORTFOLIO_UPDATE: &str = r#"#[serde(rename_all = "camelCase")] +pub struct PortfolioUpdateRequest { + #[serde(default)] + pub title: String, + #[serde(default, deserialize_with = "deserialize_optional_field")] + pub production_end_date: Option>, +}"#; + +/// A request-only type whose views differ is emitted once, as its request +/// view, under its own name: no `PortfolioUpdateRequestInput`, no orphan +/// response view. The `deserialize_with` field is documented from its Rust +/// type (`Option>` → a nullable date, not required; its +/// `#[serde(default)]` documents `default: null`). +#[test] +fn request_only_type_keeps_its_name() { + let doc = doc_for( + &[ + ("PortfolioUpdateRequest", PORTFOLIO_UPDATE), + ("Portfolio", "pub struct Portfolio { pub id: u64 }"), + ], + &[( + "/portfolio", + "update", + "async fn update(Json(r): Json) -> Json", + )], + ); + assert_eq!( + component_names(&doc), + ["Portfolio", "PortfolioUpdateRequest"] + ); + assert_eq!( + *request_ref(&doc, "/portfolio"), + schema_ref("PortfolioUpdateRequest") + ); + let request = &doc["components"]["schemas"]["PortfolioUpdateRequest"]; + assert_eq!( + request["properties"]["productionEndDate"], + json!({"type": ["string", "null"], "format": "date", "default": null}) + ); + insta::assert_snapshot!( + "request_only_portfolio_update_request", + serde_json::to_string_pretty(request).unwrap() + ); +} + +/// A type only returned keeps its single response view (`x` required). +#[test] +fn response_only_type_is_unchanged() { + let doc = doc_for( + &[( + "Settings", + "pub struct Settings { #[serde(default)] pub x: u8 }", + )], + &[("/settings", "get", "async fn get() -> Json")], + ); + assert_eq!(component_names(&doc), ["Settings"]); + assert_eq!( + doc["components"]["schemas"]["Settings"]["required"], + json!(["x"]) + ); +} + +/// A type read and returned keeps both views: `{Name}` and `{Name}Input`. +#[test] +fn type_used_on_both_sides_gets_an_input() { + let doc = doc_for( + &[( + "Settings", + "pub struct Settings { #[serde(default)] pub x: u8 }", + )], + &[( + "/settings", + "put", + "async fn put(Json(s): Json) -> Json", + )], + ); + assert_eq!(component_names(&doc), ["Settings", "SettingsInput"]); + assert_eq!(*request_ref(&doc, "/settings"), schema_ref("SettingsInput")); + assert_eq!( + doc["components"]["schemas"]["Settings"]["required"], + json!(["x"]) + ); + assert_eq!( + doc["components"]["schemas"]["SettingsInput"]["required"], + Value::Null + ); +} + +const CREATE_ORDER: (&str, &str) = ( + "CreateOrder", + "pub struct CreateOrder { pub items: Vec }", +); +const LINE_ITEM: (&str, &str) = ( + "LineItem", + "pub struct LineItem { pub sku: String, #[serde(default)] pub qty: u32 }", +); +const ORDER: (&str, &str) = ("Order", "pub struct Order { pub id: u64 }"); + +fn items_ref(doc: &Value, component: &str) -> Value { + doc["components"]["schemas"][component]["properties"]["items"]["items"].clone() +} + +/// `CreateOrder { items: Vec }` read only, `LineItem` nowhere +/// else: both keep their names, as their request views. +#[test] +fn transitive_request_only_types_keep_their_names() { + let doc = doc_for( + &[CREATE_ORDER, LINE_ITEM, ORDER], + &[( + "/orders", + "create", + "async fn create(Json(o): Json) -> Json", + )], + ); + assert_eq!(component_names(&doc), ["CreateOrder", "LineItem", "Order"]); + assert_eq!(*request_ref(&doc, "/orders"), schema_ref("CreateOrder")); + assert_eq!(items_ref(&doc, "CreateOrder"), schema_ref("LineItem")); + assert_eq!( + doc["components"]["schemas"]["LineItem"]["required"], + json!(["sku"]) + ); +} + +/// `LineItem` is also returned: it keeps `LineItem` + `LineItemInput`, and +/// the request-only `CreateOrder` (its request view) references the input. +#[test] +fn transitive_type_also_returned_keeps_its_input() { + let doc = doc_for( + &[CREATE_ORDER, LINE_ITEM, ORDER], + &[ + ( + "/orders", + "create", + "async fn create(Json(o): Json) -> Json", + ), + ("/items", "items", "async fn items() -> Json>"), + ], + ); + assert_eq!( + component_names(&doc), + ["CreateOrder", "LineItem", "LineItemInput", "Order"] + ); + assert_eq!(*request_ref(&doc, "/orders"), schema_ref("CreateOrder")); + assert_eq!(items_ref(&doc, "CreateOrder"), schema_ref("LineItemInput")); + assert_eq!( + doc["components"]["schemas"]["LineItem"]["required"], + json!(["sku", "qty"]) + ); +} + +/// `CreateOrder` is returned too: its response view reaches `LineItem`, so +/// both types keep both views. +#[test] +fn transitive_types_used_on_both_sides_keep_their_inputs() { + let doc = doc_for( + &[CREATE_ORDER, LINE_ITEM], + &[( + "/orders", + "create", + "async fn create(Json(o): Json) -> Json", + )], + ); + assert_eq!( + component_names(&doc), + [ + "CreateOrder", + "CreateOrderInput", + "LineItem", + "LineItemInput" + ] + ); + assert_eq!( + *request_ref(&doc, "/orders"), + schema_ref("CreateOrderInput") + ); + assert_eq!(items_ref(&doc, "CreateOrder"), schema_ref("LineItem")); + assert_eq!( + items_ref(&doc, "CreateOrderInput"), + schema_ref("LineItemInput") + ); +} + +/// A documented type no route uses stays documented with what it references: +/// `Wrapper` (unused) keeps `Inner`'s response view alive, so the +/// request-only use of `Inner` still goes through `InnerInput`. +#[test] +fn unused_types_keep_the_response_views_they_reference() { + let doc = doc_for( + &[ + ("Wrapper", "pub struct Wrapper { pub inner: Inner }"), + ("Inner", "pub struct Inner { #[serde(default)] pub x: u8 }"), + ], + &[( + "/inner", + "save", + "async fn save(Json(i): Json) -> String", + )], + ); + assert_eq!(component_names(&doc), ["Inner", "InnerInput", "Wrapper"]); + assert_eq!(*request_ref(&doc, "/inner"), schema_ref("InnerInput")); +} + +const USER: (&str, &str) = ("User", "pub struct User { #[serde(default)] pub x: u8 }"); +const USER_INPUT: (&str, &str) = ("UserInput", "pub struct UserInput { pub y: u8 }"); + +/// A real `UserInput` type owns that name: a `User` read and returned gets +/// `UserInput2`; read only, it keeps `User` and the real `UserInput` is +/// left alone. +#[test] +fn input_name_collisions() { + let both = doc_for( + &[USER, USER_INPUT], + &[( + "/user", + "save", + "async fn save(Json(u): Json) -> Json", + )], + ); + assert_eq!(component_names(&both), ["User", "UserInput", "UserInput2"]); + assert_eq!(*request_ref(&both, "/user"), schema_ref("UserInput2")); + + let request_only = doc_for( + &[USER, USER_INPUT], + &[( + "/user", + "save", + "async fn save(Json(u): Json) -> Json", + )], + ); + assert_eq!(component_names(&request_only), ["User", "UserInput"]); + assert_eq!(*request_ref(&request_only, "/user"), schema_ref("User")); + let schemas = &request_only["components"]["schemas"]; + assert_eq!(schemas["User"]["required"], Value::Null); + assert_eq!(schemas["UserInput"]["required"], json!(["y"])); +} + +/// A recursive generic instance read only: `Tree_i32.Input` becomes +/// `Tree_i32` (its request view), and its self-references follow. +#[test] +fn request_only_generic_instance_keeps_its_name() { + let doc = doc_for( + &[( + "Tree", + "pub struct Tree { pub value: T, #[serde(default)] pub children: Vec> }", + )], + &[( + "/tree", + "tree", + "async fn tree(Json(t): Json>) -> String", + )], + ); + let names = component_names(&doc); + assert!( + !names.iter().any(|name| name.contains("Input")), + "{names:?}" + ); + let text = serde_json::to_string(&doc).unwrap(); + assert!(!text.contains(".Input"), "{text}"); + assert_eq!( + doc["components"]["schemas"]["Tree_i32"]["required"], + json!(["value"]) + ); +} diff --git a/crates/vespera_macro/src/parser/operation/snapshots/vespera_macro__parser__operation__tests_request_shapes__request_shapes_custom_deserializer_option.snap b/crates/vespera_macro/src/parser/operation/snapshots/vespera_macro__parser__operation__tests_request_shapes__request_shapes_custom_deserializer_option.snap index fcf73532a..fded997af 100644 --- a/crates/vespera_macro/src/parser/operation/snapshots/vespera_macro__parser__operation__tests_request_shapes__request_shapes_custom_deserializer_option.snap +++ b/crates/vespera_macro/src/parser/operation/snapshots/vespera_macro__parser__operation__tests_request_shapes__request_shapes_custom_deserializer_option.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/operation/tests_request_shapes.rs -assertion_line: 147 expression: "serde_json::to_string_pretty(&summary).unwrap()" --- { @@ -11,23 +10,39 @@ expression: "serde_json::to_string_pretty(&summary).unwrap()" "name": "since", "required": true, "schema": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "format": "int64", + "type": [ + "integer", + "null" + ] } }, { + "explode": true, "in": "query", "name": "tags", "required": true, "schema": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." - } + "items": { + "type": "string" + }, + "type": [ + "array", + "null" + ] + }, + "style": "form" }, { "in": "query", "name": "until", "required": false, "schema": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "format": "int64", + "type": [ + "integer", + "null" + ] } }, { diff --git a/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__path__tests__path_wire_override_fields.snap b/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__path__tests__path_wire_override_fields.snap index c7cfdfa03..ac665024b 100644 --- a/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__path__tests__path_wire_override_fields.snap +++ b/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__path__tests__path_wire_override_fields.snap @@ -1,7 +1,6 @@ --- source: crates/vespera_macro/src/parser/parameters/path.rs -assertion_line: 229 expression: "schemas.join(\"\\n\")" --- {"type":"string"} -{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."} +{"type":"array","items":{"type":"integer","format":"uint8","minimum":0,"maximum":255}} diff --git a/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__query__tests__query_wire_override_fields.snap b/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__query__tests__query_wire_override_fields.snap index 2690b0890..f9ce3ea2f 100644 --- a/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__query__tests__query_wire_override_fields.snap +++ b/crates/vespera_macro/src/parser/parameters/snapshots/vespera_macro__parser__parameters__query__tests__query_wire_override_fields.snap @@ -1,7 +1,6 @@ --- source: crates/vespera_macro/src/parser/parameters/query.rs -assertion_line: 685 expression: "schemas.join(\"\\n\")" --- {"type":"integer","format":"int64"} -{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."} +{"type":"array","items":{"type":"string"}} diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_tuple_variant_fields.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_tuple_variant_fields.snap index b6303a979..fc158c7ba 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_tuple_variant_fields.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_tuple_variant_fields.snap @@ -4,4 +4,4 @@ expression: both_views(src) --- enum E { Pair(#[schema(value_type = String)] Id, #[serde(deserialize_with = "d")] u8), One(#[serde(with = "m")] Thing) } response: {"oneOf":[{"type":"object","properties":{"Pair":{"type":"array","prefixItems":[{"type":"string"},{"type":"integer","format":"uint8","minimum":0,"maximum":255}],"minItems":2,"maxItems":2}},"required":["Pair"],"maxProperties":1},{"type":"object","properties":{"One":{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."}},"required":["One"],"maxProperties":1}]} -request: {"oneOf":[{"type":"object","properties":{"Pair":{"type":"array","prefixItems":[{"type":"string"},{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."}],"minItems":2,"maxItems":2}},"required":["Pair"],"maxProperties":1},{"type":"object","properties":{"One":{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."}},"required":["One"],"maxProperties":1}]} +request: {"oneOf":[{"type":"object","properties":{"Pair":{"type":"array","prefixItems":[{"type":"string"},{"type":"integer","format":"uint8","minimum":0,"maximum":255}],"minItems":2,"maxItems":2}},"required":["Pair"],"maxProperties":1},{"type":"object","properties":{"One":{}},"required":["One"],"maxProperties":1}]} diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_variant_codec_untagged.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_variant_codec_untagged.snap index 1ab91e57b..16a009aef 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_variant_codec_untagged.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_fidelity__enum_views_variant_codec_untagged.snap @@ -1,8 +1,7 @@ --- source: crates/vespera_macro/src/parser/schema/enum_schema/representations/tests_fidelity.rs -assertion_line: 101 expression: both_views(src) --- #[serde(untagged)] enum E { #[serde(with = "m")] Newtype(Thing), Pair(u8, #[serde(with = "m")] Thing) } response: {"anyOf":[{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."},{"type":"array","prefixItems":[{"type":"integer","format":"uint8","minimum":0,"maximum":255},{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."}],"minItems":2,"maxItems":2}]} -request: {"anyOf":[{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."},{"type":"array","prefixItems":[{"type":"integer","format":"uint8","minimum":0,"maximum":255},{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."}],"minItems":2,"maxItems":2}]} +request: {"anyOf":[{"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."},{"type":"array","prefixItems":[{"type":"integer","format":"uint8","minimum":0,"maximum":255},{}],"minItems":2,"maxItems":2}]} diff --git a/crates/vespera_macro/src/parser/schema/request_view.rs b/crates/vespera_macro/src/parser/schema/request_view.rs index f551e1001..58d74558b 100644 --- a/crates/vespera_macro/src/parser/schema/request_view.rs +++ b/crates/vespera_macro/src/parser/schema/request_view.rs @@ -17,8 +17,9 @@ //! - the container is documented through a different type per direction //! (`#[serde(into = "A")]` and/or `from` / `try_from = "B"`, see //! `wire_override`), -//! - a field has a one-sided `serialize_with` / `deserialize_with` (without -//! `#[schema(value_type)]`), or is an `Option` read through a custom +//! - a field has a `with` / `serialize_with` (without +//! `#[schema(value_type)]`: the request view documents the Rust type), +//! or is an `Option` read through a custom //! deserializer (serde then requires it), //! - a field has `#[serde(alias)]` names (accepted keys), or a non-`Option` //! `skip_serializing_if` field without `default` (optional on output, @@ -78,7 +79,7 @@ use super::{ extract_tag, extract_transparent, extract_untagged, }, struct_schema::{flattened_member, peel}, - wire_override::container_override_type, + wire_override::{codec_hides_shape, container_override_type}, }; use crate::schema_macro::type_utils::is_option_type; @@ -271,14 +272,24 @@ fn container_override_differs(attrs: &[syn::Attribute]) -> bool { } /// The field's documented schema or `required`-ness differs per direction -/// because of a custom serde function: a one-sided `serialize_with` / -/// `deserialize_with` without `value_type`, or an `Option` read through a -/// custom function (serde no longer defaults it to `None` when absent). +/// because of a custom serde function: a serialize-side one (`with` / +/// `serialize_with`) without `value_type` hides the response shape while +/// the request view documents the Rust type (see `wire_override`), and an +/// `Option` read through a custom function is required (serde no longer +/// defaults it to `None` when absent). A `deserialize_with` alone documents +/// the same type on both sides. fn field_codec_differs(field: &syn::Field) -> bool { - one_sided_codec(&field.attrs) + codec_differs(&field.attrs) || (extract_field_codec(&field.attrs).deserialize && is_option_type(&field.ty)) } +/// A field's custom serde function documents a different schema per side +/// (see [`field_codec_differs`]). +fn codec_differs(attrs: &[syn::Attribute]) -> bool { + codec_hides_shape(attrs, SerdeSide::Serialize) + && extract_schema_constraints(attrs).value_type.is_none() +} + /// The type's own attributes make its request view differ. `flat` classifies /// the types a flattened member may name (see [`FlatKinds`]). fn directly_differs(item: &syn::Item, flat: &FlatKinds) -> bool { @@ -550,13 +561,14 @@ fn field_differs(field: &syn::Field) -> bool { } /// A tuple-struct / tuple-variant position reads differently than it -/// writes: skipped on one side only (the array length differs), a one-sided -/// custom serde function, or a type whose schema differs per side. +/// writes: skipped on one side only (the array length differs), a +/// serialize-side custom serde function, or a type whose schema differs +/// per side. fn positional_differs(field: &syn::Field) -> bool { let skip = extract_serde_skip_flags(&field.attrs); !skip.fully_skipped() && (skip.skip_serializing != skip.skip_deserializing - || one_sided_codec(&field.attrs) + || codec_differs(&field.attrs) || field_type_differs(field)) } @@ -580,7 +592,7 @@ fn tuple_differs(fields: &syn::FieldsUnnamed, container_default: bool) -> bool { }))) } -/// A one-sided `serialize_with` / `deserialize_with` (field or variant) +/// A one-sided variant-level `serialize_with` / `deserialize_with` /// without `#[schema(value_type)]`. fn one_sided_codec(attrs: &[syn::Attribute]) -> bool { let codec = extract_field_codec(attrs); diff --git a/crates/vespera_macro/src/parser/schema/request_view/tests.rs b/crates/vespera_macro/src/parser/schema/request_view/tests.rs index 3ab4ebae7..801476862 100644 --- a/crates/vespera_macro/src/parser/schema/request_view/tests.rs +++ b/crates/vespera_macro/src/parser/schema/request_view/tests.rs @@ -214,7 +214,12 @@ fn scoped_names( false )] #[case::enum_into(r#"#[serde(into = "String")] enum E { A }"#, true)] -#[case::with_both_sides(r#"struct A { #[serde(with = "m")] x: u8 }"#, false)] +// The response view hides a `with` / `serialize_with` field's shape, the +// request view documents its Rust type; a `deserialize_with` alone documents +// the Rust type on both sides. +#[case::with_both_sides(r#"struct A { #[serde(with = "m")] x: u8 }"#, true)] +#[case::deserialize_with(r#"struct A { #[serde(deserialize_with = "f")] x: u8 }"#, false)] +#[case::tuple_deserialize_with(r#"struct A(#[serde(deserialize_with = "f")] u8);"#, false)] #[case::serialize_with(r#"struct A { #[serde(serialize_with = "f")] x: u8 }"#, true)] #[case::deserialize_with_value_type( r#"struct A { #[serde(deserialize_with = "f")] #[schema(value_type = u8)] x: u8 }"#, diff --git a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__wire_override__tests__wire_override_field_deserialize_with_on_deserialize.snap b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__wire_override__tests__wire_override_field_deserialize_with_on_deserialize.snap index c9e642a9e..7e82417ac 100644 --- a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__wire_override__tests__wire_override_field_deserialize_with_on_deserialize.snap +++ b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__wire_override__tests__wire_override_field_deserialize_with_on_deserialize.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/wire_override.rs -assertion_line: 119 expression: "format!(\"{src} ({side:?}) => {}\", serde_json::to_string(&schema).unwrap())" --- -#[serde(deserialize_with = "f")] x: u8 (Deserialize) => {"description":"Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it."} +#[serde(deserialize_with = "f")] x: u8 (Deserialize) => {"type":"integer","format":"uint8","minimum":0,"maximum":255} diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs index 96687b68e..a500559b3 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs @@ -61,8 +61,9 @@ use super::{ enum_schema::{parse_enum_to_schema, without_other_map, without_single_key_bounds}, request_view::{self, FlatRead}, schema_attrs::{SchemaConstraints, extract_schema_constraints}, - serde_attrs::{SerdeSide, extract_field_codec}, + serde_attrs::SerdeSide, type_schema::{generic_instances, parse_type_to_schema_ref}, + wire_override::codec_hides_shape, }, parse_struct_to_schema, }; @@ -121,7 +122,7 @@ pub(super) fn flatten_part( // `#[schema(value_type = T)]` documents a custom codec's wire shape, // exactly as on a field that is not flattened. let custom = constraints.is_any() - || (constraints.value_type.is_none() && extract_field_codec(&field.attrs).custom_for(side)); + || (constraints.value_type.is_none() && codec_hides_shape(&field.attrs, side)); let leaves = !custom && leaves_keys(ty, struct_definitions, WRAPPER_DEPTH); let schema = if custom { SchemaRef::Inline(Box::default()) diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_tuple_codecs.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_tuple_codecs.snap index 2bfed5cdb..bceccd870 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_tuple_codecs.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_tuple_codecs.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_serde_fidelity.rs -assertion_line: 209 expression: both_views(src) --- struct P(#[serde(with = "ts")] DateTime, #[schema(value_type = String)] Id, #[serde(serialize_with = "f")] u8); @@ -24,7 +23,8 @@ request: { "type": "array", "prefixItems": [ { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "string", + "format": "date-time" }, { "type": "string" diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap index a145340fb..e41fdcf30 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap @@ -51,10 +51,19 @@ struct Event { "type": "object", "properties": { "in_only": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "integer", + "format": "uint8", + "minimum": 0, + "maximum": 255 }, "maybe": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": [ + "integer", + "null" + ], + "format": "uint8", + "minimum": 0, + "maximum": 255 }, "out_only": { "type": "integer", @@ -64,7 +73,13 @@ struct Event { "maximum": 255 }, "raw": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0, + "maximum": 255 + } } }, "required": [ diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_transparent_with.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_transparent_with.snap index 5d2dd5b1f..54b3424f7 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_transparent_with.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_transparent_with.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_wire_override.rs -assertion_line: 83 expression: "format!(\"{src}\\n\\n--- response ---\\n{}\\n--- request ---\\n{}\",\nrender(src, false), render(src, true))" --- #[serde(transparent)] struct Stamp { #[serde(with = "ts_seconds")] at: DateTime } @@ -11,5 +10,6 @@ expression: "format!(\"{src}\\n\\n--- response ---\\n{}\\n--- request ---\\n{}\" } --- request --- { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "string", + "format": "date-time" } diff --git a/crates/vespera_macro/src/parser/schema/wire_override.rs b/crates/vespera_macro/src/parser/schema/wire_override.rs index 364db8e81..74bcc4609 100644 --- a/crates/vespera_macro/src/parser/schema/wire_override.rs +++ b/crates/vespera_macro/src/parser/schema/wire_override.rs @@ -5,11 +5,15 @@ //! `#[serde(from = "T")]` / `try_from` deserializes from `T` (the request //! view, see [`super::request_view`]); an explicit container //! `#[schema(value_type = ..)]` wins over both. -//! - A field written / read by a custom serde function (`with`, -//! `serialize_with`, `deserialize_with`) without a `value_type` has an -//! unknowable shape. It is documented as any value (`{}`) with a -//! description saying why — never as the declared type, which would be a -//! confident lie (`ts_seconds` turns a date-time string into an integer). +//! - A field WRITTEN by a custom serde function (`with`, `serialize_with`) +//! without a `value_type` has an unknowable output shape: the response +//! view documents it as any value (`{}`) with a description saying why. +//! - A field READ by one (`with`, `deserialize_with`) is documented from its +//! Rust type in the request view, like a plain field: a custom +//! deserializer most often reads the type's own shape (the +//! `Option>` "absent vs `null`" helpers), and an untyped request +//! field is useless to a generated client. A `value_type` documents any +//! other shape (`ts_seconds`: `#[schema(value_type = i64)]`). use std::{ borrow::Borrow, @@ -46,7 +50,7 @@ pub fn field_schema_ref( if let Some(value_type) = &constraints.value_type { return parse_type_to_schema_ref(&value_type.0, known_schemas, struct_definitions); } - if extract_field_codec(&field.attrs).custom_for(side) { + if codec_hides_shape(&field.attrs, side) { return SchemaRef::Inline(Box::new(Schema { description: Some(CUSTOM_CODEC_DESCRIPTION.to_string()), ..Schema::default() @@ -55,6 +59,14 @@ pub fn field_schema_ref( parse_type_to_schema_ref(&field.ty, known_schemas, struct_definitions) } +/// A field's custom serde function hides its wire shape on `side`: only a +/// serialize-side one (`with` / `serialize_with`) — the request view +/// documents a field read by one from its Rust type (see the module docs). +/// `value_type` / `#[schema(any)]` are the caller's to check. +pub fn codec_hides_shape(attrs: &[syn::Attribute], side: SerdeSide) -> bool { + side == SerdeSide::Serialize && extract_field_codec(attrs).serialize +} + /// The type a container is documented as on `side` instead of its own /// fields / variants: `#[schema(value_type = T)]`, else serde's `into` /// (serialize) or `from` / `try_from` (deserialize). diff --git a/crates/vespera_macro/src/router_codegen.rs b/crates/vespera_macro/src/router_codegen.rs index abdd666b7..aea6f76ee 100644 --- a/crates/vespera_macro/src/router_codegen.rs +++ b/crates/vespera_macro/src/router_codegen.rs @@ -12,7 +12,8 @@ mod route_dir; mod security_dsl; pub use export::{ - ExportAppInput, apply_export_prefix, namespace_export_schemas, schema_namespace_from_prefix, + ExportAppInput, apply_export_prefix, namespace_export_schemas, rewrite_schema_refs, + schema_namespace_from_prefix, }; pub use generator::generate_router_code; #[cfg(test)] diff --git a/crates/vespera_macro/src/router_codegen/export.rs b/crates/vespera_macro/src/router_codegen/export.rs index cc956fe1c..c45f7f486 100644 --- a/crates/vespera_macro/src/router_codegen/export.rs +++ b/crates/vespera_macro/src/router_codegen/export.rs @@ -249,7 +249,8 @@ pub fn namespace_export_schemas( Ok(()) } -fn rewrite_schema_refs(value: &mut serde_json::Value, renames: &BTreeMap) { +/// Point every `#/components/schemas/{old}` `$ref` inside `value` at `renames[old]`. +pub fn rewrite_schema_refs(value: &mut serde_json::Value, renames: &BTreeMap) { match value { serde_json::Value::Object(object) => { if let Some(serde_json::Value::String(reference)) = object.get_mut("$ref") diff --git a/examples/axum-example/openapi.json b/examples/axum-example/openapi.json index 9e8cc07c9..e5cff2ffb 100644 --- a/examples/axum-example/openapi.json +++ b/examples/axum-example/openapi.json @@ -315,7 +315,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateConfigRequestInput" + "$ref": "#/components/schemas/UpdateConfigRequest" } } } @@ -800,7 +800,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserListRequestInput" + "$ref": "#/components/schemas/UserListRequest" } } } @@ -831,7 +831,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdvancedSearchRequestInput" + "$ref": "#/components/schemas/AdvancedSearchRequest" } } } @@ -3031,7 +3031,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateUuidItemRequestInput" + "$ref": "#/components/schemas/CreateUuidItemRequest" } } } @@ -3674,26 +3674,6 @@ } ] }, - "AdvancedSearchRequestInput": { - "description": "Request combining multiple flattened structs", - "allOf": [ - { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Search query string" - } - }, - "required": [ - "query" - ] - }, - { - "$ref": "#/components/schemas/PaginationInput" - } - ] - }, "Audit": { "type": "object", "description": "Optional audit block flattened into [`Telemetry`].", @@ -3730,6 +3710,7 @@ "type": "string" }, "flagship": { + "description": "`HasOne` selected through the target's `FlagshipOf` relation.", "anyOf": [ { "$ref": "#/components/schemas/BakerySchema_Flagship" @@ -3737,8 +3718,7 @@ { "type": "null" } - ], - "description": "`HasOne` selected through the target's `FlagshipOf` relation." + ] }, "id": { "type": "integer", @@ -4475,35 +4455,6 @@ ] }, "CreateUuidItemRequest": { - "type": "object", - "description": "UUID item model for testing UUID format in OpenAPI", - "properties": { - "externalRef": { - "type": [ - "string", - "null" - ], - "format": "uuid", - "description": "External reference UUID" - }, - "name": { - "type": "string", - "description": "Item name" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, - "required": [ - "name", - "tags" - ] - }, - "CreateUuidItemRequestInput": { "type": "object", "description": "UUID item model for testing UUID format in OpenAPI", "properties": { @@ -5064,7 +5015,13 @@ "description": "Timestamps written by custom serde functions.", "properties": { "checksum": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0, + "maximum": 255 + } }, "createdAt": { "type": "integer", @@ -6217,28 +6174,6 @@ ] }, "Pagination": { - "type": "object", - "description": "Common pagination parameters that can be reused across requests", - "properties": { - "page": { - "type": "integer", - "format": "int32", - "description": "Page number (1-indexed)", - "default": 1 - }, - "perPage": { - "type": "integer", - "format": "int32", - "description": "Items per page", - "default": 20 - } - }, - "required": [ - "page", - "perPage" - ] - }, - "PaginationInput": { "type": "object", "description": "Common pagination parameters that can be reused across requests", "properties": { @@ -7220,76 +7155,6 @@ ] }, "UpdateConfigRequest": { - "type": "object", - "properties": { - "delimiter": { - "type": [ - "string", - "null" - ], - "format": "char" - }, - "discountRate": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "maxItems": { - "type": [ - "integer", - "null" - ], - "minimum": 0 - }, - "maxPrice": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "minPrice": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "priority": { - "type": [ - "integer", - "null" - ], - "format": "int32" - }, - "retryCount": { - "type": [ - "integer", - "null" - ], - "format": "uint8", - "minimum": 0, - "maximum": 255 - }, - "separator": { - "type": [ - "string", - "null" - ], - "format": "char" - }, - "taxRate": { - "type": [ - "string", - "null" - ], - "format": "decimal" - } - } - }, - "UpdateConfigRequestInput": { "type": "object", "properties": { "delimiter": { @@ -7568,34 +7433,6 @@ ] }, "UserListRequest": { - "description": "Request with flattened pagination parameters\n\nThe pagination fields (page, per_page) are merged into this struct's JSON representation.", - "allOf": [ - { - "type": "object", - "properties": { - "filter": { - "type": [ - "string", - "null" - ], - "description": "Filter users by name (optional)" - }, - "sort": { - "type": "string", - "description": "Sort order: \"asc\" or \"desc\"", - "default": "asc" - } - }, - "required": [ - "sort" - ] - }, - { - "$ref": "#/components/schemas/Pagination" - } - ] - }, - "UserListRequestInput": { "description": "Request with flattened pagination parameters\n\nThe pagination fields (page, per_page) are merged into this struct's JSON representation.", "allOf": [ { @@ -7616,7 +7453,7 @@ } }, { - "$ref": "#/components/schemas/PaginationInput" + "$ref": "#/components/schemas/Pagination" } ] }, diff --git a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimesInput.snap b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimesInput.snap index 3268cd2a2..e87bdd7ed 100644 --- a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimesInput.snap +++ b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimesInput.snap @@ -1,13 +1,18 @@ --- source: examples/axum-example/tests/integration_codecs.rs -assertion_line: 86 expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][component]).unwrap()" --- { "description": "Timestamps written by custom serde functions.", "properties": { "checksum": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "items": { + "format": "uint8", + "maximum": 255, + "minimum": 0, + "type": "integer" + }, + "type": "array" }, "createdAt": { "description": "Unix seconds (`chrono::serde::ts_seconds`) — an integer, not a\ndate-time string.", diff --git a/examples/axum-example/tests/snapshots/integration_test__openapi.snap b/examples/axum-example/tests/snapshots/integration_test__openapi.snap index 2215a1add..cd4e402fc 100644 --- a/examples/axum-example/tests/snapshots/integration_test__openapi.snap +++ b/examples/axum-example/tests/snapshots/integration_test__openapi.snap @@ -1,6 +1,5 @@ --- source: examples/axum-example/tests/integration_test.rs -assertion_line: 529 expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" --- { @@ -320,7 +319,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UpdateConfigRequestInput" + "$ref": "#/components/schemas/UpdateConfigRequest" } } } @@ -805,7 +804,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/UserListRequestInput" + "$ref": "#/components/schemas/UserListRequest" } } } @@ -836,7 +835,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/AdvancedSearchRequestInput" + "$ref": "#/components/schemas/AdvancedSearchRequest" } } } @@ -3036,7 +3035,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateUuidItemRequestInput" + "$ref": "#/components/schemas/CreateUuidItemRequest" } } } @@ -3679,26 +3678,6 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } ] }, - "AdvancedSearchRequestInput": { - "description": "Request combining multiple flattened structs", - "allOf": [ - { - "type": "object", - "properties": { - "query": { - "type": "string", - "description": "Search query string" - } - }, - "required": [ - "query" - ] - }, - { - "$ref": "#/components/schemas/PaginationInput" - } - ] - }, "Audit": { "type": "object", "description": "Optional audit block flattened into [`Telemetry`].", @@ -3735,6 +3714,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "type": "string" }, "flagship": { + "description": "`HasOne` selected through the target's `FlagshipOf` relation.", "anyOf": [ { "$ref": "#/components/schemas/BakerySchema_Flagship" @@ -3742,8 +3722,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" { "type": "null" } - ], - "description": "`HasOne` selected through the target's `FlagshipOf` relation." + ] }, "id": { "type": "integer", @@ -4480,35 +4459,6 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "CreateUuidItemRequest": { - "type": "object", - "description": "UUID item model for testing UUID format in OpenAPI", - "properties": { - "externalRef": { - "type": [ - "string", - "null" - ], - "format": "uuid", - "description": "External reference UUID" - }, - "name": { - "type": "string", - "description": "Item name" - }, - "tags": { - "type": "array", - "items": { - "type": "string" - }, - "uniqueItems": true - } - }, - "required": [ - "name", - "tags" - ] - }, - "CreateUuidItemRequestInput": { "type": "object", "description": "UUID item model for testing UUID format in OpenAPI", "properties": { @@ -5069,7 +5019,13 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "description": "Timestamps written by custom serde functions.", "properties": { "checksum": { - "description": "Converted by a custom serde function (`with` / `serialize_with` / `deserialize_with`); its wire shape is not known. Add `#[schema(value_type = T)]` to document it." + "type": "array", + "items": { + "type": "integer", + "format": "uint8", + "minimum": 0, + "maximum": 255 + } }, "createdAt": { "type": "integer", @@ -6222,28 +6178,6 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "Pagination": { - "type": "object", - "description": "Common pagination parameters that can be reused across requests", - "properties": { - "page": { - "type": "integer", - "format": "int32", - "description": "Page number (1-indexed)", - "default": 1 - }, - "perPage": { - "type": "integer", - "format": "int32", - "description": "Items per page", - "default": 20 - } - }, - "required": [ - "page", - "perPage" - ] - }, - "PaginationInput": { "type": "object", "description": "Common pagination parameters that can be reused across requests", "properties": { @@ -7225,76 +7159,6 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "UpdateConfigRequest": { - "type": "object", - "properties": { - "delimiter": { - "type": [ - "string", - "null" - ], - "format": "char" - }, - "discountRate": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "maxItems": { - "type": [ - "integer", - "null" - ], - "minimum": 0 - }, - "maxPrice": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "minPrice": { - "type": [ - "string", - "null" - ], - "format": "decimal" - }, - "priority": { - "type": [ - "integer", - "null" - ], - "format": "int32" - }, - "retryCount": { - "type": [ - "integer", - "null" - ], - "format": "uint8", - "minimum": 0, - "maximum": 255 - }, - "separator": { - "type": [ - "string", - "null" - ], - "format": "char" - }, - "taxRate": { - "type": [ - "string", - "null" - ], - "format": "decimal" - } - } - }, - "UpdateConfigRequestInput": { "type": "object", "properties": { "delimiter": { @@ -7573,34 +7437,6 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "UserListRequest": { - "description": "Request with flattened pagination parameters\n\nThe pagination fields (page, per_page) are merged into this struct's JSON representation.", - "allOf": [ - { - "type": "object", - "properties": { - "filter": { - "type": [ - "string", - "null" - ], - "description": "Filter users by name (optional)" - }, - "sort": { - "type": "string", - "description": "Sort order: \"asc\" or \"desc\"", - "default": "asc" - } - }, - "required": [ - "sort" - ] - }, - { - "$ref": "#/components/schemas/Pagination" - } - ] - }, - "UserListRequestInput": { "description": "Request with flattened pagination parameters\n\nThe pagination fields (page, per_page) are merged into this struct's JSON representation.", "allOf": [ { @@ -7621,7 +7457,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } }, { - "$ref": "#/components/schemas/PaginationInput" + "$ref": "#/components/schemas/Pagination" } ] }, From 9fb5d70bd48d88efbcb9300b4ab1de8ec66929e1 Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 14:18:28 +0900 Subject: [PATCH 2/7] refactor(macro): rename request-only inputs through JSON text, single-expression .Input scan Co-Authored-By: Claude Opus 5.5 --- .../openapi_generator/component_schemas.rs | 53 +++++++++++-------- 1 file changed, 30 insertions(+), 23 deletions(-) diff --git a/crates/vespera_macro/src/openapi_generator/component_schemas.rs b/crates/vespera_macro/src/openapi_generator/component_schemas.rs index 48c3cde3c..e18a1d328 100644 --- a/crates/vespera_macro/src/openapi_generator/component_schemas.rs +++ b/crates/vespera_macro/src/openapi_generator/component_schemas.rs @@ -145,11 +145,11 @@ pub(super) fn collapse_request_only_inputs( }) .map(|(component, input)| (input.as_str(), component.as_str())) .collect(); - for name in schemas.keys() { - if let Some(component) = name.strip_suffix(".Input") { - inputs.insert(name, component); - } - } + inputs.extend( + schemas + .keys() + .filter_map(|name| Some((name.as_str(), name.strip_suffix(".Input")?))), + ); if inputs.is_empty() { return Ok(()); } @@ -181,25 +181,32 @@ pub(super) fn collapse_request_only_inputs( schemas.insert(component.clone(), schema); } } - // A plain-data round-trip (cannot fail). - let rename = |value: serde_json::Result| { - value.map(|mut value| { - crate::router_codegen::rewrite_schema_refs(&mut value, &renames); - value - }) - }; - let rebuild_error = |error: serde_json::Error| { - syn::Error::new( - proc_macro2::Span::call_site(), - format!("vespera: failed to rename request-only input components: {error}"), - ) + // A plain-data round-trip (cannot fail) through JSON text, like + // `export_app!`'s: the text reader is already instantiated for every + // OpenAPI type, a `from_value` one would compile a second copy. + let rename = |text: serde_json::Result| { + text.and_then(|text| serde_json::from_str::(&text)) + .map(|mut value| { + crate::router_codegen::rewrite_schema_refs(&mut value, &renames); + value.to_string() + }) }; - *schemas = rename(serde_json::to_value(&*schemas)) - .and_then(serde_json::from_value) - .map_err(rebuild_error)?; - *paths = rename(serde_json::to_value(&*paths)) - .and_then(serde_json::from_value) - .map_err(rebuild_error)?; + *schemas = rename(serde_json::to_string(&*schemas)) + .and_then(|text| serde_json::from_str(&text)) + .map_err(|error| { + syn::Error::new( + proc_macro2::Span::call_site(), + format!("vespera: failed to rename request-only input components: {error}"), + ) + })?; + *paths = rename(serde_json::to_string(&*paths)) + .and_then(|text| serde_json::from_str(&text)) + .map_err(|error| { + syn::Error::new( + proc_macro2::Span::call_site(), + format!("vespera: failed to rename request-only input paths: {error}"), + ) + })?; Ok(()) } From 4680fdbe6589be2547ed0eb4cb2445b6244bb0af Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 15:05:24 +0900 Subject: [PATCH 3/7] fix(macro): response views require Option fields and drop skip_serializing fields serde always writes an Option field (null for None), so the response view requires it with a nullable type; only skip_serializing_if leaves a key out. A skip_serializing field is never written, so it is absent from the response view instead of an optional writeOnly property. Request views keep Option fields optional, so a type with Option fields read and returned gets a {Name}Input. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_request-view-naming.json | 2 +- README.md | 2 +- SKILL.md | 4 +- .../[...name]/concept.concept-2.mdx | 2 +- .../app/documentation/[...name]/migration.mdx | 2 + crates/vespera/tests/schema_round5.rs | 4 +- ...ccuracy__accuracy_request_view_inputs.snap | 4 - ...__parser_views_transparent_extractors.snap | 3 +- ...internally_tagged_closed_borrowed_ref.snap | 4 +- ...__internally_tagged_closed_closed_ref.snap | 3 +- ...ged_closed_closed_with_variant_rename.snap | 3 +- ...nally_tagged_closed_value_type_closed.snap | 3 +- .../src/parser/schema/request_view.rs | 17 +- .../src/parser/schema/request_view/tests.rs | 9 +- .../src/parser/schema/serde_attrs/extract.rs | 10 +- ...lly_tagged_snapshot@internally_tagged.snap | 1 + ...med_variants@tuple_named_named_object.snap | 1 + .../src/parser/schema/struct_schema.rs | 68 ++-- .../parser/schema/struct_schema/flatten.rs | 7 +- ...tten__tests__flatten_omittable_always.snap | 3 +- ...ny_unknown_fields_with_flatten_closed.snap | 4 +- ...__struct_field_access_and_deprecation.snap | 4 - ...delity__struct_views_alias_duplicates.snap | 1 + ...e_fidelity__struct_views_alias_fields.snap | 4 +- ...fidelity__struct_views_alias_optional.snap | 2 +- ...lity__struct_views_flatten_other_enum.snap | 6 +- ...rride__wire_override_field_value_type.snap | 2 +- ...ide__wire_override_field_with_unknown.snap | 3 +- .../src/parser/schema/struct_schema/tests.rs | 19 +- .../vespera_macro/src/schema_macro/codegen.rs | 29 +- e2e/devup-api/src/calls.ts | 2 +- examples/axum-example/openapi.json | 326 ++++++++++++++++-- .../axum-example/tests/integration_schema.rs | 13 +- ...cs__codecs_component_DocumentResponse.snap | 4 +- ...n_codecs__codecs_component_EventTimes.snap | 2 +- ...codecs__codecs_component_JsonPayloads.snap | 2 +- .../snapshots/integration_test__openapi.snap | 326 ++++++++++++++++-- 37 files changed, 730 insertions(+), 171 deletions(-) diff --git a/.changepacks/changepack_log_request-view-naming.json b/.changepacks/changepack_log_request-view-naming.json index 31154c475..a6476a7d5 100644 --- a/.changepacks/changepack_log_request-view-naming.json +++ b/.changepacks/changepack_log_request-view-naming.json @@ -1 +1 @@ -{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro request views: a type whose request view differs but that only request bodies reach (no response, directly or through another type) keeps its own component name — {Name} is its request view and no {Name}Input or orphan response view is emitted (0.8.0 renamed request-only DTOs to {Name}Input); types read and returned keep {Name} + {Name}Input (collision names {Name}Input2, ... unchanged). Fields read by a custom serde function (deserialize_with / with) are documented from their Rust type (or #[schema(value_type)]) in request views instead of an untyped {} — Option> is a nullable T — and a deserialize_with alone no longer creates a {Name}Input; with / serialize_with still document {} in responses.","date":"2026-11-17T00:00:00.000Z"} +{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro request views: a type whose request view differs but that only request bodies reach (no response, directly or through another type) keeps its own component name — {Name} is its request view and no {Name}Input or orphan response view is emitted (0.8.0 renamed request-only DTOs to {Name}Input); types read and returned keep {Name} + {Name}Input (collision names {Name}Input2, ... unchanged). Fields read by a custom serde function (deserialize_with / with) are documented from their Rust type (or #[schema(value_type)]) in request views instead of an untyped {} — Option> is a nullable T — and a deserialize_with alone no longer creates a {Name}Input; with / serialize_with still document {} in responses. Response views follow what serde writes: Option fields are required (nullable type; serde writes null) unless skip_serializing_if, and skip_serializing fields are absent instead of an optional writeOnly property; request views keep Option optional, so a type with Option fields used on both sides gets a {Name}Input.","date":"2026-11-17T00:00:00.000Z"} \ No newline at end of file diff --git a/README.md b/README.md index 4a23f782b..20bd56f92 100644 --- a/README.md +++ b/README.md @@ -932,7 +932,7 @@ Fields with database defaults automatically get `default` values in the generate | `default_value = "gen_random_uuid()"` | `"00000000-0000-0000-0000-000000000000"` | | `default_value = "true"` | `true` (literal passthrough) | -> **Note:** `required` is determined solely by nullability (`Option`). Fields with defaults are still `required` unless they are `Option`. +> **Note:** In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional, and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. ### SeaORM Integration diff --git a/SKILL.md b/SKILL.md index 72fe77e19..55eafa6b6 100644 --- a/SKILL.md +++ b/SKILL.md @@ -240,7 +240,7 @@ pub async fn reindex() {} | `bool` | `boolean` | | | `Vec` | `array` + items | | | `BTreeSet`, `HashSet` | `array` + items + `uniqueItems: true` | Set types | -| `Option` | T (nullable context) | Parent marks as optional | +| `Option` | T, nullable | Required in responses (serde writes `null`), optional in request bodies | | `HashMap` | `object` + additionalProperties | | | `Uuid` | `string` + `format: uuid` | | | `Decimal` | `string` + `format: decimal` | | @@ -644,7 +644,7 @@ vespera::schema_type!(Schema from Model, name = "MemoSchema"); **Database Defaults in OpenAPI:** Fields with `#[sea_orm(default_value = "...")]` or `#[sea_orm(primary_key)]` automatically get `default` values in the generated OpenAPI schema. SQL functions like `NOW()` and `gen_random_uuid()` are mapped to type-appropriate defaults. -**Required Logic:** `required` follows nullability (`Option`) and what serde writes: `skip_serializing` / `skip_serializing_if` fields are not required in the response view. +**Required Logic:** the response view requires every field serde writes (`Option` included — it is written as `null`, with a nullable type); `skip_serializing_if` fields are not required and `skip_serializing` fields are absent. Request views make `Option` and `#[serde(default)]` fields optional. **Request views (`{Name}Input`):** when serde reads a type differently than it writes it (`#[serde(default)]` on a field or the container, one-sided `skip_deserializing` / `skip_serializing`, `rename(deserialize = ..)` / `rename_all(deserialize = ..)` differing from the serialize side, a container `into` / `from` / `try_from` documented through a different type per direction, a `with` / `serialize_with` (response shape unknown, request typed), an `Option` read by a custom deserializer (required in requests), or a field type that itself has an input view), request bodies (`Json` / `Form` / `TypedMultipart`) reference an extra `{Name}Input` component: defaulted fields are optional, `skip_deserializing` fields are absent, keys use the deserialize name. `{Name}` stays the response view. Nothing extra is emitted when both views are identical or no request body uses the type; a type only request bodies reach (no response, directly or transitively) keeps its name — `{Name}` is then its request view, no `{Name}Input`. `#[schema(name = "X")]` gives `XInput`; if that name is taken, `XInput2`, `XInput3`, …. diff --git a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx index 3dced523e..eea6e0ab9 100644 --- a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx +++ b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx @@ -283,7 +283,7 @@ Fields with SeaORM database defaults get `default` values in the generated schem | `default_value = "gen_random_uuid()"` | `"00000000-0000-0000-0000-000000000000"` | | `default_value = "true"` | `true` | -> `required` is determined solely by nullability (`Option`). Fields with defaults are still `required` unless they are `Option`. +> In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional, and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. ## Configuring the OpenAPI Output diff --git a/apps/landing/src/app/documentation/[...name]/migration.mdx b/apps/landing/src/app/documentation/[...name]/migration.mdx index 7a3aaaa74..7f9e3cde0 100644 --- a/apps/landing/src/app/documentation/[...name]/migration.mdx +++ b/apps/landing/src/app/documentation/[...name]/migration.mdx @@ -36,6 +36,8 @@ These change the generated document without any code change: - **`TypedHeader`** header names come from `T` — the wire name for known `headers::*` types, otherwise `T` in kebab-case (`XRequestId` → `x-request-id`) — instead of the argument binding; `TypedHeader(_)` is no longer dropped. - **`#[serde(default)]` fields stay `required` in response schemas**; only the `{Name}Input` request view makes them optional. - **Request-only types keep their name (0.8.1).** A type whose request view differs but that no response returns (directly or through another type) is emitted once, as its request view, under `{Name}` — 0.8.0 emitted an unused `{Name}` plus `{Name}Input`. Clients generated from 0.8.0 that use `PortfolioUpdateRequestInput`-style names go back to `PortfolioUpdateRequest`. Types used on both sides keep `{Name}` + `{Name}Input`. +- **`Option` fields are `required` in responses (0.8.1)**: serde always writes them (`null` for `None`), so the response view requires them with a nullable type (`bio: string | null` instead of `bio?: string | null` in generated clients); a `skip_serializing_if` field stays optional. Request views keep `Option` optional, so a type with `Option` fields used in both requests and responses now gets a `{Name}Input`. +- **`skip_serializing` fields are absent from responses (0.8.1)** instead of an optional `writeOnly` property — serde never writes them; request views keep them. - **`deserialize_with` / `with` fields are typed in request views (0.8.1)**: documented from the Rust type (or `#[schema(value_type = T)]`) instead of an untyped `{}`; `Option>` is a nullable `T`. A `deserialize_with` alone no longer creates a `{Name}Input`; `with` / `serialize_with` still document `{}` in responses. - **Type mappings:** naive date-times / times (`NaiveDateTime`, `PrimitiveDateTime`, sea-orm `DateTime`, `NaiveTime`, `time::Time`) no longer carry the offset-requiring `date-time` / `time` format; unit structs are `{type: null}`; `Option<()>` is a single `null` type; `u8`–`u64` get `minimum: 0` (and `u8` / `u16` / `u32` a `maximum`); unknown types and unresolved generic parameters are `{}` (any) instead of `{type: object}`; user `Schema` types named like builtins (`Date`, `Decimal`, `Uuid`, …) keep their `$ref`. - **Enums:** concrete generic enums (`ApiResponse>`) are inlined with their type arguments; `serde_repr` enums are `{type: integer, enum: [...]}`; enum `{Name}Input` views follow the deserialize side; an internally tagged newtype variant over a closed or map payload merges the tag into the payload object. diff --git a/crates/vespera/tests/schema_round5.rs b/crates/vespera/tests/schema_round5.rs index b66eb9d97..fecaaf909 100644 --- a/crates/vespera/tests/schema_round5.rs +++ b/crates/vespera/tests/schema_round5.rs @@ -73,8 +73,10 @@ fn derived_schemas_compile_and_document_their_fields() { }; assert_eq!((tree.value, tree.children.len()), (6, 0)); + // `schema!` is the response view: serde never writes the + // `skip_serializing` `item` (the request view documents it). let schema = vespera::schema!(WithSkipped); let properties = schema.properties.expect("properties"); let keys: Vec<&str> = properties.keys().map(String::as_str).collect(); - assert_eq!(keys, ["id", "item"]); + assert_eq!(keys, ["id"]); } diff --git a/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_accuracy__accuracy_request_view_inputs.snap b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_accuracy__accuracy_request_view_inputs.snap index 8254ade08..e8579d8b8 100644 --- a/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_accuracy__accuracy_request_view_inputs.snap +++ b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_accuracy__accuracy_request_view_inputs.snap @@ -252,10 +252,6 @@ expression: pretty(&doc) "plain": { "type": "boolean" }, - "secret": { - "type": "string", - "writeOnly": true - }, "theme": { "type": "string", "default": "" diff --git a/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_parser_views__parser_views_transparent_extractors.snap b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_parser_views__parser_views_transparent_extractors.snap index be4aaac5e..a6540bac3 100644 --- a/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_parser_views__parser_views_transparent_extractors.snap +++ b/crates/vespera_macro/src/openapi_generator/snapshots/vespera_macro__openapi_generator__tests_parser_views__parser_views_transparent_extractors.snap @@ -145,7 +145,8 @@ expression: doc } }, "required": [ - "q" + "q", + "page" ] }, "Kind": { diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_borrowed_ref.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_borrowed_ref.snap index 7ab286588..1639bed69 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_borrowed_ref.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_borrowed_ref.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/enum_schema/representations/tests_closed.rs -assertion_line: 58 expression: "serde_json::to_string_pretty(&schema).unwrap()" --- { @@ -29,7 +28,8 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" }, "required": [ "type", - "id" + "id", + "note" ], "additionalProperties": false } diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_ref.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_ref.snap index b6bff0022..08db4d570 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_ref.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_ref.snap @@ -29,7 +29,8 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" }, "required": [ "type", - "id" + "id", + "note" ], "additionalProperties": false }, diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_with_variant_rename.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_with_variant_rename.snap index 6ce9ddc46..0b549e7d7 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_with_variant_rename.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_closed_with_variant_rename.snap @@ -28,7 +28,8 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" }, "required": [ "kind", - "id" + "id", + "note" ], "additionalProperties": false } diff --git a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_value_type_closed.snap b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_value_type_closed.snap index b9723ddaa..4d1d2e075 100644 --- a/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_value_type_closed.snap +++ b/crates/vespera_macro/src/parser/schema/enum_schema/representations/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests_closed__internally_tagged_closed_value_type_closed.snap @@ -28,7 +28,8 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" }, "required": [ "type", - "id" + "id", + "note" ], "additionalProperties": false } diff --git a/crates/vespera_macro/src/parser/schema/request_view.rs b/crates/vespera_macro/src/parser/schema/request_view.rs index 58d74558b..4f2d8685f 100644 --- a/crates/vespera_macro/src/parser/schema/request_view.rs +++ b/crates/vespera_macro/src/parser/schema/request_view.rs @@ -21,9 +21,11 @@ //! `#[schema(value_type)]`: the request view documents the Rust type), //! or is an `Option` read through a custom //! deserializer (serde then requires it), -//! - a field has `#[serde(alias)]` names (accepted keys), or a non-`Option` +//! - a field has `#[serde(alias)]` names (accepted keys), a non-`Option` //! `skip_serializing_if` field without `default` (optional on output, -//! required on input), +//! required on input), or an `Option` field without `skip_serializing_if` +//! (always written, as `null` when `None`, so required on output; optional +//! on input), //! - a tuple position is skipped / custom-converted on one side only, or a //! tuple of two or more fields has a `#[serde(default)]` position (or //! container `default`): trailing items may be omitted, or a @@ -554,9 +556,16 @@ fn field_differs(field: &syn::Field) -> bool { || extract_default(&field.attrs).is_some() || crate::multipart_impl::has_form_data_default(&field.attrs) || !extract_aliases(&field.attrs).is_empty() - // Omitted from output when the predicate holds, but read as a - // required key (serde has no default to fill it in). + // `required` differs: a `skip_serializing_if` field may be + // omitted from output but is a required key on input (serde has + // no default to fill it in), and an `Option` is always written + // (as `null`) but may be omitted on input. An `Option` with a + // predicate is optional on both sides; a flattened `Option` has + // no key of its own (see [`flatten_differs`]). || (skip.skip_serializing_if && !is_option_type(&field.ty)) + || (is_option_type(&field.ty) + && !skip.skip_serializing_if + && !extract_flatten(&field.attrs)) || sided_differs(|side| extract_field_rename_for(&field.attrs, side))) } diff --git a/crates/vespera_macro/src/parser/schema/request_view/tests.rs b/crates/vespera_macro/src/parser/schema/request_view/tests.rs index 801476862..c97ed8817 100644 --- a/crates/vespera_macro/src/parser/schema/request_view/tests.rs +++ b/crates/vespera_macro/src/parser/schema/request_view/tests.rs @@ -41,7 +41,14 @@ fn scoped_names( } #[rstest] -#[case::plain("struct A { x: i32, y: Option }", false)] +#[case::plain("struct A { x: i32, y: u8 }", false)] +// An `Option` is written as `null` (required on output) but may be omitted +// on input, unless a `skip_serializing_if` omits it on output too. +#[case::option("struct A { x: i32, y: Option }", true)] +#[case::option_skip_if( + r#"struct A { #[serde(skip_serializing_if = "Option::is_none")] y: Option }"#, + false +)] #[case::flatten_option("struct A { #[serde(flatten)] p: Option }", true)] #[case::flatten_map_then_struct( "struct A { #[serde(flatten)] m: HashMap, #[serde(flatten)] p: Page }", diff --git a/crates/vespera_macro/src/parser/schema/serde_attrs/extract.rs b/crates/vespera_macro/src/parser/schema/serde_attrs/extract.rs index b361fb2af..a84d3a55a 100644 --- a/crates/vespera_macro/src/parser/schema/serde_attrs/extract.rs +++ b/crates/vespera_macro/src/parser/schema/serde_attrs/extract.rs @@ -168,13 +168,6 @@ impl SerdeSkipFlags { pub const fn fully_skipped(self) -> bool { self.skip || (self.skip_serializing && self.skip_deserializing) } - - /// The member may be absent from serialized output (`skip_serializing` - /// or a `skip_serializing_if` predicate), so it must not be `required`. - #[must_use] - pub const fn maybe_omitted_on_output(self) -> bool { - self.skip_serializing || self.skip_serializing_if - } } /// Collect [`SerdeSkipFlags`] from `#[serde(...)]` attributes. @@ -791,14 +784,13 @@ mod tests { skip_serializing: true, ..SerdeSkipFlags::default() }; - assert!(only_ser.maybe_omitted_on_output()); assert!(!only_ser.fully_skipped()); let both = SerdeSkipFlags { skip_deserializing: true, ..only_ser }; assert!(both.fully_skipped()); - assert!(!SerdeSkipFlags::default().maybe_omitted_on_output()); + assert!(!SerdeSkipFlags::default().fully_skipped()); } #[test] diff --git a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__internally_tagged_snapshot@internally_tagged.snap b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__internally_tagged_snapshot@internally_tagged.snap index 3ff3c7f15..6c3cb382a 100644 --- a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__internally_tagged_snapshot@internally_tagged.snap +++ b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__internally_tagged_snapshot@internally_tagged.snap @@ -420,6 +420,7 @@ Schema { [ "type", "id", + "result", ], ), additional_properties: None, diff --git a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__tests__parse_enum_to_schema_tuple_and_named_variants@tuple_named_named_object.snap b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__tests__parse_enum_to_schema_tuple_and_named_variants@tuple_named_named_object.snap index cb7b573ab..8b75eec1a 100644 --- a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__tests__parse_enum_to_schema_tuple_and_named_variants@tuple_named_named_object.snap +++ b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__tests__parse_enum_to_schema_tuple_and_named_variants@tuple_named_named_object.snap @@ -192,6 +192,7 @@ Schema { required: Some( [ "id", + "note", ], ), additional_properties: None, diff --git a/crates/vespera_macro/src/parser/schema/struct_schema.rs b/crates/vespera_macro/src/parser/schema/struct_schema.rs index 6d3a487af..eff6beb60 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema.rs @@ -228,7 +228,7 @@ pub(super) fn tuple_fields_schema( .map(|field| { let schema_ref = positional_field_schema(field, side, known_schemas, struct_definitions); - annotate_field(schema_ref, field, false, false) + annotate_field(schema_ref, field, false) }) .collect(); // Slot `k` holds field `j >= k` when `j - k` omittable positions precede @@ -410,9 +410,10 @@ fn at_most_one(names: &[String]) -> SchemaRef { /// `#[serde(skip)]` (and `skip_serializing` + `skip_deserializing`), /// `#[serde(flatten)]`, `#[serde(rename)]` / `rename_all` / `alias`, doc /// comments, `#[schema(...)]` constraints (incl. `any`), and `required` -/// inference (`Option`, `skip_serializing`, and `skip_serializing_if` -/// fields are not required in the response view; `default` fields in the -/// request view). +/// inference (`skip_serializing_if` fields are not required in the response +/// view; `Option` and `default` fields in the request view). A field one +/// side never touches is absent from that view (`skip_serializing` from the +/// response view, `skip_deserializing` from the request view). pub(super) fn collect_named_fields( fields_named: &syn::FieldsNamed, rename_all: Option<&str>, @@ -436,14 +437,17 @@ pub(super) fn collect_named_fields( }; for field in &fields_named.named { let skip_flags = extract_serde_skip_flags(&field.attrs); - if skip_flags.fully_skipped() || (request && skip_flags.skip_deserializing) { + if skip_flags.fully_skipped() + || (request && skip_flags.skip_deserializing) + || (!request && skip_flags.skip_serializing) + { continue; } if extract_flatten(&field.attrs) { - // Response view: a `skip_serializing(_if)` member may be left - // out of the output entirely, so its keys are never required. - let omittable = !request && skip_flags.maybe_omitted_on_output(); + // Response view: a `skip_serializing_if` member may be left out + // of the output entirely, so its keys are never required. + let omittable = !request && skip_flags.skip_serializing_if; out.flattened.push(flatten_part( field, side, @@ -468,34 +472,32 @@ pub(super) fn collect_named_fields( field_schema_ref(field, &constraints, side, known_schemas, struct_definitions); // Doc comment → description; Rust `#[deprecated]` → `deprecated`; - // `skip_deserializing` (output only) → `readOnly`, `skip_serializing` - // (input only) → `writeOnly`. A `$ref` is wrapped in `allOf` so the - // annotations can sit beside it; explicit `#[schema(read_only, ..)]` - // constraints applied below still win. - // (Both are meaningless in a request-only view.) + // `skip_deserializing` (output only) → `readOnly` in the response + // view. A `$ref` is wrapped in `allOf` so the annotations can sit + // beside it; explicit `#[schema(read_only, ..)]` constraints applied + // below still win. let read_only = !request && skip_flags.skip_deserializing; - let write_only = !request && skip_flags.skip_serializing; - schema_ref = annotate_field(schema_ref, field, read_only, write_only); + schema_ref = annotate_field(schema_ref, field, read_only); apply_field_rules(&mut schema_ref, field, &constraints); - // Required is determined by nullability (Option) and, in the - // response view, by whether the field can be omitted from serialized - // output (`skip_serializing`, `skip_serializing_if`); in the request - // view by `#[serde(default)]` (field or container), since serde fills - // a missing defaulted field in (the Multipart derive's - // `#[form_data(default)]` likewise). + // Required in the response view unless a `skip_serializing_if` + // predicate may leave the key out: serde always writes the rest, an + // `Option` as `null` (its schema is nullable). In the request view a + // field is optional with `#[serde(default)]` (field or container), + // since serde fills a missing defaulted field in (the Multipart + // derive's `#[form_data(default)]` likewise), and an `Option`, which + // serde fills with `None` — unless a custom `deserialize_with` reads + // it, which makes it mandatory. let optional = if request { container_default || extract_default(&field.attrs).is_some() || crate::multipart_impl::has_form_data_default(&field.attrs) } else { - skip_flags.maybe_omitted_on_output() + skip_flags.skip_serializing_if }; - // serde fills an absent `Option` with `None` only when it reads the - // field itself: a custom `deserialize_with` makes it mandatory. - let absent_is_none = is_option_type(&field.ty) - && !(request && extract_field_codec(&field.attrs).deserialize); + let absent_is_none = + request && is_option_type(&field.ty) && !extract_field_codec(&field.attrs).deserialize; // `#[serde(alias = "..")]`: serde's Deserialize also accepts each // alias as the key (a second key for the same field is a "duplicate @@ -533,20 +535,15 @@ pub(super) fn collect_named_fields( } /// A field's doc comment → `description`, Rust `#[deprecated]` → -/// `deprecated`, plus `readOnly` / `writeOnly` when set. A `$ref` is wrapped -/// in `allOf` so the annotations can sit beside it. -fn annotate_field( - schema_ref: SchemaRef, - field: &syn::Field, - read_only: bool, - write_only: bool, -) -> SchemaRef { +/// `deprecated`, plus `readOnly` when set. A `$ref` is wrapped in `allOf` +/// so the annotations can sit beside it. +fn annotate_field(schema_ref: SchemaRef, field: &syn::Field, read_only: bool) -> SchemaRef { let doc = extract_doc_comment(&field.attrs); let deprecated = field .attrs .iter() .any(|attr| attr.path().is_ident("deprecated")); - if !(doc.is_some() || deprecated || read_only || write_only) { + if !(doc.is_some() || deprecated || read_only) { return schema_ref; } let mut schema = match schema_ref { @@ -561,7 +558,6 @@ fn annotate_field( } schema.deprecated = deprecated.then_some(true).or(schema.deprecated); schema.read_only = read_only.then_some(true).or(schema.read_only); - schema.write_only = write_only.then_some(true).or(schema.write_only); SchemaRef::Inline(schema) } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs index a500559b3..93e8aa310 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs @@ -744,9 +744,10 @@ mod tests { } /// A flattened member serde may leave out of the output - /// (`skip_serializing` / `skip_serializing_if`) requires none of its keys - /// in the response view (an opaque member becomes lenient); the request - /// view still requires them. + /// (`skip_serializing_if`) requires none of its keys in the response view + /// (an opaque member becomes lenient); one it never writes + /// (`skip_serializing`) adds no keys there at all. The request view still + /// requires them. #[rstest] #[case::skip_serializing_if("if", r#"skip_serializing_if = "Meta::is_empty""#, "Meta")] #[case::skip_serializing("always", "skip_serializing", "Meta")] diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__flatten__tests__flatten_omittable_always.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__flatten__tests__flatten_omittable_always.snap index 8b2f16c9a..81372de13 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__flatten__tests__flatten_omittable_always.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__flatten__tests__flatten_omittable_always.snap @@ -1,7 +1,6 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs -assertion_line: 589 expression: "format!(\"response: {}\\nrequest: {}\", serde_json::to_string(&schema).unwrap(),\nserde_json::to_string(&request).unwrap())" --- -response: {"type":"object","properties":{"by":{"type":"string"},"id":{"type":"integer","format":"uint32","minimum":0,"maximum":4294967295}},"required":["id"]} +response: {"type":"object","properties":{"id":{"type":"integer","format":"uint32","minimum":0,"maximum":4294967295}},"required":["id"]} request: {"allOf":[{"type":"object","properties":{"id":{"type":"integer","format":"uint32","minimum":0,"maximum":4294967295}},"required":["id"]},{"$ref":"#/components/schemas/Meta"}]} diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__serde_shape_deny_unknown_fields_with_flatten_closed.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__serde_shape_deny_unknown_fields_with_flatten_closed.snap index 7635b6288..6df6eade4 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__serde_shape_deny_unknown_fields_with_flatten_closed.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__serde_shape_deny_unknown_fields_with_flatten_closed.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests.rs -assertion_line: 894 expression: "serde_json::to_string_pretty(&schema).unwrap()" --- { @@ -28,7 +27,8 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" }, "required": [ "id", - "page" + "page", + "size" ], "additionalProperties": false } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__struct_field_access_and_deprecation.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__struct_field_access_and_deprecation.snap index b1db93b1a..cbc63345b 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__struct_field_access_and_deprecation.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests__struct_field_access_and_deprecation.snap @@ -10,10 +10,6 @@ expression: "serde_json::to_string_pretty(&schema).unwrap()" "format": "int32", "readOnly": true }, - "password": { - "type": "string", - "writeOnly": true - }, "plain": { "type": "boolean" }, diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_duplicates.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_duplicates.snap index 222dea89f..178d63b11 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_duplicates.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_duplicates.snap @@ -29,6 +29,7 @@ response: { }, "required": [ "userId", + "b", "d" ] } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_fields.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_fields.snap index 1bc42defd..c81e4bb88 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_fields.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_fields.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_serde_fidelity.rs -assertion_line: 323 expression: both_views(src) --- #[serde(deny_unknown_fields)] struct A { #[serde(alias = "nm", alias = "n")] name: String, #[serde(alias = "yrs", default)] age: u8, #[serde(alias = "ident")] id: u64, note: Option } @@ -31,7 +30,8 @@ response: { "required": [ "name", "age", - "id" + "id", + "note" ], "additionalProperties": false } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_optional.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_optional.snap index 3cf6e1866..526630194 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_optional.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_alias_optional.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_serde_fidelity.rs -assertion_line: 323 expression: both_views(src) --- struct A { #[serde(alias = "nm")] name: Option, #[serde(alias = "a", alias = "b", default)] x: u8 } @@ -21,6 +20,7 @@ response: { } }, "required": [ + "name", "x" ] } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_other_enum.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_other_enum.snap index 8535c04a6..b82847ac2 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_other_enum.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_serde_fidelity__struct_views_flatten_other_enum.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_serde_fidelity.rs -assertion_line: 329 expression: both_views(src) --- struct Req { a: Option, #[serde(flatten)] o: Open } @@ -15,7 +14,10 @@ response: { "null" ] } - } + }, + "required": [ + "a" + ] }, { "oneOf": [ diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_value_type.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_value_type.snap index befd31df1..ad497b55b 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_value_type.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_value_type.snap @@ -1,6 +1,5 @@ --- source: crates/vespera_macro/src/parser/schema/struct_schema/tests_wire_override.rs -assertion_line: 83 expression: "format!(\"{src}\\n\\n--- response ---\\n{}\\n--- request ---\\n{}\",\nrender(src, false), render(src, true))" --- struct Event { @@ -41,6 +40,7 @@ struct Event { }, "required": [ "at", + "until", "wires" ] } diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap index e41fdcf30..3bd0931c8 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap +++ b/crates/vespera_macro/src/parser/schema/struct_schema/snapshots/vespera_macro__parser__schema__struct_schema__tests_wire_override__wire_override_field_with_unknown.snap @@ -43,7 +43,8 @@ struct Event { "required": [ "raw", "out_only", - "in_only" + "in_only", + "maybe" ] } --- request --- diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/tests.rs b/crates/vespera_macro/src/parser/schema/struct_schema/tests.rs index 6ed30238e..5451c8494 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema/tests.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema/tests.rs @@ -28,13 +28,19 @@ fn test_parse_struct_to_schema_required_optional() { .unwrap() .contains(&"id".to_string()) ); + // serde always writes an `Option` (as `null`): required in the + // response view, with a nullable schema. assert!( - !schema + schema .required .as_ref() .unwrap() .contains(&"name".to_string()) ); + assert_eq!( + serde_json::to_value(&props["name"]).unwrap(), + serde_json::json!({"type": ["string", "null"]}) + ); } #[test] @@ -61,7 +67,7 @@ fn test_parse_struct_to_schema_rename_all_and_field_rename() { assert!(props.contains_key("displayName")); // rename_all applied let required = schema.required.as_ref().expect("required missing"); assert!(required.contains(&"id".to_string())); - assert!(!required.contains(&"displayName".to_string())); // Option makes it optional + assert!(required.contains(&"displayName".to_string())); // written as `null` } /// Tuple structs follow serde's wire shape: newtype → inner schema, @@ -106,12 +112,13 @@ fn test_parse_struct_to_schema_tuple_and_unit_structs( insta::assert_debug_snapshot!(format!("tuple_struct_{name}"), schema); } -/// `skip_serializing_if` / `skip_serializing` fields are not `required`; -/// `skip_deserializing` alone and `default` keep the field required; the -/// pair `skip_serializing` + `skip_deserializing` drops the field. +/// In the response view a `skip_serializing_if` field is not `required`; +/// `skip_deserializing` alone and `default` keep the field required; a +/// `skip_serializing` field (never written) is dropped, as is one skipped on +/// both sides. #[rstest] #[case::skip_serializing_if(r#"#[serde(skip_serializing_if = "Vec::is_empty")]"#, Some(false))] -#[case::skip_serializing("#[serde(skip_serializing)]", Some(false))] +#[case::skip_serializing("#[serde(skip_serializing)]", None)] #[case::skip_deserializing("#[serde(skip_deserializing)]", Some(true))] #[case::default("#[serde(default)]", Some(true))] #[case::both_skips("#[serde(skip_serializing, skip_deserializing)]", None)] diff --git a/crates/vespera_macro/src/schema_macro/codegen.rs b/crates/vespera_macro/src/schema_macro/codegen.rs index a70dac3fa..fc9744863 100644 --- a/crates/vespera_macro/src/schema_macro/codegen.rs +++ b/crates/vespera_macro/src/schema_macro/codegen.rs @@ -225,12 +225,13 @@ mod tests { ); } - /// A `skip_serializing_if` / `skip_serializing` field may be absent from - /// serialized output, so it is NOT required (shared struct-field walker). + /// A `skip_serializing_if` field may be absent from serialized output, + /// so it is NOT required; a `skip_serializing` one is never written, so + /// it is not a property at all (shared struct-field walker). #[rstest::rstest] - #[case::skip_serializing_if(r#"#[serde(skip_serializing_if = "String::is_empty")]"#)] - #[case::skip_serializing("#[serde(skip_serializing)]")] - fn output_omittable_field_is_not_required(#[case] attr: &str) { + #[case::skip_serializing_if(r#"#[serde(skip_serializing_if = "String::is_empty")]"#, true)] + #[case::skip_serializing("#[serde(skip_serializing)]", false)] + fn output_omittable_field_is_not_required(#[case] attr: &str, #[case] present: bool) { let item = parse(&format!( "pub struct WithSkip {{ {attr} pub field: String, pub id: i32 }}" )); @@ -238,7 +239,11 @@ mod tests { build_filtered_schema(&item, &HashSet::new(), &HashSet::new(), &empty_storage()); let required = schema.required.expect("required present"); assert_eq!(required, ["id"], "{attr}"); - assert!(schema.properties.expect("props").contains_key("field")); + assert_eq!( + schema.properties.expect("props").contains_key("field"), + present, + "{attr}" + ); } /// A field naming a renamed type by its Rust ident resolves to the @@ -261,15 +266,21 @@ mod tests { } #[test] - fn option_field_is_not_required() { + fn option_field_is_required_and_nullable() { let item = parse(r"pub struct WithOpt { pub field: Option }"); let schema = build_filtered_schema(&item, &HashSet::new(), &HashSet::new(), &empty_storage()); - let still_required = schema + // serde always writes it (as `null` when `None`). + let required = schema .required .as_ref() .is_some_and(|r| r.iter().any(|f| f == "field")); - assert!(!still_required, "an Option field must not be required"); + assert!(required, "an Option field is always written"); + let json = serde_json::to_value(&schema).unwrap(); + assert_eq!( + json["properties"]["field"]["type"], + serde_json::json!(["string", "null"]) + ); } #[test] diff --git a/e2e/devup-api/src/calls.ts b/e2e/devup-api/src/calls.ts index 44ff08556..9500c87db 100644 --- a/e2e/devup-api/src/calls.ts +++ b/e2e/devup-api/src/calls.ts @@ -116,7 +116,7 @@ export async function multipart(): Promise { /** `Validated>` — documented `422` envelope as the typed error. */ export async function validationError( - profile: DevupObject<'request'>['GardeProfile'], + profile: DevupObject<'request'>['GardeProfileInput'], ): Promise { const res = await api.post('createGardeProfile', { body: profile }) return res.error?.errors.map((e) => `${e.path}: ${e.message}`) ?? [] diff --git a/examples/axum-example/openapi.json b/examples/axum-example/openapi.json index e5cff2ffb..5cf3a00c1 100644 --- a/examples/axum-example/openapi.json +++ b/examples/axum-example/openapi.json @@ -99,7 +99,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/JsonPayloads" + "$ref": "#/components/schemas/JsonPayloadsInput" } } } @@ -461,7 +461,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InternallyTaggedMessage" + "$ref": "#/components/schemas/InternallyTaggedMessageInput" } } } @@ -2947,7 +2947,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateUserWithMeta" + "$ref": "#/components/schemas/CreateUserWithMetaInput" } } } @@ -3161,7 +3161,7 @@ "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GardeProfile" + "$ref": "#/components/schemas/GardeProfileInput" } } } @@ -3732,7 +3732,8 @@ "required": [ "id", "code", - "name" + "name", + "flagship" ] }, "BakerySchema_Flagship": { @@ -3762,7 +3763,9 @@ }, "required": [ "id", - "name" + "name", + "bakeryId", + "flagshipOfId" ] }, "CakeBakeryOnly": { @@ -3837,7 +3840,11 @@ }, "required": [ "id", - "name" + "name", + "bakeryId", + "flagshipOfId", + "bakery", + "flagshipOf" ] }, "CakeSchema_Bakery": { @@ -3929,6 +3936,8 @@ "required": [ "id", "name", + "bakeryId", + "flagshipOfId", "bakery", "flagshipOf" ] @@ -3964,7 +3973,9 @@ }, "required": [ "id", - "name" + "name", + "parentId", + "parent" ] }, "CategorySchema_Parent": { @@ -3987,7 +3998,8 @@ }, "required": [ "id", - "name" + "name", + "parentId" ] }, "ClockDto": { @@ -4246,12 +4258,14 @@ }, "required": [ "taxRate", + "discountRate", "minPrice", "maxPrice", "maxItems", "retryCount", "priority", - "separator" + "separator", + "delimiter" ] }, "ConfigSchema": { @@ -4361,9 +4375,13 @@ "required": [ "id", "userId", + "category", "title", "content", - "createdAt" + "adminReply", + "repliedAt", + "createdAt", + "updatedAt" ] }, "CreateFileUploadRequest": { @@ -4429,6 +4447,33 @@ ] }, "CreateUserWithMeta": { + "type": "object", + "description": "Full user model with all fields", + "properties": { + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "requestId": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "requestId", + "createdAt" + ] + }, + "CreateUserWithMetaInput": { "type": "object", "description": "Full user model with all fields", "properties": { @@ -4511,7 +4556,10 @@ "null" ] } - } + }, + "required": [ + "next" + ] }, "CycleASchema": { "type": "object", @@ -4544,7 +4592,9 @@ }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleASchema_Next": { @@ -4567,7 +4617,8 @@ }, "required": [ "id", - "label" + "label", + "nextId" ] }, "CycleBSchema": { @@ -4601,7 +4652,9 @@ }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleBSchema_Next": { @@ -4624,7 +4677,8 @@ }, "required": [ "id", - "label" + "label", + "nextId" ] }, "CycleCSchema": { @@ -4658,7 +4712,9 @@ }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleCSchema_Next": { @@ -4681,7 +4737,8 @@ }, "required": [ "id", - "label" + "label", + "nextId" ] }, "DocumentResponse": { @@ -4702,7 +4759,8 @@ }, "required": [ "id", - "body" + "body", + "meta" ] }, "Enum": { @@ -5007,6 +5065,7 @@ }, "required": [ "createdAt", + "expiresAt", "checksum" ] }, @@ -5148,12 +5207,99 @@ "required": [ "id", "name", + "thumbnailUrl", + "documentUrl", "tags", "isActive", "createdAt" ] }, "GardeProfile": { + "type": "object", + "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent, so the\nconstraints in `openapi.json` match the `422` this route answers.", + "properties": { + "age": { + "type": "integer", + "format": "uint8", + "description": "`range` → `minimum` / `maximum` (inclusive).", + "minimum": 18, + "maximum": 120 + }, + "avatar": { + "type": "string", + "description": "Avatar file name ending in `.png` (`suffix` → escaped `pattern`).", + "pattern": "\\.png$" + }, + "country": { + "type": "string", + "description": "ISO 3166-1 alpha-2 code (`pattern`).", + "pattern": "^[A-Z]{2}$" + }, + "display_name": { + "type": "string", + "description": "2–20 characters (`chars` mode → `minLength` / `maxLength`).", + "minLength": 2, + "maxLength": 20 + }, + "email": { + "type": "string", + "format": "email", + "description": "`email` → `format: email`." + }, + "hashtags": { + "type": "array", + "description": "1–3 hashtags, each a `#`-prefixed ASCII word of at most 16 chars\n(`inner(...)` → `items`).", + "items": { + "type": "string", + "maxLength": 16, + "pattern": "^#", + "allOf": [ + { + "pattern": "^[\\x00-\\x7F]*$" + } + ] + }, + "minItems": 1, + "maxItems": 3 + }, + "homepage": { + "type": [ + "string", + "null" + ], + "format": "uri", + "description": "Optional homepage — `url` → `format: uri` on the non-null value." + }, + "last_ip": { + "type": "string", + "description": "`ip` → `anyOf: [{format: ipv4}, {format: ipv6}]`.", + "anyOf": [ + { + "format": "ipv4" + }, + { + "format": "ipv6" + } + ] + }, + "nickname": { + "type": "string", + "description": "Unicode-aware `alphanumeric` has no portable regex — enforced at\nruntime, not documented." + } + }, + "required": [ + "display_name", + "email", + "homepage", + "age", + "hashtags", + "last_ip", + "country", + "avatar", + "nickname" + ] + }, + "GardeProfileInput": { "type": "object", "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent, so the\nconstraints in `openapi.json` match the `422` this route answers.", "properties": { @@ -5277,6 +5423,80 @@ ] }, "InternallyTaggedMessage": { + "description": "Internally tagged enum - serializes as `{\"type\": \"...\", ...fields...}`\nExample: `{\"type\": \"Request\", \"id\": 1, \"method\": \"GET\"}`", + "oneOf": [ + { + "type": "object", + "description": "A request message", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "method": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "Request" + ] + } + }, + "required": [ + "type", + "id", + "method" + ] + }, + { + "type": "object", + "description": "A response message", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "result": { + "type": [ + "string", + "null" + ] + }, + "type": { + "type": "string", + "enum": [ + "Response" + ] + } + }, + "required": [ + "type", + "id", + "result" + ] + }, + { + "type": "object", + "description": "A notification (no payload)", + "properties": { + "type": { + "type": "string", + "enum": [ + "Notification" + ] + } + }, + "required": [ + "type" + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "InternallyTaggedMessageInput": { "description": "Internally tagged enum - serializes as `{\"type\": \"...\", ...fields...}`\nExample: `{\"type\": \"Request\", \"id\": 1, \"method\": \"GET\"}`", "oneOf": [ { @@ -5369,6 +5589,26 @@ ] }, "JsonPayloads": { + "type": "object", + "description": "A free-form JSON payload in every spelling vespera maps to `{}`.", + "properties": { + "body": { + "description": "SeaORM's `Json` (= `serde_json::Value`): any JSON value." + }, + "extra": { + "description": "`serde_json::Value` itself." + }, + "meta": { + "description": "SeaORM's `JsonValue` alias." + } + }, + "required": [ + "body", + "meta", + "extra" + ] + }, + "JsonPayloadsInput": { "type": "object", "description": "A free-form JSON payload in every spelling vespera maps to `{}`.", "properties": { @@ -5429,8 +5669,10 @@ "required": [ "id", "modelId", + "dbId", "bakeryCode", "model", + "db", "byCode" ] }, @@ -5458,7 +5700,8 @@ }, "required": [ "name", - "age" + "age", + "optional_age" ] }, "MemoCardResponse": { @@ -6025,6 +6268,7 @@ "bind", "data_dir", "homepage", + "callback", "timeout" ] }, @@ -6201,7 +6445,10 @@ "null" ] } - } + }, + "required": [ + "cursor" + ] }, "PatchFileUploadRequest": { "type": "object", @@ -6368,7 +6615,8 @@ } }, "required": [ - "q" + "q", + "limit" ] }, "RejectionInput": { @@ -6451,7 +6699,8 @@ } }, "required": [ - "q" + "q", + "tags" ] }, { @@ -6606,6 +6855,10 @@ "email", "name", "phoneNumber23", + "nickname", + "birthday", + "gender", + "job", "createdAt" ] }, @@ -6653,7 +6906,8 @@ } }, "required": [ - "username" + "username", + "singleRel" ] }, "SingleSchema_SingleRel": { @@ -6745,7 +6999,11 @@ "email6", "num", "in_skip", - "in_skip3" + "in_skip2", + "in_skip3", + "in_skip4", + "in_skip5", + "in_skip6" ] }, "StrictInput": { @@ -6914,7 +7172,9 @@ "required": [ "id", "teamId", - "team" + "mentorTeamId", + "team", + "mentorTeam" ] }, "TeamSchema": { @@ -6986,7 +7246,8 @@ }, "required": [ "id", - "teamId" + "teamId", + "mentorTeamId" ] }, "TeamWithMembers_Mentees": { @@ -7010,7 +7271,8 @@ }, "required": [ "id", - "teamId" + "teamId", + "mentorTeamId" ] }, "Telemetry": { @@ -7112,7 +7374,8 @@ }, "required": [ "name", - "age" + "age", + "optional_age" ] }, "UnixSeconds": { @@ -7353,7 +7616,8 @@ "required": [ "id", "name", - "email" + "email", + "internal_score" ] }, "UserDTO": { @@ -7594,6 +7858,7 @@ "required": [ "id", "name", + "externalRef", "tags" ] }, @@ -7649,6 +7914,7 @@ "required": [ "id", "name", + "externalRef", "createdAt" ] }, diff --git a/examples/axum-example/tests/integration_schema.rs b/examples/axum-example/tests/integration_schema.rs index 476efdca8..791dac8f4 100644 --- a/examples/axum-example/tests/integration_schema.rs +++ b/examples/axum-example/tests/integration_schema.rs @@ -185,17 +185,16 @@ fn test_schema_macro_with_optional_fields() { }; assert_eq!(bio.default, Some(json!(""))); - // Required is nullability-only, matching the OpenAPI component schema: - // 'id'/'name' are non-Option, and 'bio' is non-Option too — its - // `#[serde(default)]` does NOT exclude it from `required`. Only 'email' - // (Option) is optional. (`schema!` now shares the OpenAPI generation - // path, so it no longer diverges by dropping defaulted fields.) + // `schema!` is the response view, matching the OpenAPI component + // schema: serde writes every field, so all are required — 'bio' despite + // its `#[serde(default)]` (which only matters when reading), and the + // Option 'email' too (written as `null`, its schema is nullable). let required = user_schema.required.unwrap(); assert!(required.contains(&"id".to_string())); assert!(required.contains(&"name".to_string())); assert!( - !required.contains(&"email".to_string()), - "'email' is Option, should not be required" + required.contains(&"email".to_string()), + "'email' is Option: always written (as null), so required" ); assert!( required.contains(&"bio".to_string()), diff --git a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_DocumentResponse.snap b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_DocumentResponse.snap index 42309b79f..f8b70c648 100644 --- a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_DocumentResponse.snap +++ b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_DocumentResponse.snap @@ -1,6 +1,5 @@ --- source: examples/axum-example/tests/integration_codecs.rs -assertion_line: 86 expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][component]).unwrap()" --- { @@ -20,7 +19,8 @@ expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][com }, "required": [ "id", - "body" + "body", + "meta" ], "type": "object" } diff --git a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimes.snap b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimes.snap index f8694be2d..d97aaf1f0 100644 --- a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimes.snap +++ b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_EventTimes.snap @@ -1,6 +1,5 @@ --- source: examples/axum-example/tests/integration_codecs.rs -assertion_line: 86 expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][component]).unwrap()" --- { @@ -25,6 +24,7 @@ expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][com }, "required": [ "createdAt", + "expiresAt", "checksum" ], "type": "object" diff --git a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_JsonPayloads.snap b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_JsonPayloads.snap index 36a388b56..e5fb98fcb 100644 --- a/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_JsonPayloads.snap +++ b/examples/axum-example/tests/snapshots/integration_codecs__codecs_component_JsonPayloads.snap @@ -1,6 +1,5 @@ --- source: examples/axum-example/tests/integration_codecs.rs -assertion_line: 86 expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][component]).unwrap()" --- { @@ -18,6 +17,7 @@ expression: "serde_json::to_string_pretty(&spec[\"components\"][\"schemas\"][com }, "required": [ "body", + "meta", "extra" ], "type": "object" diff --git a/examples/axum-example/tests/snapshots/integration_test__openapi.snap b/examples/axum-example/tests/snapshots/integration_test__openapi.snap index cd4e402fc..eb57b7a75 100644 --- a/examples/axum-example/tests/snapshots/integration_test__openapi.snap +++ b/examples/axum-example/tests/snapshots/integration_test__openapi.snap @@ -103,7 +103,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/JsonPayloads" + "$ref": "#/components/schemas/JsonPayloadsInput" } } } @@ -465,7 +465,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/InternallyTaggedMessage" + "$ref": "#/components/schemas/InternallyTaggedMessageInput" } } } @@ -2951,7 +2951,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/CreateUserWithMeta" + "$ref": "#/components/schemas/CreateUserWithMetaInput" } } } @@ -3165,7 +3165,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "content": { "application/json": { "schema": { - "$ref": "#/components/schemas/GardeProfile" + "$ref": "#/components/schemas/GardeProfileInput" } } } @@ -3736,7 +3736,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "code", - "name" + "name", + "flagship" ] }, "BakerySchema_Flagship": { @@ -3766,7 +3767,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "name" + "name", + "bakeryId", + "flagshipOfId" ] }, "CakeBakeryOnly": { @@ -3841,7 +3844,11 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "name" + "name", + "bakeryId", + "flagshipOfId", + "bakery", + "flagshipOf" ] }, "CakeSchema_Bakery": { @@ -3933,6 +3940,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "name", + "bakeryId", + "flagshipOfId", "bakery", "flagshipOf" ] @@ -3968,7 +3977,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "name" + "name", + "parentId", + "parent" ] }, "CategorySchema_Parent": { @@ -3991,7 +4002,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "name" + "name", + "parentId" ] }, "ClockDto": { @@ -4250,12 +4262,14 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "taxRate", + "discountRate", "minPrice", "maxPrice", "maxItems", "retryCount", "priority", - "separator" + "separator", + "delimiter" ] }, "ConfigSchema": { @@ -4365,9 +4379,13 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "userId", + "category", "title", "content", - "createdAt" + "adminReply", + "repliedAt", + "createdAt", + "updatedAt" ] }, "CreateFileUploadRequest": { @@ -4433,6 +4451,33 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "CreateUserWithMeta": { + "type": "object", + "description": "Full user model with all fields", + "properties": { + "createdAt": { + "type": [ + "string", + "null" + ] + }, + "email": { + "type": "string" + }, + "name": { + "type": "string" + }, + "requestId": { + "type": "string" + } + }, + "required": [ + "name", + "email", + "requestId", + "createdAt" + ] + }, + "CreateUserWithMetaInput": { "type": "object", "description": "Full user model with all fields", "properties": { @@ -4515,7 +4560,10 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "null" ] } - } + }, + "required": [ + "next" + ] }, "CycleASchema": { "type": "object", @@ -4548,7 +4596,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleASchema_Next": { @@ -4571,7 +4621,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId" ] }, "CycleBSchema": { @@ -4605,7 +4656,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleBSchema_Next": { @@ -4628,7 +4681,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId" ] }, "CycleCSchema": { @@ -4662,7 +4716,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId", + "next" ] }, "CycleCSchema_Next": { @@ -4685,7 +4741,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "label" + "label", + "nextId" ] }, "DocumentResponse": { @@ -4706,7 +4763,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "body" + "body", + "meta" ] }, "Enum": { @@ -5011,6 +5069,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "createdAt", + "expiresAt", "checksum" ] }, @@ -5152,12 +5211,99 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "name", + "thumbnailUrl", + "documentUrl", "tags", "isActive", "createdAt" ] }, "GardeProfile": { + "type": "object", + "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent, so the\nconstraints in `openapi.json` match the `422` this route answers.", + "properties": { + "age": { + "type": "integer", + "format": "uint8", + "description": "`range` → `minimum` / `maximum` (inclusive).", + "minimum": 18, + "maximum": 120 + }, + "avatar": { + "type": "string", + "description": "Avatar file name ending in `.png` (`suffix` → escaped `pattern`).", + "pattern": "\\.png$" + }, + "country": { + "type": "string", + "description": "ISO 3166-1 alpha-2 code (`pattern`).", + "pattern": "^[A-Z]{2}$" + }, + "display_name": { + "type": "string", + "description": "2–20 characters (`chars` mode → `minLength` / `maxLength`).", + "minLength": 2, + "maxLength": 20 + }, + "email": { + "type": "string", + "format": "email", + "description": "`email` → `format: email`." + }, + "hashtags": { + "type": "array", + "description": "1–3 hashtags, each a `#`-prefixed ASCII word of at most 16 chars\n(`inner(...)` → `items`).", + "items": { + "type": "string", + "maxLength": 16, + "pattern": "^#", + "allOf": [ + { + "pattern": "^[\\x00-\\x7F]*$" + } + ] + }, + "minItems": 1, + "maxItems": 3 + }, + "homepage": { + "type": [ + "string", + "null" + ], + "format": "uri", + "description": "Optional homepage — `url` → `format: uri` on the non-null value." + }, + "last_ip": { + "type": "string", + "description": "`ip` → `anyOf: [{format: ipv4}, {format: ipv6}]`.", + "anyOf": [ + { + "format": "ipv4" + }, + { + "format": "ipv6" + } + ] + }, + "nickname": { + "type": "string", + "description": "Unicode-aware `alphanumeric` has no portable regex — enforced at\nruntime, not documented." + } + }, + "required": [ + "display_name", + "email", + "homepage", + "age", + "hashtags", + "last_ip", + "country", + "avatar", + "nickname" + ] + }, + "GardeProfileInput": { "type": "object", "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent, so the\nconstraints in `openapi.json` match the `422` this route answers.", "properties": { @@ -5281,6 +5427,80 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "InternallyTaggedMessage": { + "description": "Internally tagged enum - serializes as `{\"type\": \"...\", ...fields...}`\nExample: `{\"type\": \"Request\", \"id\": 1, \"method\": \"GET\"}`", + "oneOf": [ + { + "type": "object", + "description": "A request message", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "method": { + "type": "string" + }, + "type": { + "type": "string", + "enum": [ + "Request" + ] + } + }, + "required": [ + "type", + "id", + "method" + ] + }, + { + "type": "object", + "description": "A response message", + "properties": { + "id": { + "type": "integer", + "format": "int32" + }, + "result": { + "type": [ + "string", + "null" + ] + }, + "type": { + "type": "string", + "enum": [ + "Response" + ] + } + }, + "required": [ + "type", + "id", + "result" + ] + }, + { + "type": "object", + "description": "A notification (no payload)", + "properties": { + "type": { + "type": "string", + "enum": [ + "Notification" + ] + } + }, + "required": [ + "type" + ] + } + ], + "discriminator": { + "propertyName": "type" + } + }, + "InternallyTaggedMessageInput": { "description": "Internally tagged enum - serializes as `{\"type\": \"...\", ...fields...}`\nExample: `{\"type\": \"Request\", \"id\": 1, \"method\": \"GET\"}`", "oneOf": [ { @@ -5373,6 +5593,26 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" ] }, "JsonPayloads": { + "type": "object", + "description": "A free-form JSON payload in every spelling vespera maps to `{}`.", + "properties": { + "body": { + "description": "SeaORM's `Json` (= `serde_json::Value`): any JSON value." + }, + "extra": { + "description": "`serde_json::Value` itself." + }, + "meta": { + "description": "SeaORM's `JsonValue` alias." + } + }, + "required": [ + "body", + "meta", + "extra" + ] + }, + "JsonPayloadsInput": { "type": "object", "description": "A free-form JSON payload in every spelling vespera maps to `{}`.", "properties": { @@ -5433,8 +5673,10 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "modelId", + "dbId", "bakeryCode", "model", + "db", "byCode" ] }, @@ -5462,7 +5704,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "name", - "age" + "age", + "optional_age" ] }, "MemoCardResponse": { @@ -6029,6 +6272,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "bind", "data_dir", "homepage", + "callback", "timeout" ] }, @@ -6205,7 +6449,10 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "null" ] } - } + }, + "required": [ + "cursor" + ] }, "PatchFileUploadRequest": { "type": "object", @@ -6372,7 +6619,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } }, "required": [ - "q" + "q", + "limit" ] }, "RejectionInput": { @@ -6455,7 +6703,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } }, "required": [ - "q" + "q", + "tags" ] }, { @@ -6610,6 +6859,10 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "email", "name", "phoneNumber23", + "nickname", + "birthday", + "gender", + "job", "createdAt" ] }, @@ -6657,7 +6910,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" } }, "required": [ - "username" + "username", + "singleRel" ] }, "SingleSchema_SingleRel": { @@ -6749,7 +7003,11 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "email6", "num", "in_skip", - "in_skip3" + "in_skip2", + "in_skip3", + "in_skip4", + "in_skip5", + "in_skip6" ] }, "StrictInput": { @@ -6918,7 +7176,9 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "teamId", - "team" + "mentorTeamId", + "team", + "mentorTeam" ] }, "TeamSchema": { @@ -6990,7 +7250,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "teamId" + "teamId", + "mentorTeamId" ] }, "TeamWithMembers_Mentees": { @@ -7014,7 +7275,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "id", - "teamId" + "teamId", + "mentorTeamId" ] }, "Telemetry": { @@ -7116,7 +7378,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" }, "required": [ "name", - "age" + "age", + "optional_age" ] }, "UnixSeconds": { @@ -7357,7 +7620,8 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "name", - "email" + "email", + "internal_score" ] }, "UserDTO": { @@ -7598,6 +7862,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "name", + "externalRef", "tags" ] }, @@ -7653,6 +7918,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "required": [ "id", "name", + "externalRef", "createdAt" ] }, From 25b742adf56e8bc505d6aee8a6c4d77b48e7dd2a Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 15:14:30 +0900 Subject: [PATCH 4/7] test(macro): keep the identical-input fixture identical under the new Option rule Co-Authored-By: Claude Opus 5.5 --- .../vespera_macro/src/openapi_generator/tests_accuracy.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs index 89be784e3..0e374e032 100644 --- a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs +++ b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs @@ -322,11 +322,11 @@ fn identical_or_unused_request_views_emit_nothing() { "Holder", "pub struct Holder { pub opt: Opt, pub same: Same }", )); - // `default` on an `Option` field: optional in both views, so the built - // `SameInput` equals `Same` and is dropped. + // `default` on an `Option` field serde omits when `None`: optional in + // both views, so the built `SameInput` equals `Same` and is dropped. metadata.structs.push(schema( "Same", - "pub struct Same { #[serde(default)] pub x: Option }", + r#"pub struct Same { #[serde(default, skip_serializing_if = "Option::is_none")] pub x: Option }"#, )); metadata.structs.push(schema( "Out", From 712fc9fbe4e3210e508a673b9addaccb81202f4f Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 15:55:52 +0900 Subject: [PATCH 5/7] test(example): response schema matches the body axum's Json sends A None is sent as null (required, nullable), a skip_serializing_if None is left out (not required), a skip_serializing field is never sent. Co-Authored-By: Claude Opus 5.5 --- .../axum-example/tests/integration_schema.rs | 48 +++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/examples/axum-example/tests/integration_schema.rs b/examples/axum-example/tests/integration_schema.rs index 791dac8f4..342fcd24b 100644 --- a/examples/axum-example/tests/integration_schema.rs +++ b/examples/axum-example/tests/integration_schema.rs @@ -414,3 +414,51 @@ fn decimal_serializes_as_string_at_runtime() { ); assert_eq!(value, serde_json::json!("10.50")); } + +/// A response type mixing every `Option` / skip combination. +#[derive(Serialize, Deserialize, Clone, Schema)] +#[serde(rename_all = "camelCase")] +pub struct WireProfile { + pub name: String, + pub nickname: Option, + #[serde(skip_serializing_if = "Option::is_none")] + pub email: Option, + #[serde(skip_serializing)] + pub secret: String, +} + +/// The response schema matches what axum's `Json` actually sends: a `None` +/// is sent as `"nickname": null` (so `nickname` is required and nullable), +/// a `skip_serializing_if` `None` is left out (not required), and a +/// `skip_serializing` field is never sent (not a property). +#[tokio::test] +async fn response_schema_matches_the_serialized_body() { + use vespera::axum::{Json, Router, routing::get}; + + let app = Router::new().route( + "/profile", + get(|| async { + Json(WireProfile { + name: "n".to_string(), + nickname: None, + email: None, + secret: "s".to_string(), + }) + }), + ); + let body: serde_json::Value = TestServer::new(app).get("/profile").await.json(); + assert_eq!(body, json!({"name": "n", "nickname": null})); + + let schema = serde_json::to_value(schema!(WireProfile)).unwrap(); + assert_eq!(schema["required"], json!(["name", "nickname"])); + assert_eq!( + schema["properties"]["nickname"]["type"], + json!(["string", "null"]) + ); + assert!(schema["properties"].get("email").is_some()); + assert!(schema["properties"].get("secret").is_none()); + // Every required key is really in the body. + for key in schema["required"].as_array().unwrap() { + assert!(body.get(key.as_str().unwrap()).is_some(), "{key} missing"); + } +} From 4bf0053152b4905bf32badf1ea07581f91069a8f Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 16:14:29 +0900 Subject: [PATCH 6/7] fix(macro): an Option skipped by Option::is_none is not nullable in responses serde never writes null for a field with skip_serializing_if = "Option::is_none" (serde_with's #[skip_serializing_none] adds exactly that), so the response view documents the Some value: optional and not nullable. Option> keeps the inner null (Some(None) is written as null); other predicates keep the nullable type. Request views still accept null. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_request-view-naming.json | 2 +- README.md | 2 +- SKILL.md | 2 +- .../[...name]/concept.concept-2.mdx | 2 +- .../app/documentation/[...name]/migration.mdx | 2 +- .../src/parser/schema/request_view.rs | 13 ++- .../src/parser/schema/request_view/tests.rs | 5 +- .../src/parser/schema/serde_attrs.rs | 2 +- .../src/parser/schema/serde_attrs/codec.rs | 32 +++++++ ...ts__enum_variant_attrs_internal_other.snap | 4 +- ...um_variant_attrs_untagged_field_attrs.snap | 4 +- .../src/parser/schema/struct_schema.rs | 47 +++++++++- .../struct_schema/tests_option_output.rs | 93 +++++++++++++++++++ examples/axum-example/openapi.json | 5 +- .../axum-example/tests/integration_schema.rs | 34 ++++--- .../snapshots/integration_test__openapi.snap | 5 +- 16 files changed, 208 insertions(+), 46 deletions(-) create mode 100644 crates/vespera_macro/src/parser/schema/struct_schema/tests_option_output.rs diff --git a/.changepacks/changepack_log_request-view-naming.json b/.changepacks/changepack_log_request-view-naming.json index a6476a7d5..640246ee5 100644 --- a/.changepacks/changepack_log_request-view-naming.json +++ b/.changepacks/changepack_log_request-view-naming.json @@ -1 +1 @@ -{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro request views: a type whose request view differs but that only request bodies reach (no response, directly or through another type) keeps its own component name — {Name} is its request view and no {Name}Input or orphan response view is emitted (0.8.0 renamed request-only DTOs to {Name}Input); types read and returned keep {Name} + {Name}Input (collision names {Name}Input2, ... unchanged). Fields read by a custom serde function (deserialize_with / with) are documented from their Rust type (or #[schema(value_type)]) in request views instead of an untyped {} — Option> is a nullable T — and a deserialize_with alone no longer creates a {Name}Input; with / serialize_with still document {} in responses. Response views follow what serde writes: Option fields are required (nullable type; serde writes null) unless skip_serializing_if, and skip_serializing fields are absent instead of an optional writeOnly property; request views keep Option optional, so a type with Option fields used on both sides gets a {Name}Input.","date":"2026-11-17T00:00:00.000Z"} \ No newline at end of file +{"changes":{"crates/vespera/Cargo.toml":"Patch","crates/vespera_core/Cargo.toml":"Patch","crates/vespera_macro/Cargo.toml":"Patch","crates/vespera_inprocess/Cargo.toml":"Patch","crates/vespera_jni/Cargo.toml":"Patch","libs/vespera-bridge/build.gradle.kts":"Patch","libs/vespera-bridge-gradle-plugin/build.gradle.kts":"Patch"},"note":"vespera_macro request views: a type whose request view differs but that only request bodies reach (no response, directly or through another type) keeps its own component name — {Name} is its request view and no {Name}Input or orphan response view is emitted (0.8.0 renamed request-only DTOs to {Name}Input); types read and returned keep {Name} + {Name}Input (collision names {Name}Input2, ... unchanged). Fields read by a custom serde function (deserialize_with / with) are documented from their Rust type (or #[schema(value_type)]) in request views instead of an untyped {} — Option> is a nullable T — and a deserialize_with alone no longer creates a {Name}Input; with / serialize_with still document {} in responses. Response views follow what serde writes: Option fields are required (nullable type; serde writes null) unless skip_serializing_if, and an Option skipped by skip_serializing_if = \"Option::is_none\" (serde_with #[skip_serializing_none]) is optional and not nullable since null is never written, and skip_serializing fields are absent instead of an optional writeOnly property; request views keep Option optional, so a type with Option fields used on both sides gets a {Name}Input.","date":"2026-11-17T00:00:00.000Z"} \ No newline at end of file diff --git a/README.md b/README.md index 20bd56f92..9bf4f778d 100644 --- a/README.md +++ b/README.md @@ -932,7 +932,7 @@ Fields with database defaults automatically get `default` values in the generate | `default_value = "gen_random_uuid()"` | `"00000000-0000-0000-0000-000000000000"` | | `default_value = "true"` | `true` (literal passthrough) | -> **Note:** In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional, and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. +> **Note:** In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional — with `Option::is_none` (or serde_with's `#[skip_serializing_none]`) also not nullable, since `null` is never written — and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. ### SeaORM Integration diff --git a/SKILL.md b/SKILL.md index 55eafa6b6..3e6b457e7 100644 --- a/SKILL.md +++ b/SKILL.md @@ -644,7 +644,7 @@ vespera::schema_type!(Schema from Model, name = "MemoSchema"); **Database Defaults in OpenAPI:** Fields with `#[sea_orm(default_value = "...")]` or `#[sea_orm(primary_key)]` automatically get `default` values in the generated OpenAPI schema. SQL functions like `NOW()` and `gen_random_uuid()` are mapped to type-appropriate defaults. -**Required Logic:** the response view requires every field serde writes (`Option` included — it is written as `null`, with a nullable type); `skip_serializing_if` fields are not required and `skip_serializing` fields are absent. Request views make `Option` and `#[serde(default)]` fields optional. +**Required Logic:** the response view requires every field serde writes (`Option` included — it is written as `null`, with a nullable type); `skip_serializing_if` fields are not required (with `Option::is_none` / `#[skip_serializing_none]` the type is also not nullable — `null` is never written) and `skip_serializing` fields are absent. Request views make `Option` and `#[serde(default)]` fields optional. **Request views (`{Name}Input`):** when serde reads a type differently than it writes it (`#[serde(default)]` on a field or the container, one-sided `skip_deserializing` / `skip_serializing`, `rename(deserialize = ..)` / `rename_all(deserialize = ..)` differing from the serialize side, a container `into` / `from` / `try_from` documented through a different type per direction, a `with` / `serialize_with` (response shape unknown, request typed), an `Option` read by a custom deserializer (required in requests), or a field type that itself has an input view), request bodies (`Json` / `Form` / `TypedMultipart`) reference an extra `{Name}Input` component: defaulted fields are optional, `skip_deserializing` fields are absent, keys use the deserialize name. `{Name}` stays the response view. Nothing extra is emitted when both views are identical or no request body uses the type; a type only request bodies reach (no response, directly or transitively) keeps its name — `{Name}` is then its request view, no `{Name}Input`. `#[schema(name = "X")]` gives `XInput`; if that name is taken, `XInput2`, `XInput3`, …. diff --git a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx index eea6e0ab9..faca67d6b 100644 --- a/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx +++ b/apps/landing/src/app/documentation/[...name]/concept.concept-2.mdx @@ -283,7 +283,7 @@ Fields with SeaORM database defaults get `default` values in the generated schem | `default_value = "gen_random_uuid()"` | `"00000000-0000-0000-0000-000000000000"` | | `default_value = "true"` | `true` | -> In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional, and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. +> In responses every field serde writes is `required` — defaulted fields, and `Option` too (written as `null`, its type is nullable); only `skip_serializing_if` fields are optional — with `Option::is_none` (or serde_with's `#[skip_serializing_none]`) also not nullable, since `null` is never written — and `skip_serializing` fields are absent. In request bodies (`{Name}Input`, or `{Name}` for a request-only type) `#[serde(default)]` and `Option` fields are optional. ## Configuring the OpenAPI Output diff --git a/apps/landing/src/app/documentation/[...name]/migration.mdx b/apps/landing/src/app/documentation/[...name]/migration.mdx index 7f9e3cde0..44f2b4924 100644 --- a/apps/landing/src/app/documentation/[...name]/migration.mdx +++ b/apps/landing/src/app/documentation/[...name]/migration.mdx @@ -36,7 +36,7 @@ These change the generated document without any code change: - **`TypedHeader`** header names come from `T` — the wire name for known `headers::*` types, otherwise `T` in kebab-case (`XRequestId` → `x-request-id`) — instead of the argument binding; `TypedHeader(_)` is no longer dropped. - **`#[serde(default)]` fields stay `required` in response schemas**; only the `{Name}Input` request view makes them optional. - **Request-only types keep their name (0.8.1).** A type whose request view differs but that no response returns (directly or through another type) is emitted once, as its request view, under `{Name}` — 0.8.0 emitted an unused `{Name}` plus `{Name}Input`. Clients generated from 0.8.0 that use `PortfolioUpdateRequestInput`-style names go back to `PortfolioUpdateRequest`. Types used on both sides keep `{Name}` + `{Name}Input`. -- **`Option` fields are `required` in responses (0.8.1)**: serde always writes them (`null` for `None`), so the response view requires them with a nullable type (`bio: string | null` instead of `bio?: string | null` in generated clients); a `skip_serializing_if` field stays optional. Request views keep `Option` optional, so a type with `Option` fields used in both requests and responses now gets a `{Name}Input`. +- **`Option` fields are `required` in responses (0.8.1)**: serde always writes them (`null` for `None`), so the response view requires them with a nullable type (`bio: string | null` instead of `bio?: string | null` in generated clients); a `skip_serializing_if` field stays optional, and with `skip_serializing_if = "Option::is_none"` (serde_with's `#[skip_serializing_none]` too) its type is no longer nullable (`email?: string`) — serde never writes `null` for it. Request views keep `Option` optional, so a type with `Option` fields used in both requests and responses now gets a `{Name}Input`. - **`skip_serializing` fields are absent from responses (0.8.1)** instead of an optional `writeOnly` property — serde never writes them; request views keep them. - **`deserialize_with` / `with` fields are typed in request views (0.8.1)**: documented from the Rust type (or `#[schema(value_type = T)]`) instead of an untyped `{}`; `Option>` is a nullable `T`. A `deserialize_with` alone no longer creates a `{Name}Input`; `with` / `serialize_with` still document `{}` in responses. - **Type mappings:** naive date-times / times (`NaiveDateTime`, `PrimitiveDateTime`, sea-orm `DateTime`, `NaiveTime`, `time::Time`) no longer carry the offset-requiring `date-time` / `time` format; unit structs are `{type: null}`; `Option<()>` is a single `null` type; `u8`–`u64` get `minimum: 0` (and `u8` / `u16` / `u32` a `maximum`); unknown types and unresolved generic parameters are `{}` (any) instead of `{type: object}`; user `Schema` types named like builtins (`Date`, `Decimal`, `Uuid`, …) keep their `$ref`. diff --git a/crates/vespera_macro/src/parser/schema/request_view.rs b/crates/vespera_macro/src/parser/schema/request_view.rs index 4f2d8685f..8b05b219b 100644 --- a/crates/vespera_macro/src/parser/schema/request_view.rs +++ b/crates/vespera_macro/src/parser/schema/request_view.rs @@ -25,7 +25,8 @@ //! `skip_serializing_if` field without `default` (optional on output, //! required on input), or an `Option` field without `skip_serializing_if` //! (always written, as `null` when `None`, so required on output; optional -//! on input), +//! on input) or with `skip_serializing_if = "Option::is_none"` (never +//! `null` on output; nullable on input), //! - a tuple position is skipped / custom-converted on one side only, or a //! tuple of two or more fields has a `#[serde(default)]` position (or //! container `default`): trailing items may be omitted, or a @@ -78,7 +79,7 @@ use super::{ SerdeEnumRepr, SerdeSide, extract_aliases, extract_default, extract_deny_unknown_fields, extract_enum_repr, extract_field_codec, extract_field_rename_for, extract_flatten, extract_rename_all_fields_for, extract_rename_all_for, extract_serde_skip_flags, - extract_tag, extract_transparent, extract_untagged, + extract_tag, extract_transparent, extract_untagged, skips_none_on_output, }, struct_schema::{flattened_member, peel}, wire_override::{codec_hides_shape, container_override_type}, @@ -560,11 +561,13 @@ fn field_differs(field: &syn::Field) -> bool { // omitted from output but is a required key on input (serde has // no default to fill it in), and an `Option` is always written // (as `null`) but may be omitted on input. An `Option` with a - // predicate is optional on both sides; a flattened `Option` has - // no key of its own (see [`flatten_differs`]). + // predicate is optional on both sides — and with + // `Option::is_none` never `null` on output, while input accepts + // `null`. A flattened `Option` has no key of its own (see + // [`flatten_differs`]). || (skip.skip_serializing_if && !is_option_type(&field.ty)) || (is_option_type(&field.ty) - && !skip.skip_serializing_if + && (!skip.skip_serializing_if || skips_none_on_output(&field.attrs)) && !extract_flatten(&field.attrs)) || sided_differs(|side| extract_field_rename_for(&field.attrs, side))) } diff --git a/crates/vespera_macro/src/parser/schema/request_view/tests.rs b/crates/vespera_macro/src/parser/schema/request_view/tests.rs index c97ed8817..6b11bea53 100644 --- a/crates/vespera_macro/src/parser/schema/request_view/tests.rs +++ b/crates/vespera_macro/src/parser/schema/request_view/tests.rs @@ -46,7 +46,7 @@ fn scoped_names( // on input, unless a `skip_serializing_if` omits it on output too. #[case::option("struct A { x: i32, y: Option }", true)] #[case::option_skip_if( - r#"struct A { #[serde(skip_serializing_if = "Option::is_none")] y: Option }"#, + r#"struct A { #[serde(skip_serializing_if = "is_zero")] y: Option }"#, false )] #[case::flatten_option("struct A { #[serde(flatten)] p: Option }", true)] @@ -157,9 +157,10 @@ fn scoped_names( r#"struct A { #[serde(skip_serializing_if = "Vec::is_empty")] v: Vec }"#, true )] +// `Option::is_none` never writes `null`; the request view accepts it. #[case::skip_serializing_if_option( r#"struct A { #[serde(skip_serializing_if = "Option::is_none")] v: Option }"#, - false + true )] #[case::alias(r#"struct A { #[serde(alias = "b")] a: u8 }"#, true)] #[case::hash_set("struct A { tags: std::collections::HashSet }", true)] diff --git a/crates/vespera_macro/src/parser/schema/serde_attrs.rs b/crates/vespera_macro/src/parser/schema/serde_attrs.rs index 84c9e32f2..4d55f301f 100644 --- a/crates/vespera_macro/src/parser/schema/serde_attrs.rs +++ b/crates/vespera_macro/src/parser/schema/serde_attrs.rs @@ -7,7 +7,7 @@ mod extract; mod fallback; mod rename_case; -pub use codec::{extract_container_conversion, extract_field_codec}; +pub use codec::{extract_container_conversion, extract_field_codec, skips_none_on_output}; pub use common::{ EntityTarget, capitalize_first, entity_target, extract_doc_comment, extract_schema_default, extract_schema_ref_override, extract_transparent, strip_raw_prefix_owned, diff --git a/crates/vespera_macro/src/parser/schema/serde_attrs/codec.rs b/crates/vespera_macro/src/parser/schema/serde_attrs/codec.rs index 78ce1975e..0f3ba53e1 100644 --- a/crates/vespera_macro/src/parser/schema/serde_attrs/codec.rs +++ b/crates/vespera_macro/src/parser/schema/serde_attrs/codec.rs @@ -41,6 +41,24 @@ pub fn extract_field_codec(attrs: &[syn::Attribute]) -> FieldCodec { codec } +/// `#[serde(skip_serializing_if = "Option::is_none")]` (any path to it, as +/// serde_with's `#[skip_serializing_none]` writes it): serde never writes a +/// `None`, so the output never holds `null` for this field. +pub fn skips_none_on_output(attrs: &[syn::Attribute]) -> bool { + let mut found = false; + walk_serde_keys(attrs, |meta| { + if !meta.path.is_ident("skip_serializing_if") { + return Ok(false); + } + let path = meta.value()?.parse::()?.parse::()?; + let mut segments = path.segments.iter().rev(); + found |= segments.next().is_some_and(|last| last.ident == "is_none") + && segments.next().is_some_and(|ty| ty.ident == "Option"); + Ok(true) + }); + found +} + /// The type a container is converted through on `side`: /// `#[serde(into = "T")]` when serializing, `#[serde(from = "T")]` / /// `#[serde(try_from = "T")]` when deserializing. @@ -77,6 +95,20 @@ mod tests { .attrs } + #[rstest] + #[case::option_is_none(r#"#[serde(skip_serializing_if = "Option::is_none")]"#, true)] + #[case::std_path( + r#"#[serde(skip_serializing_if = "std::option::Option::is_none")]"#, + true + )] + #[case::other_predicate(r#"#[serde(skip_serializing_if = "Vec::is_empty")]"#, false)] + #[case::bare_is_none(r#"#[serde(skip_serializing_if = "is_none")]"#, false)] + #[case::other_type(r#"#[serde(skip_serializing_if = "Maybe::is_none")]"#, false)] + #[case::absent("#[serde(default)]", false)] + fn skips_none(#[case] src: &str, #[case] expected: bool) { + assert_eq!(skips_none_on_output(&attrs(src)), expected, "{src}"); + } + #[rstest] #[case::none("#[serde(rename = \"x\")]", false, false)] #[case::with("#[serde(with = \"m\")]", true, true)] diff --git a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_internal_other.snap b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_internal_other.snap index e050135fb..88cdf2f19 100644 --- a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_internal_other.snap +++ b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_internal_other.snap @@ -199,9 +199,7 @@ Schema { one_of: None, not: None, discriminator: None, - nullable: Some( - true, - ), + nullable: None, read_only: None, write_only: None, deprecated: None, diff --git a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_untagged_field_attrs.snap b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_untagged_field_attrs.snap index 661250331..661e4417b 100644 --- a/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_untagged_field_attrs.snap +++ b/crates/vespera_macro/src/parser/schema/snapshots/vespera_macro__parser__schema__enum_schema__representations__tests__enum_variant_attrs_untagged_field_attrs.snap @@ -149,9 +149,7 @@ Schema { one_of: None, not: None, discriminator: None, - nullable: Some( - true, - ), + nullable: None, read_only: None, write_only: None, deprecated: None, diff --git a/crates/vespera_macro/src/parser/schema/struct_schema.rs b/crates/vespera_macro/src/parser/schema/struct_schema.rs index eff6beb60..2f7c753c7 100644 --- a/crates/vespera_macro/src/parser/schema/struct_schema.rs +++ b/crates/vespera_macro/src/parser/schema/struct_schema.rs @@ -14,18 +14,18 @@ use vespera_core::schema::{Schema, SchemaRef, SchemaType}; use super::{ garde_rules::{apply_garde_rules, extract_garde_rules}, - schema_attrs::{SchemaConstraints, extract_schema_constraints}, + schema_attrs::{SchemaConstraints, SchemaValueType, extract_schema_constraints}, serde_attrs::{ SerdeSide, extract_aliases, extract_default, extract_deny_unknown_fields, extract_doc_comment, extract_field_codec, extract_field_rename_for, extract_flatten, extract_rename_all, extract_rename_all_for, extract_schema_ref_override, extract_serde_skip_flags, extract_tag, extract_transparent, rename_field, - strip_raw_prefix_owned, + skips_none_on_output, strip_raw_prefix_owned, }, type_schema::parse_type_to_schema_ref, wire_override::{current_container_override, field_schema_ref}, }; -use crate::schema_macro::type_utils::is_option_type; +use crate::schema_macro::type_utils::{is_option_type, option_inner}; mod flatten; @@ -468,8 +468,18 @@ pub(super) fn collect_named_fields( // `#[schema(any)]` / `#[schema(value_type = T)]` / serde `with` // replace the Rust type's schema (see `wire_override`). let constraints = extract_schema_constraints(&field.attrs); + // Response view of an `Option` serde skips when `None`: only a + // `Some` is ever written, so its value is documented (no `null`). + let some_only = (!request && skips_none_on_output(&field.attrs)) + .then(|| some_value(field, &constraints)) + .flatten(); + let (field, constraints) = some_only + .as_ref() + .map_or((field, &constraints), |(field, constraints)| { + (field, constraints) + }); let mut schema_ref = - field_schema_ref(field, &constraints, side, known_schemas, struct_definitions); + field_schema_ref(field, constraints, side, known_schemas, struct_definitions); // Doc comment → description; Rust `#[deprecated]` → `deprecated`; // `skip_deserializing` (output only) → `readOnly` in the response @@ -479,7 +489,7 @@ pub(super) fn collect_named_fields( let read_only = !request && skip_flags.skip_deserializing; schema_ref = annotate_field(schema_ref, field, read_only); - apply_field_rules(&mut schema_ref, field, &constraints); + apply_field_rules(&mut schema_ref, field, constraints); // Required in the response view unless a `skip_serializing_if` // predicate may leave the key out: serde always writes the rest, an @@ -534,6 +544,30 @@ pub(super) fn collect_named_fields( out } +/// `field` documented as the `T` of its `Option` (or of a +/// `#[schema(value_type = Option)]`), or `None` when it is no `Option`. +fn some_value( + field: &syn::Field, + constraints: &SchemaConstraints, +) -> Option<(syn::Field, SchemaConstraints)> { + match &constraints.value_type { + Some(value_type) => Some(( + field.clone(), + SchemaConstraints { + value_type: Some(SchemaValueType(option_inner(&value_type.0)?.clone())), + ..constraints.clone() + }, + )), + None => Some(( + syn::Field { + ty: option_inner(&field.ty)?.clone(), + ..field.clone() + }, + constraints.clone(), + )), + } +} + /// A field's doc comment → `description`, Rust `#[deprecated]` → /// `deprecated`, plus `readOnly` when set. A `$ref` is wrapped in `allOf` /// so the annotations can sit beside it. @@ -702,3 +736,6 @@ mod tests_serde_fidelity; #[cfg(test)] mod tests_transparent; + +#[cfg(test)] +mod tests_option_output; diff --git a/crates/vespera_macro/src/parser/schema/struct_schema/tests_option_output.rs b/crates/vespera_macro/src/parser/schema/struct_schema/tests_option_output.rs new file mode 100644 index 000000000..e15d5ec77 --- /dev/null +++ b/crates/vespera_macro/src/parser/schema/struct_schema/tests_option_output.rs @@ -0,0 +1,93 @@ +//! How an `Option` field is written: serde writes `None` as `null` (the +//! response view requires the key, with a nullable schema) unless +//! `skip_serializing_if = "Option::is_none"` leaves it out — then the output +//! never holds `null`, and the response view documents the `Some` value as +//! an optional property. The request view accepts `null` either way. + +use rstest::rstest; +use serde_json::{Value, json}; + +use super::*; +use crate::parser::schema::request_view::with_request_view; + +/// `(property x, required)` of `struct S { }` in one view. +fn view(field: &str, request: bool) -> (Value, Value) { + let known = HashSet::from(["User".to_string()]); + let defs = HashMap::from([("User".to_string(), "struct User { id: u8 }".to_string())]); + let item: syn::ItemStruct = syn::parse_str(&format!("struct S {{ {field} }}")).unwrap(); + let build = || parse_struct_to_schema(&item, &known, &defs); + let schema = serde_json::to_value(if request { + with_request_view(build) + } else { + build() + }) + .unwrap(); + ( + schema["properties"]["x"].clone(), + schema["required"].clone(), + ) +} + +const SKIP_NONE: &str = r#"#[serde(skip_serializing_if = "Option::is_none")]"#; + +#[rstest] +#[case::plain("x: Option", json!({"type": ["string", "null"]}), json!(["x"]))] +#[case::skip_none( + &format!("{SKIP_NONE} x: Option"), + json!({"type": "string"}), + Value::Null +)] +#[case::skip_none_std_path( + r#"#[serde(skip_serializing_if = "std::option::Option::is_none")] x: Option"#, + json!({"type": "integer", "format": "uint8", "minimum": 0, "maximum": 255}), + Value::Null +)] +// `Some(None)` is still written as `null`. +#[case::skip_none_double_option( + &format!("{SKIP_NONE} x: Option>"), + json!({"type": ["string", "null"]}), + Value::Null +)] +#[case::skip_none_ref( + &format!("{SKIP_NONE} x: Option"), + json!({"$ref": "#/components/schemas/User"}), + Value::Null +)] +#[case::skip_none_value_type( + &format!("{SKIP_NONE} #[schema(value_type = Option)] x: Option"), + json!({"type": "integer", "format": "int64"}), + Value::Null +)] +// A `value_type` that is no `Option` documents itself. +#[case::skip_none_plain_value_type( + &format!("{SKIP_NONE} #[schema(value_type = i64)] x: Option"), + json!({"type": "integer", "format": "int64"}), + Value::Null +)] +// Another predicate may still let a `None` through as `null`. +#[case::other_predicate( + r#"#[serde(skip_serializing_if = "is_hidden")] x: Option"#, + json!({"type": ["string", "null"]}), + Value::Null +)] +// Not an `Option`: the predicate only makes the key optional. +#[case::skip_none_non_option( + &format!("{SKIP_NONE} x: String"), + json!({"type": "string"}), + Value::Null +)] +fn response_view(#[case] field: &str, #[case] schema: Value, #[case] required: Value) { + assert_eq!(view(field, false), (schema, required), "{field}"); +} + +/// The request view reads `null` for any `Option`, predicate or not. +#[rstest] +#[case::plain("x: Option")] +#[case::skip_none(&format!("{SKIP_NONE} x: Option"))] +fn request_view_stays_nullable(#[case] field: &str) { + assert_eq!( + view(field, true), + (json!({"type": ["string", "null"]}), Value::Null), + "{field}" + ); +} diff --git a/examples/axum-example/openapi.json b/examples/axum-example/openapi.json index 5cf3a00c1..101443759 100644 --- a/examples/axum-example/openapi.json +++ b/examples/axum-example/openapi.json @@ -6925,10 +6925,7 @@ "type": "object", "properties": { "email4": { - "type": [ - "string", - "null" - ] + "type": "string" }, "email5": { "type": "string", diff --git a/examples/axum-example/tests/integration_schema.rs b/examples/axum-example/tests/integration_schema.rs index 342fcd24b..29875c9c7 100644 --- a/examples/axum-example/tests/integration_schema.rs +++ b/examples/axum-example/tests/integration_schema.rs @@ -429,25 +429,31 @@ pub struct WireProfile { /// The response schema matches what axum's `Json` actually sends: a `None` /// is sent as `"nickname": null` (so `nickname` is required and nullable), -/// a `skip_serializing_if` `None` is left out (not required), and a +/// an `Option::is_none`-skipped field is a string when `Some` and left out +/// when `None` — never `null` (optional, not nullable) — and a /// `skip_serializing` field is never sent (not a property). #[tokio::test] async fn response_schema_matches_the_serialized_body() { use vespera::axum::{Json, Router, routing::get}; - let app = Router::new().route( - "/profile", - get(|| async { - Json(WireProfile { - name: "n".to_string(), - nickname: None, - email: None, - secret: "s".to_string(), - }) - }), - ); - let body: serde_json::Value = TestServer::new(app).get("/profile").await.json(); + let profile = |email: Option<&str>| WireProfile { + name: "n".to_string(), + nickname: None, + email: email.map(str::to_string), + secret: "s".to_string(), + }; + let (without, with) = (profile(None), profile(Some("e@x"))); + let app = Router::new() + .route("/none", get(|| async move { Json(without) })) + .route("/some", get(|| async move { Json(with) })); + let server = TestServer::new(app); + let body: serde_json::Value = server.get("/none").await.json(); assert_eq!(body, json!({"name": "n", "nickname": null})); + let with_email: serde_json::Value = server.get("/some").await.json(); + assert_eq!( + with_email, + json!({"name": "n", "nickname": null, "email": "e@x"}) + ); let schema = serde_json::to_value(schema!(WireProfile)).unwrap(); assert_eq!(schema["required"], json!(["name", "nickname"])); @@ -455,7 +461,7 @@ async fn response_schema_matches_the_serialized_body() { schema["properties"]["nickname"]["type"], json!(["string", "null"]) ); - assert!(schema["properties"].get("email").is_some()); + assert_eq!(schema["properties"]["email"], json!({"type": "string"})); assert!(schema["properties"].get("secret").is_none()); // Every required key is really in the body. for key in schema["required"].as_array().unwrap() { diff --git a/examples/axum-example/tests/snapshots/integration_test__openapi.snap b/examples/axum-example/tests/snapshots/integration_test__openapi.snap index eb57b7a75..56e539ce5 100644 --- a/examples/axum-example/tests/snapshots/integration_test__openapi.snap +++ b/examples/axum-example/tests/snapshots/integration_test__openapi.snap @@ -6929,10 +6929,7 @@ expression: "std::fs::read_to_string(\"openapi.json\").unwrap()" "type": "object", "properties": { "email4": { - "type": [ - "string", - "null" - ] + "type": "string" }, "email5": { "type": "string", From 2249561e5b7c6e96e3e8c8d0e1448036f10d25bb Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 17 Nov 2026 16:25:32 +0900 Subject: [PATCH 7/7] test(macro): identical-input fixture without an Option An Option skipped by Option::is_none now differs between views, so the fixture that exercises dropping an identical input uses a plain field. Co-Authored-By: Claude Opus 5.5 --- .../vespera_macro/src/openapi_generator/tests_accuracy.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs index 0e374e032..a04a1ceb0 100644 --- a/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs +++ b/crates/vespera_macro/src/openapi_generator/tests_accuracy.rs @@ -322,11 +322,11 @@ fn identical_or_unused_request_views_emit_nothing() { "Holder", "pub struct Holder { pub opt: Opt, pub same: Same }", )); - // `default` on an `Option` field serde omits when `None`: optional in - // both views, so the built `SameInput` equals `Same` and is dropped. + // `default` on a field serde may omit: optional in both views, so the + // built `SameInput` equals `Same` and is dropped. metadata.structs.push(schema( "Same", - r#"pub struct Same { #[serde(default, skip_serializing_if = "Option::is_none")] pub x: Option }"#, + r#"pub struct Same { #[serde(default, skip_serializing_if = "is_zero")] pub x: u8 }"#, )); metadata.structs.push(schema( "Out",