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_round41.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":"Route files gated by an inner #![cfg(..)] (or a declarer's inner cfg) are no longer documented or mounted ungated when the slow path collects them; a #[path] inline module in a non-mod-rs file resolves its children beside the declaring file (rustc rule); $ref fragments are percent-decoded before the component name is taken (Pet%2Fx names Pet); a responses type with generic arguments is a spanned error; a lifetime named like a module no longer rejects a responses path; cron jobs spelled through a local alias of vespera::cron or of the vespera crate are discovered, and a file's inner cfg gates its jobs; export_app! cache hits validate the include copy against its sidecar. vespera_core gains split_schema_ref.","date":"2026-11-24T00:00:00.000Z"}
2 changes: 1 addition & 1 deletion crates/vespera_core/src/schema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ pub use components::{
};
pub use schema_ref::{
AdditionalProperties, Reference, SchemaRef, escape_schema_name, schema_name_of_ref,
unescape_schema_name,
split_schema_ref, unescape_schema_name,
};

use serde::{Deserialize, Serialize};
Expand Down
52 changes: 46 additions & 6 deletions crates/vespera_core/src/schema/schema_ref.rs
Original file line number Diff line number Diff line change
Expand Up @@ -559,13 +559,33 @@ const fn hex_value(digit: u8) -> Option<u8> {
/// [`escape_schema_name`] never hold a raw `/`, so they are unaffected.
#[must_use]
pub fn schema_name_of_ref(ref_path: &str) -> Option<String> {
split_schema_ref(ref_path).map(|(name, _)| name)
}

/// [`schema_name_of_ref`] plus the raw text after the name token, kept exactly
/// as written: the JSON Pointer suffix (`/properties/b`), or an encoded `%2F`
/// and what follows it. The name ends at the first raw `/` or `%2F`, so the
/// suffix is empty or starts with one of them.
#[must_use]
pub fn split_schema_ref(ref_path: &str) -> Option<(String, &str)> {
let segment = ref_path.strip_prefix(SCHEMA_REF_PREFIX)?;
let decoded = percent_decode(segment.as_bytes());
let end = decoded
.iter()
.position(|&byte| byte == b'/')
.unwrap_or(decoded.len());
Some(pointer_unescape(&decoded[..end]))
let bytes = segment.as_bytes();
let mut end = 0;
while let Some(&byte) = bytes.get(end) {
let escaped = if byte == b'%' {
hex_pair(&bytes[end + 1..])
} else {
None
};
if byte == b'/' || escaped == Some(b'/') {
break;
}
end += if escaped.is_some() { 3 } else { 1 };
}
Some((
pointer_unescape(&percent_decode(&bytes[..end])),
&segment[end..],
))
}

impl Reference {
Expand Down Expand Up @@ -899,4 +919,24 @@ mod escape_tests {
) {
assert_eq!(schema_name_of_ref(ref_path).as_deref(), name);
}

#[rstest]
#[case::pointer_suffix("#/components/schemas/A/properties/b", Some(("A", "/properties/b")))]
#[case::encoded_slash_keeps_raw_suffix("#/components/schemas/Pet%2Fdog/items", Some(("Pet", "%2Fdog/items")))]
#[case::encoded_slash_is_the_only_suffix("#/components/schemas/Pet%2fdog", Some(("Pet", "%2fdog")))]
#[case::escaped_pointer_name_keeps_raw_suffix("#/components/schemas/a~1b%2Fc", Some(("a/b", "%2Fc")))]
#[case::bare_name("#/components/schemas/A", Some(("A", "")))]
#[case::not_a_schema("#/components/parameters/A/x", None)]
fn split_schema_ref_separates_the_name_from_the_raw_suffix(
#[case] ref_path: &str,
#[case] expected: Option<(&str, &str)>,
) {
let actual = split_schema_ref(ref_path);
assert_eq!(
actual
.as_ref()
.map(|(name, suffix)| (name.as_str(), *suffix)),
expected
);
}
}
20 changes: 18 additions & 2 deletions crates/vespera_macro/src/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,20 @@ use crate::{
route_impl::StoredRouteInfo,
};

/// The `#![cfg(..)]` predicates of a route file's own inner attributes: they
/// gate every route in it, as its declaration's `#[cfg(..)]` does.
fn inner_cfgs(file: &Path) -> Vec<String> {
crate::schema_macro::file_cache::get_parsed_file(file).map_or_else(Vec::new, |file_ast| {
module_scope::cfg_predicates(&file_ast.attrs)
})
}

/// Whether `file` is test-only through its own inner `#![cfg(test)]`.
fn inner_test_only(file: &Path) -> bool {
crate::schema_macro::file_cache::get_parsed_file(file)
.is_some_and(|file_ast| test_scope::attrs_test_only(&file_ast.attrs))
}

/// Kebab-case a route path for the file-based routing convention
/// (snake_case file / folder segments → kebab-case URL), but PRESERVE the
/// contents of `{...}` path parameters verbatim. Hyphenating a `{user_id}`
Expand Down Expand Up @@ -406,7 +420,7 @@ pub fn collect_metadata_from_files<'a>(
}
// Compiled routes behind a test-only `#[cfg(..)]` (a test build
// registered them): mounted, but never documented.
let file_test_only = test_scope.file_test_only(file);
let file_test_only = test_scope.file_test_only(file) || inner_test_only(file);
let defs = test_scope::fn_definitions(file);
metadata.test_only_routes.extend(stored_test_only_routes(
&file_path,
Expand All @@ -427,7 +441,7 @@ pub fn collect_metadata_from_files<'a>(
// into SCHEMA_STORAGE.field_defaults (Priority 0 in process_default_functions)
} else {
let parsed = crate::schema_macro::file_cache::get_parsed_file(file);
let module_cfg = modules.cfg_predicates(&segments);
let module_cfg = [modules.cfg_predicates(&segments), inner_cfgs(file)].concat();
if !module_cfg.is_empty() {
// Never registered by `#[route]` and declared behind
// `#[cfg(..)]`: compiled out, or expanded after `vespera!`.
Expand Down Expand Up @@ -481,4 +495,6 @@ pub fn collect_metadata_from_files<'a>(
#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_inner_cfg;
#[cfg(test)]
mod tests_twins;
47 changes: 46 additions & 1 deletion crates/vespera_macro/src/collector/module_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,16 @@ fn declared_mods(declarer: &Path) -> Vec<DeclaredMod> {
file_cache::derived(declarer, |content| {
Declared(
syn::parse_file(content)
.map(|file| declared_items(&file.items))
.map(|file| {
// The declarer's own inner `#![cfg(..)]` gates every `mod`
// it declares, as an outer `#[cfg(..)]` on each would.
let inner = cfg_predicates(&file.attrs);
let mut mods = declared_items(&file.items);
for module in &mut mods {
module.cfgs.extend(inner.iter().cloned());
}
mods
})
.unwrap_or_default(),
)
})
Expand Down Expand Up @@ -610,6 +619,42 @@ mod tests {
assert_eq!(table.cfg_predicates(&segments), Vec::<String>::new());
}

/// An inline `#[path = "routes"] mod h { mod x; }` in `src/routes.rs` (not
/// `routes/mod.rs`) names its directory from the file's own directory, as
/// rustc does: `x` loads `routes/x.rs` (round-41 R41-M1-L1).
#[test]
fn inline_path_block_in_sibling_file_resolves_beside_the_file() {
let dir = tree(&[
(
"routes.rs",
"#[cfg(unix)]\n#[path = \"routes\"]\nmod h {\n mod x;\n}\n",
),
("routes/x.rs", ""),
]);
let table = ModuleTable::new(&dir.path().join("routes"));
let segments = segs(&["x"]);
assert_eq!(table.declared_segments(&segments), ["h", "x"]);
assert_eq!(table.cfg_predicates(&segments), ["unix"]);
}

/// A declarer's inner `#![cfg(..)]` gates every `mod` it declares: a
/// folder's `mod.rs` gating `users` gates `routes/users.rs`, the same as an
/// outer `#[cfg]` on the declaration (round-41 R41-MR0-M1).
#[test]
fn declarer_inner_cfg_gates_the_modules_it_declares() {
let dir = tree(&[
(
"routes/mod.rs",
"#![cfg(feature = \"admin\")]\npub mod users;\n",
),
("routes/users.rs", ""),
]);
let table = ModuleTable::new(&dir.path().join("routes"));
let segments = segs(&["users"]);
assert_eq!(table.declared_segments(&segments), ["users"]);
assert_eq!(table.cfg_predicates(&segments), ["feature = \"admin\""]);
}

/// `#[path = "helpers/x.rs"]` declared in `routes/admin.rs` loads
/// `routes/helpers/x.rs` (relative to the declaring file's directory), so
/// the route file is the module `routes::admin::x` and its gate applies.
Expand Down
26 changes: 19 additions & 7 deletions crates/vespera_macro/src/collector/test_scope/path_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
//! relative to the module's directory (`<dir>/a/`).
//! - An inline `#[path = "d"] mod h { .. }` names the directory its children
//! load from (`<dir>/d/`, not `<dir>/h/`): the `#[path]` value replaces the
//! module name as that block's directory segment.
//! module name as that block's directory segment. Outside any inline block
//! `<dir>` is the declaring file's directory, not the directory named after a
//! non-mod-rs file: `src/routes.rs` holding `#[path = "d"] mod h { mod x; }`
//! loads `src/d/x.rs` (checked against rustc, `cargo run` of a scratch crate).
//!
//! The tree is walked from the target, so it covers each child module of a
//! path-loaded file, however deep. Ungated edges only, for the modules every
Expand Down Expand Up @@ -48,6 +51,10 @@ struct Block {
/// The directory segment its children load from: its `#[path]` value, or
/// its name.
dir: String,
/// A top-level block (no enclosing inline module) with a `#[path]`: rustc
/// resolves that value against the declaring file's directory, not the
/// directory of its child modules.
file_relative: bool,
}

/// One `mod` declaration of a file.
Expand Down Expand Up @@ -125,6 +132,7 @@ impl Collector {
}
inline.push(Block {
id,
file_relative: inline.is_empty() && path.is_some(),
dir: path.unwrap_or(name),
});
self.items(nested, inline, gated);
Expand Down Expand Up @@ -219,7 +227,7 @@ fn children(file: &Path, children_dir: &Path, reach: Reach, within: Option<usize
} else {
// A by-name child: `<dir>/<name>.rs` or `<dir>/<name>/mod.rs` (the
// one that exists is the module; the other holds no declarations).
let child_dir = inline_dir(children_dir, decl).join(&decl.name);
let child_dir = inline_dir(file, children_dir, decl).join(&decl.name);
nodes.push(Node {
file: child_dir.with_extension("rs"),
children_dir: child_dir.clone(),
Expand All @@ -236,12 +244,16 @@ fn children(file: &Path, children_dir: &Path, reach: Reach, within: Option<usize
/// The directory a `mod` declaration of a file with child directory
/// `children_dir` is resolved in: its inline blocks nest under it, each by
/// its directory segment (`#[path]` value or name).
fn inline_dir(children_dir: &Path, decl: &ModDecl) -> PathBuf {
fn inline_dir(file: &Path, children_dir: &Path, decl: &ModDecl) -> PathBuf {
let start = match decl.inline.first() {
Some(block) if block.file_relative => {
file.parent().map(Path::to_path_buf).unwrap_or_default()
}
_ => children_dir.to_path_buf(),
};
decl.inline
.iter()
.fold(children_dir.to_path_buf(), |dir, block| {
dir.join(&block.dir)
})
.fold(start, |dir, block| dir.join(&block.dir))
}

/// The file a `#[path]` declaration names, the one rustc resolves: outside
Expand All @@ -252,7 +264,7 @@ fn path_target(file: &Path, children_dir: &Path, decl: &ModDecl) -> Option<PathB
let base = if decl.inline.is_empty() {
file.parent().map(Path::to_path_buf).unwrap_or_default()
} else {
inline_dir(children_dir, decl)
inline_dir(file, children_dir, decl)
};
lexical(&base.join(path_value))
}
Expand Down
20 changes: 20 additions & 0 deletions crates/vespera_macro/src/collector/test_scope/tests_inline_path.rs
Original file line number Diff line number Diff line change
Expand Up @@ -74,3 +74,23 @@ fn gated_inline_path_module_nests_under_its_enclosing_block() {
assert!(scope.file_test_only(&src.join("outer/fixtures/x.rs")));
assert!(!scope.file_test_only(&src.join("outer/helpers/x.rs")));
}

/// rustc resolves an inline `#[path = "d"] mod h { .. }` of a non-mod-rs file
/// (`routes.rs`) against that file's own directory, so its gated child loads
/// `d/x.rs`, not `routes/d/x.rs` (checked against rustc, round-41 R41-M1-L1).
#[test]
fn test_gated_child_of_an_inline_path_module_in_a_non_mod_rs_file_is_beside_the_file() {
let krate = crate_with(&[
("lib.rs", "mod routes;\n"),
(
"routes.rs",
"#[path = \"d\"]\nmod h {\n #[cfg(test)]\n mod x;\n}\n",
),
("d/x.rs", "pub struct Fixture {}"),
("routes/d/x.rs", "pub struct Kept {}"),
]);
let src = krate.path().join("src");
let mut scope = TestScope::new(Some(&src));
assert!(scope.file_test_only(&src.join("d/x.rs")));
assert!(!scope.file_test_only(&src.join("routes/d/x.rs")));
}
72 changes: 72 additions & 0 deletions crates/vespera_macro/src/collector/tests_inner_cfg.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
//! Collector tests for a route file's own inner `#![cfg(..)]` (round-41
//! R41-MR0-M1): the file's gate applies to every route in it, as a
//! declaration's `#[cfg(..)]` does.

use std::fs;

use tempfile::TempDir;

use super::*;

fn create_temp_file(dir: &TempDir, filename: &str, content: &str) -> std::path::PathBuf {
let file_path = dir.path().join(filename);
fs::write(&file_path, content).expect("Failed to write temp file");
file_path
}

/// Slow path (no `#[route]` storage entry): a route file whose inner
/// `#![cfg(feature = "admin")]` gates it is mounted only under that predicate,
/// never as an ungated route the router would reference unconditionally.
#[test]
fn slow_path_inner_cfg_gates_the_route_file() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
create_temp_file(&temp_dir, "mod.rs", "pub mod panel;\n");
create_temp_file(
&temp_dir,
"panel.rs",
"#![cfg(feature = \"admin\")]\n#[route(get)] pub async fn panel() {}\n",
);
crate::schema_macro::file_cache::bump_epoch();

let (metadata, _) = collect_metadata(temp_dir.path(), "routes", &[]).unwrap();

assert!(metadata.routes.is_empty());
let gated: Vec<(&str, &[String])> = metadata
.cfg_routes
.iter()
.map(|route| (route.function_name.as_str(), route.cfg.as_slice()))
.collect();
assert_eq!(gated, [("panel", &["feature = \"admin\"".to_string()][..])]);
}

/// Fast path (this build registered the route): a test build's
/// `#![cfg(test)]` route file is test-only as a whole, so the route is
/// recorded as test-only and kept out of the document, as a `#[cfg(test)]`
/// module's routes are.
#[test]
fn fast_path_inner_test_cfg_makes_the_route_file_test_only() {
let temp_dir = TempDir::new().expect("Failed to create temp dir");
let file = create_temp_file(
&temp_dir,
"probe.rs",
"#![cfg(test)]\n#[route(get)] pub async fn probe() {}\n",
);
crate::schema_macro::file_cache::bump_epoch();
let file_path = file.display().to_string();
let storage = [StoredRouteInfo {
fn_name: "probe".to_string(),
method: Some("get".to_string()),
fn_sig_str: "async fn probe()".to_string(),
file_path: Some(file_path),
..StoredRouteInfo::default()
}];

let (metadata, _) = collect_metadata(temp_dir.path(), "routes", &storage).unwrap();

let names: Vec<&str> = metadata
.test_only_routes
.iter()
.map(|route| route.function_name.as_str())
.collect();
assert_eq!(names, ["probe"]);
}
9 changes: 6 additions & 3 deletions crates/vespera_macro/src/route/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -189,9 +189,12 @@ fn extract_typed_responses(array: &syn::ExprArray) -> Option<Vec<(u16, String)>>
(!responses.is_empty()).then_some(responses)
}

/// The `responses = [(404, errors::NotFound)]` type as written, without
/// generic arguments (`errors::NotFound`): the module qualifier lets the
/// OpenAPI generator tell same-named renamed types apart.
/// The `responses = [(404, errors::NotFound)]` type as written
/// (`errors::NotFound`): the module qualifier lets the OpenAPI generator tell
/// same-named renamed types apart. The segment idents only, so generic
/// arguments are dropped; the `#[route]` argument parser (`args.rs`,
/// `responses`) rejects a path that has them, so only argument-free paths reach
/// this.
pub fn response_type_path(path: &syn::Path) -> Option<String> {
let segments: Vec<String> = path
.segments
Expand Down
Loading
Loading