fraiseql-cli 2.3.2

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//! Doctor command — systematic diagnostic checks for common FraiseQL setup problems.
//!
//! Usage:
//!   fraiseql doctor
//!   fraiseql doctor --config fraiseql.toml --schema schema.compiled.json
//!   fraiseql doctor --json

use std::{net::TcpStream, path::Path, time::Duration};

use serde::{Deserialize, Serialize};

use crate::config::toml_schema::TomlSchema;

// ─── Types ────────────────────────────────────────────────────────────────────

/// Outcome of a single diagnostic check.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
#[non_exhaustive]
pub enum CheckStatus {
    /// Check passed.
    Pass,
    /// Check produced a non-fatal warning.
    Warn,
    /// Check failed (fatal).
    Fail,
}

/// A single diagnostic check result.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DoctorCheck {
    /// Short display name shown in the report.
    pub name:   &'static str,
    /// Outcome of the check.
    pub status: CheckStatus,
    /// One-line detail appended after the name.
    pub detail: String,
    /// Optional actionable hint shown on the next line when status is not Pass.
    pub hint:   Option<String>,
}

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

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

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

// ─── Individual checks ────────────────────────────────────────────────────────

/// Check that the compiled schema file exists and is readable.
pub fn check_schema_exists(path: &Path) -> DoctorCheck {
    if path.exists() {
        DoctorCheck::pass("Schema file exists", path.display().to_string())
    } else {
        DoctorCheck::fail(
            "Schema file exists",
            format!("not found: {}", path.display()),
            "Run `fraiseql compile fraiseql.toml` to generate schema.compiled.json",
        )
    }
}

/// Check that the compiled schema file is valid JSON.
pub fn check_schema_parses(path: &Path) -> DoctorCheck {
    match std::fs::read_to_string(path) {
        Err(e) => DoctorCheck::fail(
            "Schema parses",
            format!("cannot read: {e}"),
            "Check file permissions or run `fraiseql compile`",
        ),
        Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
            Err(e) => DoctorCheck::fail(
                "Schema parses",
                format!("JSON parse error: {e}"),
                "Run `fraiseql compile fraiseql.toml` to regenerate the schema",
            ),
            Ok(schema) => {
                let types = schema.get("types").and_then(|v| v.as_array()).map_or(0, Vec::len);
                let queries = schema.get("queries").and_then(|v| v.as_array()).map_or(0, Vec::len);
                let mutations =
                    schema.get("mutations").and_then(|v| v.as_array()).map_or(0, Vec::len);
                DoctorCheck::pass(
                    "Schema parses",
                    format!("types={types}, queries={queries}, mutations={mutations}"),
                )
            },
        },
    }
}

/// Check the schema format version field.
pub fn check_schema_version(path: &Path) -> DoctorCheck {
    let Ok(content) = std::fs::read_to_string(path) else {
        return DoctorCheck::warn(
            "Schema format version",
            "could not read schema file",
            "Ensure schema.compiled.json is readable",
        );
    };
    let Ok(schema) = serde_json::from_str::<serde_json::Value>(&content) else {
        return DoctorCheck::warn(
            "Schema format version",
            "schema is not valid JSON — version check skipped",
            "Run `fraiseql compile` to regenerate",
        );
    };

    match schema.get("version").and_then(serde_json::Value::as_u64) {
        None => DoctorCheck::warn(
            "Schema format version",
            "no version field (older schema)",
            "Run `fraiseql compile fraiseql.toml` to get a versioned schema",
        ),
        Some(v) if v == 1 => {
            DoctorCheck::pass("Schema format version", format!("version={v} (current)"))
        },
        Some(v) => DoctorCheck::warn(
            "Schema format version",
            format!("version={v} (expected 1)"),
            "Run `fraiseql compile fraiseql.toml` to recompile with the current compiler",
        ),
    }
}

/// Check whether `fraiseql.toml` exists.
pub fn check_toml_exists(path: &Path) -> DoctorCheck {
    if path.exists() {
        DoctorCheck::pass("fraiseql.toml found", path.display().to_string())
    } else {
        DoctorCheck::warn(
            "fraiseql.toml found",
            format!("not found: {} (using defaults)", path.display()),
            "Create fraiseql.toml with `fraiseql init` or provide --config",
        )
    }
}

/// Parse `fraiseql.toml`. Only called when the file actually exists.
pub fn check_toml_parses(path: &Path) -> DoctorCheck {
    let content = match std::fs::read_to_string(path) {
        Ok(c) => c,
        Err(e) => {
            return DoctorCheck::fail(
                "TOML syntax valid",
                format!("cannot read: {e}"),
                "Check file permissions",
            );
        },
    };
    match TomlSchema::parse_toml(&content) {
        Ok(_) => DoctorCheck::pass("TOML syntax valid", ""),
        Err(e) => {
            // Keep only the first line of the error to avoid overwhelming output.
            let first_line = e.to_string();
            let short = first_line.lines().next().unwrap_or("parse error");
            DoctorCheck::fail(
                "TOML syntax valid",
                format!("parse error: {short}"),
                "Fix TOML syntax in fraiseql.toml and retry",
            )
        },
    }
}

/// Check whether `DATABASE_URL` is set in the environment.
pub fn check_database_url_set(db_url_override: Option<&str>) -> DoctorCheck {
    let val = db_url_override
        .map(std::borrow::Cow::Borrowed)
        .or_else(|| std::env::var("DATABASE_URL").ok().map(std::borrow::Cow::Owned));
    if val.is_some() {
        DoctorCheck::pass("DATABASE_URL set", "")
    } else {
        DoctorCheck::fail(
            "DATABASE_URL set",
            "not set",
            "Set DATABASE_URL=postgres://user:pass@host:port/dbname in your environment",
        )
    }
}

/// Attempt a TCP connection to the database host:port extracted from the URL.
///
/// This does **not** run any SQL — it only validates that a TCP socket can be
/// opened within a 5-second timeout.
pub fn check_db_reachable(db_url_override: Option<&str>) -> DoctorCheck {
    let url_str = match db_url_override
        .map(std::borrow::Cow::Borrowed)
        .or_else(|| std::env::var("DATABASE_URL").ok().map(std::borrow::Cow::Owned))
    {
        Some(u) => u.into_owned(),
        None => {
            return DoctorCheck::fail(
                "DATABASE_URL reachable",
                "DATABASE_URL not set — cannot check connectivity",
                "Set DATABASE_URL first",
            );
        },
    };

    match parse_host_port(&url_str) {
        None => DoctorCheck::warn(
            "DATABASE_URL reachable",
            format!("could not parse host:port from URL: {url_str}"),
            "Ensure DATABASE_URL is a valid postgres:// or mysql:// URL",
        ),
        Some((host, port)) => {
            let addr = format!("{host}:{port}");
            // Parse the socket addr; fall back to a guaranteed-refused addr on parse failure.
            let sock_addr = addr.parse().unwrap_or_else(|_| {
                std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
            });
            match TcpStream::connect_timeout(&sock_addr, Duration::from_secs(5)) {
                Ok(_) => DoctorCheck::pass("DATABASE_URL reachable", addr),
                Err(e) => DoctorCheck::fail(
                    "DATABASE_URL reachable",
                    format!("connection refused ({addr}): {e}"),
                    format!(
                        "Check that the database is running: pg_isready -h {host} -p {port}\n\
                         Or set DATABASE_URL=postgres://user:pass@host:port/dbname"
                    ),
                ),
            }
        },
    }
}

/// Check whether `FRAISEQL_JWT_SECRET` is set.
pub fn check_jwt_secret() -> DoctorCheck {
    if std::env::var("FRAISEQL_JWT_SECRET").is_ok() {
        DoctorCheck::pass("FRAISEQL_JWT_SECRET", "set")
    } else {
        DoctorCheck::warn(
            "FRAISEQL_JWT_SECRET",
            "not set (auth will reject all tokens)",
            "Set FRAISEQL_JWT_SECRET in your environment or .env file",
        )
    }
}

/// Check Redis if `REDIS_URL` is set.
pub fn check_redis_reachable() -> DoctorCheck {
    let Ok(url_str) = std::env::var("REDIS_URL") else {
        return DoctorCheck::pass("FRAISEQL_REDIS_URL", "not set (OK: cache disabled)");
    };

    match parse_host_port(&url_str) {
        None => DoctorCheck::warn(
            "FRAISEQL_REDIS_URL",
            format!("could not parse host:port from REDIS_URL: {url_str}"),
            "Ensure REDIS_URL is a valid redis:// URL",
        ),
        Some((host, port)) => {
            let addr = format!("{host}:{port}");
            let sock_addr = addr.parse().unwrap_or_else(|_| {
                std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
            });
            match TcpStream::connect_timeout(&sock_addr, Duration::from_secs(5)) {
                Ok(_) => DoctorCheck::pass("FRAISEQL_REDIS_URL", format!("reachable ({addr})")),
                Err(e) => DoctorCheck::fail(
                    "FRAISEQL_REDIS_URL",
                    format!("set but not reachable ({addr}): {e}"),
                    "Check that Redis is running or unset REDIS_URL to disable caching",
                ),
            }
        },
    }
}

/// Check TLS: if the TOML config enables TLS, the cert file must exist.
pub fn check_tls(config_path: &Path) -> DoctorCheck {
    // Only run this check when the config file exists and is readable.
    let Ok(content) = std::fs::read_to_string(config_path) else {
        return DoctorCheck::pass("TLS certificate", "not configured (OK: TLS disabled)");
    };
    let Ok(schema) = TomlSchema::parse_toml(&content) else {
        return DoctorCheck::pass("TLS certificate", "TOML unreadable — TLS check skipped");
    };

    if !schema.server.tls.enabled {
        return DoctorCheck::pass("TLS certificate", "not configured (OK: TLS disabled)");
    }

    let cert = &schema.server.tls.cert_file;
    if cert.is_empty() {
        return DoctorCheck::fail(
            "TLS certificate",
            "TLS enabled but cert_file is empty",
            "Set [server.tls] cert_file and key_file in fraiseql.toml",
        );
    }
    if Path::new(cert).exists() {
        DoctorCheck::pass("TLS certificate", format!("found: {cert}"))
    } else {
        DoctorCheck::fail(
            "TLS certificate",
            format!("TLS enabled but cert_file not found: {cert}"),
            "Provide a valid PEM certificate at the configured path",
        )
    }
}

/// Cross-check: warn if caching is enabled without any authorization policy.
///
/// When caching is active but no authorization policies are configured, cached
/// results may be served to unauthenticated users — a potential data-leak.
pub fn check_rls_cache_coherence(config_path: &Path) -> DoctorCheck {
    // Config not present — nothing to cross-check.
    let Ok(content) = std::fs::read_to_string(config_path) else {
        return DoctorCheck::pass("Cache + auth coherence", "no config (defaults: cache disabled)");
    };
    let Ok(schema) = TomlSchema::parse_toml(&content) else {
        return DoctorCheck::pass("Cache + auth coherence", "TOML unreadable — check skipped");
    };

    let caching_enabled = schema.caching.enabled;
    let has_auth_policy =
        !schema.security.policies.is_empty() || schema.security.default_policy.is_some();

    match (caching_enabled, has_auth_policy) {
        (false, _) => {
            DoctorCheck::pass("Cache + auth coherence", "cache disabled — no cross-user risk")
        },
        (true, true) => {
            DoctorCheck::pass("Cache + auth coherence", "caching + auth policy both configured")
        },
        (true, false) => DoctorCheck::warn(
            "Cache + auth coherence",
            "caching enabled without authorization policy — cached results may leak across users",
            "Add [security.policies] entries or set [security] default_policy in fraiseql.toml",
        ),
    }
}

// ─── Helpers ─────────────────────────────────────────────────────────────────

/// Extract (host, port) from a URL like `postgres://user:pass@host:5432/db`.
///
/// Returns `None` if the URL cannot be parsed.
pub(crate) fn parse_host_port(url: &str) -> Option<(String, u16)> {
    // Strip the scheme prefix and credentials; we only need the host:port.
    let after_scheme = url.split("://").nth(1)?;
    // Drop path/query after the first `/` following host:port.
    let host_part = after_scheme.split('/').next()?;
    // Drop user:pass@.
    let host_port = host_part.split('@').next_back()?;

    // Handle IPv6 addresses: [::1]:5432
    if host_port.starts_with('[') {
        let bracket_end = host_port.find(']')?;
        let host = host_port[1..bracket_end].to_string();
        let after_bracket = &host_port[bracket_end + 1..];
        let port = after_bracket.trim_start_matches(':').parse::<u16>().ok()?;
        return Some((host, port));
    }

    let mut parts = host_port.rsplitn(2, ':');
    let port = parts.next()?.parse::<u16>().ok()?;
    let host = parts.next().unwrap_or("localhost").to_string();
    Some((host, port))
}

// ─── Output ───────────────────────────────────────────────────────────────────

/// Print the doctor report in text format to stdout.
pub fn print_text_report(checks: &[DoctorCheck]) {
    println!("\nChecking FraiseQL setup...\n");

    for check in checks {
        let symbol = match check.status {
            CheckStatus::Pass => "",
            CheckStatus::Warn => "!",
            CheckStatus::Fail => "",
        };
        let detail = if check.detail.is_empty() {
            String::new()
        } else {
            format!("    {}", check.detail)
        };
        println!("  [{symbol}] {:<30}{detail}", check.name);
        if let Some(hint) = &check.hint {
            for line in hint.lines() {
                println!("{line}");
            }
        }
    }

    let errors = checks.iter().filter(|c| c.status == CheckStatus::Fail).count();
    let warnings = checks.iter().filter(|c| c.status == CheckStatus::Warn).count();

    println!();
    match (errors, warnings) {
        (0, 0) => println!("All checks passed."),
        (0, w) => println!("Summary: 0 errors, {w} warning(s)"),
        (e, 0) => println!("Summary: {e} error(s), 0 warnings"),
        (e, w) => println!("Summary: {e} error(s), {w} warning(s)"),
    }
}

/// Print the doctor report as JSON to stdout.
pub fn print_json_report(checks: &[DoctorCheck]) {
    let json = serde_json::to_string_pretty(checks).unwrap_or_else(|_| "[]".to_string());
    println!("{json}");
}

// ─── Entry point ──────────────────────────────────────────────────────────────

/// Run all doctor checks and return the list of results.
pub fn run_checks(
    config_path: &Path,
    schema_path: &Path,
    db_url_override: Option<&str>,
) -> Vec<DoctorCheck> {
    let mut checks = Vec::new();

    // Schema checks
    checks.push(check_schema_exists(schema_path));
    if schema_path.exists() {
        checks.push(check_schema_parses(schema_path));
        checks.push(check_schema_version(schema_path));
    }

    // TOML config checks
    checks.push(check_toml_exists(config_path));
    if config_path.exists() {
        checks.push(check_toml_parses(config_path));
    }

    // Environment / connectivity checks
    checks.push(check_database_url_set(db_url_override));
    checks.push(check_db_reachable(db_url_override));
    checks.push(check_jwt_secret());
    checks.push(check_redis_reachable());

    // TLS and coherence checks (only meaningful when config is present)
    checks.push(check_tls(config_path));
    checks.push(check_rls_cache_coherence(config_path));

    checks
}

/// Execute the doctor command.
///
/// Returns `true` if all checks passed (exit 0), `false` if any check failed
/// (exit 1). Warnings do not trigger an exit-1.
pub fn run(config: &Path, schema: &Path, db_url: Option<&str>, json: bool) -> bool {
    let checks = run_checks(config, schema, db_url);

    if json {
        print_json_report(&checks);
    } else {
        print_text_report(&checks);
    }

    checks.iter().all(|c| c.status != CheckStatus::Fail)
}