autumn-cli 0.9.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
//! Integration tests for the edge lane of `autumn build` and the `edge_target`
//! / `edge_routes` doctor checks (issue #1790).
//!
//! Each test scaffolds a throwaway project in a `TempDir` and drives the real
//! `autumn` binary against it. The fixture `.rs` files are only ever *parsed* by
//! the source scanner, so they need to be syntactically valid Rust but need not
//! compile or link — and the scaffold's `Cargo.toml` deliberately has no
//! dependencies, so nothing here may reach a real `cargo build`.
//!
//! The `--edge` refusal must occur before the native cargo build. These tests
//! use the empty-`PATH` runner, where `cargo` cannot start. They also assert
//! that no compile started.

use std::fs;
use std::path::Path;
use std::process::{Command, Output};

use tempfile::TempDir;

use crate::common::run_autumn;

const fn autumn_bin() -> &'static str {
    env!("CARGO_BIN_EXE_autumn")
}

/// A minimal project: a dependency-free `Cargo.toml` plus the given
/// `(relative path, contents)` sources.
fn project(files: &[(&str, &str)]) -> TempDir {
    let dir = tempfile::tempdir().expect("create temp project dir");
    fs::write(
        dir.path().join("Cargo.toml"),
        "[workspace]\n\n[package]\nname = \"edgeapp\"\nversion = \"0.1.0\"\nedition = \"2021\"\n",
    )
    .expect("write Cargo.toml");
    for (rel, contents) in files {
        let path = dir.path().join(rel);
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent).expect("create source dir");
        }
        fs::write(path, contents).expect("write source");
    }
    dir
}

/// Like [`project`], but `Cargo.toml` is replaced wholesale by `manifest`
/// afterward — for tests that need a manifest shape `project`'s fixed one
/// doesn't cover (a virtual workspace root, `autobins = false`, a custom
/// `[[bin]]` entry).
fn project_with_manifest(manifest: &str, files: &[(&str, &str)]) -> TempDir {
    let dir = project(files);
    fs::write(dir.path().join("Cargo.toml"), manifest).expect("overwrite Cargo.toml");
    dir
}

/// Run `autumn doctor --json` in `root` and return the parsed report.
///
/// Runs with an empty `PATH` (mirrors `common::run_autumn`'s
/// `psql_free_path` pattern) rather than the ambient one: none of this
/// file's tests assert on `edge_target`'s pass/fail outcome — the only check
/// here whose result depends on a real toolchain probe — so there is nothing
/// for the ambient PATH to serve, and the empty PATH keeps the run hermetic.
fn doctor_json(root: &Path) -> (serde_json::Value, Option<i32>) {
    let empty_path = tempfile::tempdir().expect("create empty PATH dir");
    let out: Output = Command::new(autumn_bin())
        .args(["doctor", "--json"])
        .current_dir(root)
        .env("PATH", empty_path.path())
        .output()
        .expect("failed to run autumn doctor");
    let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
    // Parse from the first `{` rather than assuming the whole of stdout is
    // one clean JSON blob: a stray character ahead of it would otherwise
    // fail with a confusing "expected value at line 1 column 1" instead of
    // this clearer panic.
    let json_str = stdout
        .find('{')
        .map_or(stdout.as_str(), |idx| &stdout[idx..]);
    let report = serde_json::from_str(json_str).unwrap_or_else(|e| {
        panic!(
            "`autumn doctor --json` must emit parseable JSON: {e}\nstdout:\n{stdout}\nstderr:\n{}",
            String::from_utf8_lossy(&out.stderr)
        )
    });
    (report, out.status.code())
}

/// Pull one check out of a `doctor --json` report by name.
fn check<'a>(report: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
    report["checks"]
        .as_array()
        .expect("report carries a checks array")
        .iter()
        .find(|c| c["name"] == name)
        .unwrap_or_else(|| panic!("doctor must emit a `{name}` check; got {report}"))
}

/// A handler marked `#[edge]` that also carries `#[secured]` — a pair the
/// `#[edge]` macro rejects, so doctor must fail on it before the build does.
const GUARDED_EDGE_APP: &str = r#"
use autumn_web::prelude::*;

#[get("/dashboard")]
#[edge]
#[secured]
pub async fn dashboard() -> &'static str {
    "private"
}

pub fn edge_route_list() -> Vec<EdgeRoute> {
    edge_routes![dashboard]
}
"#;

/// A well-formed edge handler that nothing registers.
const UNREGISTERED_EDGE_APP: &str = r#"
use autumn_web::prelude::*;

#[get("/greet")]
#[edge]
pub async fn greet() -> &'static str {
    "hello"
}
"#;

/// An ordinary app with no edge routes at all.
const PLAIN_APP: &str = r#"
use autumn_web::prelude::*;

#[get("/")]
pub async fn home() -> &'static str {
    "hello"
}
"#;

/// A well-formed edge handler that is properly registered — no guard, no
/// missing registration, so `edge_routes` only turns non-Pass on the
/// capsule-bin check.
const REGISTERED_EDGE_APP: &str = r#"
use autumn_web::prelude::*;

#[get("/greet")]
#[edge]
pub async fn greet() -> &'static str {
    "hello"
}

pub fn edge_route_list() -> Vec<EdgeRoute> {
    edge_routes![greet]
}
"#;

/// An edge handler that needs a database: a capability the edge cannot give.
const DB_EDGE_APP: &str = r#"
use autumn_web::prelude::*;

#[get("/dashboard")]
#[edge(needs(db))]
pub async fn dashboard(db: Db) -> &'static str {
    "rows"
}

pub fn edge_route_list() -> Vec<EdgeRoute> {
    edge_routes![dashboard]
}
"#;

/// A warning: the scan is a best guess, and rustc is the authority.
/// `--strict` turns it into a non-zero exit.
#[test]
fn doctor_warns_on_edge_route_with_unsupported_capability() {
    let dir = project(&[
        ("src/main.rs", DB_EDGE_APP),
        (
            "src/bin/edge-capsule.rs",
            "fn main() { autumn_edge::serve(edgeapp::edge_route_list()); }\n",
        ),
    ]);
    let (report, _) = doctor_json(dir.path());

    let caps = check(&report, "edge_capabilities");
    assert_eq!(caps["status"], "warn", "{caps}");
    let detail = caps["detail"].as_str().unwrap_or_default();
    assert!(detail.contains("dashboard @ src/main.rs:"), "{detail}");
    assert!(detail.contains("needs(db)"), "{detail}");
    assert!(detail.contains("`Db`"), "{detail}");
    assert!(
        caps["hint"]
            .as_str()
            .unwrap_or_default()
            .contains("Remove #[edge]"),
        "{caps}"
    );
}

/// The build names the route before it compiles. It does not stop on the
/// scan alone: the scan reads files that `mod` may not declare, so rustc
/// decides. Here the empty `PATH` makes cargo fail.
/// A file that no `mod` declares is not compiled. doctor must not fail the
/// app for a route in it, even one registered in the same file.
#[test]
fn doctor_only_warns_for_an_unsupported_route_in_an_orphan_file() {
    let dir = project(&[
        ("src/main.rs", "fn main() {}\n"),
        ("src/old_routes.rs", DB_EDGE_APP),
        (
            "src/bin/edge-capsule.rs",
            "fn main() { autumn_edge::serve(edgeapp::edge_route_list()); }\n",
        ),
    ]);
    let (report, _) = doctor_json(dir.path());

    let caps = check(&report, "edge_capabilities");
    assert_eq!(caps["status"], "warn", "{caps}");
    assert!(
        caps["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("dashboard @ src/old_routes.rs:"),
        "{caps}"
    );
}

#[test]
fn build_names_an_unsupported_edge_capability_before_compiling() {
    let dir = project(&[
        ("src/main.rs", DB_EDGE_APP),
        (
            "src/bin/edge-capsule.rs",
            "fn main() { autumn_edge::serve(edgeapp::edge_route_list()); }\n",
        ),
    ]);
    let (stdout, stderr, code) = run_autumn(dir.path(), &["build"], &[]);
    let combined = format!("{stdout}{stderr}");

    assert_ne!(code, Some(0), "{combined}");
    let named = combined
        .find("dashboard @ src/main.rs:")
        .unwrap_or_else(|| panic!("the route must be named: {combined}"));
    assert!(combined.contains("needs(db)"), "{combined}");
    assert!(combined.contains("Remove #[edge]"), "{combined}");
    if let Some(compiling) = combined.find("Compiling") {
        assert!(
            named < compiling,
            "the name must come before the compile: {combined}"
        );
    }
}

#[test]
fn doctor_fails_on_edge_route_with_auth_guard() {
    let dir = project(&[
        ("src/main.rs", GUARDED_EDGE_APP),
        (
            "src/bin/edge-capsule.rs",
            "fn main() { autumn_edge::serve(edgeapp::edge_route_list()); }\n",
        ),
    ]);
    let (report, code) = doctor_json(dir.path());

    assert_ne!(
        code,
        Some(0),
        "an #[edge] route behind #[secured] must fail doctor: {report}"
    );
    let edge_routes = check(&report, "edge_routes");
    assert_eq!(edge_routes["status"], "fail", "{edge_routes}");
    let detail = edge_routes["detail"].as_str().unwrap_or_default();
    assert!(
        detail.contains("dashboard @ src/main.rs:"),
        "detail must name the handler and its location: {detail}"
    );
    assert!(detail.contains("#[secured]"), "{detail}");
    assert!(
        edge_routes["hint"]
            .as_str()
            .unwrap_or_default()
            .contains("unauthenticated read-path"),
        "the hint must say why the pair is impossible: {edge_routes}"
    );
}

#[test]
fn doctor_warns_on_unregistered_edge_route() {
    let dir = project(&[("src/main.rs", UNREGISTERED_EDGE_APP)]);
    let (report, _) = doctor_json(dir.path());

    let edge_routes = check(&report, "edge_routes");
    assert_eq!(edge_routes["status"], "warn", "{edge_routes}");
    assert!(
        edge_routes["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("greet @ src/main.rs:"),
        "{edge_routes}"
    );
    assert!(
        edge_routes["hint"]
            .as_str()
            .unwrap_or_default()
            .contains("edge_routes![]"),
        "{edge_routes}"
    );
}

#[test]
fn doctor_edge_checks_pass_without_edge_routes() {
    // Deliberately asserts on the edge checks rather than on the exit code: this
    // must hold on a runner that has no `wasm32-wasip1` target installed, which
    // is exactly what "no edge routes ⇒ no wasm requirement" means.
    let dir = project(&[("src/main.rs", PLAIN_APP)]);
    let (report, _) = doctor_json(dir.path());

    for name in ["edge_target", "edge_routes", "edge_capabilities"] {
        let result = check(&report, name);
        assert_eq!(result["status"], "pass", "{result}");
        assert_eq!(result["detail"], "no #[edge] routes", "{result}");
    }
}

#[test]
fn doctor_warns_from_a_virtual_workspace_root() {
    // A bare workspace root (`[workspace]`, no `[package]`) has no sources
    // of its own — real sources live under a member crate. All edge checks
    // must warn instead of silently reporting "no #[edge] routes".
    let dir = tempfile::tempdir().expect("create temp project dir");
    fs::write(
        dir.path().join("Cargo.toml"),
        "[workspace]\nmembers = [\"app\"]\n",
    )
    .expect("write Cargo.toml");
    let (report, _) = doctor_json(dir.path());

    for name in ["edge_target", "edge_routes", "edge_capabilities"] {
        let result = check(&report, name);
        assert_eq!(result["status"], "warn", "{result}");
        assert_eq!(
            result["detail"], "Cargo.toml is a workspace root with no [package]",
            "{result}"
        );
        assert!(
            result["hint"]
                .as_str()
                .unwrap_or_default()
                .contains("member crate directory"),
            "{result}"
        );
    }
}

#[test]
fn doctor_warns_capsule_missing_when_autobins_disabled_and_undeclared() {
    // The conventional file exists on disk, but with `autobins = false` and
    // no explicit `[[bin]]` entry, cargo never turns it into a build target.
    let dir = project_with_manifest(
        "[workspace]\n\n[package]\nname = \"edgeapp\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\
         autobins = false\n",
        &[
            ("src/main.rs", REGISTERED_EDGE_APP),
            (
                "src/bin/edge-capsule.rs",
                "fn main() { autumn_edge::serve(edgeapp::edge_route_list()); }\n",
            ),
        ],
    );
    let (report, _) = doctor_json(dir.path());

    let edge_routes = check(&report, "edge_routes");
    assert_eq!(edge_routes["status"], "warn", "{edge_routes}");
    assert!(
        edge_routes["detail"]
            .as_str()
            .unwrap_or_default()
            .contains("edge-capsule.rs is missing"),
        "{edge_routes}"
    );
}

#[test]
fn doctor_honors_a_custom_capsule_bin_path() {
    // A custom `[[bin]] path` for `edge-capsule` must be checked directly,
    // not the conventional `src/bin/edge-capsule.rs` (which doesn't exist
    // here at all). The registration lives ONLY in `cmd/edge.rs` — outside
    // `src/` — so this also proves that file is scanned, not just probed for
    // existence (issue #2244).
    let dir = project_with_manifest(
        "[workspace]\n\n[package]\nname = \"edgeapp\"\nversion = \"0.1.0\"\nedition = \"2021\"\n\n\
         [[bin]]\nname = \"edge-capsule\"\npath = \"cmd/edge.rs\"\n",
        &[
            ("src/main.rs", UNREGISTERED_EDGE_APP),
            (
                "cmd/edge.rs",
                "fn main() { autumn_edge::serve(edge_routes![greet]); }\n",
            ),
        ],
    );
    let (report, _) = doctor_json(dir.path());

    let edge_routes = check(&report, "edge_routes");
    assert_eq!(
        edge_routes["status"], "pass",
        "a registration written only in a custom [[bin]] path must be seen, \
         not reported as missing: {edge_routes}"
    );
}

#[test]
fn build_edge_flag_without_edge_routes_fails_before_compiling() {
    let dir = project(&[("src/main.rs", PLAIN_APP)]);
    // Empty PATH: a `cargo` invocation could not even spawn here, so reaching
    // the native build would surface as a different failure entirely.
    let (stdout, stderr, code) = run_autumn(dir.path(), &["build", "--edge"], &[]);
    let combined = format!("{stdout}{stderr}");

    assert_ne!(code, Some(0), "{combined}");
    assert!(
        combined.contains("no #[edge] routes found"),
        "the error must say what is missing: {combined}"
    );
    assert!(
        combined.contains("edge_routes![]"),
        "the error must say how to fix it: {combined}"
    );
    assert!(
        !combined.contains("Compiling"),
        "the flag check must run before the native build: {combined}"
    );
}

/// A build that makes a capsule checks for the WASI target before any cargo
/// build (#1790). The empty `PATH` hides `rustc`, so the target is missing.
#[test]
fn build_with_edge_routes_checks_the_wasi_target_before_compiling() {
    let dir = project(&[
        ("src/main.rs", UNREGISTERED_EDGE_APP),
        (
            "src/bin/edge-capsule.rs",
            "fn main() { autumn_edge::serve(edge_routes![greet]); }\n",
        ),
    ]);
    for args in [&["build"][..], &["build", "--embed"][..]] {
        let (stdout, stderr, code) = run_autumn(dir.path(), args, &[]);
        let combined = format!("{stdout}{stderr}");

        assert_ne!(code, Some(0), "{args:?}: {combined}");
        assert!(
            combined.contains("`wasm32-wasip1` target is not installed"),
            "{args:?}: the error must name the missing target: {combined}"
        );
        assert!(
            combined.contains("rustup target add wasm32-wasip1"),
            "{args:?}: the error must say how to fix it: {combined}"
        );
        assert!(
            !combined.contains("Compiling"),
            "{args:?}: the check must run before the native build: {combined}"
        );
    }
}