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
//! Health check endpoint.

use axum::{Json, extract::State, http::StatusCode, response::IntoResponse};
use fraiseql_core::db::traits::DatabaseAdapter;
use serde::Serialize;
use tracing::{debug, error};

use crate::routes::graphql::AppState;

/// Health check response.
#[derive(Debug, Serialize)]
pub struct HealthResponse {
    /// Overall server status: `"healthy"`, `"degraded"`, or `"unhealthy"`.
    ///
    /// - `"healthy"` — database and all enabled subsystems are reachable.
    /// - `"degraded"` — database is healthy but an optional subsystem is failing. Returns HTTP 200
    ///   so load balancers keep the pod in rotation; alert on the field value.
    /// - `"unhealthy"` — database is unreachable. Returns HTTP 503.
    pub status: String,

    /// Database status.
    pub database: DatabaseStatus,

    /// Observer runtime health (present when the `observers` feature is compiled in).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub observers: Option<ObserverHealth>,

    /// Cache / Redis health (present when a Redis cache backend is configured).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cache: Option<CacheHealth>,

    /// Secrets backend health (present when Vault or another secrets backend is configured).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub secrets: Option<SecretsHealth>,

    /// Federation circuit breaker state (present when federation is configured).
    #[cfg(feature = "federation")]
    #[serde(skip_serializing_if = "Option::is_none")]
    pub federation: Option<FederationHealth>,

    /// Server version.
    pub version: String,

    /// 32-character hex SHA-256 content hash of the compiled schema.
    ///
    /// Operators can compare this value across server instances to verify
    /// all instances are running the same schema. Different values indicate
    /// a schema mismatch (e.g. partial rollout or stale deployment).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub schema_hash: Option<String>,
}

/// Federation circuit breaker health snapshot.
#[cfg(feature = "federation")]
#[derive(Debug, Serialize)]
pub struct FederationHealth {
    /// Whether federation is configured at all.
    pub configured: bool,
    /// Per-entity circuit breaker state.
    pub subgraphs:  Vec<crate::federation::circuit_breaker::SubgraphCircuitHealth>,
}

/// Observer runtime health snapshot.
#[derive(Debug, Serialize)]
pub struct ObserverHealth {
    /// Whether the observer runtime is currently running.
    pub running:        bool,
    /// Approximate number of events pending in the internal queue.
    pub pending_events: usize,
    /// Last error message from the observer runtime, if any.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_error:     Option<String>,
}

/// Cache subsystem health.
#[derive(Debug, Serialize)]
pub struct CacheHealth {
    /// Whether the cache backend is reachable (Redis ping succeeded, or always
    /// `true` for the in-memory backend).
    pub connected: bool,
    /// Cache backend type: `"redis"` or `"in-memory"`.
    pub backend:   String,
}

/// Secrets backend health.
#[derive(Debug, Serialize)]
pub struct SecretsHealth {
    /// Whether the secrets backend is reachable and the token is valid.
    pub connected: bool,
    /// Backend type: `"vault"`, `"env"`, `"aws-secrets"`, etc.
    pub backend:   String,
}

/// Readiness response (subset of `HealthResponse`).
#[derive(Debug, Serialize)]
pub struct ReadinessResponse {
    /// `"ready"` or `"not_ready"`.
    pub status: String,
    /// Human-readable reason when `status = "not_ready"`.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub reason: Option<String>,
}

/// Database status.
#[derive(Debug, Serialize)]
pub struct DatabaseStatus {
    /// Connection status.
    pub connected: bool,

    /// Database type.
    pub database_type: String,

    /// Active connections (if available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub active_connections: Option<usize>,

    /// Idle connections (if available).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idle_connections: Option<usize>,
}

/// Federation health response.
#[cfg(feature = "federation")]
#[derive(Debug, Serialize)]
pub struct FederationHealthResponse {
    /// Overall federation status: healthy, degraded, unhealthy, unknown
    pub status: String,

    /// Per-subgraph status
    pub subgraphs: Vec<crate::federation::SubgraphHealthStatus>,

    /// Response timestamp
    pub timestamp: String,
}

/// Health check handler.
///
/// Returns server and database health status.
///
/// # Response Codes
///
/// - 200: Everything healthy
/// - 503: Database connection failed
pub async fn health_handler<A: DatabaseAdapter + Clone + Send + Sync + 'static>(
    State(state): State<AppState<A>>,
) -> impl IntoResponse {
    debug!("Health check requested");

    // Bind executor guard once for consistency within this handler
    let executor = state.executor();

    // Perform real database health check
    let health_result = executor.adapter().health_check().await;
    let db_healthy = health_result.is_ok();

    let adapter = executor.adapter();
    let db_type = adapter.database_type();
    let metrics = adapter.pool_metrics();

    let database = if db_healthy {
        DatabaseStatus {
            connected:          true,
            database_type:      format!("{db_type:?}"),
            active_connections: Some(metrics.active_connections as usize),
            idle_connections:   Some(metrics.idle_connections as usize),
        }
    } else {
        error!("Database health check failed: {:?}", health_result.err());
        DatabaseStatus {
            connected:          false,
            database_type:      format!("{db_type:?}"),
            active_connections: Some(metrics.active_connections as usize),
            idle_connections:   Some(metrics.idle_connections as usize),
        }
    };

    let schema_hash = Some(executor.schema().content_hash());

    #[cfg(feature = "federation")]
    let federation = state.circuit_breaker.as_ref().map(|cb| FederationHealth {
        configured: true,
        subgraphs:  cb.health_snapshot(),
    });

    // Probe observer health when the runtime is attached to AppState.
    #[cfg(feature = "observers")]
    let observers = if let Some(ref runtime) = state.observer_runtime {
        let rt = runtime.read().await;
        let health = rt.health();
        #[allow(clippy::cast_possible_truncation)]
        // Reason: events_processed is a counter that won't realistically exceed usize on any target
        let pending = health.events_processed as usize;
        Some(ObserverHealth {
            running:        health.running,
            pending_events: pending,
            last_error:     if health.errors > 0 {
                Some(format!("{} errors encountered", health.errors))
            } else {
                None
            },
        })
    } else {
        None
    };
    #[cfg(not(feature = "observers"))]
    let observers: Option<ObserverHealth> = None;

    // Probe cache health when the Arrow cache is attached to AppState.
    #[cfg(feature = "arrow")]
    let cache = state.cache.as_ref().map(|_| CacheHealth {
        connected: true, // In-memory cache is always "connected"
        backend:   "in-memory".to_string(),
    });
    #[cfg(not(feature = "arrow"))]
    let cache: Option<CacheHealth> = None;

    // Probe secrets backend health.
    #[cfg(feature = "secrets")]
    let secrets = if let Some(ref sm) = state.secrets_manager {
        let connected = sm.health_check().await.is_ok();
        Some(SecretsHealth {
            connected,
            backend: sm.backend_name().to_string(),
        })
    } else {
        None
    };
    #[cfg(not(feature = "secrets"))]
    let secrets: Option<SecretsHealth> = None;

    #[cfg(feature = "federation")]
    let status =
        determine_status(db_healthy, observers.as_ref(), secrets.as_ref(), federation.as_ref());
    #[cfg(not(feature = "federation"))]
    let status = determine_status(db_healthy, observers.as_ref(), secrets.as_ref());

    let response = HealthResponse {
        status: status.to_string(),
        database,
        observers,
        cache,
        secrets,
        #[cfg(feature = "federation")]
        federation,
        version: env!("CARGO_PKG_VERSION").to_string(),
        schema_hash,
    };

    let status_code = if status == "unhealthy" {
        StatusCode::SERVICE_UNAVAILABLE
    } else {
        StatusCode::OK
    };

    (status_code, Json(response))
}

/// Readiness probe handler.
///
/// Returns `200 OK` when the server can serve traffic (database reachable),
/// or `503 Service Unavailable` when it cannot.
///
/// Kubernetes usage:
/// - `livenessProbe` → `GET /health` (always 200 while process is alive)
/// - `readinessProbe` → `GET /readiness` (503 while not ready to serve traffic)
pub async fn readiness_handler<A: DatabaseAdapter + Clone + Send + Sync + 'static>(
    State(state): State<AppState<A>>,
) -> impl IntoResponse {
    debug!("Readiness check requested");

    let db_healthy = state.executor().adapter().health_check().await.is_ok();

    if db_healthy {
        (
            StatusCode::OK,
            Json(ReadinessResponse {
                status: "ready".to_string(),
                reason: None,
            }),
        )
    } else {
        (
            StatusCode::SERVICE_UNAVAILABLE,
            Json(ReadinessResponse {
                status: "not_ready".to_string(),
                reason: Some("Database connection unavailable".to_string()),
            }),
        )
    }
}

/// Federation health check handler.
///
/// Returns federation-specific health status.
///
/// When federation is configured in the compiled schema, reports `healthy`.
/// When federation is not configured, reports `not_configured`.
///
/// # Response Codes
///
/// - 200: Federation status retrieved
#[cfg(feature = "federation")]
pub async fn federation_health_handler<A: DatabaseAdapter + Clone + Send + Sync + 'static>(
    State(state): State<AppState<A>>,
) -> impl IntoResponse {
    debug!("Federation health check requested");

    let executor = state.executor();
    let schema = executor.schema();
    let (status, status_code) = match schema.federation.as_ref() {
        Some(fed) if fed.enabled => ("healthy", StatusCode::OK),
        _ => ("not_configured", StatusCode::OK),
    };

    let subgraphs = state.circuit_breaker.as_ref().map_or_else(Vec::new, |cb| {
        cb.health_snapshot()
            .into_iter()
            .map(|entry| {
                let available = matches!(
                    entry.state,
                    crate::federation::circuit_breaker::CircuitHealthState::Closed
                        | crate::federation::circuit_breaker::CircuitHealthState::HalfOpen
                );
                crate::federation::SubgraphHealthStatus {
                    name: entry.subgraph,
                    available,
                    latency_ms: 0.0,
                    last_check: chrono::Utc::now().to_rfc3339(),
                    error_count_last_60s: 0,
                    error_rate_percent: 0.0,
                }
            })
            .collect()
    });

    let response = FederationHealthResponse {
        status: status.to_string(),
        subgraphs,
        timestamp: chrono::Utc::now().to_rfc3339(),
    };

    (status_code, Json(response))
}

/// Determines overall health status.
///
/// - `"unhealthy"` (503): database is down
/// - `"degraded"` (200): database is up but one or more optional subsystems are failing
/// - `"healthy"` (200): all enabled subsystems are operational
#[cfg(feature = "federation")]
fn determine_status(
    db_healthy: bool,
    observers: Option<&ObserverHealth>,
    secrets: Option<&SecretsHealth>,
    federation: Option<&FederationHealth>,
) -> &'static str {
    if !db_healthy {
        return "unhealthy";
    }

    let observers_degraded = observers.is_some_and(|o| !o.running);
    let secrets_degraded = secrets.is_some_and(|s| !s.connected);
    let federation_degraded = federation.is_some_and(|f| {
        f.configured
            && f.subgraphs.iter().any(|sg| {
                matches!(sg.state, crate::federation::circuit_breaker::CircuitHealthState::Open)
            })
    });

    if observers_degraded || secrets_degraded || federation_degraded {
        "degraded"
    } else {
        "healthy"
    }
}

#[cfg(not(feature = "federation"))]
fn determine_status(
    db_healthy: bool,
    observers: Option<&ObserverHealth>,
    secrets: Option<&SecretsHealth>,
) -> &'static str {
    if !db_healthy {
        return "unhealthy";
    }

    let observers_degraded = observers.is_some_and(|o| !o.running);
    let secrets_degraded = secrets.is_some_and(|s| !s.connected);

    if observers_degraded || secrets_degraded {
        "degraded"
    } else {
        "healthy"
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
    #![allow(clippy::cast_precision_loss)] // Reason: test metrics reporting
    #![allow(clippy::cast_sign_loss)] // Reason: test data uses small positive integers
    #![allow(clippy::cast_possible_truncation)] // Reason: test data values are bounded
    #![allow(clippy::cast_possible_wrap)] // Reason: test data values are bounded
    #![allow(clippy::missing_panics_doc)] // Reason: test helpers
    #![allow(clippy::missing_errors_doc)] // Reason: test helpers
    #![allow(missing_docs)] // Reason: test code
    #![allow(clippy::items_after_statements)] // Reason: test helpers defined near use site

    use super::*;

    #[test]
    fn test_determine_status_all_healthy() {
        #[cfg(feature = "federation")]
        assert_eq!(determine_status(true, None, None, None), "healthy");
        #[cfg(not(feature = "federation"))]
        assert_eq!(determine_status(true, None, None), "healthy");
    }

    #[test]
    fn test_determine_status_db_down_is_unhealthy() {
        #[cfg(feature = "federation")]
        assert_eq!(determine_status(false, None, None, None), "unhealthy");
        #[cfg(not(feature = "federation"))]
        assert_eq!(determine_status(false, None, None), "unhealthy");
    }

    #[test]
    fn test_determine_status_observers_not_running_is_degraded() {
        let observers = Some(ObserverHealth {
            running:        false,
            pending_events: 0,
            last_error:     None,
        });
        #[cfg(feature = "federation")]
        assert_eq!(determine_status(true, observers.as_ref(), None, None), "degraded");
        #[cfg(not(feature = "federation"))]
        assert_eq!(determine_status(true, observers.as_ref(), None), "degraded");
    }

    #[test]
    fn test_determine_status_secrets_disconnected_is_degraded() {
        let secrets = Some(SecretsHealth {
            connected: false,
            backend:   "vault".to_string(),
        });
        #[cfg(feature = "federation")]
        assert_eq!(determine_status(true, None, secrets.as_ref(), None), "degraded");
        #[cfg(not(feature = "federation"))]
        assert_eq!(determine_status(true, None, secrets.as_ref()), "degraded");
    }

    #[cfg(feature = "federation")]
    #[test]
    fn test_determine_status_federation_circuit_open_is_degraded() {
        use crate::federation::circuit_breaker::{CircuitHealthState, SubgraphCircuitHealth};

        let federation = Some(FederationHealth {
            configured: true,
            subgraphs:  vec![SubgraphCircuitHealth {
                subgraph: "Product".to_string(),
                state:    CircuitHealthState::Open,
            }],
        });
        assert_eq!(determine_status(true, None, None, federation.as_ref()), "degraded");
    }

    #[test]
    fn test_determine_status_db_down_overrides_degraded() {
        let secrets = Some(SecretsHealth {
            connected: false,
            backend:   "vault".to_string(),
        });
        #[cfg(feature = "federation")]
        assert_eq!(determine_status(false, None, secrets.as_ref(), None), "unhealthy");
        #[cfg(not(feature = "federation"))]
        assert_eq!(determine_status(false, None, secrets.as_ref()), "unhealthy");
    }

    #[test]
    fn test_health_response_serialization() {
        let response = HealthResponse {
            status: "healthy".to_string(),
            database: DatabaseStatus {
                connected:          true,
                database_type:      "PostgreSQL".to_string(),
                active_connections: Some(2),
                idle_connections:   Some(8),
            },
            observers: None,
            cache: None,
            secrets: None,
            #[cfg(feature = "federation")]
            federation: None,
            version: "2.0.0-a1".to_string(),
            schema_hash: Some("abc123def456abc1".to_string()),
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("healthy"));
        assert!(json.contains("PostgreSQL"));
    }

    #[cfg(feature = "federation")]
    #[test]
    fn test_health_response_omits_federation_when_none() {
        let response = HealthResponse {
            status:      "healthy".to_string(),
            database:    DatabaseStatus {
                connected:          true,
                database_type:      "PostgreSQL".to_string(),
                active_connections: None,
                idle_connections:   None,
            },
            observers:   None,
            cache:       None,
            secrets:     None,
            federation:  None,
            version:     "2.0.0".to_string(),
            schema_hash: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(!json.contains("federation"), "federation key must be absent when field is None");
    }

    #[cfg(feature = "federation")]
    #[test]
    fn test_health_response_includes_federation_when_present() {
        use crate::federation::circuit_breaker::{CircuitHealthState, SubgraphCircuitHealth};

        let response = HealthResponse {
            status:      "healthy".to_string(),
            database:    DatabaseStatus {
                connected:          true,
                database_type:      "PostgreSQL".to_string(),
                active_connections: None,
                idle_connections:   None,
            },
            observers:   None,
            cache:       None,
            secrets:     None,
            federation:  Some(FederationHealth {
                configured: true,
                subgraphs:  vec![SubgraphCircuitHealth {
                    subgraph: "Product".to_string(),
                    state:    CircuitHealthState::Open,
                }],
            }),
            version:     "2.0.0".to_string(),
            schema_hash: None,
        };

        let json = serde_json::to_string(&response).unwrap();
        assert!(json.contains("federation"), "federation key must be present");
        assert!(json.contains("configured"), "configured field must appear");
        assert!(json.contains("Product"), "subgraph name must appear");
        assert!(json.contains("open"), "circuit state must be serialised as snake_case");
    }
}