1use std::{collections::HashSet, env};
9
10use fraiseql_error::ConfigError;
11
12use crate::config::RuntimeConfig;
13
14pub struct ValidationResult {
16 pub errors: Vec<ConfigError>,
18 pub warnings: Vec<String>,
20}
21
22impl ValidationResult {
23 #[must_use]
25 pub const fn new() -> Self {
26 Self {
27 errors: Vec::new(),
28 warnings: Vec::new(),
29 }
30 }
31
32 #[must_use]
34 pub const fn is_ok(&self) -> bool {
35 self.errors.is_empty()
36 }
37
38 #[must_use]
40 pub const fn is_err(&self) -> bool {
41 !self.errors.is_empty()
42 }
43
44 pub fn add_error(&mut self, error: ConfigError) {
46 self.errors.push(error);
47 }
48
49 pub fn add_warning(&mut self, warning: impl Into<String>) {
51 self.warnings.push(warning.into());
52 }
53
54 pub fn into_result(self) -> Result<Vec<String>, ConfigError> {
66 if self.errors.is_empty() {
67 Ok(self.warnings)
68 } else if self.errors.len() == 1 {
69 Err(self.errors.into_iter().next().expect("errors.len() == 1 confirmed above"))
70 } else {
71 Err(ConfigError::MultipleErrors {
72 errors: self.errors,
73 })
74 }
75 }
76}
77
78impl Default for ValidationResult {
79 fn default() -> Self {
80 Self::new()
81 }
82}
83
84pub struct ConfigValidator<'a> {
86 config: &'a RuntimeConfig,
87 result: ValidationResult,
88 checked_env_vars: HashSet<String>,
89}
90
91impl<'a> ConfigValidator<'a> {
92 #[must_use]
94 pub fn new(config: &'a RuntimeConfig) -> Self {
95 Self {
96 config,
97 result: ValidationResult::new(),
98 checked_env_vars: HashSet::new(),
99 }
100 }
101
102 #[must_use]
104 pub fn validate(mut self) -> ValidationResult {
105 self.validate_server();
106 self.validate_database();
107 self.validate_webhooks();
108 self.validate_auth();
109 self.validate_files();
110 self.validate_cross_field();
111 self.validate_env_vars();
112 self.validate_placeholder_sections();
113 self.result
114 }
115
116 fn validate_placeholder_sections(&mut self) {
122 if self.config.notifications.is_some() {
123 self.result.add_error(ConfigError::ValidationError {
124 field: "notifications".to_string(),
125 message: "config section 'notifications' is not yet implemented; \
126 remove it from fraiseql.toml to proceed"
127 .to_string(),
128 });
129 }
130 if self.config.logging.is_some() {
131 self.result.add_error(ConfigError::ValidationError {
132 field: "logging".to_string(),
133 message: "config section 'logging' is not yet implemented; \
134 use the 'tracing' section for observability"
135 .to_string(),
136 });
137 }
138 if self.config.search.is_some() {
139 self.result.add_error(ConfigError::ValidationError {
140 field: "search".to_string(),
141 message: "config section 'search' is not yet implemented; \
142 remove it from fraiseql.toml to proceed"
143 .to_string(),
144 });
145 }
146 if self.config.cache.is_some() {
147 self.result.add_error(ConfigError::ValidationError {
148 field: "cache".to_string(),
149 message: "config section 'cache' is not yet implemented; \
150 use fraiseql_core::cache::CacheConfig for query-result caching"
151 .to_string(),
152 });
153 }
154 if self.config.queues.is_some() {
155 self.result.add_error(ConfigError::ValidationError {
156 field: "queues".to_string(),
157 message: "config section 'queues' is not yet implemented; \
158 remove it from fraiseql.toml to proceed"
159 .to_string(),
160 });
161 }
162 if self.config.custom_endpoints.is_some() {
170 self.result.add_error(ConfigError::ValidationError {
171 field: "custom_endpoints".to_string(),
172 message: "config section 'custom_endpoints' is not yet implemented; \
173 remove it from fraiseql.toml to proceed"
174 .to_string(),
175 });
176 }
177 }
178
179 fn validate_server(&mut self) {
180 if self.config.server.port == 0 {
182 self.result.add_error(ConfigError::ValidationError {
183 field: "server.port".to_string(),
184 message: "Port cannot be 0".to_string(),
185 });
186 }
187
188 if let Some(limits) = &self.config.server.limits {
190 if let Err(e) = crate::config::env::parse_size(&limits.max_request_size) {
191 self.result.add_error(ConfigError::ValidationError {
192 field: "server.limits.max_request_size".to_string(),
193 message: format!("Invalid size format: {}", e),
194 });
195 }
196
197 if let Err(e) = crate::config::env::parse_duration(&limits.request_timeout) {
198 self.result.add_error(ConfigError::ValidationError {
199 field: "server.limits.request_timeout".to_string(),
200 message: format!("Invalid duration format: {}", e),
201 });
202 }
203
204 if limits.max_concurrent_requests == 0 {
205 self.result.add_error(ConfigError::ValidationError {
206 field: "server.limits.max_concurrent_requests".to_string(),
207 message: "Must be greater than 0".to_string(),
208 });
209 }
210 }
211
212 if let Some(tls) = &self.config.server.tls {
214 if !tls.cert_file.exists() {
215 self.result.add_error(ConfigError::ValidationError {
216 field: "server.tls.cert_file".to_string(),
217 message: format!("Certificate file not found: {}", tls.cert_file.display()),
218 });
219 }
220 if !tls.key_file.exists() {
221 self.result.add_error(ConfigError::ValidationError {
222 field: "server.tls.key_file".to_string(),
223 message: format!("Key file not found: {}", tls.key_file.display()),
224 });
225 }
226 }
227 }
228
229 fn validate_database(&mut self) {
230 if self.config.database.url_env.is_empty() {
232 self.result.add_error(ConfigError::ValidationError {
233 field: "database.url_env".to_string(),
234 message: "Database URL environment variable must be specified".to_string(),
235 });
236 } else {
237 self.checked_env_vars.insert(self.config.database.url_env.clone());
238 }
239
240 if self.config.database.pool_size == 0 {
242 self.result.add_error(ConfigError::ValidationError {
243 field: "database.pool_size".to_string(),
244 message: "Pool size must be greater than 0".to_string(),
245 });
246 }
247
248 for (i, replica) in self.config.database.replicas.iter().enumerate() {
250 if replica.url_env.is_empty() {
251 self.result.add_error(ConfigError::ValidationError {
252 field: format!("database.replicas[{}].url_env", i),
253 message: "Replica URL environment variable must be specified".to_string(),
254 });
255 } else {
256 self.checked_env_vars.insert(replica.url_env.clone());
257 }
258 }
259 }
260
261 fn validate_webhooks(&mut self) {
262 for (name, webhook) in &self.config.webhooks {
263 if webhook.secret_env.is_empty() {
265 self.result.add_error(ConfigError::ValidationError {
266 field: format!("webhooks.{}.secret_env", name),
267 message: "Webhook secret environment variable must be specified".to_string(),
268 });
269 } else {
270 self.checked_env_vars.insert(webhook.secret_env.clone());
271 }
272
273 let valid_providers = [
275 "stripe",
276 "github",
277 "shopify",
278 "twilio",
279 "sendgrid",
280 "paddle",
281 "slack",
282 "discord",
283 "linear",
284 "svix",
285 "clerk",
286 "supabase",
287 "novu",
288 "resend",
289 "generic_hmac",
290 ];
291 if !valid_providers.contains(&webhook.provider.as_str()) {
292 self.result.add_warning(format!(
293 "Unknown webhook provider '{}' for webhook '{}'. Using generic_hmac.",
294 webhook.provider, name
295 ));
296 }
297 }
298 }
299
300 fn validate_auth(&mut self) {
301 if let Some(auth) = &self.config.auth {
302 if auth.jwt.secret_env.is_empty() {
304 self.result.add_error(ConfigError::ValidationError {
305 field: "auth.jwt.secret_env".to_string(),
306 message: "JWT secret environment variable must be specified".to_string(),
307 });
308 } else {
309 self.checked_env_vars.insert(auth.jwt.secret_env.clone());
310 }
311
312 for (name, provider) in &auth.providers {
314 self.checked_env_vars.insert(provider.client_id_env.clone());
315 self.checked_env_vars.insert(provider.client_secret_env.clone());
316
317 if provider.provider_type == "oidc" && provider.issuer_url.is_none() {
319 self.result.add_error(ConfigError::ValidationError {
320 field: format!("auth.providers.{}.issuer_url", name),
321 message: "OIDC providers require issuer_url".to_string(),
322 });
323 }
324 }
325
326 if !auth.providers.is_empty() && auth.callback_base_url.is_none() {
328 self.result.add_error(ConfigError::ValidationError {
329 field: "auth.callback_base_url".to_string(),
330 message: "callback_base_url is required when OAuth providers are configured"
331 .to_string(),
332 });
333 }
334 }
335 }
336
337 fn validate_files(&mut self) {
338 for (name, file_config) in &self.config.files {
339 if !self.config.storage.contains_key(&file_config.storage) {
341 self.result.add_error(ConfigError::ValidationError {
342 field: format!("files.{}.storage", name),
343 message: format!(
344 "Storage backend '{}' not found in storage configuration",
345 file_config.storage
346 ),
347 });
348 }
349
350 if let Err(e) = crate::config::env::parse_size(&file_config.max_size) {
352 self.result.add_error(ConfigError::ValidationError {
353 field: format!("files.{}.max_size", name),
354 message: format!("Invalid size format: {}", e),
355 });
356 }
357 }
358
359 for (name, storage) in &self.config.storage {
361 match storage.backend.as_str() {
362 "s3" | "r2" | "gcs" => {
363 if storage.bucket.is_none() {
364 self.result.add_error(ConfigError::ValidationError {
365 field: format!("storage.{}.bucket", name),
366 message: "Bucket name is required for cloud storage".to_string(),
367 });
368 }
369 },
370 "local" => {
371 if storage.path.is_none() {
372 self.result.add_error(ConfigError::ValidationError {
373 field: format!("storage.{}.path", name),
374 message: "Path is required for local storage".to_string(),
375 });
376 }
377 },
378 _ => {
379 self.result.add_error(ConfigError::ValidationError {
380 field: format!("storage.{}.backend", name),
381 message: format!("Unknown storage backend: {}", storage.backend),
382 });
383 },
384 }
385 }
386 }
387
388 fn validate_cross_field(&mut self) {
389 for (name, observer) in &self.config.observers {
391 for action in &observer.actions {
392 match action.action_type.as_str() {
393 "email" | "slack" | "sms" | "push" => {
394 if self.config.notifications.is_none() {
395 self.result.add_error(ConfigError::ValidationError {
396 field: format!("observers.{}.actions", name),
397 message: format!(
398 "Observer '{}' uses '{}' action but notifications are not configured",
399 name, action.action_type
400 ),
401 });
402 }
403 },
404 _ => {},
405 }
406 }
407 }
408
409 if let Some(rate_limit) = &self.config.rate_limiting {
411 if rate_limit.backend == "redis" && self.config.cache.is_none() {
412 self.result.add_error(ConfigError::ValidationError {
413 field: "rate_limiting.backend".to_string(),
414 message: "Redis rate limiting requires cache configuration. \
415 Add a [cache] section to fraiseql.toml or change \
416 [rate_limiting] backend from 'redis' to 'memory'."
417 .to_string(),
418 });
419 }
420 }
421 }
422
423 fn validate_env_vars(&mut self) {
424 for var_name in &self.checked_env_vars {
426 if env::var(var_name).is_err() {
427 self.result.add_error(ConfigError::MissingEnvVar {
428 name: var_name.clone(),
429 });
430 }
431 }
432 }
433}