fraiseql-server 2.2.0

HTTP server for FraiseQL v2 GraphQL engine
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
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
//! Admin API endpoints.
//!
//! Provides endpoints for:
//! - Hot-reloading schema without restart
//! - Invalidating cache by scope (all, entity type, or pattern)
//! - Inspecting runtime configuration (sanitized)

use std::{collections::HashMap, fs};

use axum::{Json, extract::State};
use fraiseql_core::{db::traits::DatabaseAdapter, schema::CompiledSchema};
use serde::{Deserialize, Serialize};
use tracing::{error, info};

use crate::routes::{
    api::types::{ApiError, ApiResponse},
    graphql::AppState,
};

/// Current status of the query result cache as understood by the server.
///
/// Used in the admin config endpoint and startup logs to give operators
/// an accurate picture of what `cache_enabled` actually activates.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum CacheStatus {
    /// `cache_enabled = false` — no cache guard or caching active.
    Disabled,
    /// `cache_enabled = true` — RLS safety guard is active, but full
    /// query result caching (`CachedDatabaseAdapter`) is not yet wired.
    #[deprecated(
        since = "2.2.0",
        note = "CachedDatabaseAdapter is now always wired when cache_enabled = true. \
                Use `Active` or `Disabled` instead."
    )]
    RlsGuardOnly,
    /// Full query result caching is active.
    ///
    /// `CachedDatabaseAdapter` is wired into the server when `cache_enabled = true`.
    Active,
}

impl CacheStatus {
    /// Derive cache status from the `cache_enabled` flag.
    ///
    /// # Deprecated
    ///
    /// Use `AppState::adapter_cache_enabled` to determine the true cache state.
    #[must_use]
    #[deprecated(
        since = "2.2.0",
        note = "Use `AppState::adapter_cache_enabled` to determine the true cache state. \
                This function returns `RlsGuardOnly` which is no longer accurate."
    )]
    pub const fn from_cache_enabled(cache_enabled: bool) -> Self {
        #[allow(deprecated)] // Reason: function itself is deprecated; returns deprecated variant
        if cache_enabled {
            Self::RlsGuardOnly
        } else {
            Self::Disabled
        }
    }
}

/// Request to reload schema from file.
#[derive(Debug, Deserialize, Serialize)]
pub struct ReloadSchemaRequest {
    /// Path to compiled schema file
    pub schema_path:   String,
    /// If true, only validate the schema without applying changes
    pub validate_only: bool,
}

/// Response after schema reload attempt.
#[derive(Debug, Serialize)]
pub struct ReloadSchemaResponse {
    /// Whether the operation succeeded
    pub success: bool,
    /// Human-readable message about the result
    pub message: String,
}

/// Request to clear cache entries.
#[derive(Debug, Deserialize, Serialize)]
pub struct CacheClearRequest {
    /// Scope for clearing: "all", "entity", or "pattern"
    pub scope:       String,
    /// Entity type (required if scope is "entity")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub entity_type: Option<String>,
    /// Pattern (required if scope is "pattern")
    #[serde(skip_serializing_if = "Option::is_none")]
    pub pattern:     Option<String>,
}

/// Response after cache clear operation.
#[derive(Debug, Serialize)]
pub struct CacheClearResponse {
    /// Whether the operation succeeded
    pub success:         bool,
    /// Number of entries cleared
    pub entries_cleared: usize,
    /// Human-readable message about the result
    pub message:         String,
}

/// Response containing runtime configuration (sanitized).
#[derive(Debug, Serialize)]
pub struct AdminConfigResponse {
    /// Server version
    pub version: String,
    /// Runtime configuration (secrets redacted)
    pub config:  HashMap<String, String>,
}

/// Reload schema from file.
///
/// Supports validation-only mode via `validate_only` flag.
/// When applied, the schema is atomically swapped without stopping execution.
///
/// # Errors
///
/// Returns `ApiError` with a validation error if `schema_path` is empty.
/// Returns `ApiError` with a parse error if the schema file cannot be read or parsed.
///
/// Requires admin token authentication.
pub async fn reload_schema_handler<A: DatabaseAdapter>(
    State(state): State<AppState<A>>,
    Json(req): Json<ReloadSchemaRequest>,
) -> Result<Json<ApiResponse<ReloadSchemaResponse>>, ApiError> {
    let _ = &state; // used conditionally by #[cfg(feature = "arrow")]
    if req.schema_path.is_empty() {
        return Err(ApiError::validation_error("schema_path cannot be empty"));
    }

    // Step 1: Load schema from file
    let schema_json = fs::read_to_string(&req.schema_path)
        .map_err(|e| ApiError::parse_error(format!("Failed to read schema file: {}", e)))?;

    // Step 2: Validate schema structure
    let _validated_schema = CompiledSchema::from_json(&schema_json)
        .map_err(|e| ApiError::parse_error(format!("Invalid schema JSON: {}", e)))?;

    if req.validate_only {
        info!(
            operation = "admin.reload_schema",
            schema_path = %req.schema_path,
            validate_only = true,
            success = true,
            "Admin: schema validation requested"
        );
        let response = ReloadSchemaResponse {
            success: true,
            message: "Schema validated successfully (not applied)".to_string(),
        };
        Ok(Json(ApiResponse {
            status: "success".to_string(),
            data:   response,
        }))
    } else {
        // Step 3: Atomically swap the executor with the new schema
        let start = std::time::Instant::now();
        let schema_path = std::path::Path::new(&req.schema_path);

        match state.reload_schema(schema_path).await {
            Ok(()) => {
                let duration_ms = start.elapsed().as_millis();
                state
                    .metrics
                    .schema_reloads_total
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                info!(
                    operation = "admin.reload_schema",
                    schema_path = %req.schema_path,
                    duration_ms,
                    "Schema reloaded successfully"
                );

                let response = ReloadSchemaResponse {
                    success: true,
                    message: format!("Schema reloaded from {} in {duration_ms}ms", req.schema_path),
                };
                Ok(Json(ApiResponse {
                    status: "success".to_string(),
                    data:   response,
                }))
            },
            Err(e) => {
                state
                    .metrics
                    .schema_reload_errors_total
                    .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
                error!(
                    operation = "admin.reload_schema",
                    schema_path = %req.schema_path,
                    error = %e,
                    "Schema reload failed"
                );
                Err(ApiError::internal_error(format!("Schema reload failed: {e}")))
            },
        }
    }
}

/// Cache statistics response.
#[derive(Debug, Serialize)]
pub struct CacheStatsResponse {
    /// Number of entries currently in cache
    pub entries_count: usize,
    /// Whether cache is enabled
    pub cache_enabled: bool,
    /// Cache TTL in seconds
    pub ttl_secs:      u64,
    /// Human-readable message
    pub message:       String,
}

/// Clear cache entries by scope.
///
/// Supports three clearing scopes:
/// - **all**: Clear all cache entries
/// - **entity**: Clear entries for a specific entity type
/// - **pattern**: Clear entries matching a glob pattern
///
/// # Errors
///
/// Returns `ApiError` with an internal error if the cache feature is not enabled.
/// Returns `ApiError` with a validation error if required parameters are missing or scope is
/// invalid.
///
/// Requires admin token authentication.
pub async fn cache_clear_handler<A: DatabaseAdapter>(
    State(state): State<AppState<A>>,
    Json(req): Json<CacheClearRequest>,
) -> Result<Json<ApiResponse<CacheClearResponse>>, ApiError> {
    // Cache operations require the `arrow` feature.
    #[cfg(not(feature = "arrow"))]
    {
        let _ = (state, req);
        Err(ApiError::internal_error("Cache not configured"))
    }

    #[cfg(feature = "arrow")]
    // Validate scope and required parameters
    match req.scope.as_str() {
        "all" => {
            if let Some(cache) = state.cache() {
                let entries_before = cache.len();
                cache.clear();
                info!(
                    operation = "admin.cache_clear",
                    scope = "all",
                    entries_cleared = entries_before,
                    success = true,
                    "Admin: cache cleared (all entries)"
                );
                let response = CacheClearResponse {
                    success:         true,
                    entries_cleared: entries_before,
                    message:         format!("Cleared {} cache entries", entries_before),
                };
                Ok(Json(ApiResponse {
                    status: "success".to_string(),
                    data:   response,
                }))
            } else {
                Err(ApiError::internal_error("Cache not configured"))
            }
        },
        "entity" => {
            if req.entity_type.is_none() {
                return Err(ApiError::validation_error(
                    "entity_type is required when scope is 'entity'",
                ));
            }

            if let Some(cache) = state.cache() {
                let entity_type = req.entity_type.as_ref().ok_or_else(|| {
                    ApiError::internal_error(
                        "entity_type was None after validation — this is a bug",
                    )
                })?;
                // Convert entity type to view name pattern (e.g., User → v_user)
                let view_name = format!("v_{}", entity_type.to_lowercase());
                let entries_cleared = cache.invalidate_views(&[&view_name]);
                info!(
                    operation = "admin.cache_clear",
                    scope = "entity",
                    entity_type = %entity_type,
                    entries_cleared,
                    success = true,
                    "Admin: cache cleared for entity"
                );
                let response = CacheClearResponse {
                    success: true,
                    entries_cleared,
                    message: format!(
                        "Cleared {} cache entries for entity type '{}'",
                        entries_cleared, entity_type
                    ),
                };
                Ok(Json(ApiResponse {
                    status: "success".to_string(),
                    data:   response,
                }))
            } else {
                Err(ApiError::internal_error("Cache not configured"))
            }
        },
        "pattern" => {
            if req.pattern.is_none() {
                return Err(ApiError::validation_error(
                    "pattern is required when scope is 'pattern'",
                ));
            }

            if let Some(cache) = state.cache() {
                let pattern = req.pattern.as_ref().ok_or_else(|| {
                    ApiError::internal_error("pattern was None after validation — this is a bug")
                })?;
                let entries_cleared = cache.invalidate_pattern(pattern);
                info!(
                    operation = "admin.cache_clear",
                    scope = "pattern",
                    %pattern,
                    entries_cleared,
                    success = true,
                    "Admin: cache cleared by pattern"
                );
                let response = CacheClearResponse {
                    success: true,
                    entries_cleared,
                    message: format!(
                        "Cleared {} cache entries matching pattern '{}'",
                        entries_cleared, pattern
                    ),
                };
                Ok(Json(ApiResponse {
                    status: "success".to_string(),
                    data:   response,
                }))
            } else {
                Err(ApiError::internal_error("Cache not configured"))
            }
        },
        _ => Err(ApiError::validation_error("scope must be 'all', 'entity', or 'pattern'")),
    }
}

/// Get cache statistics.
///
/// Returns current cache metrics including entry count, enabled status, and TTL.
///
/// # Errors
///
/// This handler currently always succeeds; it is infallible.
///
/// Requires admin token authentication.
pub async fn cache_stats_handler<A: DatabaseAdapter>(
    State(state): State<AppState<A>>,
) -> Result<Json<ApiResponse<CacheStatsResponse>>, ApiError> {
    #[cfg(feature = "arrow")]
    if let Some(cache) = state.cache() {
        let response = CacheStatsResponse {
            entries_count: cache.len(),
            cache_enabled: true,
            ttl_secs:      60, // Default TTL from QueryCache::new(60)
            message:       format!("Cache contains {} entries with 60-second TTL", cache.len()),
        };
        return Ok(Json(ApiResponse {
            status: "success".to_string(),
            data:   response,
        }));
    }
    {
        let _ = state;
        let response = CacheStatsResponse {
            entries_count: 0,
            cache_enabled: false,
            ttl_secs:      0,
            message:       "Cache is not configured".to_string(),
        };
        Ok(Json(ApiResponse {
            status: "success".to_string(),
            data:   response,
        }))
    }
}

/// Get sanitized runtime configuration.
///
/// Returns server version and runtime configuration with secrets redacted.
/// Configuration includes database settings, cache settings, etc.
/// but excludes API keys, passwords, and other sensitive data.
///
/// # Errors
///
/// This handler currently always succeeds; it is infallible.
///
/// Requires admin token authentication.
// Reason: `cache_enabled = "false"` appears in both the else-branch and the
// `#[cfg(not(feature = "arrow"))]` inner path. Clippy sees them as shared code, but
// extracting it would break the `#[cfg]` conditional logic that sets a different value
// when `arrow` is enabled.
#[allow(clippy::branches_sharing_code)] // Reason: branches are logically distinct; extracting shared code would obscure intent
pub async fn config_handler<A: DatabaseAdapter>(
    State(state): State<AppState<A>>,
) -> Result<Json<ApiResponse<AdminConfigResponse>>, ApiError> {
    let mut config = HashMap::new();

    // Get actual server configuration
    if let Some(server_config) = state.server_config() {
        // Safe configuration values - no secrets
        config.insert("port".to_string(), server_config.port.to_string());
        config.insert("host".to_string(), server_config.host.clone());

        if let Some(workers) = server_config.workers {
            config.insert("workers".to_string(), workers.to_string());
        }

        // TLS status (boolean only, paths are redacted)
        config.insert("tls_enabled".to_string(), server_config.tls.is_some().to_string());

        // Request limits
        if let Some(limits) = &server_config.limits {
            config.insert("max_request_size".to_string(), limits.max_request_size.clone());
            config.insert("request_timeout".to_string(), limits.request_timeout.clone());
            config.insert(
                "max_concurrent_requests".to_string(),
                limits.max_concurrent_requests.to_string(),
            );
            config.insert("max_queue_depth".to_string(), limits.max_queue_depth.to_string());
        }

        // Cache status: read from adapter_cache_enabled (set at startup by ServerBuilder).
        // This reflects the CachedDatabaseAdapter state, independent of the Arrow cache.
        let cache_active = state.adapter_cache_enabled;

        config.insert("cache_enabled".to_string(), cache_active.to_string());
        let cache_status = if cache_active {
            CacheStatus::Active
        } else {
            CacheStatus::Disabled
        };
        config.insert(
            "cache_status".to_string(),
            serde_json::to_string(&cache_status)
                .unwrap_or_else(|_| "\"disabled\"".to_string())
                .trim_matches('"')
                .to_string(),
        );
        let _ = server_config; // consumed above for other fields
    } else {
        // Minimal configuration if not available
        config.insert("cache_enabled".to_string(), "false".to_string());
        config.insert("cache_status".to_string(), "disabled".to_string());
    }

    let response = AdminConfigResponse {
        version: env!("CARGO_PKG_VERSION").to_string(),
        config,
    };

    Ok(Json(ApiResponse {
        status: "success".to_string(),
        data:   response,
    }))
}

/// Request body for `POST /api/v1/admin/explain`.
#[derive(Debug, Deserialize, Serialize)]
pub struct ExplainRequest {
    /// Name of the regular query to explain (e.g., `"users"`).
    pub query: String,

    /// GraphQL-style variable filters passed as a JSON object.
    ///
    /// Each key-value pair becomes an equality condition in the WHERE clause.
    /// Example: `{"status": "active"}` → `WHERE data->>'status' = 'active'`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub variables: Option<serde_json::Value>,

    /// Optional row limit to pass to the query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub limit: Option<u32>,

    /// Optional row offset to pass to the query.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub offset: Option<u32>,
}

/// Return the pre-built Grafana dashboard JSON for FraiseQL metrics.
///
/// The dashboard JSON is embedded at compile time from
/// `deploy/grafana/fraiseql-dashboard.json`.  Operators can import it into
/// Grafana with a single `curl` command (see `deploy/grafana/README.md`).
///
/// # Errors
///
/// This handler is infallible — the embedded JSON is validated at compile time
/// by the `test_grafana_dashboard_is_valid_json` unit test.
///
/// Requires admin token authentication.
pub async fn grafana_dashboard_handler<A: DatabaseAdapter>(
    State(_state): State<AppState<A>>,
) -> impl axum::response::IntoResponse {
    const DASHBOARD_JSON: &str = include_str!("../../../resources/fraiseql-dashboard.json");

    (
        axum::http::StatusCode::OK,
        [(axum::http::header::CONTENT_TYPE, "application/json")],
        DASHBOARD_JSON,
    )
}

/// Run `EXPLAIN (ANALYZE, BUFFERS, FORMAT JSON)` for a named query.
///
/// Accepts a query name and optional variable filters, then executes
/// `EXPLAIN ANALYZE` against the backing PostgreSQL view using the exact
/// same parameterized SQL that a live query would use.
///
/// # Errors
///
/// * `400 Bad Request` — empty query name, unknown query, or mutation given
/// * `500 Internal Server Error` — database execution failure
///
/// Requires admin token authentication.
pub async fn explain_handler<A: DatabaseAdapter + 'static>(
    State(state): State<AppState<A>>,
    Json(req): Json<ExplainRequest>,
) -> Result<Json<ApiResponse<fraiseql_core::runtime::ExplainResult>>, ApiError> {
    if req.query.is_empty() {
        return Err(ApiError::validation_error("query cannot be empty"));
    }

    state
        .executor()
        .explain(&req.query, req.variables.as_ref(), req.limit, req.offset)
        .await
        .map(ApiResponse::success)
        .map_err(|e| match e {
            fraiseql_core::error::FraiseQLError::Validation { message, .. } => {
                ApiError::validation_error(message)
            },
            fraiseql_core::error::FraiseQLError::Unsupported { message } => {
                ApiError::validation_error(format!("Unsupported: {message}"))
            },
            other => ApiError::internal_error(other.to_string()),
        })
}

#[cfg(test)]
#[allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
mod tests {
    use super::*;

    // ── CacheStatus (Phase 02, Issue #183) ─────────────────────────────────

    #[test]
    #[allow(deprecated)] // Reason: testing deprecated variant
    fn cache_status_serializes_to_snake_case() {
        let json = serde_json::to_string(&CacheStatus::RlsGuardOnly).unwrap();
        assert_eq!(json, "\"rls_guard_only\"");

        let json = serde_json::to_string(&CacheStatus::Disabled).unwrap();
        assert_eq!(json, "\"disabled\"");

        let json = serde_json::to_string(&CacheStatus::Active).unwrap();
        assert_eq!(json, "\"active\"");
    }

    #[test]
    #[allow(deprecated)] // Reason: testing deprecated function
    fn cache_status_from_config_enabled() {
        assert_eq!(CacheStatus::from_cache_enabled(true), CacheStatus::RlsGuardOnly);
    }

    #[test]
    #[allow(deprecated)] // Reason: testing deprecated function
    fn cache_status_from_config_disabled() {
        assert_eq!(CacheStatus::from_cache_enabled(false), CacheStatus::Disabled);
    }

    #[test]
    #[allow(deprecated)] // Reason: testing deprecated variant
    fn cache_status_deserializes_from_snake_case() {
        let status: CacheStatus = serde_json::from_str("\"rls_guard_only\"").unwrap();
        assert_eq!(status, CacheStatus::RlsGuardOnly);

        let status: CacheStatus = serde_json::from_str("\"active\"").unwrap();
        assert_eq!(status, CacheStatus::Active);
    }

    // ── Grafana & other tests ───────────────────────────────────────────────

    #[test]
    fn test_grafana_dashboard_is_valid_json() {
        let parsed: serde_json::Value =
            serde_json::from_str(include_str!("../../../resources/fraiseql-dashboard.json"))
                .expect("fraiseql-dashboard.json must be valid JSON");

        assert_eq!(parsed["title"], "FraiseQL Performance");
        assert_eq!(parsed["uid"], "fraiseql-perf-v1");
        assert!(
            parsed["panels"].as_array().map_or(0, |p| p.len()) >= 10,
            "dashboard should have at least 10 panels"
        );
    }

    #[test]
    fn test_reload_schema_request_empty_path() {
        let request = ReloadSchemaRequest {
            schema_path:   String::new(),
            validate_only: false,
        };

        assert!(request.schema_path.is_empty());
    }

    #[test]
    fn test_reload_schema_request_with_path() {
        let request = ReloadSchemaRequest {
            schema_path:   "/path/to/schema.json".to_string(),
            validate_only: false,
        };

        assert!(!request.schema_path.is_empty());
    }

    #[test]
    fn test_cache_clear_scope_validation() {
        let valid_scopes = vec!["all", "entity", "pattern"];

        for scope in valid_scopes {
            let request = CacheClearRequest {
                scope:       scope.to_string(),
                entity_type: None,
                pattern:     None,
            };
            assert_eq!(request.scope, scope);
        }
    }

    #[test]
    fn test_admin_config_response_has_version() {
        let response = AdminConfigResponse {
            version: "2.0.0-a1".to_string(),
            config:  HashMap::new(),
        };

        assert!(!response.version.is_empty());
    }

    #[test]
    fn test_reload_schema_response_success() {
        let response = ReloadSchemaResponse {
            success: true,
            message: "Reloaded".to_string(),
        };

        assert!(response.success);
    }

    #[test]
    fn test_reload_schema_response_failure() {
        let response = ReloadSchemaResponse {
            success: false,
            message: "Failed to load".to_string(),
        };

        assert!(!response.success);
    }

    #[test]
    fn test_cache_clear_response_counts_entries() {
        let response = CacheClearResponse {
            success:         true,
            entries_cleared: 42,
            message:         "Cleared".to_string(),
        };

        assert_eq!(response.entries_cleared, 42);
    }

    #[test]
    fn test_cache_clear_request_entity_required_for_entity_scope() {
        let request = CacheClearRequest {
            scope:       "entity".to_string(),
            entity_type: Some("User".to_string()),
            pattern:     None,
        };

        assert_eq!(request.scope, "entity");
        assert_eq!(request.entity_type.as_deref(), Some("User"));
    }

    #[test]
    fn test_cache_clear_request_pattern_required_for_pattern_scope() {
        let request = CacheClearRequest {
            scope:       "pattern".to_string(),
            entity_type: None,
            pattern:     Some("*_user".to_string()),
        };

        assert_eq!(request.scope, "pattern");
        assert_eq!(request.pattern.as_deref(), Some("*_user"));
    }

    #[test]
    fn test_admin_config_response_sanitization_excludes_paths() {
        let response = AdminConfigResponse {
            version: "2.0.0".to_string(),
            config:  {
                let mut m = HashMap::new();
                m.insert("port".to_string(), "8000".to_string());
                m.insert("host".to_string(), "0.0.0.0".to_string());
                m.insert("tls_enabled".to_string(), "true".to_string());
                m
            },
        };

        assert_eq!(response.config.get("port"), Some(&"8000".to_string()));
        assert_eq!(response.config.get("host"), Some(&"0.0.0.0".to_string()));
        assert_eq!(response.config.get("tls_enabled"), Some(&"true".to_string()));
        // Verify no cert_file or key_file keys (paths redacted)
        assert!(!response.config.contains_key("cert_file"));
        assert!(!response.config.contains_key("key_file"));
    }

    #[test]
    fn test_admin_config_response_includes_limits() {
        let response = AdminConfigResponse {
            version: "2.0.0".to_string(),
            config:  {
                let mut m = HashMap::new();
                m.insert("max_request_size".to_string(), "10MB".to_string());
                m.insert("request_timeout".to_string(), "30s".to_string());
                m.insert("max_concurrent_requests".to_string(), "1000".to_string());
                m
            },
        };

        assert!(response.config.contains_key("max_request_size"));
        assert!(response.config.contains_key("request_timeout"));
        assert!(response.config.contains_key("max_concurrent_requests"));
    }

    #[test]
    fn test_cache_stats_response_structure() {
        let response = CacheStatsResponse {
            entries_count: 100,
            cache_enabled: true,
            ttl_secs:      60,
            message:       "Cache statistics".to_string(),
        };

        assert_eq!(response.entries_count, 100);
        assert!(response.cache_enabled);
        assert_eq!(response.ttl_secs, 60);
        assert!(!response.message.is_empty());
    }

    #[test]
    fn test_reload_schema_request_validates_path() {
        let request = ReloadSchemaRequest {
            schema_path:   "/path/to/schema.json".to_string(),
            validate_only: false,
        };

        assert!(!request.schema_path.is_empty());
    }

    #[test]
    fn test_reload_schema_request_validate_only_flag() {
        let request = ReloadSchemaRequest {
            schema_path:   "/path/to/schema.json".to_string(),
            validate_only: true,
        };

        assert!(request.validate_only);
    }

    #[test]
    fn test_reload_schema_response_indicates_success() {
        let response = ReloadSchemaResponse {
            success: true,
            message: "Schema reloaded".to_string(),
        };

        assert!(response.success);
        assert!(!response.message.is_empty());
    }

    // ── Admin audit log tests (15-5) ────────────────────────────────────────

    #[test]
    fn test_reload_schema_request_carries_audit_fields() {
        // Verifies that the request type exposes the fields needed to emit a
        // complete audit log entry (schema_path + validate_only).
        let req = ReloadSchemaRequest {
            schema_path:   "/var/run/fraiseql/schema.compiled.json".to_string(),
            validate_only: false,
        };
        assert!(!req.schema_path.is_empty(), "schema_path must be present for audit log");
        // validate_only is always set (bool field) — no assertion needed.
        let _ = req.validate_only;
    }

    #[test]
    fn test_cache_clear_request_carries_audit_fields() {
        // Verifies that CacheClearRequest exposes the fields needed for audit logging
        // (scope, optional entity_type, optional pattern).
        let all_req = CacheClearRequest {
            scope:       "all".to_string(),
            entity_type: None,
            pattern:     None,
        };
        assert_eq!(all_req.scope, "all");

        let entity_req = CacheClearRequest {
            scope:       "entity".to_string(),
            entity_type: Some("Order".to_string()),
            pattern:     None,
        };
        assert!(
            entity_req.entity_type.is_some(),
            "entity scope must carry entity_type for audit"
        );

        let pattern_req = CacheClearRequest {
            scope:       "pattern".to_string(),
            entity_type: None,
            pattern:     Some("v_order*".to_string()),
        };
        assert!(pattern_req.pattern.is_some(), "pattern scope must carry pattern for audit");
    }
}