autumn-cli 0.7.0

CLI tool for the Autumn web framework
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
//! Source scan for `#[edge]` route markers and `edge_routes![]` registrations
//! (issue #1790).
//!
//! `autumn build` and `autumn doctor` both need to know, *without compiling the
//! project*, whether it has any edge-eligible routes: the build needs it to
//! decide whether to emit an edge capsule at all, and doctor needs it to run its
//! `edge_target` / `edge_routes` preflights in a project whose dependencies may
//! not even be fetched yet. Compiling to find out would defeat the purpose of a
//! preflight, so — exactly like `autumn a11y verify`, `autumn i18n check`, and
//! `autumn lifecycle check` — this is a source scanner: it parses each `.rs`
//! file under `src/` with `syn` and inspects the attributes each function
//! carries, and it tokenizes the same file to find `edge_routes![...]`
//! invocations and the handler identifiers they register.
//!
//! It records, per marked function: its name, the file and line it is declared
//! at, and whether the *same* function also carries one of the auth/guard
//! attributes (`#[secured]`, `#[authorize]`, `#[step_up]`, `#[throttle]`) that
//! the `#[edge]` macro rejects — the edge capsule has no session or auth state,
//! so that combination is a compile error, and catching it here turns a failed
//! build into a doctor line.
//!
//! **Recognition limits.** Like its sibling scanners this is a best-effort
//! textual pass, not a name resolver:
//!
//! - `#[edge]` is recognized under a bare `#[edge]` / `#[edge(needs(kv))]` path
//!   and under any qualified path whose **last** segment is `edge` (so
//!   `#[autumn_web::edge]` and `#[macros::edge]` are recognized). An `use ...
//!   ::edge as e;` rename is **not** resolved, so `#[e]` is invisible to the
//!   scan.
//! - Guard attributes are matched the same way (last path segment), on the same
//!   function only. A guard applied by an enclosing module or a layer is not
//!   visible here — that is the macro's and the router's job, not this scan's.
//! - `edge_routes![...]` is recognized as the identifier `edge_routes` followed
//!   by `!` and a delimited group, anywhere in the file (item position, inside a
//!   function body, nested in another macro's group). A re-exported alias of the
//!   macro under a different name is not recognized. Each comma-separated entry
//!   contributes its **last** path segment, so `edge_routes![handlers::greet]`
//!   registers `greet`.
//! - Only free functions are scanned, including those declared in *inline*
//!   modules (`mod routes { ... }`). A function generated by another macro, or
//!   declared in a file the scan does not reach, is invisible.
//! - `#[cfg(...)]` is not evaluated: a `#[cfg(feature = "x")]`-gated `#[edge]`
//!   function counts as an edge route whether or not that feature is enabled.
//! - A file that does not parse is skipped silently (it will fail the build with
//!   a far better message than this scanner could produce).
//!
//! Every consequence of a miss is conservative: a missed marker means the edge
//! capsule step is skipped (the native build is unaffected), and a missed
//! registration means at most a warning that names the function.

use std::collections::BTreeSet;
use std::path::{Path, PathBuf};
use std::str::FromStr as _;

use proc_macro2::{Delimiter, TokenStream, TokenTree};

/// Attribute names that cannot coexist with `#[edge]`: the edge capsule has no
/// session, no auth state, and no rate-limit store, and `#[intercept]` layers
/// are origin-only tower middleware that never run in the capsule, so the
/// `#[edge]` macro rejects each of these on the same handler.
pub const EDGE_GUARD_ATTRS: &[&str] = &["secured", "authorize", "step_up", "throttle", "intercept"];

/// One `#[edge]`-marked handler function found in the project's sources.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EdgeFn {
    /// The function's name — also the identifier `edge_routes![]` registers it by.
    pub name: String,
    /// Path of the declaring file, relative to the scan root (`src/routes/home.rs`).
    pub file: String,
    /// 1-based line of the function's declaration.
    pub line: usize,
    /// Guard attributes carried by the same function, in source order
    /// (a subset of [`EDGE_GUARD_ATTRS`]).
    pub guards: Vec<String>,
}

impl EdgeFn {
    /// `name @ file:line`, the form used in build warnings and doctor details.
    #[must_use]
    pub fn location(&self) -> String {
        format!("{} @ {}:{}", self.name, self.file, self.line)
    }
}

/// Result of scanning a project's sources for edge routes.
#[derive(Debug, Clone, Default)]
pub struct EdgeScan {
    /// Every `#[edge]`-marked function, in scan order (files sorted by path).
    pub functions: Vec<EdgeFn>,
    /// Handler identifiers registered by an `edge_routes![...]` invocation.
    pub registered: BTreeSet<String>,
    /// Number of `edge_routes![...]` invocations seen (0 means the app never
    /// registers its marked handlers, so the capsule would serve nothing).
    pub registrations: usize,
    /// Number of `.rs` files read.
    pub files_scanned: usize,
}

impl EdgeScan {
    /// `true` when the project has no `#[edge]`-marked function at all.
    #[must_use]
    pub const fn is_empty(&self) -> bool {
        self.functions.is_empty()
    }

    /// Names of every marked function, in scan order.
    #[must_use]
    pub fn names(&self) -> Vec<&str> {
        self.functions.iter().map(|f| f.name.as_str()).collect()
    }

    /// Marked functions that no `edge_routes![...]` invocation registers — they
    /// compile, but never reach the capsule's router.
    #[must_use]
    pub fn unregistered(&self) -> Vec<&EdgeFn> {
        self.functions
            .iter()
            .filter(|f| !self.registered.contains(&f.name))
            .collect()
    }

    /// Marked functions that an `edge_routes![...]` invocation registers — the
    /// routes the capsule actually serves.
    #[must_use]
    pub fn registered_fns(&self) -> Vec<&EdgeFn> {
        self.functions
            .iter()
            .filter(|f| self.registered.contains(&f.name))
            .collect()
    }

    /// Marked functions that also carry an auth/guard attribute — a combination
    /// the `#[edge]` macro rejects at compile time.
    #[must_use]
    pub fn guarded(&self) -> Vec<&EdgeFn> {
        self.functions
            .iter()
            .filter(|f| !f.guards.is_empty())
            .collect()
    }
}

/// Scan a set of in-memory `(file, source)` pairs. The pure core of the scan:
/// [`resolve_edge_scan`] is the thin filesystem wrapper around it, and every
/// unit test drives this directly with inline source strings.
#[must_use]
pub fn scan_sources(sources: &[(&str, &str)]) -> EdgeScan {
    let mut scan = EdgeScan::default();
    for (file, src) in sources {
        scan_source(file, src, &mut scan);
        scan.files_scanned += 1;
    }
    scan
}

/// Walk `project_root/src` and scan every `.rs` file below it. Paths are
/// recorded relative to `project_root` (`src/routes/home.rs`). A missing `src/`
/// yields an empty scan — a project without sources simply has no edge routes.
#[must_use]
pub fn resolve_edge_scan(project_root: &Path) -> EdgeScan {
    let mut files = Vec::new();
    collect_rs_files(&project_root.join("src"), &mut files);
    // Sorted so warnings, doctor details, and the build's route list are stable
    // across platforms and filesystem orderings.
    files.sort();

    // Read first, scan second, so the filesystem half and the pure half stay
    // separable: `scan_sources` is the same entry point the unit tests drive
    // with inline sources. An unreadable file is skipped, like the sibling
    // scanners do.
    let sources: Vec<(String, String)> = files
        .iter()
        .filter_map(|path| {
            let src = std::fs::read_to_string(path).ok()?;
            let rel = path
                .strip_prefix(project_root)
                .unwrap_or(path)
                .to_string_lossy()
                .replace('\\', "/");
            Some((rel, src))
        })
        .collect();
    let borrowed: Vec<(&str, &str)> = sources
        .iter()
        .map(|(file, src)| (file.as_str(), src.as_str()))
        .collect();
    scan_sources(&borrowed)
}

/// Recursively collect `.rs` files under `dir`, skipping build output, dot-dirs,
/// and `tests/` trees, and never following symlinks (a symlinked directory cycle
/// would otherwise hang this tool).
fn collect_rs_files(dir: &Path, out: &mut Vec<PathBuf>) {
    let Ok(entries) = std::fs::read_dir(dir) else {
        return;
    };
    for entry in entries.flatten() {
        let Ok(file_type) = entry.file_type() else {
            continue;
        };
        if file_type.is_symlink() {
            continue;
        }
        let path = entry.path();
        let name = entry.file_name();
        let name = name.to_string_lossy();
        if file_type.is_dir() {
            if name == "target" || name == "tests" || name.starts_with('.') {
                continue;
            }
            collect_rs_files(&path, out);
        } else if file_type.is_file() && path.extension().and_then(|s| s.to_str()) == Some("rs") {
            out.push(path);
        }
    }
}

/// Scan one source: `syn` for the marked functions, tokens for the registrations.
///
/// The two halves are independent on purpose — a file whose *items* fail to
/// parse can still contribute registrations, and vice versa.
fn scan_source(file: &str, src: &str, scan: &mut EdgeScan) {
    if let Ok(ast) = syn::parse_file(src) {
        scan_items(&ast.items, file, scan);
    }
    if let Ok(stream) = TokenStream::from_str(src) {
        collect_registrations(&stream, scan);
    }
}

/// Walk items, collecting `#[edge]`-marked functions and descending into inline
/// modules (`mod routes { ... }`). `mod routes;` has no items here — its file is
/// visited separately by the directory walk.
fn scan_items(items: &[syn::Item], file: &str, scan: &mut EdgeScan) {
    for item in items {
        match item {
            syn::Item::Fn(item_fn) => {
                if let Some(found) = edge_fn(&item_fn.attrs, &item_fn.sig, file) {
                    scan.functions.push(found);
                }
            }
            syn::Item::Mod(item_mod) => {
                if let Some((_, inner)) = &item_mod.content {
                    scan_items(inner, file, scan);
                }
            }
            _ => {}
        }
    }
}

/// The last `::` segment of an attribute path, e.g. `edge` for
/// `#[autumn_web::edge]`. Attribute paths with generic arguments are not
/// attribute macros, so a plain segment match is enough.
fn attr_name(attr: &syn::Attribute) -> Option<String> {
    attr.path().segments.last().map(|s| s.ident.to_string())
}

/// Build an [`EdgeFn`] when `attrs` contains an `#[edge]` marker.
fn edge_fn(attrs: &[syn::Attribute], sig: &syn::Signature, file: &str) -> Option<EdgeFn> {
    let names: Vec<String> = attrs.iter().filter_map(attr_name).collect();
    if !names.iter().any(|n| n == "edge") {
        return None;
    }
    let guards: Vec<String> = names
        .into_iter()
        .filter(|n| EDGE_GUARD_ATTRS.contains(&n.as_str()))
        .collect();
    Some(EdgeFn {
        name: sig.ident.to_string(),
        file: file.to_owned(),
        line: sig.ident.span().start().line,
        guards,
    })
}

/// Find every `edge_routes![...]` invocation in a token stream and record the
/// handler identifiers it registers.
///
/// Token-level rather than AST-level because the invocation is equally valid in
/// item position, inside a function body, or nested in another macro's group —
/// and because the registration list is a plain path list, so no parsing beyond
/// "last identifier of each comma-separated entry" is needed.
fn collect_registrations(stream: &TokenStream, scan: &mut EdgeScan) {
    let trees: Vec<TokenTree> = stream.clone().into_iter().collect();
    for (index, tree) in trees.iter().enumerate() {
        match tree {
            TokenTree::Group(group) => collect_registrations(&group.stream(), scan),
            TokenTree::Ident(ident) if ident == "edge_routes" => {
                let bang =
                    matches!(trees.get(index + 1), Some(TokenTree::Punct(p)) if p.as_char() == '!');
                if !bang {
                    // `fn edge_routes()` / a path mention — not an invocation.
                    continue;
                }
                let Some(TokenTree::Group(group)) = trees.get(index + 2) else {
                    continue;
                };
                if group.delimiter() == Delimiter::None {
                    continue;
                }
                scan.registrations += 1;
                for name in registered_idents(&group.stream()) {
                    scan.registered.insert(name);
                }
            }
            _ => {}
        }
    }
}

/// Split a macro argument list on top-level commas and keep each entry's last
/// identifier, so `handlers::greet, note,` yields `["greet", "note"]`.
fn registered_idents(stream: &TokenStream) -> Vec<String> {
    let mut out = Vec::new();
    let mut current: Option<String> = None;
    for tree in stream.clone() {
        match tree {
            TokenTree::Punct(p) if p.as_char() == ',' => {
                out.extend(current.take());
            }
            TokenTree::Ident(ident) => current = Some(ident.to_string()),
            _ => {}
        }
    }
    out.extend(current);
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    fn scan_one(src: &str) -> EdgeScan {
        scan_sources(&[("src/main.rs", src)])
    }

    #[test]
    fn bare_edge_attribute_is_found() {
        let scan = scan_one(
            r#"
            #[get("/hello")]
            #[edge]
            pub async fn hello() -> &'static str { "hi" }
            "#,
        );
        assert_eq!(scan.names(), vec!["hello"]);
        assert_eq!(scan.functions[0].file, "src/main.rs");
        assert!(scan.functions[0].guards.is_empty());
        assert!(!scan.is_empty());
    }

    #[test]
    fn qualified_edge_paths_are_recognized() {
        let scan = scan_sources(&[
            ("src/a.rs", "#[autumn_web::edge]\nfn a() {}"),
            ("src/b.rs", "#[macros::edge]\nfn b() {}"),
            ("src/c.rs", "#[edge(needs(kv))]\nfn c() {}"),
        ]);
        assert_eq!(scan.names(), vec!["a", "b", "c"]);
        assert_eq!(scan.files_scanned, 3);
    }

    #[test]
    fn unmarked_functions_are_ignored() {
        let scan = scan_one("#[get(\"/x\")]\nfn plain() {}\n#[edgy]\nfn other() {}");
        assert!(scan.is_empty(), "{:?}", scan.functions);
    }

    #[test]
    fn guard_attributes_on_the_same_fn_are_recorded() {
        let scan = scan_one(
            r#"
            #[get("/dash")]
            #[edge]
            #[secured]
            fn dash() {}

            #[get("/t")]
            #[edge]
            #[autumn_web::throttle(per_minute = 5)]
            fn throttled() {}

            #[get("/ok")]
            #[edge]
            fn ok() {}
            "#,
        );
        let guarded: Vec<&str> = scan.guarded().iter().map(|f| f.name.as_str()).collect();
        assert_eq!(guarded, vec!["dash", "throttled"]);
        assert_eq!(scan.functions[0].guards, vec!["secured".to_owned()]);
        assert_eq!(scan.functions[1].guards, vec!["throttle".to_owned()]);
    }

    #[test]
    fn every_guard_attribute_is_detected() {
        for guard in EDGE_GUARD_ATTRS {
            let scan = scan_one(&format!("#[edge]\n#[{guard}]\nfn g() {{}}"));
            assert_eq!(
                scan.guarded().len(),
                1,
                "#[{guard}] must be detected next to #[edge]"
            );
        }
    }

    #[test]
    fn registrations_collect_handler_idents() {
        let scan = scan_one(
            r"
            #[edge]
            fn greet() {}
            #[edge]
            fn note() {}

            pub fn edge_routes() -> Vec<EdgeRoute> {
                autumn_edge::edge_routes![handlers::greet, note,]
            }
            ",
        );
        assert_eq!(scan.registrations, 1);
        assert!(scan.registered.contains("greet"));
        assert!(scan.registered.contains("note"));
        assert!(scan.unregistered().is_empty());
        assert_eq!(
            scan.registered_fns()
                .iter()
                .map(|f| f.name.as_str())
                .collect::<Vec<_>>(),
            vec!["greet", "note"]
        );
    }

    #[test]
    fn a_function_named_edge_routes_is_not_a_registration() {
        let scan = scan_one(
            r"
            #[edge]
            fn greet() {}
            pub fn edge_routes() -> Vec<EdgeRoute> { Vec::new() }
            ",
        );
        assert_eq!(scan.registrations, 0);
        assert_eq!(
            scan.unregistered()
                .iter()
                .map(|f| f.name.as_str())
                .collect::<Vec<_>>(),
            vec!["greet"]
        );
    }

    #[test]
    fn unregistered_lists_only_the_missing_handlers() {
        let scan = scan_one(
            r"
            #[edge]
            fn greet() {}
            #[edge]
            fn stats() {}
            fn wire() { edge_routes![greet]; }
            ",
        );
        let missing: Vec<String> = scan.unregistered().iter().map(|f| f.location()).collect();
        assert_eq!(missing.len(), 1);
        assert!(
            missing[0].starts_with("stats @ src/main.rs:"),
            "{missing:?}"
        );
    }

    #[test]
    fn inline_modules_are_scanned() {
        let scan = scan_one(
            r"
            mod routes {
                #[edge]
                pub fn nested() {}
            }
            ",
        );
        assert_eq!(scan.names(), vec!["nested"]);
    }

    #[test]
    fn line_numbers_point_at_the_declaration() {
        let scan = scan_one("// header\n\n#[edge]\nfn marked() {}\n");
        assert_eq!(scan.functions[0].line, 4);
    }

    #[test]
    fn unparseable_source_is_skipped() {
        let scan = scan_one("fn broken( {");
        assert!(scan.is_empty());
        assert_eq!(scan.registrations, 0);
    }

    #[test]
    fn registrations_are_found_across_files() {
        let scan = scan_sources(&[
            ("src/handlers.rs", "#[edge]\nfn greet() {}"),
            (
                "src/bin/edge-capsule.rs",
                "fn main() { autumn_edge::serve(edge_routes![greet]); }",
            ),
        ]);
        assert_eq!(scan.registrations, 1);
        assert!(scan.unregistered().is_empty());
    }

    #[test]
    fn resolve_reads_src_tree_relative_to_project_root() {
        let dir = tempfile::tempdir().unwrap();
        std::fs::create_dir_all(dir.path().join("src/routes")).unwrap();
        std::fs::create_dir_all(dir.path().join("target")).unwrap();
        std::fs::write(
            dir.path().join("src/routes/home.rs"),
            "#[edge]\npub fn home() {}\n",
        )
        .unwrap();
        std::fs::write(dir.path().join("src/main.rs"), "fn main() {}\n").unwrap();
        // Build output must never be scanned.
        std::fs::write(dir.path().join("target/gen.rs"), "#[edge]\nfn gen() {}\n").unwrap();

        let scan = resolve_edge_scan(dir.path());
        assert_eq!(scan.names(), vec!["home"]);
        assert_eq!(scan.functions[0].file, "src/routes/home.rs");
        assert_eq!(scan.files_scanned, 2);
    }

    #[test]
    fn resolve_without_src_is_empty() {
        let dir = tempfile::tempdir().unwrap();
        let scan = resolve_edge_scan(dir.path());
        assert!(scan.is_empty());
        assert_eq!(scan.files_scanned, 0);
    }
}