vespera_macro 0.4.0

Procedural macros for Vespera - automatic route discovery and OpenAPI generation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Route-folder scanning and the path-normalization key that makes
//! `#[route]`'s cwd-relative span paths comparable with the
//! collector's absolute walk paths (the fast-path match).

use std::collections::HashMap;
use std::path::Path;

use crate::error::{MacroResult, err_call_site};

/// Single directory walk returning `(path, mtime)` pairs — the shared
/// scan that both cache fingerprinting and route collection consume.
pub fn scan_route_folder(folder_path: &Path) -> MacroResult<Vec<(std::path::PathBuf, u64)>> {
    crate::file_utils::collect_files_with_mtimes(folder_path).map_err(|e| err_call_site(format!("vespera! macro: failed to scan route folder '{}': {}. Verify the folder exists and is readable.", folder_path.display(), e)))
}

/// Build the cache fingerprint map (`.rs` files only) from a scan.
pub fn fingerprints_from_scan(scanned: &[(std::path::PathBuf, u64)]) -> HashMap<String, u64> {
    scanned
        .iter()
        .filter(|(file, _)| file.extension().is_some_and(|e| e == "rs"))
        .map(|(file, mtime)| (file.display().to_string(), *mtime))
        .collect()
}

#[cfg(test)]
mod tests {
    use std::fs;

    use rstest::rstest;
    use tempfile::TempDir;

    use super::*;
    use crate::collector::collect_metadata;
    use crate::file_utils::normalize_path_key;
    use crate::route_impl::StoredRouteInfo;

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

    //
    // The fast path matches `#[route]`'s `Span::local_file()` strings
    // (cwd-relative) against the collector's absolute walk paths.
    // Before normalization existed the keys NEVER matched and the
    // fast path was silently dead — every route file was re-parsed on
    // every cache miss with zero test failures.  These tests pin the
    // matching semantics so a regression is loud.

    #[rstest]
    // Relative path resolves against cwd → equals the absolute form.
    #[case("src/routes/users.rs", "/work/src/routes/users.rs", "/work")]
    // Separator style must not matter.
    #[case("src\\routes\\users.rs", "/work/src/routes/users.rs", "/work")]
    // `.` and `..` components fold on either side.
    #[case(
        "src/./routes/../routes/users.rs",
        "/work/src/routes/users.rs",
        "/work"
    )]
    #[case("src/routes/users.rs", "/work/extra/../src/routes/users.rs", "/work")]
    fn normalize_path_key_matches_equivalent_paths(
        #[case] stored: &str,
        #[case] walked: &str,
        #[case] cwd: &str,
    ) {
        let cwd = Path::new(cwd);
        assert_eq!(
            normalize_path_key(stored, cwd),
            normalize_path_key(walked, cwd),
            "stored={stored:?} and walked={walked:?} must produce the same key"
        );
    }

    #[test]
    fn normalize_path_key_distinguishes_different_files() {
        let cwd = Path::new("/work");
        assert_ne!(
            normalize_path_key("src/routes/users.rs", cwd),
            normalize_path_key("src/routes/posts.rs", cwd),
        );
    }

    #[cfg(windows)]
    #[test]
    fn normalize_path_key_windows_verbatim_prefix_and_case() {
        let cwd = Path::new("C:\\work");
        // `fs::canonicalize` output style (\\?\ verbatim prefix) must
        // match plain absolute paths, and drive/file case must fold.
        assert_eq!(
            normalize_path_key("\\\\?\\C:\\Work\\Src\\Users.RS", cwd),
            normalize_path_key("c:/work/src/users.rs", cwd),
        );
    }

    /// END-TO-END lock for the fast-path activation bug: storage
    /// carries a **cwd-relative** path (exactly what
    /// `Span::local_file()` yields) while the collector walks an
    /// absolute folder.  The route file is deliberately INVALID Rust —
    /// the slow path would fail with a parse error, so a successful
    /// collect proves the fast path matched without parsing.
    #[test]
    fn fast_path_matches_cwd_relative_storage_paths_without_parsing() {
        // cargo runs tests with cwd = this crate's manifest dir, so a
        // path under the workspace `target/` dir has a stable relative
        // form mirroring rustc's span paths.
        let unique = format!("vespera_fastpath_lock_{}", std::process::id());
        let abs_dir = Path::new(env!("CARGO_MANIFEST_DIR"))
            .join("..")
            .join("..")
            .join("target")
            .join(&unique);
        fs::create_dir_all(&abs_dir).expect("create test route dir");
        fs::write(
            abs_dir.join("users.rs"),
            "this is deliberately not rust {{{",
        )
        .expect("write route file");

        let relative_stored_path = format!("../../target/{unique}/users.rs");
        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_users".to_string(),
            method: None,
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            fn_sig_str: "async fn get_users() -> String".to_string(),
            file_path: Some(relative_stored_path),
        }];

        let result = collect_metadata(&abs_dir, "routes", &route_storage);
        fs::remove_dir_all(&abs_dir).ok();

        let (metadata, file_asts) = result.expect(
            "fast path must match the relative storage path WITHOUT parsing — \
             a parse error here means key normalization regressed and the \
             slow path ran against the invalid file",
        );
        assert_eq!(metadata.routes.len(), 1, "route must come from storage");
        assert!(
            file_asts.is_empty(),
            "fast path must not parse any file ASTs"
        );
    }

    /// Lock for the method-default bug: `#[route]` without a method
    /// stores `method: None`; the fast path must resolve it to "get"
    /// like the slow path does.  The original `unwrap_or_default()`
    /// produced "" — silently dropping such routes from the OpenAPI
    /// doc AND the generated router.
    #[test]
    fn fast_path_defaults_missing_method_to_get() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let file_path = create_temp_file(&temp_dir, "items.rs", "// placeholder\n");

        let route_storage = vec![StoredRouteInfo {
            fn_name: "list_items".to_string(),
            method: None, // bare `#[route]` / `#[route(path = ...)]`
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            fn_sig_str: "async fn list_items() -> String".to_string(),
            file_path: Some(file_path.display().to_string()),
        }];

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

        assert_eq!(metadata.routes.len(), 1);
        assert_eq!(
            metadata.routes[0].method, "get",
            "missing method must default to GET — \"\" silently drops the route"
        );

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_with_route_storage() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        // Create a .rs file that the fast path will match against
        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
    pub async fn get_users() -> String {
    "users".to_string()
    }
    "#,
        );

        let file_path_str = file_path.display().to_string();

        // Create StoredRouteInfo entries that match this file
        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_users".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: Some(vec!["users".to_string()]),
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: Some("Get all users".to_string()),
            fn_sig_str: "async fn get_users() -> String".to_string(),
            file_path: Some(file_path_str.clone()),
        }];

        let (metadata, file_asts) =
            collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        // Fast path should produce route metadata
        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.function_name, "get_users");
        assert_eq!(route.method, "get");
        assert_eq!(route.tags, Some(vec!["users".to_string()]));
        assert_eq!(route.description, Some("Get all users".to_string()));
        assert_eq!(route.module_path, "routes::users");

        // Fast path should NOT insert file ASTs (no parsing needed)
        assert!(
            file_asts.is_empty(),
            "Fast path should not populate file_asts"
        );

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_with_custom_path() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
    pub async fn get_user() -> String {
    "user".to_string()
    }
    "#,
        );

        let file_path_str = file_path.display().to_string();

        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_user".to_string(),
            method: Some("get".to_string()),
            custom_path: Some("/{id}".to_string()),
            error_status: Some(vec![404]),
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            fn_sig_str: "async fn get_user(id: i32) -> String".to_string(),
            file_path: Some(file_path_str.clone()),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        assert_eq!(route.path, "/users/{id}");
        assert!(route.error_status.is_some());
        assert_eq!(route.error_status.as_ref().unwrap(), &vec![404]);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_empty_folder_name() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "";

        let file_path = create_temp_file(
            &temp_dir,
            "users.rs",
            r#"
    pub async fn list_users() -> String {
    "list".to_string()
    }
    "#,
        );

        let file_path_str = file_path.display().to_string();

        let route_storage = vec![StoredRouteInfo {
            fn_name: "list_users".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            fn_sig_str: "async fn list_users() -> String".to_string(),
            file_path: Some(file_path_str),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        let route = &metadata.routes[0];
        // With empty folder_name, module_path should be just segments (no prefix)
        assert_eq!(route.module_path, "users");

        drop(temp_dir);
    }

    #[test]
    fn test_collect_metadata_fast_path_uses_stored_description() {
        let temp_dir = TempDir::new().expect("Failed to create temp dir");
        let folder_name = "routes";

        let file_path = create_temp_file(&temp_dir, "items.rs", "// placeholder\n");

        let file_path_str = file_path.display().to_string();

        // `#[route]` resolves the description (explicit attribute OR doc
        // comment) at expansion time — see `process_route_attribute`.
        // The collector fast path must pass it through verbatim WITHOUT
        // re-parsing `fn_sig_str`.
        let route_storage = vec![StoredRouteInfo {
            fn_name: "get_items".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: Some("List all items".to_string()),
            fn_sig_str:
                "/// List all items\npub async fn get_items() -> String { \"items\".to_string() }"
                    .to_string(),
            file_path: Some(file_path_str.clone()),
        }];

        let (metadata, _) = collect_metadata(temp_dir.path(), folder_name, &route_storage).unwrap();

        assert_eq!(metadata.routes.len(), 1);
        assert_eq!(
            metadata.routes[0].description,
            Some("List all items".to_string())
        );

        // A storage entry with no description stays None — the fast path
        // does NOT re-extract from fn_sig_str (expansion already did).
        let route_storage_none = vec![StoredRouteInfo {
            fn_name: "get_items".to_string(),
            method: Some("get".to_string()),
            custom_path: None,
            error_status: None,
            typed_responses: None,
            tags: None,
            security: None,
            headers: Vec::new(),
            success_status: None,
            operation_id: None,
            summary: None,
            request_example: None,
            response_example: None,
            deprecated: false,
            description: None,
            fn_sig_str: "async fn get_items() -> String".to_string(),
            file_path: Some(file_path_str),
        }];
        let (metadata, _) =
            collect_metadata(temp_dir.path(), folder_name, &route_storage_none).unwrap();
        assert_eq!(metadata.routes[0].description, None);

        drop(temp_dir);
    }

    #[test]
    fn test_collect_file_fingerprints_skips_non_rs_files() {
        // Exercises line 121: non-.rs files should be skipped
        let temp_dir = TempDir::new().expect("Failed to create temp dir");

        // Create both .rs and non-.rs files
        create_temp_file(&temp_dir, "valid.rs", "pub fn hello() {}");
        create_temp_file(&temp_dir, "readme.txt", "This is a readme");
        create_temp_file(&temp_dir, "data.json", "{}");
        create_temp_file(&temp_dir, "script.py", "print('hello')");

        let fingerprints = fingerprints_from_scan(&scan_route_folder(temp_dir.path()).unwrap());

        // Only .rs files should be in fingerprints
        assert_eq!(
            fingerprints.len(),
            1,
            "Only .rs files should be fingerprinted"
        );
        let keys: Vec<&String> = fingerprints.keys().collect();
        assert!(
            keys[0].ends_with("valid.rs"),
            "The only fingerprinted file should be valid.rs"
        );

        drop(temp_dir);
    }

    #[test]
    fn scan_route_folder_reports_missing_folder() {
        let missing = Path::new("target/vespera-missing-route-folder");
        let error = scan_route_folder(missing).expect_err("missing folder must fail scanning");
        let message = error.to_string();
        assert!(message.contains("failed to scan route folder"));
        assert!(message.contains("vespera-missing-route-folder"));
    }
}