cargo-rustapi 0.1.443

The official CLI tool for the RustAPI framework. Scaffold new projects, run development servers, and manage database migrations.
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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! Doctor command to check environment health

use anyhow::{bail, Context, Result};
use clap::Args;
use console::{style, Emoji};
use std::fs;
use std::path::{Path, PathBuf};
use tokio::process::Command;
use walkdir::WalkDir;

#[derive(Args, Debug, Clone)]
pub struct DoctorArgs {
    /// Project or workspace path to inspect.
    #[arg(long, default_value = ".", value_name = "PATH")]
    pub path: PathBuf,
    /// Exit with a non-zero code when warnings are found.
    #[arg(long, default_value_t = false)]
    pub strict: bool,
}

static CHECK: Emoji<'_, '_> = Emoji("", "+ ");
static WARN: Emoji<'_, '_> = Emoji("⚠️ ", "! ");
static ERROR: Emoji<'_, '_> = Emoji("", "x ");

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum DoctorStatus {
    Pass,
    Warn,
    Fail,
}

#[derive(Debug, Clone)]
struct DoctorCheck {
    status: DoctorStatus,
    name: &'static str,
    detail: String,
}

impl DoctorCheck {
    fn pass(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            status: DoctorStatus::Pass,
            name,
            detail: detail.into(),
        }
    }

    fn warn(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            status: DoctorStatus::Warn,
            name,
            detail: detail.into(),
        }
    }

    fn fail(name: &'static str, detail: impl Into<String>) -> Self {
        Self {
            status: DoctorStatus::Fail,
            name,
            detail: detail.into(),
        }
    }
}

#[derive(Debug, Default, Clone)]
struct WorkspaceSignals {
    production_defaults: bool,
    env_production: bool,
    health_endpoints: bool,
    health_checks: bool,
    request_id: bool,
    tracing: bool,
    shutdown: bool,
    shutdown_hooks: bool,
    structured_logging: bool,
    otel: bool,
    rate_limit: bool,
    security_headers: bool,
    timeout: bool,
    cors: bool,
    body_limit: bool,
}

pub async fn doctor(args: DoctorArgs) -> Result<()> {
    println!("{}", style("Checking environment health...").bold());
    println!();

    let mut checks = Vec::new();

    println!("{}", style("Toolchain").bold());
    checks.push(check_tool("rustc", &["--version"], "Rust compiler", true).await);
    checks.push(check_tool("cargo", &["--version"], "Cargo package manager", true).await);
    checks.push(
        check_tool(
            "cargo",
            &["watch", "--version"],
            "cargo-watch (for hot reload)",
            false,
        )
        .await,
    );
    checks.push(
        check_tool(
            "docker",
            &["--version"],
            "Docker (for containerization)",
            false,
        )
        .await,
    );
    checks.push(
        check_tool(
            "sqlx",
            &["--version"],
            "sqlx-cli (for database migrations)",
            false,
        )
        .await,
    );

    for check in &checks {
        print_check(check);
    }

    let inspect_path = if args.path.is_absolute() {
        args.path.clone()
    } else {
        std::env::current_dir()
            .context("failed to determine current directory")?
            .join(&args.path)
    };

    println!();
    println!("{}", style("Production checklist alignment").bold());

    if let Some(workspace_root) = find_workspace_root(&inspect_path) {
        print_check(&DoctorCheck::pass(
            "Workspace root",
            format!("found {}", workspace_root.display()),
        ));

        let project_checks = build_project_checks(&workspace_root)?;
        for check in &project_checks {
            print_check(check);
        }
        checks.extend(project_checks);
    } else {
        checks.push(DoctorCheck::warn(
            "Workspace root",
            format!(
                "No Cargo.toml found above {} — skipped project-level checklist checks",
                inspect_path.display()
            ),
        ));
        print_check(checks.last().unwrap());
    }

    println!();

    let failures = checks
        .iter()
        .filter(|check| check.status == DoctorStatus::Fail)
        .count();
    let warnings = checks
        .iter()
        .filter(|check| check.status == DoctorStatus::Warn)
        .count();

    if failures == 0 && warnings == 0 {
        println!("{}", style("Doctor check passed cleanly.").green());
        return Ok(());
    }

    if failures > 0 {
        println!(
            "{}",
            style(format!(
                "Doctor found {} failure(s) and {} warning(s).",
                failures, warnings
            ))
            .red()
        );
        bail!("doctor found {failures} failure(s)");
    }

    if args.strict {
        println!(
            "{}",
            style(format!(
                "Doctor found {} warning(s) and strict mode is enabled.",
                warnings
            ))
            .yellow()
        );
        bail!("doctor found {warnings} warning(s) in strict mode");
    }

    println!(
        "{}",
        style(format!(
            "Doctor completed with {} warning(s). Use --strict to fail on warnings.",
            warnings
        ))
        .yellow()
    );

    Ok(())
}

async fn check_tool(cmd: &str, args: &[&str], name: &'static str, required: bool) -> DoctorCheck {
    let output = Command::new(cmd).args(args).output().await;

    match output {
        Ok(out) if out.status.success() => {
            let version = String::from_utf8_lossy(&out.stdout)
                .lines()
                .next()
                .unwrap_or("")
                .trim()
                .to_string();
            DoctorCheck::pass(name, version)
        }
        Ok(_) => {
            if required {
                DoctorCheck::fail(name, "installed but returned error")
            } else {
                DoctorCheck::warn(name, "installed but returned error")
            }
        }
        Err(_) => {
            let msg = if cmd == "cargo" && args[0] == "watch" {
                "(install with: cargo install cargo-watch)"
            } else if cmd == "sqlx" {
                "(install with: cargo install sqlx-cli)"
            } else if cmd == "docker" {
                "(install Docker Desktop or Docker Engine)"
            } else {
                "(not found)"
            };

            if required {
                DoctorCheck::fail(name, msg)
            } else {
                DoctorCheck::warn(name, msg)
            }
        }
    }
}

fn print_check(check: &DoctorCheck) {
    let icon = match check.status {
        DoctorStatus::Pass => CHECK,
        DoctorStatus::Warn => WARN,
        DoctorStatus::Fail => ERROR,
    };

    let detail = match check.status {
        DoctorStatus::Pass => style(&check.detail).dim(),
        DoctorStatus::Warn => style(&check.detail).yellow(),
        DoctorStatus::Fail => style(&check.detail).red(),
    };

    println!("{} {} {}", icon, style(check.name).bold(), detail);
}

fn build_project_checks(workspace_root: &Path) -> Result<Vec<DoctorCheck>> {
    let signals = scan_workspace_signals(workspace_root)?;
    let mut checks = Vec::new();

    if workspace_root.join("scripts/check_quality.ps1").exists() {
        checks.push(DoctorCheck::pass(
            "Quality gate",
            "scripts/check_quality.ps1 is available",
        ));
    } else {
        checks.push(DoctorCheck::warn(
            "Quality gate",
            "scripts/check_quality.ps1 was not found; run your equivalent build/test gate before deploy",
        ));
    }

    checks.push(if signals.production_defaults {
        DoctorCheck::pass("Application baseline", "production_defaults usage detected")
    } else {
        DoctorCheck::warn(
            "Application baseline",
            "No production_defaults(...) or production_defaults_with_config(...) call detected",
        )
    });

    checks.push(if signals.env_production {
        DoctorCheck::pass(
            "Production environment",
            "RUSTAPI_ENV=production detected in project files",
        )
    } else {
        DoctorCheck::warn(
            "Production environment",
            "RUSTAPI_ENV=production was not detected in scanned config files",
        )
    });

    checks.push(if signals.production_defaults || signals.health_endpoints || signals.health_checks {
        DoctorCheck::pass(
            "Health and readiness",
            "Health endpoint configuration detected",
        )
    } else {
        DoctorCheck::warn(
            "Health and readiness",
            "No .health_endpoints(...), .with_health_check(...), or production preset usage detected",
        )
    });

    checks.push(if signals.shutdown || signals.shutdown_hooks {
        DoctorCheck::pass(
            "Graceful shutdown",
            "Shutdown flow or on_shutdown hook detected",
        )
    } else {
        DoctorCheck::warn(
            "Graceful shutdown",
            "No run_with_shutdown(...) or .on_shutdown(...) usage detected",
        )
    });

    checks.push(
        if signals.production_defaults || (signals.request_id && signals.tracing) {
            DoctorCheck::pass(
                "Request IDs and tracing",
                "Request ID and tracing signals detected",
            )
        } else {
            DoctorCheck::warn(
                "Request IDs and tracing",
                "RequestIdLayer/tracing signals were not clearly detected",
            )
        },
    );

    checks.push(if signals.structured_logging || signals.otel {
        DoctorCheck::pass(
            "Observability",
            "Structured logging or OpenTelemetry configuration detected",
        )
    } else {
        DoctorCheck::warn(
            "Observability",
            "No StructuredLoggingLayer/structured_logging(...) or OtelLayer/otel(...) usage detected",
        )
    });

    checks.push(
        if signals.rate_limit || signals.security_headers || signals.timeout || signals.cors {
            DoctorCheck::pass(
                "Edge protections",
                "Detected timeout, rate limit, CORS, or security header configuration",
            )
        } else {
            DoctorCheck::warn(
                "Edge protections",
                "No timeout, rate limit, CORS, or security header configuration was detected",
            )
        },
    );

    checks.push(if signals.body_limit {
        DoctorCheck::pass(
            "Payload management",
            "Body limit configuration detected",
        )
    } else {
        DoctorCheck::warn(
            "Payload management",
            "No body limit override detected; validate that the default 1 MB limit matches your traffic",
        )
    });

    Ok(checks)
}

fn scan_workspace_signals(workspace_root: &Path) -> Result<WorkspaceSignals> {
    let mut signals = WorkspaceSignals::default();

    for entry in WalkDir::new(workspace_root)
        .into_iter()
        .filter_entry(|entry| should_scan(entry.path()))
    {
        let entry = entry?;
        if !entry.file_type().is_file() || !is_scannable_file(entry.path()) {
            continue;
        }

        let contents = match fs::read_to_string(entry.path()) {
            Ok(contents) => contents,
            Err(_) => continue,
        };

        signals.production_defaults |= contains_any(
            &contents,
            &[".production_defaults(", ".production_defaults_with_config("],
        );
        signals.health_endpoints |= contains_any(
            &contents,
            &[
                ".health_endpoints(",
                ".health_endpoint_config(",
                "HealthEndpointConfig",
            ],
        );
        signals.health_checks |= contents.contains(".with_health_check(");
        signals.request_id |= contents.contains("RequestIdLayer");
        signals.tracing |= contains_any(&contents, &["TracingLayer", "tracing_subscriber"]);
        signals.shutdown |= contents.contains("run_with_shutdown(");
        signals.shutdown_hooks |= contents.contains(".on_shutdown(");
        signals.structured_logging |= contains_any(
            &contents,
            &["StructuredLoggingLayer", "structured_logging("],
        );
        signals.otel |= contains_any(&contents, &["OtelLayer", "otel("]);
        signals.rate_limit |= contains_any(&contents, &["RateLimitLayer", "rate_limit("]);
        signals.security_headers |=
            contains_any(&contents, &["SecurityHeadersLayer", "security_headers("]);
        signals.timeout |= contains_any(&contents, &["TimeoutLayer", "timeout("]);
        signals.cors |= contains_any(&contents, &["CorsLayer", "cors("]);
        signals.body_limit |= contains_any(&contents, &["BodyLimitLayer", ".body_limit("]);
        signals.env_production |= contains_any(
            &contents,
            &[
                "RUSTAPI_ENV=production",
                "RUSTAPI_ENV: production",
                "RUSTAPI_ENV = \"production\"",
                "RUSTAPI_ENV','production",
                "RUSTAPI_ENV\", \"production\"",
            ],
        );
    }

    Ok(signals)
}

fn find_workspace_root(start: &Path) -> Option<PathBuf> {
    let mut current = if start.is_dir() {
        start.to_path_buf()
    } else {
        start.parent()?.to_path_buf()
    };

    loop {
        if current.join("Cargo.toml").exists() {
            return Some(current);
        }

        if !current.pop() {
            return None;
        }
    }
}

fn contains_any(haystack: &str, patterns: &[&str]) -> bool {
    patterns.iter().any(|pattern| haystack.contains(pattern))
}

fn should_scan(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
        return true;
    };

    !matches!(
        name,
        ".git" | "target" | "node_modules" | ".next" | "dist" | "build"
    )
}

fn is_scannable_file(path: &Path) -> bool {
    let Some(name) = path.file_name().and_then(|name| name.to_str()) else {
        return false;
    };

    if matches!(name, ".env" | ".env.example" | "Dockerfile") {
        return true;
    }

    matches!(
        path.extension().and_then(|ext| ext.to_str()),
        Some("rs" | "toml" | "md" | "yml" | "yaml" | "env")
    )
}

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

    #[test]
    fn find_workspace_root_walks_upwards() {
        let dir = tempdir().unwrap();
        fs::write(dir.path().join("Cargo.toml"), "[workspace]\nmembers=[]\n").unwrap();
        let nested = dir.path().join("crates").join("app").join("src");
        fs::create_dir_all(&nested).unwrap();

        let root = find_workspace_root(&nested).unwrap();
        assert_eq!(root, dir.path());
    }

    #[test]
    fn scan_workspace_signals_detects_production_patterns() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname='demo'\nversion='0.1.0'\n",
        )
        .unwrap();
        fs::write(dir.path().join(".env"), "RUSTAPI_ENV=production\n").unwrap();

        let src_dir = dir.path().join("src");
        fs::create_dir_all(&src_dir).unwrap();
        fs::write(
            src_dir.join("main.rs"),
            r#"
            use rustapi_rs::prelude::*;

            fn app() {
                let _app = RustApi::new()
                    .production_defaults("svc")
                    .with_health_check(|| async { Ok(()) })
                    .on_shutdown(|| async {})
                    .layer(StructuredLoggingLayer::default())
                    .layer(RateLimitLayer::new(100, std::time::Duration::from_secs(60)))
                    .layer(BodyLimitLayer::new(2 * 1024 * 1024));
            }
            "#,
        )
        .unwrap();

        let signals = scan_workspace_signals(dir.path()).unwrap();
        assert!(signals.production_defaults);
        assert!(signals.env_production);
        assert!(signals.health_checks);
        assert!(signals.shutdown_hooks);
        assert!(signals.structured_logging);
        assert!(signals.rate_limit);
        assert!(signals.body_limit);
    }

    #[test]
    fn build_project_checks_warns_when_signals_are_missing() {
        let dir = tempdir().unwrap();
        fs::write(
            dir.path().join("Cargo.toml"),
            "[package]\nname='demo'\nversion='0.1.0'\n",
        )
        .unwrap();
        fs::create_dir_all(dir.path().join("src")).unwrap();
        fs::write(dir.path().join("src").join("main.rs"), "fn main() {}\n").unwrap();

        let checks = build_project_checks(dir.path()).unwrap();
        assert!(checks
            .iter()
            .any(|check| check.status == DoctorStatus::Warn));
        assert!(checks
            .iter()
            .any(|check| check.name == "Application baseline"));
    }
}