1use std::{net::TcpStream, path::Path, time::Duration};
9
10use fraiseql_observers::migrations::ENTITY_CHANGE_LOG_CONTRACT;
11use serde::{Deserialize, Serialize};
12
13use crate::{
14 config::toml_schema::TomlSchema,
15 schema::pg_catalog::{LiveColumn, PgCatalog, PlpgsqlCheckOutcome},
16};
17
18#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
22#[serde(rename_all = "lowercase")]
23#[non_exhaustive]
24pub enum CheckStatus {
25 Pass,
27 Warn,
29 Fail,
31}
32
33#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct DoctorCheck {
36 pub name: &'static str,
38 pub status: CheckStatus,
40 pub detail: String,
42 pub hint: Option<String>,
44}
45
46impl DoctorCheck {
47 pub(crate) fn pass(name: &'static str, detail: impl Into<String>) -> Self {
48 Self {
49 name,
50 status: CheckStatus::Pass,
51 detail: detail.into(),
52 hint: None,
53 }
54 }
55
56 pub(crate) fn warn(
57 name: &'static str,
58 detail: impl Into<String>,
59 hint: impl Into<String>,
60 ) -> Self {
61 Self {
62 name,
63 status: CheckStatus::Warn,
64 detail: detail.into(),
65 hint: Some(hint.into()),
66 }
67 }
68
69 pub(crate) fn fail(
70 name: &'static str,
71 detail: impl Into<String>,
72 hint: impl Into<String>,
73 ) -> Self {
74 Self {
75 name,
76 status: CheckStatus::Fail,
77 detail: detail.into(),
78 hint: Some(hint.into()),
79 }
80 }
81}
82
83pub fn check_schema_exists(path: &Path) -> DoctorCheck {
87 if path.exists() {
88 DoctorCheck::pass("Schema file exists", path.display().to_string())
89 } else {
90 DoctorCheck::fail(
91 "Schema file exists",
92 format!("not found: {}", path.display()),
93 "Run `fraiseql compile fraiseql.toml` to generate schema.compiled.json",
94 )
95 }
96}
97
98pub fn check_schema_parses(path: &Path) -> DoctorCheck {
100 match std::fs::read_to_string(path) {
101 Err(e) => DoctorCheck::fail(
102 "Schema parses",
103 format!("cannot read: {e}"),
104 "Check file permissions or run `fraiseql compile`",
105 ),
106 Ok(content) => match serde_json::from_str::<serde_json::Value>(&content) {
107 Err(e) => DoctorCheck::fail(
108 "Schema parses",
109 format!("JSON parse error: {e}"),
110 "Run `fraiseql compile fraiseql.toml` to regenerate the schema",
111 ),
112 Ok(schema) => {
113 let types = schema.get("types").and_then(|v| v.as_array()).map_or(0, Vec::len);
114 let queries = schema.get("queries").and_then(|v| v.as_array()).map_or(0, Vec::len);
115 let mutations =
116 schema.get("mutations").and_then(|v| v.as_array()).map_or(0, Vec::len);
117 DoctorCheck::pass(
118 "Schema parses",
119 format!("types={types}, queries={queries}, mutations={mutations}"),
120 )
121 },
122 },
123 }
124}
125
126pub fn check_schema_version(path: &Path) -> DoctorCheck {
128 let Ok(content) = std::fs::read_to_string(path) else {
129 return DoctorCheck::warn(
130 "Schema format version",
131 "could not read schema file",
132 "Ensure schema.compiled.json is readable",
133 );
134 };
135 let Ok(schema) = serde_json::from_str::<serde_json::Value>(&content) else {
136 return DoctorCheck::warn(
137 "Schema format version",
138 "schema is not valid JSON — version check skipped",
139 "Run `fraiseql compile` to regenerate",
140 );
141 };
142
143 match schema.get("version").and_then(serde_json::Value::as_u64) {
144 None => DoctorCheck::warn(
145 "Schema format version",
146 "no version field (older schema)",
147 "Run `fraiseql compile fraiseql.toml` to get a versioned schema",
148 ),
149 Some(v) if v == 1 => {
150 DoctorCheck::pass("Schema format version", format!("version={v} (current)"))
151 },
152 Some(v) => DoctorCheck::warn(
153 "Schema format version",
154 format!("version={v} (expected 1)"),
155 "Run `fraiseql compile fraiseql.toml` to recompile with the current compiler",
156 ),
157 }
158}
159
160pub fn check_toml_exists(path: &Path) -> DoctorCheck {
162 if path.exists() {
163 DoctorCheck::pass("fraiseql.toml found", path.display().to_string())
164 } else {
165 DoctorCheck::warn(
166 "fraiseql.toml found",
167 format!("not found: {} (using defaults)", path.display()),
168 "Create fraiseql.toml with `fraiseql init` or provide --config",
169 )
170 }
171}
172
173pub fn check_toml_parses(path: &Path) -> DoctorCheck {
175 let content = match std::fs::read_to_string(path) {
176 Ok(c) => c,
177 Err(e) => {
178 return DoctorCheck::fail(
179 "TOML syntax valid",
180 format!("cannot read: {e}"),
181 "Check file permissions",
182 );
183 },
184 };
185 match TomlSchema::parse_toml(&content) {
186 Ok(_) => DoctorCheck::pass("TOML syntax valid", ""),
187 Err(e) => {
188 let first_line = e.to_string();
190 let short = first_line.lines().next().unwrap_or("parse error");
191 DoctorCheck::fail(
192 "TOML syntax valid",
193 format!("parse error: {short}"),
194 "Fix TOML syntax in fraiseql.toml and retry",
195 )
196 },
197 }
198}
199
200pub fn check_database_url_set(db_url_override: Option<&str>) -> DoctorCheck {
202 let val = db_url_override
203 .map(std::borrow::Cow::Borrowed)
204 .or_else(|| std::env::var("DATABASE_URL").ok().map(std::borrow::Cow::Owned));
205 if val.is_some() {
206 DoctorCheck::pass("DATABASE_URL set", "")
207 } else {
208 DoctorCheck::fail(
209 "DATABASE_URL set",
210 "not set",
211 "Set DATABASE_URL=postgres://user:pass@host:port/dbname in your environment",
212 )
213 }
214}
215
216pub fn check_db_reachable(db_url_override: Option<&str>) -> DoctorCheck {
221 let url_str = match db_url_override
222 .map(std::borrow::Cow::Borrowed)
223 .or_else(|| std::env::var("DATABASE_URL").ok().map(std::borrow::Cow::Owned))
224 {
225 Some(u) => u.into_owned(),
226 None => {
227 return DoctorCheck::fail(
228 "DATABASE_URL reachable",
229 "DATABASE_URL not set — cannot check connectivity",
230 "Set DATABASE_URL first",
231 );
232 },
233 };
234
235 match parse_host_port(&url_str) {
236 None => DoctorCheck::warn(
237 "DATABASE_URL reachable",
238 format!("could not parse host:port from URL: {url_str}"),
239 "Ensure DATABASE_URL is a valid postgres:// or mysql:// URL",
240 ),
241 Some((host, port)) => {
242 let addr = format!("{host}:{port}");
243 let sock_addr = addr.parse().unwrap_or_else(|_| {
245 std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
246 });
247 match TcpStream::connect_timeout(&sock_addr, Duration::from_secs(5)) {
248 Ok(_) => DoctorCheck::pass("DATABASE_URL reachable", addr),
249 Err(e) => DoctorCheck::fail(
250 "DATABASE_URL reachable",
251 format!("connection refused ({addr}): {e}"),
252 format!(
253 "Check that the database is running: pg_isready -h {host} -p {port}\n\
254 Or set DATABASE_URL=postgres://user:pass@host:port/dbname"
255 ),
256 ),
257 }
258 },
259 }
260}
261
262pub fn check_jwt_secret() -> DoctorCheck {
264 if std::env::var("FRAISEQL_JWT_SECRET").is_ok() {
265 DoctorCheck::pass("FRAISEQL_JWT_SECRET", "set")
266 } else {
267 DoctorCheck::warn(
268 "FRAISEQL_JWT_SECRET",
269 "not set (auth will reject all tokens)",
270 "Set FRAISEQL_JWT_SECRET in your environment or .env file",
271 )
272 }
273}
274
275pub fn check_redis_reachable() -> DoctorCheck {
277 let Ok(url_str) = std::env::var("REDIS_URL") else {
278 return DoctorCheck::pass("FRAISEQL_REDIS_URL", "not set (OK: cache disabled)");
279 };
280
281 match parse_host_port(&url_str) {
282 None => DoctorCheck::warn(
283 "FRAISEQL_REDIS_URL",
284 format!("could not parse host:port from REDIS_URL: {url_str}"),
285 "Ensure REDIS_URL is a valid redis:// URL",
286 ),
287 Some((host, port)) => {
288 let addr = format!("{host}:{port}");
289 let sock_addr = addr.parse().unwrap_or_else(|_| {
290 std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED), 0)
291 });
292 match TcpStream::connect_timeout(&sock_addr, Duration::from_secs(5)) {
293 Ok(_) => DoctorCheck::pass("FRAISEQL_REDIS_URL", format!("reachable ({addr})")),
294 Err(e) => DoctorCheck::fail(
295 "FRAISEQL_REDIS_URL",
296 format!("set but not reachable ({addr}): {e}"),
297 "Check that Redis is running or unset REDIS_URL to disable caching",
298 ),
299 }
300 },
301 }
302}
303
304pub fn check_tls(config_path: &Path) -> DoctorCheck {
306 let Ok(content) = std::fs::read_to_string(config_path) else {
308 return DoctorCheck::pass("TLS certificate", "not configured (OK: TLS disabled)");
309 };
310 let Ok(schema) = TomlSchema::parse_toml(&content) else {
311 return DoctorCheck::pass("TLS certificate", "TOML unreadable — TLS check skipped");
312 };
313
314 if !schema.server.tls.enabled {
315 return DoctorCheck::pass("TLS certificate", "not configured (OK: TLS disabled)");
316 }
317
318 let cert = &schema.server.tls.cert_file;
319 if cert.is_empty() {
320 return DoctorCheck::fail(
321 "TLS certificate",
322 "TLS enabled but cert_file is empty",
323 "Set [server.tls] cert_file and key_file in fraiseql.toml",
324 );
325 }
326 if Path::new(cert).exists() {
327 DoctorCheck::pass("TLS certificate", format!("found: {cert}"))
328 } else {
329 DoctorCheck::fail(
330 "TLS certificate",
331 format!("TLS enabled but cert_file not found: {cert}"),
332 "Provide a valid PEM certificate at the configured path",
333 )
334 }
335}
336
337pub fn check_rls_cache_coherence(config_path: &Path) -> DoctorCheck {
342 let Ok(content) = std::fs::read_to_string(config_path) else {
344 return DoctorCheck::pass("Cache + auth coherence", "no config (defaults: cache disabled)");
345 };
346 let Ok(schema) = TomlSchema::parse_toml(&content) else {
347 return DoctorCheck::pass("Cache + auth coherence", "TOML unreadable — check skipped");
348 };
349
350 let caching_enabled = schema.caching.enabled;
351 let has_auth_policy =
352 !schema.security.policies.is_empty() || schema.security.default_policy.is_some();
353
354 match (caching_enabled, has_auth_policy) {
355 (false, _) => {
356 DoctorCheck::pass("Cache + auth coherence", "cache disabled — no cross-user risk")
357 },
358 (true, true) => {
359 DoctorCheck::pass("Cache + auth coherence", "caching + auth policy both configured")
360 },
361 (true, false) => DoctorCheck::warn(
362 "Cache + auth coherence",
363 "caching enabled without authorization policy — cached results may leak across users",
364 "Add [security.policies] entries or set [security] default_policy in fraiseql.toml",
365 ),
366 }
367}
368
369pub(crate) fn parse_host_port(url: &str) -> Option<(String, u16)> {
375 let after_scheme = url.split("://").nth(1)?;
377 let host_part = after_scheme.split('/').next()?;
379 let host_port = host_part.split('@').next_back()?;
381
382 if host_port.starts_with('[') {
384 let bracket_end = host_port.find(']')?;
385 let host = host_port[1..bracket_end].to_string();
386 let after_bracket = &host_port[bracket_end + 1..];
387 let port = after_bracket.trim_start_matches(':').parse::<u16>().ok()?;
388 return Some((host, port));
389 }
390
391 let mut parts = host_port.rsplitn(2, ':');
392 let port = parts.next()?.parse::<u16>().ok()?;
393 let host = parts.next().unwrap_or("localhost").to_string();
394 Some((host, port))
395}
396
397pub fn print_text_report(checks: &[DoctorCheck]) {
401 println!("\nChecking FraiseQL setup...\n");
402
403 for check in checks {
404 let symbol = match check.status {
405 CheckStatus::Pass => "✓",
406 CheckStatus::Warn => "!",
407 CheckStatus::Fail => "✗",
408 };
409 let detail = if check.detail.is_empty() {
410 String::new()
411 } else {
412 format!(" {}", check.detail)
413 };
414 println!(" [{symbol}] {:<30}{detail}", check.name);
415 if let Some(hint) = &check.hint {
416 for line in hint.lines() {
417 println!(" → {line}");
418 }
419 }
420 }
421
422 let errors = checks.iter().filter(|c| c.status == CheckStatus::Fail).count();
423 let warnings = checks.iter().filter(|c| c.status == CheckStatus::Warn).count();
424
425 println!();
426 match (errors, warnings) {
427 (0, 0) => println!("All checks passed."),
428 (0, w) => println!("Summary: 0 errors, {w} warning(s)"),
429 (e, 0) => println!("Summary: {e} error(s), 0 warnings"),
430 (e, w) => println!("Summary: {e} error(s), {w} warning(s)"),
431 }
432}
433
434pub fn print_json_report(checks: &[DoctorCheck]) {
436 let json = serde_json::to_string_pretty(checks).unwrap_or_else(|_| "[]".to_string());
437 println!("{json}");
438}
439
440pub fn run_checks(
444 config_path: &Path,
445 schema_path: &Path,
446 db_url_override: Option<&str>,
447) -> Vec<DoctorCheck> {
448 let mut checks = Vec::new();
449
450 checks.push(check_schema_exists(schema_path));
452 if schema_path.exists() {
453 checks.push(check_schema_parses(schema_path));
454 checks.push(check_schema_version(schema_path));
455 }
456
457 checks.push(check_toml_exists(config_path));
459 if config_path.exists() {
460 checks.push(check_toml_parses(config_path));
461 }
462
463 checks.push(check_database_url_set(db_url_override));
465 checks.push(check_db_reachable(db_url_override));
466 checks.push(check_jwt_secret());
467 checks.push(check_redis_reachable());
468
469 checks.push(check_tls(config_path));
471 checks.push(check_rls_cache_coherence(config_path));
472
473 checks
474}
475
476pub async fn run_with_db_checks(
489 config: &Path,
490 schema: &Path,
491 db_url: Option<&str>,
492 against_db: Option<&str>,
493 schemas: &[String],
494 json: bool,
495) -> bool {
496 let mut checks = run_checks(config, schema, db_url);
497 if let Some(url) = against_db {
498 checks.extend(changelog_contract_checks(url).await);
499 checks.extend(body_resolution_checks(url, schemas).await);
500 }
501
502 if json {
503 print_json_report(&checks);
504 } else {
505 print_text_report(&checks);
506 }
507
508 checks.iter().all(|c| c.status != CheckStatus::Fail)
509}
510
511async fn body_resolution_checks(db_url: &str, schemas: &[String]) -> Vec<DoctorCheck> {
517 const NAME: &str = "PL/pgSQL body resolution";
518
519 let catalog = match PgCatalog::connect(db_url) {
520 Ok(c) => c,
521 Err(e) => {
522 return vec![DoctorCheck::fail(
523 NAME,
524 format!("cannot connect: {e}"),
525 "Pass a reachable postgres:// URL to --against-db",
526 )];
527 },
528 };
529
530 match catalog.plpgsql_check_unresolved_calls(schemas).await {
531 Err(e) => vec![DoctorCheck::fail(
532 NAME,
533 format!("pass failed: {e}"),
534 "Ensure the connecting role may CREATE EXTENSION plpgsql_check",
535 )],
536 Ok(PlpgsqlCheckOutcome::Unavailable) => vec![DoctorCheck::warn(
537 NAME,
538 "plpgsql_check not installed — skipped",
539 "Install the plpgsql_check extension to enable internal-call checking",
540 )],
541 Ok(PlpgsqlCheckOutcome::Ran { errors }) if errors.is_empty() => vec![DoctorCheck::pass(
542 NAME,
543 format!("all internal calls resolve in {}", schemas.join(", ")),
544 )],
545 Ok(PlpgsqlCheckOutcome::Ran { errors }) => errors
546 .iter()
547 .map(|e| {
548 let location = e.lineno.map_or_else(String::new, |l| format!(" (line {l})"));
549 DoctorCheck::fail(
550 NAME,
551 format!("{}{location}: {}", e.caller, e.message),
552 "A migration changed a function signature — update its internal callers",
553 )
554 })
555 .collect(),
556 }
557}
558
559const CHANGELOG_CONTRACT_NAME: &str = "Change-log contract";
560
561async fn changelog_contract_checks(db_url: &str) -> Vec<DoctorCheck> {
567 let catalog = match PgCatalog::connect(db_url) {
568 Ok(c) => c,
569 Err(e) => {
570 return vec![DoctorCheck::fail(
571 CHANGELOG_CONTRACT_NAME,
572 format!("cannot connect: {e}"),
573 "Pass a reachable postgres:// URL to --against-db",
574 )];
575 },
576 };
577
578 match catalog.table_columns("core", "tb_entity_change_log").await {
579 Ok(live) => changelog_contract_drift(&live),
580 Err(e) => vec![DoctorCheck::fail(
581 CHANGELOG_CONTRACT_NAME,
582 format!("introspection failed: {e}"),
583 "Ensure the connecting role can read information_schema for the core schema",
584 )],
585 }
586}
587
588pub(crate) fn changelog_contract_drift(live: &[LiveColumn]) -> Vec<DoctorCheck> {
606 if live.is_empty() {
607 return vec![DoctorCheck::warn(
608 CHANGELOG_CONTRACT_NAME,
609 "core.tb_entity_change_log not found",
610 "Run `fraiseql migrate up` to install the change-log contract",
611 )];
612 }
613
614 let mut checks = Vec::new();
615
616 for contract in ENTITY_CHANGE_LOG_CONTRACT {
618 let Some(col) = live.iter().find(|c| c.name == contract.name) else {
619 continue;
620 };
621 if col.udt_name == contract.udt {
622 continue;
623 }
624 checks.push(DoctorCheck::fail(
625 CHANGELOG_CONTRACT_NAME,
626 format!(
627 "column `{}` is `{}`, contract expects `{}`",
628 contract.name, col.udt_name, contract.udt
629 ),
630 format!(
631 "The additive migration cannot retype an existing column; ALTER it manually, \
632 e.g. ALTER TABLE core.tb_entity_change_log ALTER COLUMN {name} TYPE {udt} \
633 USING {name}::{udt};",
634 name = contract.name,
635 udt = contract.udt,
636 ),
637 ));
638 }
639
640 let missing: Vec<&str> = ENTITY_CHANGE_LOG_CONTRACT
642 .iter()
643 .map(|c| c.name)
644 .filter(|name| !live.iter().any(|c| c.name == *name))
645 .collect();
646 if !missing.is_empty() {
647 checks.push(DoctorCheck::warn(
648 CHANGELOG_CONTRACT_NAME,
649 format!("{} contract column(s) missing: {}", missing.len(), missing.join(", ")),
650 "Run `fraiseql migrate up` — the additive migration adds these columns",
651 ));
652 }
653
654 let extra: Vec<&str> = live
656 .iter()
657 .map(|c| c.name.as_str())
658 .filter(|name| !ENTITY_CHANGE_LOG_CONTRACT.iter().any(|c| c.name == *name))
659 .collect();
660 if !extra.is_empty() {
661 checks.push(DoctorCheck::warn(
662 CHANGELOG_CONTRACT_NAME,
663 format!("{} non-contract column(s) present: {}", extra.len(), extra.join(", ")),
664 "Left untouched by the migration — app-specific columns are safe to keep",
665 ));
666 }
667
668 if checks.is_empty() {
669 checks.push(DoctorCheck::pass(
670 CHANGELOG_CONTRACT_NAME,
671 format!(
672 "all {} contract columns present and correctly typed",
673 ENTITY_CHANGE_LOG_CONTRACT.len()
674 ),
675 ));
676 }
677
678 checks
679}