Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .changepacks/changepack_log_parser_round49.json
Original file line number Diff line number Diff line change
@@ -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":"Parser round 49: under deny_unknown_fields a flattened struct that has a flatten field of its own no longer lists the enum keys it flattens (serde leaves every key of such a member in the buffer, so the closed request schema now rejects them as serde does); a route handler lookup prefers the routed fn over an attribute-less same-named cfg variant; a String path extractor is refined by a later integer one (doc fix); the generic instance encoding doc now lists the any-value types.","date":"2026-11-29T00:00:00.000Z"}
28 changes: 28 additions & 0 deletions crates/vespera/tests/flatten_optional_enum_deny.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,31 @@ fn two_variant_keys_are_rejected_and_zero_or_one_accepted() {
assert!(serde_json::from_str::<Req>(r#"{"id":1,"Text":"a"}"#).is_ok());
assert!(serde_json::from_str::<Req>(r#"{"id":1}"#).is_ok());
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
#[allow(dead_code)]
struct NestedReq {
id: i32,
#[serde(flatten)]
nested: Nested,
}

#[derive(Deserialize)]
#[allow(dead_code)]
struct Nested {
#[serde(flatten)]
data: Option<DataOnly>,
}

/// R49-P3-M1: the same shape one level down, inside a REQUIRED flattened
/// struct, takes NO variant key under the outer `deny_unknown_fields`: the
/// nested struct reads its member through `deserialize_map`, so the keys stay
/// in the buffer and the outer struct rejects every one of them (one key or
/// two). Only an absent enum is accepted.
#[test]
fn nested_optional_enum_rejects_every_variant_key() {
assert!(serde_json::from_str::<NestedReq>(r#"{"id":1,"Text":"a","Bytes":"b"}"#).is_err());
assert!(serde_json::from_str::<NestedReq>(r#"{"id":1,"Text":"a"}"#).is_err());
assert!(serde_json::from_str::<NestedReq>(r#"{"id":1}"#).is_ok());
}
4 changes: 3 additions & 1 deletion crates/vespera/tests/schema_crate_alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ fn aliased_serde_json_map_documents_the_bare_object() {

#[test]
fn aliased_serde_json_value_documents_like_the_bare_value() {
assert_eq!(documented("raw"), documented("bare_value"));
let raw = documented("raw");
assert_eq!(raw, documented("bare_value"));
assert_eq!(raw, serde_json::json!({}), "{raw}");
}

#[test]
Expand Down
31 changes: 22 additions & 9 deletions crates/vespera_macro/src/parser/extractor_validation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -256,21 +256,34 @@ fn is_test_only(metadata: &CollectedMetadata, route: &crate::metadata::RouteMeta
/// `ast`, the one not gated by a test-only `cfg` whose `#[route(<method>)]`
/// is the route's method. A `#[cfg(test)]` twin, or a same-named fn of
/// another method, is never the handler, so its extractors are not checked
/// against the route. `None` when no such fn exists (nothing to check).
/// against the route. A fn carrying such a `#[route]` wins over an
/// attribute-less same-named fn (a `cfg`-gated variant of the handler, which
/// is not a route of its own); the attribute-less fn is the fallback only when
/// no routed twin exists. `None` when no such fn exists (nothing to check).
fn handler_fn<'a>(
ast: &'a syn::File,
route: &crate::metadata::RouteMetadata,
) -> Option<&'a syn::ItemFn> {
ast.items.iter().find_map(|item| match item {
syn::Item::Fn(f)
if f.sig.ident == route.function_name
&& !attrs_test_only(&f.attrs)
&& is_handler_of(f, &route.method) =>
let mut fallback = None;
for item in &ast.items {
let syn::Item::Fn(f) = item else {
continue;
};
if f.sig.ident != route.function_name
|| attrs_test_only(&f.attrs)
|| !is_handler_of(f, &route.method)
{
Some(f)
continue;
}
_ => None,
})
if f.attrs
.iter()
.any(|attr| crate::route::check_route_by_meta(&attr.meta))
{
return Some(f);
}
fallback.get_or_insert(f);
}
fallback
}

/// Whether `f` can be the handler of a `method` route: its `#[route(..)]`
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -359,3 +359,28 @@ fn generic_parameters_shadow_module_items(#[case] handler: &str, #[case] ok: boo
let src = format!("pub struct Body {{ pub a: i32 }} {handler}");
assert_eq!(run(&src).is_ok(), ok, "{handler}");
}

/// R49-P0-L2: a `cfg`-gated attribute-less fn with the handler's name is not a
/// route, so it does not stand in for the routed POST handler that comes after
/// it in source order (the first-match lookup checked the legacy `Json<Local>`
/// and reported a false error).
#[test]
fn routed_twin_wins_over_an_attribute_less_same_named_fn() {
let mut metadata = CollectedMetadata::new();
metadata.routes.push(handler_route("post"));
let src = "pub struct Local { pub a: i32 } #[derive(Schema)] pub struct Body { pub a: i32 } \
#[cfg(feature = \"legacy\")] pub fn handler(Json(l): Json<Local>) {} \
#[cfg(not(feature = \"legacy\"))] #[route(post)] pub fn handler(Json(b): Json<Body>) {}";
assert!(check_with(&metadata, src).is_ok());
}

/// Without a routed twin the attribute-less fn is still the handler, so its
/// non-`Schema` extractor is flagged.
#[test]
fn attribute_less_fn_is_the_handler_without_a_routed_twin() {
let mut metadata = CollectedMetadata::new();
metadata.routes.push(handler_route("post"));
let src = "pub struct Local { pub a: i32 } pub fn handler(Json(l): Json<Local>) {}";
let message = check_with(&metadata, src).expect_err("handler").to_string();
assert!(message.contains("`Json<Local>`"), "{message}");
}
9 changes: 5 additions & 4 deletions crates/vespera_macro/src/parser/operation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -399,10 +399,11 @@ fn response_description_for_status(status_code: u16) -> String {
}

/// The path parameters of every `Path<T>` extractor, one per segment name. The
/// first extractor's parameter wins, unless it is only the string placeholder
/// a struct / tuple that does not type the segment leaves behind, and a later
/// extractor types it (axum deserializes each extractor from the same route
/// segments, so the typed one is the segment's real type).
/// first extractor's parameter wins, unless it is a string schema (the
/// placeholder a struct / tuple that does not type the segment leaves behind,
/// or a `Path<String>`) and a later extractor's non-string parameter names the
/// same segment: axum deserializes every extractor from the same route
/// segments, so that later, stricter type documents the segment.
fn merge_path_extractor_parameters(
extracted: impl IntoIterator<Item = Vec<Parameter>>,
) -> Vec<Parameter> {
Expand Down
13 changes: 13 additions & 0 deletions crates/vespera_macro/src/parser/operation/tests_path_extractors.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,3 +57,16 @@ fn a_segment_no_extractor_types_is_a_string() {
);
assert_eq!(schema["type"], "string");
}

/// R49-P0-L1: a `Path<String>` is a string schema like the placeholder, so a
/// later integer extractor for the same segment refines it (both extractors
/// accept the segment; the integer one is the stricter constraint).
#[test]
fn a_string_path_extractor_is_refined_by_a_later_integer() {
let schema = parameter_schema(
"async fn f(Path(a): Path<String>, Path(b): Path<u64>) -> String",
"/{id}",
"id",
);
assert_eq!(schema["type"], "integer");
}
107 changes: 10 additions & 97 deletions crates/vespera_macro/src/parser/schema/struct_schema/flatten.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,10 @@
//! other variant key to the outer struct, so its request-view branches are
//! an `anyOf` (several may match), never a `oneOf`. Under the outer
//! `deny_unknown_fields` the request view lists the keys it takes (the
//! variant keys, or the tag and content of an adjacently tagged enum; a
//! struct flattening one lists its own) and its branches are a `oneOf`
//! (exactly one may match, see `list_keys`);
//! variant keys, or the tag and content of an adjacently tagged enum) and
//! its branches are a `oneOf` (exactly one may match, see `list_keys`). A
//! struct flattening one takes none of them (it leaves them in the buffer,
//! see the next bullet), so none are listed (R49-P3-M1);
//! - the OUTER `deny_unknown_fields` rejects any key no member consumed
//! (a map borrows, never consumes, so with it the map stays empty);
//! - a flattened newtype (`deserialize_newtype_struct` passes the buffer
Expand Down Expand Up @@ -81,10 +82,7 @@ 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::{
SerdeEnumRepr, SerdeSide, extract_enum_repr, extract_flatten, extract_serde_skip_flags,
extract_untagged,
},
serde_attrs::{SerdeEnumRepr, SerdeSide, extract_enum_repr, extract_untagged},
type_schema::{generic_instances, parse_type_to_schema_ref},
wire_override::codec_applies,
},
Expand All @@ -95,7 +93,7 @@ use crate::schema_macro::type_utils::option_inner;
mod combinators;
use combinators::{any_of_branches, both, either, lenient};
mod keyed;
use keyed::{exclusive_enum, exclusive_enums, optional_enum_keys};
use keyed::exclusive_enum;

thread_local! {
/// Rust idents whose definitions are being resolved (cycle guard: a
Expand Down Expand Up @@ -128,8 +126,6 @@ pub(super) enum FlatPart {
parts: ObjectParts,
optional: bool,
leaves: bool,
/// Keys a deny-closed request view lists (see `list_keys`).
listed: Vec<(String, SchemaRef)>,
},
/// A member whose keys cannot be known.
Opaque {
Expand All @@ -154,26 +150,6 @@ pub(super) fn flatten_part(
omittable: bool,
known_schemas: &HashSet<impl Borrow<str> + Eq + Hash>,
struct_definitions: &HashMap<impl Borrow<str> + Eq + Hash, impl AsRef<str>>,
) -> FlatPart {
classify_member(
field,
side,
omittable,
known_schemas,
struct_definitions,
WRAPPER_DEPTH,
)
}

/// [`flatten_part`] with `depth` bounding how many flattened members are
/// followed to list their keys (`nested_keys`).
fn classify_member(
field: &syn::Field,
side: SerdeSide,
omittable: bool,
known_schemas: &HashSet<impl Borrow<str> + Eq + Hash>,
struct_definitions: &HashMap<impl Borrow<str> + Eq + Hash, impl AsRef<str>>,
depth: usize,
) -> FlatPart {
let constraints = extract_schema_constraints(&field.attrs);
// serde sees through `Box` / `Arc` / ... to a flattened `Option` too.
Expand Down Expand Up @@ -210,11 +186,6 @@ fn classify_member(
.as_ref()
.and_then(|schema| decompose(schema, known_schemas, struct_definitions))
{
let listed = if request {
nested_keys(ty, side, known_schemas, struct_definitions, depth)
} else {
Vec::new()
};
return FlatPart::Known {
// A unit struct (`null`) has no keys: its `$ref` would make an
// `allOf` member nothing satisfies next to the object.
Expand All @@ -226,7 +197,6 @@ fn classify_member(
parts,
optional,
leaves,
listed: lenient_keys(listed, optional),
};
}
// A newtype / transparent wrapper around an enum is flattened like that
Expand Down Expand Up @@ -386,47 +356,6 @@ fn variant_keys(schema: &SchemaRef) -> Vec<(String, SchemaRef)> {
keys
}

/// The keys a flattened struct `ty` lists for a deny-closed request view: the
/// listed keys of its own flattened members (a struct flattening an enum
/// leaves that enum's keys to the outer struct, see `classify_member`).
/// `depth` bounds the members followed.
fn nested_keys(
ty: &syn::Type,
side: SerdeSide,
known_schemas: &HashSet<impl Borrow<str> + Eq + Hash>,
struct_definitions: &HashMap<impl Borrow<str> + Eq + Hash, impl AsRef<str>>,
depth: usize,
) -> Vec<(String, SchemaRef)> {
let Some(item) = flat_item(ty, struct_definitions) else {
return Vec::new();
};
match (request_view::flat_read(&item), &item) {
(FlatRead::Through(inner), _) if depth > 0 => {
nested_keys(inner, side, known_schemas, struct_definitions, depth - 1)
}
(FlatRead::Leaves { known_keys: true }, syn::Item::Struct(item)) if depth > 0 => item
.fields
.iter()
.filter(|field| {
let flags = extract_serde_skip_flags(&field.attrs);
extract_flatten(&field.attrs) && !flags.skip && !flags.skip_deserializing
})
.flat_map(|field| {
classify_member(
field,
side,
false,
known_schemas,
struct_definitions,
depth - 1,
)
.listed()
})
.collect(),
_ => Vec::new(),
}
}

/// `keys` with each value made lenient when its member is optional (a failing
/// optional member is `None`, so its keys are accepted).
fn lenient_keys(keys: Vec<(String, SchemaRef)>, optional: bool) -> Vec<(String, SchemaRef)> {
Expand All @@ -442,15 +371,6 @@ fn list_keys(own: &mut ObjectParts, keys: Vec<(String, SchemaRef)>) {
}
}

impl FlatPart {
/// The keys this member lists for a deny-closed request view.
fn listed(self) -> Vec<(String, SchemaRef)> {
match self {
Self::Known { listed, .. } | Self::Opaque { listed, .. } => listed,
}
}
}

/// The flattened form of an externally tagged enum `schema` with unit
/// variants: serde writes (and reads) a flattened unit variant as the key
/// `{"A": null}`, never as the string `"A"`, so every `{type: string, enum:
Expand Down Expand Up @@ -886,25 +806,18 @@ pub(super) fn assemble(
mut parts,
optional,
leaves,
listed,
..
} => {
// serde rejects every key such a member leaves behind, its
// unknown members' keys too: they do not open the object.
// unknown members' keys too: they do not open the object. Its
// nested enums' keys are left behind as well (R49-P3-M1: serde
// consumes none of them under the outer `deny_unknown_fields`),
// so, like its own keys, they are not listed.
let rejected = request && deny_unknown_fields && leaves;
if request {
let left = leaves.then_some((later, deny_unknown_fields));
earlier_maps = request_member(&mut parts, optional, earlier_maps, left);
}
if request && deny_unknown_fields {
// A nested enum's variant keys are exclusive too (serde
// takes one of them); an optional one's `parts` are dropped
// by `merge`, so its exclusive keys are kept as a member.
exclusive_enums(&mut parts.opaque, &listed);
own.opaque
.extend(optional_enum_keys(optional, &parts.opaque, &listed));
list_keys(&mut own, listed);
}
open |= merge(&mut own, parts, optional) && !rejected;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,6 @@ pub(super) fn any_of_branches(schema: &mut SchemaRef) {
}
}

/// Turns the `anyOf` branches of an inline `schema` into `oneOf` ones, unless
/// one of them is the empty schema `{}` (the lenient branch of a flattened
/// `Option`, see [`lenient`]).
pub(super) fn exclusive_branches(schema: &mut SchemaRef) {
if let SchemaRef::Inline(inline) = schema
&& inline.one_of.is_none()
&& inline
.any_of
.as_ref()
.is_some_and(|branches| branches.iter().all(|branch| !is_empty_schema(branch)))
{
inline.one_of = inline.any_of.take();
}
}

/// Whether `schema` is the empty schema `{}` (it accepts every value).
fn is_empty_schema(schema: &SchemaRef) -> bool {
matches!(schema, SchemaRef::Inline(inline)
if serde_json::to_value(inline)
.is_ok_and(|value| value.as_object().is_some_and(serde_json::Map::is_empty)))
}

/// `anyOf: [schema, {}]` — documents `schema` without rejecting anything
/// (a flattened `Option` is `None` when its value fails).
pub(super) fn lenient(schema: SchemaRef) -> SchemaRef {
Expand Down
Loading
Loading