diff --git a/.changepacks/changepack_log_macrorest_round30.json b/.changepacks/changepack_log_macrorest_round30.json new file mode 100644 index 00000000..995c023d --- /dev/null +++ b/.changepacks/changepack_log_macrorest_round30.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":"Macro rest round 30: the changepacks version-PR sync runs the sync script from the main checkout, never the branch copy, and cargo update reads manifests only. A cfg-gated route module declared after vespera! is served but left out of the document (README known limit). A renamed dependency whose app name the current crate also exports resolves to the other exporter. A bare relative module file at a package root finds its crate root. The example garde doc, the multipart WrongFieldType body checks, the bench work-dir cleanup and two test-quality fixes are included.","date":"2026-11-19T00:00:00.000Z"} diff --git a/.github/workflows/CI.yml b/.github/workflows/CI.yml index 2de94695..fafcac9f 100644 --- a/.github/workflows/CI.yml +++ b/.github/workflows/CI.yml @@ -678,9 +678,20 @@ jobs: if ! git fetch --depth 1 origin changepacks/main 2>/dev/null; then echo "no version PR branch"; exit 0 fi + # The write token must never run code from the changepacks/main tree. + # The sync script and the modules it imports are copied from this + # (main) checkout first; the copy rewrites the branch checkout through + # VERSION_SYNC_ROOT. + trusted="$RUNNER_TEMP/version-sync" + mkdir -p "$trusted/scripts" "$trusted/apps/landing/src/constants" + cp scripts/sync-landing-versions.ts scripts/check-version-alignment.ts "$trusted/scripts/" + cp apps/landing/src/constants/index.ts "$trusted/apps/landing/src/constants/" git checkout -B changepacks/main FETCH_HEAD + # cargo update only resolves the manifests and Cargo.lock: it runs no + # build.rs, proc macro or workspace code (verified with a path + # dependency carrying a build script and a proc-macro crate). cargo update --workspace - bun scripts/sync-landing-versions.ts + VERSION_SYNC_ROOT="$PWD" bun "$trusted/scripts/sync-landing-versions.ts" if ! git diff --quiet; then git config user.name "github-actions[bot]" git config user.email "41898282+github-actions[bot]@users.noreply.github.com" diff --git a/README.md b/README.md index f98a387c..10d337f8 100644 --- a/README.md +++ b/README.md @@ -150,6 +150,11 @@ cannot match) is a compile error on the path literal. A static prefix is fine (`/report-{year}` documents `year`); escaped literal braces `{{` / `}}` are not parameters and are documented percent-encoded (`%7B` / `%7D`). +Known limit: a route module behind `#[cfg(..)]` that is compiled in is served, +but the OpenAPI document leaves it out when the module is declared after +`vespera!`. Declare gated route modules before `vespera!` so the document lists +them. + ### Route Handlers Handlers must be `pub async fn` with the `#[vespera::route]` attribute: diff --git a/crates/vespera_macro/src/openapi_generator/component_schemas.rs b/crates/vespera_macro/src/openapi_generator/component_schemas.rs index 9c00f455..cba60658 100644 --- a/crates/vespera_macro/src/openapi_generator/component_schemas.rs +++ b/crates/vespera_macro/src/openapi_generator/component_schemas.rs @@ -400,12 +400,6 @@ fn rust_ident_aliases(metadata: &CollectedMetadata) -> BTreeMap<&str, BTreeMap<& aliases } -/// Reject a Rust type name that two `#[schema(name = "..")]` renames share -/// (`mod a { #[schema(name = "A")] struct Foo }` + `mod b { #[schema(name = -/// "B")] struct Foo }`) when a handler signature, a `responses = [...]` entry -/// or another schema uses it: -/// the macro sees only the bare ident, so it cannot tell which `Foo` is meant. -/// A schema actually NAMED like the ident wins, so it is never ambiguous. /// Whether the document describes the stored route `stored`. A `cfg(test)` /// route is mounted only in test builds and is left out of the document, so /// its signature cannot make an alias ambiguous for it (round-29 @@ -428,6 +422,12 @@ fn documented_stored_route( documented || !test_only } +/// Reject a Rust type name that two `#[schema(name = "..")]` renames share +/// (`mod a { #[schema(name = "A")] struct Foo }` + `mod b { #[schema(name = +/// "B")] struct Foo }`) when a handler signature, a `responses = [...]` entry +/// or another schema uses it: +/// the macro sees only the bare ident, so it cannot tell which `Foo` is meant. +/// A schema actually NAMED like the ident wins, so it is never ambiguous. pub(super) fn check_ambiguous_aliases( metadata: &CollectedMetadata, file_cache: &HashMap, diff --git a/crates/vespera_macro/src/openapi_generator/component_schemas/rust_scope.rs b/crates/vespera_macro/src/openapi_generator/component_schemas/rust_scope.rs index 9b4dcdc5..1beb9969 100644 --- a/crates/vespera_macro/src/openapi_generator/component_schemas/rust_scope.rs +++ b/crates/vespera_macro/src/openapi_generator/component_schemas/rust_scope.rs @@ -42,6 +42,21 @@ fn is_crate_root_dir(dir: &Path) -> bool { /// the root naming nothing. The root is the nearest ancestor that is a crate /// root by [`is_crate_root_dir`] and holds a `lib.rs` or `main.rs`. fn file_modules(file: &Path) -> Option> { + file_modules_from(file, &std::env::current_dir().ok()?) +} + +/// [`file_modules`] with the directory a relative file name is anchored to. +/// Cargo runs rustc in the package root, so a bare `models.rs` names the +/// package root's own file: anchoring it there finds that root. A `..` path +/// stays relative, since anchoring would hide the parent components. +fn file_modules_from(file: &Path, cwd: &Path) -> Option> { + let anchored; + let file = if file.is_relative() && !file.components().any(|c| c == Component::ParentDir) { + anchored = cwd.join(file); + anchored.as_path() + } else { + file + }; let root = file.ancestors().skip(1).find(|dir| { !dir.as_os_str().is_empty() && (dir.join("lib.rs").is_file() || dir.join("main.rs").is_file()) @@ -271,6 +286,28 @@ mod tests { assert_eq!(file_modules(&file).unwrap(), ["bin", "tool"]); } + /// A package with `lib.rs` and `models.rs` at its root (no `src/`): the + /// bare relative name `models.rs` is the root's own file, so it is + /// `models`. A `..` path is not anchored and never reaches the cwd root. + #[test] + fn bare_relative_file_at_the_package_root_has_a_module() { + let dir = tempfile::tempdir().unwrap(); + fs::write(dir.path().join("Cargo.toml"), "").unwrap(); + fs::write(dir.path().join("lib.rs"), "").unwrap(); + assert_eq!( + file_modules_from(Path::new("models.rs"), dir.path()).unwrap(), + ["models"] + ); + assert_eq!( + file_modules_from(Path::new("lib.rs"), dir.path()).unwrap(), + Vec::::new() + ); + assert_eq!( + file_modules_from(Path::new("../models.rs"), dir.path()), + None + ); + } + #[test] fn file_outside_a_crate_root_has_no_module() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/vespera_macro/src/vespera_impl/merge_lookup.rs b/crates/vespera_macro/src/vespera_impl/merge_lookup.rs index d77c8c93..99c9c6a7 100644 --- a/crates/vespera_macro/src/vespera_impl/merge_lookup.rs +++ b/crates/vespera_macro/src/vespera_impl/merge_lookup.rs @@ -238,6 +238,16 @@ pub(super) fn ambiguous_alias_error( }) } +/// `app` as exported by crate `krate`, when that crate published a spec for it. +fn export_in(vespera_dir: &Path, krate: String, app: &str) -> Option { + let spec_file = export_spec_path(vespera_dir, &krate, app); + spec_file.is_file().then(|| ResolvedExport { + krate, + app: app.to_owned(), + spec_file, + }) +} + /// Resolve `merge_path` against the call-site `aliases` and the exported /// specs under `vespera_dir`. pub(super) fn resolve_export( @@ -268,23 +278,36 @@ pub(super) fn resolve_export( .filter(|_| segments.len() > 1) .filter(|first| !matches!(first.as_str(), "crate" | "self" | "super")) .cloned(); - let candidates = named.into_iter().chain(std::iter::once(current.clone())); - for krate in candidates { - let spec_file = export_spec_path(vespera_dir, &krate, &app); - if spec_file.is_file() { - return Some(ResolvedExport { - krate, - app, - spec_file, - }); - } + // A crate the path names (`child::App`) that exported the app wins. + let is_bare = named.is_none(); + // A first segment the crate declares itself (`mod routes`, `use .. as + // routes`, an item) is a local path: the current crate's own export. + let local = named + .as_ref() + .is_some_and(|first| crate_root_names().contains(first)); + if let Some(resolved) = named.and_then(|krate| export_in(vespera_dir, krate, &app)) { + return Some(resolved); } - // Renamed dependency: the only crate that exported this app name. - let mut exporters = exporters_of(vespera_dir, &app); - let krate = if exporters.len() == 1 { - exporters.pop()? - } else { + // A bare name is the current crate's own export. + if (is_bare || local) + && let Some(resolved) = export_in(vespera_dir, current.clone(), &app) + { + return Some(resolved); + } + let krate = if local { current + } else { + // Renamed dependency (only an extern crate can be left): the unique + // exporter other than the current crate. The current crate is the + // fallback when no other exporter, or several, exist. + let others: Vec = exporters_of(vespera_dir, &app) + .into_iter() + .filter(|krate| *krate != current) + .collect(); + match others.as_slice() { + [only] => only.clone(), + _ => current, + } }; Some(ResolvedExport { spec_file: export_spec_path(vespera_dir, &krate, &app), @@ -293,6 +316,47 @@ pub(super) fn resolve_export( }) } +/// The names the current crate declares at its root, read from `src/lib.rs` +/// and `src/main.rs` under `CARGO_MANIFEST_DIR`: `mod`s, items, and the local +/// names of its `use` items (`use .. as name`). Empty outside cargo. +fn crate_root_names() -> HashSet { + let Some(manifest) = crate::env_access::var_os("CARGO_MANIFEST_DIR") else { + return HashSet::new(); + }; + let mut names = HashSet::new(); + for root in ["src/lib.rs", "src/main.rs"] { + let path = Path::new(&manifest).join(root); + let Some(file) = crate::schema_macro::file_cache::get_parsed_file(&path) else { + continue; + }; + names.extend(use_bindings(Some(&path)).into_iter().map(|(name, _)| name)); + names.extend(file.items.iter().filter_map(declared_name)); + } + names +} + +/// The name a top-level item declares (`None` for impls, macros, ...). +fn declared_name(item: &syn::Item) -> Option { + match item { + syn::Item::Mod(item) => Some(item.ident.to_string()), + syn::Item::Fn(item) => Some(item.sig.ident.to_string()), + syn::Item::Struct(item) => Some(item.ident.to_string()), + syn::Item::Enum(item) => Some(item.ident.to_string()), + syn::Item::Union(item) => Some(item.ident.to_string()), + syn::Item::Trait(item) => Some(item.ident.to_string()), + syn::Item::Type(item) => Some(item.ident.to_string()), + syn::Item::Const(item) => Some(item.ident.to_string()), + syn::Item::Static(item) => Some(item.ident.to_string()), + syn::Item::ExternCrate(item) => Some( + item.rename + .as_ref() + .map_or(&item.ident, |(_, name)| name) + .to_string(), + ), + _ => None, + } +} + /// Every crate directory under [`export_root`] holding `app`'s spec, sorted. fn exporters_of(vespera_dir: &Path, app: &str) -> Vec { let mut exporters: Vec = std::fs::read_dir(export_root(vespera_dir)) @@ -561,6 +625,108 @@ mod tests { ); } + /// A renamed dependency (`dep::SharedApp`) whose app name the current crate + /// also exports resolves to the other exporter, not to the current crate. + /// A bare name stays with the current crate, and with two other exporters + /// the current crate is the fallback as before. + #[test] + fn renamed_dependency_prefers_the_other_exporter_over_the_current_crate() { + let temp = TempDir::new().unwrap(); + let _crate = crate::env_access::test_env::set_var("CARGO_CRATE_NAME", "parent"); + let dir = temp.path(); + publish(dir, "parent", "SharedApp"); + publish(dir, "child", "SharedApp"); + assert_eq!( + resolve("dep::SharedApp", "", dir), + Some(pair("child", "SharedApp")) + ); + assert_eq!( + resolve("SharedApp", "", dir), + Some(pair("parent", "SharedApp")) + ); + publish(dir, "other", "SharedApp"); + assert_eq!( + resolve("dep::SharedApp", "", dir), + Some(pair("parent", "SharedApp")) + ); + } + + /// A first segment the current crate declares (`routes::SharedApp` with + /// `mod routes` at the root) keeps the current crate, even when a renamed + /// dependency exports the same app name. Without that declaration the + /// segment is an extern crate and the other exporter wins. + #[test] + fn local_module_path_keeps_the_current_crate_over_a_renamed_dependency() { + let temp = TempDir::new().unwrap(); + let _crate = crate::env_access::test_env::set_var("CARGO_CRATE_NAME", "parent"); + let manifest = TempDir::new().unwrap(); + fs::create_dir_all(manifest.path().join("src")).unwrap(); + fs::write( + manifest.path().join("src").join("lib.rs"), + "pub mod routes {} +mod inner {} +", + ) + .unwrap(); + let _manifest = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", manifest.path()); + let dir = temp.path(); + publish(dir, "parent", "SharedApp"); + publish(dir, "child", "SharedApp"); + assert_eq!( + resolve("routes::SharedApp", "", dir), + Some(pair("parent", "SharedApp")) + ); + assert_eq!( + resolve("inner::SharedApp", "", dir), + Some(pair("parent", "SharedApp")) + ); + assert_eq!( + resolve("dep::SharedApp", "", dir), + Some(pair("child", "SharedApp")) + ); + } + + /// Every top-level declaration kind and `use .. as` name of the crate root + /// counts as a local name; impls and macros do not. + #[test] + fn crate_root_names_cover_every_declaration_kind() { + let manifest = TempDir::new().unwrap(); + fs::create_dir_all(manifest.path().join("src")).unwrap(); + fs::write( + manifest.path().join("src").join("lib.rs"), + "mod a {} +pub fn b() {} +pub struct C; +pub enum D { X } + pub union E { x: u8 } +pub trait F {} +pub type G = u8; + pub const H: u8 = 0; +pub static I: u8 = 0; +extern crate core as J; + use other::Thing as K; +impl C {} +", + ) + .unwrap(); + let _manifest = crate::env_access::test_env::set_var("CARGO_MANIFEST_DIR", manifest.path()); + let names = crate_root_names(); + for expected in ["a", "b", "C", "D", "E", "F", "G", "H", "I", "J", "K"] { + assert!( + names.contains(expected), + "{expected} missing from {names:?}" + ); + } + assert!(!names.contains("Thing")); + } + + /// Outside cargo there is no crate root to read, so no segment is local. + #[test] + fn crate_root_names_are_empty_without_a_manifest_dir() { + let _manifest = crate::env_access::test_env::remove_var("CARGO_MANIFEST_DIR"); + assert!(crate_root_names().is_empty()); + } + /// Found exports get a key assertion; missing ones (reported elsewhere) /// and an unresolvable environment get none. #[test] diff --git a/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs b/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs index d5a34844..75e616d4 100644 --- a/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs +++ b/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs @@ -16,6 +16,18 @@ fn include_target(tokens: &str) -> PathBuf { PathBuf::from(tokens[start..end].replace("\\\\", "\\")) } +/// The `` of a content-addressed `-<16 hex>.json` sidecar. +fn sidecar_stem(path: &Path) -> String { + let name = path.file_name().unwrap().to_string_lossy(); + let (stem, hash) = name + .strip_suffix(".json") + .unwrap() + .rsplit_once('-') + .unwrap(); + assert_eq!(hash.len(), 16, "{name}"); + stem.to_owned() +} + fn crate_with_routes(users: &str) -> TempDir { let temp_dir = TempDir::new().unwrap(); let routes = temp_dir.path().join("src").join("routes"); @@ -73,6 +85,10 @@ fn test_harness_build_never_prunes_the_library_sidecar() { .to_string() }; let harness_spec = include_target(&harness); + // Different content names different files either way; the regression is a + // shared `` (the selection marker then moves onto the harness file + // and the library file is pruned after the grace period). + assert_ne!(sidecar_stem(&library_spec), sidecar_stem(&harness_spec)); assert_ne!(library_spec, harness_spec); assert!(harness_spec.exists()); assert!( diff --git a/crates/vespera_macro/src/vespera_impl/path_utils.rs b/crates/vespera_macro/src/vespera_impl/path_utils.rs index 75dc1cf4..606d3bac 100644 --- a/crates/vespera_macro/src/vespera_impl/path_utils.rs +++ b/crates/vespera_macro/src/vespera_impl/path_utils.rs @@ -456,12 +456,13 @@ mod tests { #[test] fn find_target_dir_is_inside_the_workspace_root_by_default() { + let _vespera = crate::env_access::test_env::remove_var("VESPERA_TARGET_DIR"); + let _cargo = crate::env_access::test_env::remove_var("CARGO_TARGET_DIR"); let temp_dir = TempDir::new().expect("Failed to create temp dir"); - let expected = target_dir_in( - temp_dir.path(), - crate::env_access::var_os("CARGO_TARGET_DIR"), + assert_eq!( + find_target_dir(temp_dir.path()), + temp_dir.path().join("target") ); - assert_eq!(find_target_dir(temp_dir.path()), expected); } #[test] diff --git a/examples/axum-example/openapi.json b/examples/axum-example/openapi.json index 4c32d60f..c024e03c 100644 --- a/examples/axum-example/openapi.json +++ b/examples/axum-example/openapi.json @@ -5203,7 +5203,7 @@ }, "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.", + "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent (`alphanumeric`\nexcepted, see `nickname`), so the constraints in `openapi.json` match the\n`422` this route answers.", "properties": { "age": { "type": "integer", @@ -5288,7 +5288,7 @@ }, "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.", + "description": "Profile validated by garde's own derive — `#[derive(Schema)]` documents\nevery `#[garde(...)]` rule with a JSON Schema equivalent (`alphanumeric`\nexcepted, see `nickname`), so the constraints in `openapi.json` match the\n`422` this route answers.", "properties": { "age": { "type": "integer", diff --git a/examples/axum-example/src/routes/validated.rs b/examples/axum-example/src/routes/validated.rs index ac331eff..113ae999 100644 --- a/examples/axum-example/src/routes/validated.rs +++ b/examples/axum-example/src/routes/validated.rs @@ -167,8 +167,9 @@ pub async fn validated_page( } /// Profile validated by garde's own derive — `#[derive(Schema)]` documents -/// every `#[garde(...)]` rule with a JSON Schema equivalent, so the -/// constraints in `openapi.json` match the `422` this route answers. +/// every `#[garde(...)]` rule with a JSON Schema equivalent (`alphanumeric` +/// excepted, see `nickname`), so the constraints in `openapi.json` match the +/// `422` this route answers. #[derive(Debug, Deserialize, Serialize, Schema, garde::Validate)] pub struct GardeProfile { /// 2–20 characters (`chars` mode → `minLength` / `maxLength`). diff --git a/examples/axum-example/tests/integration_multipart.rs b/examples/axum-example/tests/integration_multipart.rs index c62a5289..9ea42202 100644 --- a/examples/axum-example/tests/integration_multipart.rs +++ b/examples/axum-example/tests/integration_multipart.rs @@ -665,6 +665,11 @@ async fn test_numeric_field_invalid_value() { let response = server.post("/numeric-char-test").multipart(form).await; response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY); + let body = response.text(); + assert!( + body.contains("Wrong type for field `count`"), + "unexpected body: {body}" + ); } #[tokio::test] @@ -680,6 +685,11 @@ async fn test_float_field_invalid_value() { let response = server.post("/numeric-char-test").multipart(form).await; response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY); + let body = response.text(); + assert!( + body.contains("Wrong type for field `score`"), + "unexpected body: {body}" + ); } #[tokio::test] @@ -695,6 +705,11 @@ async fn test_char_field_multiple_chars() { let response = server.post("/numeric-char-test").multipart(form).await; response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY); + let body = response.text(); + assert!( + body.contains("Wrong type for field `initial`"), + "unexpected body: {body}" + ); } #[tokio::test] @@ -710,6 +725,11 @@ async fn test_char_field_empty_string() { let response = server.post("/numeric-char-test").multipart(form).await; response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY); + let body = response.text(); + assert!( + body.contains("Wrong type for field `initial`"), + "unexpected body: {body}" + ); } // ─── serde(default) struct-level tests ────────────────────────────────────── @@ -824,6 +844,11 @@ async fn test_numeric_field_non_utf8_bytes() { let response = server.post("/numeric-char-test").multipart(form).await; response.assert_status(axum::http::StatusCode::UNPROCESSABLE_ENTITY); + let body = response.text(); + assert!( + body.contains("Wrong type for field `count`"), + "unexpected body: {body}" + ); } #[tokio::test] diff --git a/scripts/bench-interleaved.sh b/scripts/bench-interleaved.sh index 9ed9637f..2352f8cb 100755 --- a/scripts/bench-interleaved.sh +++ b/scripts/bench-interleaved.sh @@ -92,6 +92,9 @@ run_side() { # (cd "$4" && CRITERION_HOME="$work/criterion/$1/$2" "$3" --bench \ --noplot --warm-up-time "$warmup" --measurement-time "$measure" ${filter:+"$filter"}) } +# A caller-supplied WORK_DIR may hold an earlier run's estimates: clear them so a +# run that measures nothing cannot read them back as its own. +rm -rf "$work/criterion" for round in $(seq 1 "$rounds"); do echo "::group::round $round/$rounds" if [ $((round % 2)) -eq 1 ]; then order="base head"; else order="head base"; fi diff --git a/scripts/sync-landing-versions.ts b/scripts/sync-landing-versions.ts index 0c49e599..4100a7f0 100644 --- a/scripts/sync-landing-versions.ts +++ b/scripts/sync-landing-versions.ts @@ -95,7 +95,9 @@ function replaceCapture( } function main(): number { - const root = join(import.meta.dir, '..') + // VERSION_SYNC_ROOT lets CI run this file from a trusted copy against the + // checkout it rewrites (see the changepacks job in .github/workflows/CI.yml). + const root = process.env.VERSION_SYNC_ROOT ?? join(import.meta.dir, '..') const workspace = readFileSync(join(root, 'Cargo.toml'), 'utf8').match( /\[workspace\.package\][^[]*?\nversion\s*=\s*"([^"]+)"/, )?.[1]