Skip to content
Open
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_macrorest_round30.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":"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"}
13 changes: 12 additions & 1 deletion .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
12 changes: 6 additions & 6 deletions crates/vespera_macro/src/openapi_generator/component_schemas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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<String, syn::File>,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<String>> {
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<Vec<String>> {
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())
Expand Down Expand Up @@ -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::<String>::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();
Expand Down
196 changes: 181 additions & 15 deletions crates/vespera_macro/src/vespera_impl/merge_lookup.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ResolvedExport> {
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(
Expand Down Expand Up @@ -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<String> = 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),
Expand All @@ -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<String> {
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<String> {
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<String> {
let mut exporters: Vec<String> = std::fs::read_dir(export_root(vespera_dir))
Expand Down Expand Up @@ -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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,18 @@ fn include_target(tokens: &str) -> PathBuf {
PathBuf::from(tokens[start..end].replace("\\\\", "\\"))
}

/// The `<stem>` of a content-addressed `<stem>-<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");
Expand Down Expand Up @@ -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 `<stem>` (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!(
Expand Down
9 changes: 5 additions & 4 deletions crates/vespera_macro/src/vespera_impl/path_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down
Loading
Loading