From 991a23bd9c03717f5f9d543b7f09f089602666fe Mon Sep 17 00:00:00 2001 From: Jeong Min Oh Date: Tue, 24 Nov 2026 09:32:02 +0900 Subject: [PATCH] Fix round-41 vespera_macro findings (MR0-M1, M1-L1, MR3-L2, MR4-L1, MR5-L1, MR6-L1/L2) - Route files: a route file's own inner #![cfg(..)] gates its routes on the slow path (cfg_routes, not an ungated route), and an inner #![cfg(test)] makes a stored route file test-only. A declarer's inner cfg gates the modules it declares (module tree). - Module tree vs test-scope: rustc resolves an inline #[path = "d"] mod h at the top of a non-mod-rs file against the declaring file's directory (src/routes.rs -> src/d/x.rs, checked with a scratch crate: the src/routes/d/x.rs child-dir candidate does not compile). path_tree now follows that rule. - $ref rewrite: the fragment is percent-decoded before the name is taken (Pet%2Fx names Pet, suffix kept raw), via a new vespera_core split_schema_ref helper. - Generic handlers: only a type parameter can head a path, so a lifetime or const named like a module (a::NotFound under <'a>) is no longer rejected as a dangling reference. - Cron scan: jobs spelled through a local alias of vespera::cron (use vespera::cron as job) or of the vespera crate (use vespera as v) are discovered; a file's own inner #![cfg] gates its jobs. - export_app! cache hits validate the content-addressed include copy against its sidecar instead of only checking that it exists. - Test hygiene: the harness-build test probes prune_superseded_older_than with zero grace. Refuted: R41-MR3-L1 (a generic-argument responses type silently dropped). args.rs already rejects it at the #[route] attribute, before response_type_path runs, so no compiled route can reach the drop; only the doc was corrected. Co-Authored-By: Claude Opus 5.5 --- .../changepack_log_macrorest_round41.json | 1 + crates/vespera_core/src/schema.rs | 2 +- crates/vespera_core/src/schema/schema_ref.rs | 52 +++++- crates/vespera_macro/src/collector.rs | 20 +- .../src/collector/module_tree.rs | 47 ++++- .../src/collector/test_scope/path_tree.rs | 26 ++- .../collector/test_scope/tests_inline_path.rs | 20 ++ .../src/collector/tests_inner_cfg.rs | 72 ++++++++ crates/vespera_macro/src/route/utils.rs | 9 +- crates/vespera_macro/src/route_impl.rs | 171 ++---------------- .../src/route_impl/generic_scope.rs | 120 +++++++----- .../src/route_impl/tests_responses.rs | 31 ++++ .../src/route_impl/tests_storage.rs | 157 ++++++++++++++++ .../src/router_codegen/export.rs | 53 ++++-- .../src/vespera_impl/cron_discovery.rs | 164 ++++++++++------- .../cron_discovery/tests_alias.rs | 77 ++++++++ .../vespera_impl/cron_discovery/tests_gate.rs | 41 +++++ .../src/vespera_impl/orchestrator.rs | 20 +- .../orchestrator/tests_variants.rs | 33 ++++ .../src/vespera_impl/sidecar_write.rs | 2 +- 20 files changed, 817 insertions(+), 301 deletions(-) create mode 100644 .changepacks/changepack_log_macrorest_round41.json create mode 100644 crates/vespera_macro/src/collector/tests_inner_cfg.rs create mode 100644 crates/vespera_macro/src/route_impl/tests_storage.rs create mode 100644 crates/vespera_macro/src/vespera_impl/cron_discovery/tests_alias.rs diff --git a/.changepacks/changepack_log_macrorest_round41.json b/.changepacks/changepack_log_macrorest_round41.json new file mode 100644 index 00000000..d74032d1 --- /dev/null +++ b/.changepacks/changepack_log_macrorest_round41.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":"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"} diff --git a/crates/vespera_core/src/schema.rs b/crates/vespera_core/src/schema.rs index 1c64d611..6756f0a7 100644 --- a/crates/vespera_core/src/schema.rs +++ b/crates/vespera_core/src/schema.rs @@ -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}; diff --git a/crates/vespera_core/src/schema/schema_ref.rs b/crates/vespera_core/src/schema/schema_ref.rs index cf12238b..4bb206c1 100644 --- a/crates/vespera_core/src/schema/schema_ref.rs +++ b/crates/vespera_core/src/schema/schema_ref.rs @@ -559,13 +559,33 @@ const fn hex_value(digit: u8) -> Option { /// [`escape_schema_name`] never hold a raw `/`, so they are unaffected. #[must_use] pub fn schema_name_of_ref(ref_path: &str) -> Option { + 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 { @@ -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 + ); + } } diff --git a/crates/vespera_macro/src/collector.rs b/crates/vespera_macro/src/collector.rs index 06d44e9b..84e77e99 100644 --- a/crates/vespera_macro/src/collector.rs +++ b/crates/vespera_macro/src/collector.rs @@ -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 { + 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}` @@ -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, @@ -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!`. @@ -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; diff --git a/crates/vespera_macro/src/collector/module_tree.rs b/crates/vespera_macro/src/collector/module_tree.rs index 36aacf8f..c9179d86 100644 --- a/crates/vespera_macro/src/collector/module_tree.rs +++ b/crates/vespera_macro/src/collector/module_tree.rs @@ -316,7 +316,16 @@ fn declared_mods(declarer: &Path) -> Vec { 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(), ) }) @@ -610,6 +619,42 @@ mod tests { assert_eq!(table.cfg_predicates(&segments), Vec::::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. diff --git a/crates/vespera_macro/src/collector/test_scope/path_tree.rs b/crates/vespera_macro/src/collector/test_scope/path_tree.rs index 46ce1e21..956998c1 100644 --- a/crates/vespera_macro/src/collector/test_scope/path_tree.rs +++ b/crates/vespera_macro/src/collector/test_scope/path_tree.rs @@ -17,7 +17,10 @@ //! relative to the module's directory (`/a/`). //! - An inline `#[path = "d"] mod h { .. }` names the directory its children //! load from (`/d/`, not `/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 +//! `` 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 @@ -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. @@ -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); @@ -219,7 +227,7 @@ fn children(file: &Path, children_dir: &Path, reach: Reach, within: Option/.rs` or `//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(), @@ -236,12 +244,16 @@ fn children(file: &Path, children_dir: &Path, reach: Reach, within: Option 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 @@ -252,7 +264,7 @@ fn path_target(file: &Path, children_dir: &Path, decl: &ModDecl) -> Option 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"]); +} diff --git a/crates/vespera_macro/src/route/utils.rs b/crates/vespera_macro/src/route/utils.rs index de83cb1b..8dfbc7bd 100644 --- a/crates/vespera_macro/src/route/utils.rs +++ b/crates/vespera_macro/src/route/utils.rs @@ -189,9 +189,12 @@ fn extract_typed_responses(array: &syn::ExprArray) -> Option> (!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 { let segments: Vec = path .segments diff --git a/crates/vespera_macro/src/route_impl.rs b/crates/vespera_macro/src/route_impl.rs index d947dc62..f0d4a4d3 100644 --- a/crates/vespera_macro/src/route_impl.rs +++ b/crates/vespera_macro/src/route_impl.rs @@ -401,7 +401,7 @@ pub fn process_route_attribute( // (rejected in `typed_response_assertions`); its other types are asserted. // Checked before the route is stored, so a rejected entry never reaches // `ROUTE_STORAGE` (round-40 MR3-L3). - let generics = generic_scope::param_names(&item_fn.sig.generics); + let generics = generic_scope::Params::of(&item_fn.sig.generics); let assertions = route_args .responses .as_ref() @@ -480,7 +480,7 @@ pub fn process_route_attribute( /// other payload of such a handler is still asserted. #[cfg(feature = "validation")] fn validated_payload_assertions(sig: &syn::Signature) -> proc_macro2::TokenStream { - let generics = generic_scope::param_names(&sig.generics); + let generics = generic_scope::Params::of(&sig.generics); let assertions = sig .inputs .iter() @@ -488,7 +488,7 @@ fn validated_payload_assertions(sig: &syn::Signature) -> proc_macro2::TokenStrea syn::FnArg::Typed(pat_type) => crate::parser::validated_payload_type(&pat_type.ty), syn::FnArg::Receiver(_) => None, }) - .filter(|payload| !generic_scope::mentions(*payload, &generics)) + .filter(|payload| !generics.mentions(*payload)) .map(|payload| { quote::quote_spanned! { syn::spanned::Spanned::span(payload) => const _: () = { @@ -513,7 +513,7 @@ fn validated_payload_assertions(sig: &syn::Signature) -> proc_macro2::TokenStrea /// handler (the spec would carry a dangling `$ref` to the parameter). fn typed_response_assertions( arr: &syn::ExprArray, - generics: &[String], + generics: &generic_scope::Params, ) -> syn::Result { let assertions = arr .elems @@ -526,7 +526,7 @@ fn typed_response_assertions( _ => None, }) .map(|path| { - if generic_scope::mentions(path, generics) { + if generics.mentions(path) { return Err(syn::Error::new_spanned( path, "a generic handler's type or const parameter cannot be a `responses` type: \ @@ -632,7 +632,12 @@ mod tests { // Non-path entries (rejected by the argument parser) emit nothing. let array: syn::ExprArray = syn::parse_quote!([(404, 1), 2]); - assert!(typed_response_assertions(&array, &[]).unwrap().is_empty()); + let no_params = generic_scope::Params::default(); + assert!( + typed_response_assertions(&array, &no_params) + .unwrap() + .is_empty() + ); } #[test] @@ -763,157 +768,6 @@ mod tests { } } - // ========== Tests for ROUTE_STORAGE population ========== - - #[test] - fn test_route_storage_populated_by_process_route_attribute() { - let attr = quote!( - get, - path = "/{id}", - tags = ["users"], - description = "Get user by ID", - error_status = [404] - ); - let item = quote!( - pub async fn get_user_test_storage() -> String { - "test".to_string() - } - ); - let result = process_route_attribute(attr, item); - assert!(result.is_ok()); - - // Find our entry by unique fn_name (the current crate's routes are - // shared across parallel tests in this crate). - let storage = current_crate_routes(); - - // Find our entry and verify fields - let stored = storage - .iter() - .find(|s| s.fn_name == "get_user_test_storage"); - assert!( - stored.is_some(), - "StoredRouteInfo should be in ROUTE_STORAGE" - ); - let stored = stored.unwrap(); - assert_eq!(stored.method, Some("get".to_string())); - assert_eq!(stored.custom_path, Some("/{id}".to_string())); - assert_eq!(stored.tags, Some(vec!["users".to_string()])); - assert_eq!(stored.description, Some("Get user by ID".to_string())); - assert_eq!(stored.error_status, Some(vec![404])); - assert_eq!(stored.headers.len(), 0); - assert!(stored.fn_sig_str.contains("get_user_test_storage")); - } - - #[test] - fn test_route_storage_no_optional_fields() { - let attr = quote!(); - let item = quote!( - pub async fn minimal_handler_test() -> String { - "test".to_string() - } - ); - let result = process_route_attribute(attr, item); - assert!(result.is_ok()); - - let storage = current_crate_routes(); - - let stored = storage.iter().find(|s| s.fn_name == "minimal_handler_test"); - assert!(stored.is_some()); - let stored = stored.unwrap(); - assert_eq!(stored.method, None); - assert_eq!(stored.custom_path, None); - assert_eq!(stored.tags, None); - assert_eq!(stored.description, None); - assert_eq!(stored.error_status, None); - assert_eq!(stored.headers.len(), 0); - } - - #[test] - fn test_register_route_replaces_same_file_and_function() { - let file_path = Some("/tmp/vespera/routes/replaced.rs".to_string()); - let fn_name = "__test_replace_route".to_string(); - let base = StoredRouteInfo { - fn_name: fn_name.clone(), - method: Some("get".to_string()), - custom_path: Some("/before".to_string()), - success_status: None, - error_status: None, - typed_responses: None, - tags: None, - security: None, - headers: Vec::new(), - operation_id: None, - summary: None, - request_example: None, - response_example: None, - deprecated: false, - description: None, - file_path: file_path.clone(), - fn_sig_str: "pub async fn __test_replace_route ()".to_string(), - inline_module: None, - }; - register_route(base); - register_route(StoredRouteInfo { - method: Some("post".to_string()), - custom_path: Some("/after".to_string()), - file_path, - fn_sig_str: "pub async fn __test_replace_route ()".to_string(), - inline_module: None, - ..current_crate_routes() - .iter() - .find(|entry| entry.fn_name == fn_name) - .cloned() - .expect("first route registration should exist") - }); - - let matches: Vec<_> = current_crate_routes() - .iter() - .filter(|entry| entry.fn_name == fn_name) - .cloned() - .collect(); - assert_eq!(matches.len(), 1, "same source route should replace"); - assert_eq!(matches[0].method, Some("post".to_string())); - assert_eq!(matches[0].custom_path, Some("/after".to_string())); - } - - /// A top-level handler and a same-named one inside an inline module are - /// two entries — the inline one must not overwrite (and so hide) the - /// top-level registration, nor vice versa. - #[test] - fn test_register_route_keys_by_inline_module() { - let file_path = Some("/tmp/vespera/routes/scoped.rs".to_string()); - let fn_name = "__test_scoped_route".to_string(); - for scope in ["", "v2"] { - register_route(StoredRouteInfo { - fn_name: fn_name.clone(), - file_path: file_path.clone(), - inline_module: Some(scope.to_string()), - ..StoredRouteInfo::default() - }); - } - let scopes: Vec<_> = current_crate_routes() - .iter() - .filter(|entry| entry.fn_name == fn_name) - .map(|entry| entry.inline_module.clone()) - .collect(); - assert_eq!(scopes, [Some(String::new()), Some("v2".to_string())]); - } - - /// `#[route]` reads files through the file cache (Path-extractor check, - /// `inline_module_of`), so every invocation starts a fresh epoch. - #[test] - fn test_route_attribute_bumps_the_file_cache_epoch() { - let before = crate::schema_macro::file_cache::current_epoch(); - process_route_attribute( - quote!(get), - quote!( - pub async fn epoch_probe() {} - ), - ) - .unwrap(); - assert_ne!(crate::schema_macro::file_cache::current_epoch(), before); - } - #[test] fn test_extract_tag_strings_empty() { let arr: syn::ExprArray = syn::parse_quote!([]); @@ -993,3 +847,6 @@ mod tests_item; mod tests_responses; #[cfg(test)] mod tests_scope; + +#[cfg(test)] +mod tests_storage; diff --git a/crates/vespera_macro/src/route_impl/generic_scope.rs b/crates/vespera_macro/src/route_impl/generic_scope.rs index 17822438..2394e61b 100644 --- a/crates/vespera_macro/src/route_impl/generic_scope.rs +++ b/crates/vespera_macro/src/route_impl/generic_scope.rs @@ -11,44 +11,66 @@ use proc_macro2::{TokenStream, TokenTree}; use quote::ToTokens; -/// The names of `generics`' lifetime, type and const parameters (a lifetime -/// by its bare ident, which is how its `'a` token shows up in a type). -pub(super) fn param_names(generics: &syn::Generics) -> Vec { - generics - .params - .iter() - .map(|param| match param { - syn::GenericParam::Lifetime(param) => param.lifetime.ident.to_string(), - syn::GenericParam::Type(param) => param.ident.to_string(), - syn::GenericParam::Const(param) => param.ident.to_string(), - }) - .collect() +/// The generic parameters of a handler: every name (lifetimes by their bare +/// ident, which is how their `'a` shows up in a type) and the type parameters +/// alone. Only a type parameter can head a path (`T::Assoc`), so a lifetime or +/// const sharing a module's name (`'a` beside `a::NotFound`) names no type. +#[derive(Default)] +pub(super) struct Params { + names: Vec, + types: Vec, } -/// Whether `tokens` spells one of `names` as a whole ident, at any group depth -/// (`Vec` mentions `T`, `Tree` does not mention `T`). An ident after `::` -/// is a path segment, not the parameter (`api::Error` does not mention a -/// generic `Error`), while the head of `T::Assoc` still does. -pub(super) fn mentions(tokens: &impl ToTokens, names: &[String]) -> bool { - fn walk(stream: TokenStream, names: &[String]) -> bool { - // Consecutive `:` puncts directly before the current token. - let mut colons = 0_u8; - stream.into_iter().any(|tree| { - let path_segment = colons >= 2; - colons = match &tree { - TokenTree::Punct(punct) if punct.as_char() == ':' => colons.saturating_add(1), - _ => 0, - }; - match tree { +impl Params { + /// The parameters of `generics`. + pub(super) fn of(generics: &syn::Generics) -> Self { + let mut params = Self::default(); + for param in &generics.params { + match param { + syn::GenericParam::Lifetime(param) => { + params.names.push(param.lifetime.ident.to_string()); + } + syn::GenericParam::Type(param) => { + let name = param.ident.to_string(); + params.types.push(name.clone()); + params.names.push(name); + } + syn::GenericParam::Const(param) => params.names.push(param.ident.to_string()), + } + } + params + } + + /// Whether `tokens` spells one of the parameters as a whole ident, at any + /// group depth (`Vec` mentions `T`, `Tree` does not mention `T`). An + /// ident after `::` is a path segment, not the parameter (`api::Error` does + /// not mention a generic `Error`). The head of a path (`T::Assoc`) still + /// mentions a type parameter, but not a lifetime or const named like a + /// module (`a::NotFound` under `<'a>` names the module `a`). + pub(super) fn mentions(&self, tokens: &impl ToTokens) -> bool { + fn walk(stream: TokenStream, params: &Params) -> bool { + let trees: Vec = stream.into_iter().collect(); + trees.iter().enumerate().any(|(index, tree)| match tree { TokenTree::Ident(ident) => { - !path_segment && names.iter().any(|name| ident == name.as_str()) + let name = ident.to_string(); + let qualified = index >= 2 + && is_colon(trees.get(index - 2)) + && is_colon(trees.get(index - 1)); + let head = is_colon(trees.get(index + 1)) && is_colon(trees.get(index + 2)); + !qualified + && params.names.contains(&name) + && (!head || params.types.contains(&name)) } - TokenTree::Group(group) => walk(group.stream(), names), + TokenTree::Group(group) => walk(group.stream(), params), TokenTree::Punct(_) | TokenTree::Literal(_) => false, - } - }) + }) + } + walk(tokens.to_token_stream(), self) } - walk(tokens.to_token_stream(), names) +} + +fn is_colon(tree: Option<&TokenTree>) -> bool { + matches!(tree, Some(TokenTree::Punct(punct)) if punct.as_char() == ':') } #[cfg(test)] @@ -58,28 +80,36 @@ mod tests { use super::*; #[test] - fn param_names_cover_every_kind_of_generic_param() { + fn params_cover_every_kind_of_generic_param() { let generics: syn::Generics = syn::parse_quote!(<'a, T, const N: usize>); - assert_eq!(param_names(&generics), vec!["a", "T", "N"]); + let params = Params::of(&generics); + assert_eq!(params.names, vec!["a", "T", "N"]); + assert_eq!(params.types, vec!["T"]); } #[rstest] - #[case::type_param("Vec", &["T"], true)] - #[case::const_param("Wrap", &["N"], true)] - #[case::lifetime_param("Foo<'a>", &["a"], true)] - #[case::nested_group("Option<(u8, Vec)>", &["T"], true)] - #[case::concrete("NotFound", &["T"], false)] - #[case::longer_ident_is_not_a_match("Tree", &["T"], false)] - #[case::qualified_tail("api::T", &["T"], false)] - #[case::qualified_head("T::Assoc", &["T"], true)] - #[case::no_params("Vec", &[], false)] + #[case::type_param("Vec", &["T"], &["T"], true)] + #[case::const_param("Wrap", &["N"], &[], true)] + #[case::lifetime_param("Foo<'a>", &["a"], &[], true)] + #[case::nested_group("Option<(u8, Vec)>", &["T"], &["T"], true)] + #[case::concrete("NotFound", &["T"], &["T"], false)] + #[case::longer_ident_is_not_a_match("Tree", &["T"], &["T"], false)] + #[case::qualified_tail("api::T", &["T"], &["T"], false)] + #[case::qualified_head("T::Assoc", &["T"], &["T"], true)] + #[case::lifetime_is_not_a_path_head("a::NotFound", &["a"], &[], false)] + #[case::const_is_not_a_path_head("N::Assoc", &["N"], &[], false)] + #[case::no_params("Vec", &[], &[], false)] fn mentions_matches_whole_idents( #[case] ty: &str, #[case] names: &[&str], + #[case] types: &[&str], #[case] expected: bool, ) { let ty: syn::Type = syn::parse_str(ty).unwrap(); - let names: Vec = names.iter().map(|name| (*name).to_owned()).collect(); - assert_eq!(mentions(&ty, &names), expected); + let params = Params { + names: names.iter().map(|name| (*name).to_owned()).collect(), + types: types.iter().map(|name| (*name).to_owned()).collect(), + }; + assert_eq!(params.mentions(&ty), expected); } } diff --git a/crates/vespera_macro/src/route_impl/tests_responses.rs b/crates/vespera_macro/src/route_impl/tests_responses.rs index d1c97c4a..b08d4d5f 100644 --- a/crates/vespera_macro/src/route_impl/tests_responses.rs +++ b/crates/vespera_macro/src/route_impl/tests_responses.rs @@ -101,3 +101,34 @@ fn rejected_generic_responses_entry_is_not_stored() { "a rejected route must not be stored" ); } + +/// A lifetime named like a module does not make `a::NotFound` a generic +/// reference: only a type parameter can head a path (round-41 R41-MR3-L2). +#[test] +fn lifetime_named_like_a_module_does_not_reject_a_responses_path() { + let item = quote!( + pub async fn get_one<'a>() -> String { + String::new() + } + ); + let output = process_route_attribute(quote!(get, responses = [(404, a::NotFound)]), item) + .unwrap() + .to_string(); + assert!( + output.contains("__vespera_assert_schema :: < a :: NotFound >"), + "{output}" + ); +} + +/// The head of `T::Assoc` names a type parameter, so it is still rejected. +#[test] +fn type_param_head_of_a_responses_path_is_rejected() { + let item = quote!( + pub async fn get_one() -> String { + String::new() + } + ); + let error = + process_route_attribute(quote!(get, responses = [(404, T::Assoc)]), item).unwrap_err(); + assert!(error.to_string().contains("dangling `$ref`"), "{error}"); +} diff --git a/crates/vespera_macro/src/route_impl/tests_storage.rs b/crates/vespera_macro/src/route_impl/tests_storage.rs new file mode 100644 index 00000000..1c8a3dc4 --- /dev/null +++ b/crates/vespera_macro/src/route_impl/tests_storage.rs @@ -0,0 +1,157 @@ +//! ROUTE_STORAGE population tests: the records `process_route_attribute` stores +//! for `vespera!` (kept out of `route_impl.rs` for the 1000-line cap). + +use quote::quote; + +use super::*; + +// ========== Tests for ROUTE_STORAGE population ========== + +#[test] +fn test_route_storage_populated_by_process_route_attribute() { + let attr = quote!( + get, + path = "/{id}", + tags = ["users"], + description = "Get user by ID", + error_status = [404] + ); + let item = quote!( + pub async fn get_user_test_storage() -> String { + "test".to_string() + } + ); + let result = process_route_attribute(attr, item); + assert!(result.is_ok()); + + // Find our entry by unique fn_name (the current crate's routes are + // shared across parallel tests in this crate). + let storage = current_crate_routes(); + + // Find our entry and verify fields + let stored = storage + .iter() + .find(|s| s.fn_name == "get_user_test_storage"); + assert!( + stored.is_some(), + "StoredRouteInfo should be in ROUTE_STORAGE" + ); + let stored = stored.unwrap(); + assert_eq!(stored.method, Some("get".to_string())); + assert_eq!(stored.custom_path, Some("/{id}".to_string())); + assert_eq!(stored.tags, Some(vec!["users".to_string()])); + assert_eq!(stored.description, Some("Get user by ID".to_string())); + assert_eq!(stored.error_status, Some(vec![404])); + assert_eq!(stored.headers.len(), 0); + assert!(stored.fn_sig_str.contains("get_user_test_storage")); +} + +#[test] +fn test_route_storage_no_optional_fields() { + let attr = quote!(); + let item = quote!( + pub async fn minimal_handler_test() -> String { + "test".to_string() + } + ); + let result = process_route_attribute(attr, item); + assert!(result.is_ok()); + + let storage = current_crate_routes(); + + let stored = storage.iter().find(|s| s.fn_name == "minimal_handler_test"); + assert!(stored.is_some()); + let stored = stored.unwrap(); + assert_eq!(stored.method, None); + assert_eq!(stored.custom_path, None); + assert_eq!(stored.tags, None); + assert_eq!(stored.description, None); + assert_eq!(stored.error_status, None); + assert_eq!(stored.headers.len(), 0); +} + +#[test] +fn test_register_route_replaces_same_file_and_function() { + let file_path = Some("/tmp/vespera/routes/replaced.rs".to_string()); + let fn_name = "__test_replace_route".to_string(); + let base = StoredRouteInfo { + fn_name: fn_name.clone(), + method: Some("get".to_string()), + custom_path: Some("/before".to_string()), + success_status: None, + error_status: None, + typed_responses: None, + tags: None, + security: None, + headers: Vec::new(), + operation_id: None, + summary: None, + request_example: None, + response_example: None, + deprecated: false, + description: None, + file_path: file_path.clone(), + fn_sig_str: "pub async fn __test_replace_route ()".to_string(), + inline_module: None, + }; + register_route(base); + register_route(StoredRouteInfo { + method: Some("post".to_string()), + custom_path: Some("/after".to_string()), + file_path, + fn_sig_str: "pub async fn __test_replace_route ()".to_string(), + inline_module: None, + ..current_crate_routes() + .iter() + .find(|entry| entry.fn_name == fn_name) + .cloned() + .expect("first route registration should exist") + }); + + let matches: Vec<_> = current_crate_routes() + .iter() + .filter(|entry| entry.fn_name == fn_name) + .cloned() + .collect(); + assert_eq!(matches.len(), 1, "same source route should replace"); + assert_eq!(matches[0].method, Some("post".to_string())); + assert_eq!(matches[0].custom_path, Some("/after".to_string())); +} + +/// A top-level handler and a same-named one inside an inline module are +/// two entries — the inline one must not overwrite (and so hide) the +/// top-level registration, nor vice versa. +#[test] +fn test_register_route_keys_by_inline_module() { + let file_path = Some("/tmp/vespera/routes/scoped.rs".to_string()); + let fn_name = "__test_scoped_route".to_string(); + for scope in ["", "v2"] { + register_route(StoredRouteInfo { + fn_name: fn_name.clone(), + file_path: file_path.clone(), + inline_module: Some(scope.to_string()), + ..StoredRouteInfo::default() + }); + } + let scopes: Vec<_> = current_crate_routes() + .iter() + .filter(|entry| entry.fn_name == fn_name) + .map(|entry| entry.inline_module.clone()) + .collect(); + assert_eq!(scopes, [Some(String::new()), Some("v2".to_string())]); +} + +/// `#[route]` reads files through the file cache (Path-extractor check, +/// `inline_module_of`), so every invocation starts a fresh epoch. +#[test] +fn test_route_attribute_bumps_the_file_cache_epoch() { + let before = crate::schema_macro::file_cache::current_epoch(); + process_route_attribute( + quote!(get), + quote!( + pub async fn epoch_probe() {} + ), + ) + .unwrap(); + assert_ne!(crate::schema_macro::file_cache::current_epoch(), before); +} diff --git a/crates/vespera_macro/src/router_codegen/export.rs b/crates/vespera_macro/src/router_codegen/export.rs index ce892157..46c4f70e 100644 --- a/crates/vespera_macro/src/router_codegen/export.rs +++ b/crates/vespera_macro/src/router_codegen/export.rs @@ -5,7 +5,7 @@ use syn::{ parse::{Parse, ParseStream}, }; -use vespera_core::schema::{escape_schema_name, unescape_schema_name}; +use vespera_core::schema::{escape_schema_name, split_schema_ref}; use crate::metadata::CollectedMetadata; @@ -318,23 +318,18 @@ fn rewrite_document_refs(document: &mut serde_json::Value, renames: &BTreeMap, names: bool) { match value { serde_json::Value::Object(object) => { + // RFC 6901: the fragment is percent-decoded before it is split into + // tokens, so `Pet%2Fx` names `Pet` with the suffix `%2Fx`; the + // suffix is kept as written. if !names && let Some(serde_json::Value::String(reference)) = object.get_mut("$ref") - && let Some(target) = reference.strip_prefix("#/components/schemas/") + && let Some((name, suffix)) = split_schema_ref(reference) + && let Some(new_name) = renames.get(&name) { - // The name segment is escaped (`/` never appears raw in it), so - // the first `/` still starts the suffix (`/properties/...`). - let (segment, suffix) = target - .split_once('/') - .map_or((target, ""), |(name, suffix)| (name, suffix)); - if let Some(new_name) = renames.get(&unescape_schema_name(segment)) { - let escaped = escape_schema_name(new_name); - *reference = if suffix.is_empty() { - format!("#/components/schemas/{escaped}") - } else { - format!("#/components/schemas/{escaped}/{suffix}") - }; - } + *reference = format!( + "#/components/schemas/{}{suffix}", + escape_schema_name(new_name) + ); } for (key, child) in object.iter_mut() { if !names && DATA_KEYS.contains(&key.as_str()) { @@ -842,6 +837,34 @@ mod tests { ); } + /// RFC 6901 decodes the `$ref` fragment before it is split into tokens: + /// `Pet%2Fx` names the component `Pet` with the suffix `%2Fx`, so a renamed + /// `Pet` follows it, and the raw suffix is kept as written. + #[test] + fn encoded_slash_in_a_ref_names_the_component_before_it() { + let mut value = serde_json::json!({ + "components": { "schemas": { + "Holder": { "properties": { + "a": { "$ref": "#/components/schemas/Pet%2Fx" }, + "b": { "$ref": "#/components/schemas/Pet%2Fx/properties/id" }, + "c": { "$ref": "#/components/schemas/Pet" } + } }, + "Pet": { "type": "object" } + } } + }); + let renames = BTreeMap::from([("Pet".to_string(), "Animal".to_string())]); + + rewrite_schema_refs(&mut value, &renames); + + let props = &value["components"]["schemas"]["Holder"]["properties"]; + assert_eq!(props["a"]["$ref"], "#/components/schemas/Animal%2Fx"); + assert_eq!( + props["b"]["$ref"], + "#/components/schemas/Animal%2Fx/properties/id" + ); + assert_eq!(props["c"]["$ref"], "#/components/schemas/Animal"); + } + /// A root `webhooks` entry named like a data keyword (`default`) is a /// webhook name: its schema `$ref` follows the namespace like a path's. #[test] diff --git a/crates/vespera_macro/src/vespera_impl/cron_discovery.rs b/crates/vespera_macro/src/vespera_impl/cron_discovery.rs index fdff338d..815a5475 100644 --- a/crates/vespera_macro/src/vespera_impl/cron_discovery.rs +++ b/crates/vespera_macro/src/vespera_impl/cron_discovery.rs @@ -10,8 +10,10 @@ //! is not in the storage yet. Instead of silently dropping it, the crate's //! module tree is walked from its root (`src/lib.rs` / `src/main.rs`) //! following `mod` declarations, and every `pub async fn` carrying -//! `#[cron("…")]` / `#[vespera::cron("…")]` that the storage does not know -//! yet is added. Known jobs are matched per function, so a job declared +//! `#[cron("…")]` / `#[vespera::cron("…")]` (or a local alias of vespera's +//! `cron`, `use vespera::cron as job;`, `use vespera as v;` + `#[v::cron]`) +//! that the storage does not know yet is added. Known jobs are matched per +//! function, so a job declared //! after `vespera!` in a file whose earlier jobs are stored is found too. //! //! The same module tree places the stored jobs: a file path alone names @@ -450,7 +452,7 @@ impl ModuleTree { module_path, file: &display, inline: "", - gate: gate.clone(), + gate: gate.inside(&summary.module.gate), inherited_foreign, }; self.visit(&summary.module, &scope); @@ -584,6 +586,9 @@ struct FileSummary { struct ModuleSummary { imports: CronImports, items: Vec, + /// The file's own inner `#![cfg(..)]` gate (empty for an inline `mod`, + /// whose gate is on its declaration). + gate: CfgGate, } /// One item the walk reads: a `mod` or a function carrying a cron attribute. @@ -630,9 +635,11 @@ fn file_summary(file: &Path) -> Option> { .then(|| syn::parse_file(content).ok()) .flatten() .map(|ast| { - std::rc::Rc::new(FileSummary { - module: summarize(&ast.items, collect_jobs), - }) + let mut module = summarize(&ast.items, collect_jobs); + // The file's own inner `#![cfg(..)]` gates every job in it, + // as its declaration's `#[cfg(..)]` does. + module.gate = CfgGate::of(&ast.attrs); + std::rc::Rc::new(FileSummary { module }) }), ) })? @@ -641,36 +648,39 @@ fn file_summary(file: &Path) -> Option> { } fn summarize(items: &[syn::Item], collect_jobs: bool) -> ModuleSummary { + let imports = cron_imports(items); + let items = items + .iter() + .filter_map(|item| match item { + syn::Item::Mod(module) => Some(ItemSummary::Mod { + name: module.ident.unraw().to_string(), + gate: CfgGate::of(&module.attrs), + path: path_attr(&module.attrs), + inline: module + .content + .as_ref() + .map(|(_, inner)| summarize(inner, collect_jobs)), + }), + syn::Item::Fn(function) + if collect_jobs + && function + .attrs + .iter() + .any(|attr| !cron_entries(attr, &imports).is_empty()) => + { + Some(ItemSummary::Cron { + name: function.sig.ident.unraw().to_string(), + gate: CfgGate::of(&function.attrs), + attrs: cron_attrs(function, &imports), + }) + } + _ => None, + }) + .collect(); ModuleSummary { - imports: cron_imports(items), - items: items - .iter() - .filter_map(|item| match item { - syn::Item::Mod(module) => Some(ItemSummary::Mod { - name: module.ident.unraw().to_string(), - gate: CfgGate::of(&module.attrs), - path: path_attr(&module.attrs), - inline: module - .content - .as_ref() - .map(|(_, inner)| summarize(inner, collect_jobs)), - }), - syn::Item::Fn(function) - if collect_jobs - && function - .attrs - .iter() - .any(|attr| !cron_entries(attr).is_empty()) => - { - Some(ItemSummary::Cron { - name: function.sig.ident.unraw().to_string(), - gate: CfgGate::of(&function.attrs), - attrs: cron_attrs(function), - }) - } - _ => None, - }) - .collect(), + imports, + items, + gate: CfgGate::default(), } } @@ -678,11 +688,15 @@ fn summarize(items: &[syn::Item], collect_jobs: bool) -> ModuleSummary { /// "…")]` function (none when the function is not one: the attribute macro /// reports malformed ones itself). Which of them is the job depends on the /// module's cron imports, so it is picked at walk time ([`CronAttr`]). -fn cron_attrs(function: &syn::ItemFn) -> Vec { +fn cron_attrs(function: &syn::ItemFn, imports: &CronImports) -> Vec { if validate_cron_fn(function).is_err() { return Vec::new(); } - function.attrs.iter().flat_map(cron_entries).collect() + function + .attrs + .iter() + .flat_map(|attr| cron_entries(attr, imports)) + .collect() } /// The [`CronAttr`]s one attribute of a fn carries: a `#[cron]` itself, or the @@ -691,8 +705,8 @@ fn cron_attrs(function: &syn::ItemFn) -> Vec { /// makes it a plain job; an undecided `p` (`windows`, `test`, `target_*`, ..) /// keeps the job too, registered under `#[cfg(p)]` (see /// [`CronMetadata::cfg`]) so rustc decides exactly as it does for the attribute. -fn cron_entries(attr: &syn::Attribute) -> Vec { - if is_cron_path(attr.path()) { +fn cron_entries(attr: &syn::Attribute, imports: &CronImports) -> Vec { + if imports.is_cron_path(attr.path()) { return vec![cron_attr(attr.path(), attr.parse_args::(), &[])]; } if !attr.path().is_ident("cfg_attr") { @@ -711,7 +725,7 @@ fn cron_entries(attr: &syn::Attribute) -> Vec { }; metas .iter() - .filter(|meta| is_cron_path(meta.path())) + .filter(|meta| imports.is_cron_path(meta.path())) .map(|meta| { let args = meta .require_list() @@ -732,29 +746,17 @@ fn cfg_attr_parts( fn cron_attr(path: &syn::Path, args: syn::Result, gate: &[String]) -> CronAttr { CronAttr { - bare: path.segments.len() == 1, + bare: path.is_ident("cron"), job: args .ok() .map(|args| (args.expression.value(), args.options(), gate.to_vec())), } } -/// `cron` or `vespera::cron`. -fn is_cron_path(path: &syn::Path) -> bool { - let segments: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); - matches!( - segments - .iter() - .map(String::as_str) - .collect::>() - .as_slice(), - ["cron"] | ["vespera", "cron"] - ) -} - /// The `use` items of one module that decide what a bare `#[cron]` in it -/// names (see [`CronImports::foreign`]). -#[derive(Clone, Copy, Default)] +/// names (see [`CronImports::foreign`]), and the local names vespera's `cron` +/// and the vespera crate are bound to in it. +#[derive(Clone, Default)] #[allow(clippy::struct_excessive_bools)] struct CronImports { /// `use other::cron;`, `use other::{cron};`, `use other::job as cron;`. @@ -766,6 +768,10 @@ struct CronImports { /// `use super::*;` / `use crate::*;`: the names of the enclosing module /// (its own `cron` import) reach this module through the glob. inheriting_glob: bool, + /// Local names of `vespera::cron` (`use vespera::cron as job;`). + cron_aliases: Vec, + /// Local names of the vespera crate (`use vespera as v;`). + crate_aliases: Vec, } impl CronImports { @@ -776,16 +782,38 @@ impl CronImports { /// and so does an inheriting glob when the enclosing module's bare `cron` /// is foreign (`inherited`). `crate::*` is approximated by the enclosing /// module's decision. - fn foreign(self, inherited: bool) -> bool { + fn foreign(&self, inherited: bool) -> bool { self.explicit_foreign || (!self.explicit_vespera && (self.foreign_glob || (self.inheriting_glob && inherited))) } + + /// `cron` (or an alias of vespera's `cron`) or `vespera::cron` (or + /// `::cron`). An alias is recognised only + /// where this module's `use` items bind it, so a `job` bound to another + /// crate's `cron` is not a job. + fn is_cron_path(&self, path: &syn::Path) -> bool { + let segments: Vec = path.segments.iter().map(|s| s.ident.to_string()).collect(); + match segments.as_slice() { + [name] => name == "cron" || self.cron_aliases.contains(name), + [krate, name] => { + name == "cron" && (krate == "vespera" || self.crate_aliases.contains(krate)) + } + _ => false, + } + } } /// The [`CronImports`] of `items` (the `use` items of one module). fn cron_imports(items: &[syn::Item]) -> CronImports { - fn collect(tree: &syn::UseTree, root: Option<&syn::Ident>, out: &mut CronImports) { + // `depth` counts the path segments above `tree`: 1 is a direct child of + // the first segment (`vespera::cron as job` or `vespera::{cron as job}`). + fn collect( + tree: &syn::UseTree, + root: Option<&syn::Ident>, + depth: usize, + out: &mut CronImports, + ) { let foreign = root.is_some_and(|root| { !matches!( root.to_string().as_str(), @@ -793,7 +821,9 @@ fn cron_imports(items: &[syn::Item]) -> CronImports { ) }); match tree { - syn::UseTree::Path(path) => collect(&path.tree, root.or(Some(&path.ident)), out), + syn::UseTree::Path(path) => { + collect(&path.tree, root.or(Some(&path.ident)), depth + 1, out); + } syn::UseTree::Name(name) if name.ident == "cron" => { out.explicit_foreign |= foreign; out.explicit_vespera |= root.is_some() && !foreign; @@ -802,9 +832,19 @@ fn cron_imports(items: &[syn::Item]) -> CronImports { out.explicit_foreign |= foreign; out.explicit_vespera |= root.is_some() && !foreign; } + syn::UseTree::Rename(rename) + if rename.ident == "cron" + && depth == 1 + && root.is_some_and(|root| root == "vespera") => + { + out.cron_aliases.push(rename.rename.to_string()); + } + syn::UseTree::Rename(rename) if rename.ident == "vespera" && root.is_none() => { + out.crate_aliases.push(rename.rename.to_string()); + } syn::UseTree::Group(group) => { for tree in &group.items { - collect(tree, root, out); + collect(tree, root, depth, out); } } // A glob may bring in another crate's `cron`; only vespera's (or @@ -821,7 +861,7 @@ fn cron_imports(items: &[syn::Item]) -> CronImports { let mut imports = CronImports::default(); for item in items { if let syn::Item::Use(item) = item { - collect(&item.tree, None, &mut imports); + collect(&item.tree, None, 0, &mut imports); } } imports @@ -914,6 +954,8 @@ mod index; #[cfg(test)] mod tests; #[cfg(test)] +mod tests_alias; +#[cfg(test)] mod tests_gate; #[cfg(test)] mod tests_index; diff --git a/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_alias.rs b/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_alias.rs new file mode 100644 index 00000000..1517ee44 --- /dev/null +++ b/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_alias.rs @@ -0,0 +1,77 @@ +//! Sidecar of `tests.rs`: a job spelled through a local alias of vespera's +//! `cron` (`use vespera::cron as job;`) or of the vespera crate (`use vespera +//! as v;`) is found by the module-tree scan, not only spelled `cron` (round-41 +//! R41-MR5-L1). + +use rstest::rstest; + +use super::tests::{crate_with, discover}; +use crate::metadata::CronMetadata; + +/// `(module, function, expression)` of each job, sorted. +fn placed(jobs: &[CronMetadata]) -> Vec<(String, String, String)> { + let mut rows: Vec<_> = jobs + .iter() + .map(|job| { + ( + job.module_path.clone(), + job.function_name.clone(), + job.expression.clone(), + ) + }) + .collect(); + rows.sort(); + rows +} + +fn expected(rows: &[(&str, &str, &str)]) -> Vec<(String, String, String)> { + let mut rows: Vec<_> = rows + .iter() + .map(|(module, name, expr)| ((*module).to_owned(), (*name).to_owned(), (*expr).to_owned())) + .collect(); + rows.sort(); + rows +} + +#[rstest] +#[case::renamed_cron_import( + r#"use vespera::cron as job; #[job("1 * * * * *")] pub async fn tick() {}"#, + &[("", "tick", "1 * * * * *")] +)] +#[case::grouped_renamed_cron_import( + r#"use vespera::{cron as job}; #[job("1 * * * * *")] pub async fn tick() {}"#, + &[("", "tick", "1 * * * * *")] +)] +#[case::crate_alias( + r#"use vespera as v; #[v::cron("1 * * * * *")] pub async fn tick() {}"#, + &[("", "tick", "1 * * * * *")] +)] +#[case::alias_beats_a_foreign_glob( + r#"use other::*; use vespera::cron as job; #[job("1 * * * * *")] pub async fn tick() {}"#, + &[("", "tick", "1 * * * * *")] +)] +#[case::foreign_cron_alias_is_not_claimed( + r#"use other::cron as job; #[job("1 * * * * *")] pub async fn tick() {}"#, + &[] +)] +#[case::deeper_path_is_not_the_cron_macro( + r#"use vespera::inner::cron as job; #[job("1 * * * * *")] pub async fn tick() {}"#, + &[] +)] +#[case::longer_path_is_not_the_cron_macro( + r#"#[a::b::cron("1 * * * * *")] pub async fn tick() {}"#, + &[] +)] +#[case::unbound_crate_name_is_not_an_alias( + r#"#[v::cron("1 * * * * *")] pub async fn tick() {}"#, + &[] +)] +fn aliased_cron_attributes_are_claimed( + #[case] source: &str, + #[case] expected_jobs: &[(&str, &str, &str)], +) { + let krate = crate_with(&[("lib.rs", source)]); + let src = krate.path().join("src"); + let jobs = discover(&[], Some(&src), None); + assert_eq!(placed(&jobs), expected(expected_jobs)); +} diff --git a/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_gate.rs b/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_gate.rs index 89013eb3..5c4ac653 100644 --- a/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_gate.rs +++ b/crates/vespera_macro/src/vespera_impl/cron_discovery/tests_gate.rs @@ -112,3 +112,44 @@ fn cfg_gated_modules_and_functions_register_their_jobs_under_their_gates() { ] ); } + +/// A route-style file gated by its own inner `#![cfg(..)]` (round-41 +/// R41-MR0-M1, the cron walk's twin): its jobs are registered under that +/// predicate, and a statically false inner gate drops them. +#[test] +fn inner_cfg_of_a_file_gates_every_job_in_it() { + let krate = crate_with(&[ + ("lib.rs", "mod admin;\nmod never;\n"), + ( + "admin.rs", + r#"#![cfg(feature = "admin")] + #[cron("1 * * * * *")] pub async fn tick() {}"#, + ), + ( + "never.rs", + r#"#![cfg(any())] + #[cron("2 * * * * *")] pub async fn gone() {}"#, + ), + ]); + crate::schema_macro::file_cache::bump_epoch(); + let src = krate.path().join("src"); + let jobs = discover(&[], Some(&src), Some(&src.join("lib.rs"))); + let found: Vec<(String, String, Vec)> = jobs + .iter() + .map(|job| { + ( + job.module_path.clone(), + job.function_name.clone(), + job.cfg.clone(), + ) + }) + .collect(); + assert_eq!( + found, + vec![( + "admin".to_owned(), + "tick".to_owned(), + vec!["feature = \"admin\"".to_owned()] + )] + ); +} diff --git a/crates/vespera_macro/src/vespera_impl/orchestrator.rs b/crates/vespera_macro/src/vespera_impl/orchestrator.rs index f4ed88b5..fa529e61 100644 --- a/crates/vespera_macro/src/vespera_impl/orchestrator.rs +++ b/crates/vespera_macro/src/vespera_impl/orchestrator.rs @@ -335,6 +335,19 @@ fn namespace_and_serialize_export_openapi( Ok((spec, sidecar)) } +/// Whether the content-addressed include copy of an export is the spec its +/// validated `sidecar` carries: the sidecar is the spec minus its closing `}`, +/// then the catch-all key and its templates, so the copy must be that prefix +/// closed again. A truncated or edited copy fails, and the export regenerates +/// (round-41 R41-MR6-L1). +fn export_include_matches(include: &Path, sidecar: &str) -> bool { + let key = format!(",\"{}\":", super::merge_lookup::CATCH_ALL_KEY); + let Some(at) = sidecar.rfind(&key) else { + return false; + }; + std::fs::read_to_string(include).is_ok_and(|content| content == format!("{}}}", &sidecar[..at])) +} + fn finish_export_metadata( mut metadata: CollectedMetadata, schema_storage: &HashMap, @@ -427,8 +440,11 @@ pub fn process_export_app( let cache_hit = cached.as_ref().is_some_and(|c| { c.is_fresh(&cache_key) && sidecar_matches(&spec_file, c.spec_json_hash, c.spec_json_fingerprint) - && c.spec_json_hash - .is_some_and(|hash| content_addressed(&export_dir, &include_stem, hash).is_file()) + && c.spec_json_hash.is_some_and(|hash| { + let include = content_addressed(&export_dir, &include_stem, hash); + std::fs::read_to_string(&spec_file) + .is_ok_and(|sidecar| export_include_matches(&include, &sidecar)) + }) }); // Build a single fully-extended `metadata` per branch — previously the 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 ffd9ce1b..54fe63bd 100644 --- a/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs +++ b/crates/vespera_macro/src/vespera_impl/orchestrator/tests_variants.rs @@ -85,6 +85,13 @@ fn test_harness_build_never_prunes_the_library_sidecar() { assert_ne!(sidecar_stem(&library_spec), sidecar_stem(&harness_spec)); assert_ne!(library_spec, harness_spec); assert!(harness_spec.exists()); + // The harness build's own prune with no grace period: the library copy + // survives because its stem differs, not because nothing was old enough. + crate::vespera_impl::sidecar_write::prune_superseded_older_than( + &harness_spec, + &sidecar_stem(&harness_spec), + std::time::Duration::ZERO, + ); assert!( library_spec.exists(), "the test harness build pruned {}", @@ -230,3 +237,29 @@ fn gating_a_module_in_the_crate_root_invalidates_the_cache() { "{gated}" ); } + +/// A cache hit regenerates unless the content-addressed include copy is the +/// spec its sidecar carries (round-41 R41-MR6-L1): a truncated or edited copy +/// fails, a copy matching the sidecar's spec passes. +#[test] +fn export_include_matches_only_the_spec_its_sidecar_carries() { + let dir = TempDir::new().unwrap(); + let include = dir.path().join("app.openapi.json"); + let spec = r#"{"openapi":"3.1.0"}"#; + let body = &spec[..spec.len() - 1]; + let key = crate::vespera_impl::merge_lookup::CATCH_ALL_KEY; + let sidecar = format!("{body},\"{key}\":{{}}}}"); + + fs::write(&include, spec).unwrap(); + assert!(export_include_matches(&include, &sidecar)); + fs::write(&include, &spec[..spec.len() - 4]).unwrap(); + assert!(!export_include_matches(&include, &sidecar)); + fs::write(&include, r#"{"openapi":"3.1.1"}"#).unwrap(); + assert!(!export_include_matches(&include, &sidecar)); + // A sidecar without its catch-all key carries no spec to compare with. + assert!(!export_include_matches(&include, spec)); + assert!(!export_include_matches( + &dir.path().join("missing.json"), + &sidecar + )); +} diff --git a/crates/vespera_macro/src/vespera_impl/sidecar_write.rs b/crates/vespera_macro/src/vespera_impl/sidecar_write.rs index efe78204..5262cfde 100644 --- a/crates/vespera_macro/src/vespera_impl/sidecar_write.rs +++ b/crates/vespera_macro/src/vespera_impl/sidecar_write.rs @@ -150,7 +150,7 @@ fn unix_secs(time: SystemTime) -> u64 { .as_secs() } -fn prune_superseded_older_than(keep: &Path, stem: &str, age: Duration) { +pub(super) fn prune_superseded_older_than(keep: &Path, stem: &str, age: Duration) { let Some((marker, entries)) = keep.parent().and_then(|dir| { Some(( record_selection(dir, stem, keep)?,