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
//! HTTP handlers for observer management endpoints.

use axum::{
    Json,
    extract::{Path, Query, State},
    http::StatusCode,
    response::IntoResponse,
};
use fraiseql_core::security::SecurityContext;
use uuid::Uuid;

use super::{
    CreateObserverRequest, ListObserverLogsQuery, ListObserversQuery, ObserverRepository,
    PaginatedResponse, UpdateObserverRequest,
};
use crate::extractors::OptionalSecurityContext;

/// Application state for observer handlers.
#[derive(Clone)]
pub struct ObserverState {
    /// Repository used by all observer HTTP handlers.
    pub repository: ObserverRepository,
}

/// List observers with optional filters.
///
/// GET /api/observers
pub async fn list_observers(
    State(state): State<ObserverState>,
    OptionalSecurityContext(security_context): OptionalSecurityContext,
    Query(query): Query<ListObserversQuery>,
) -> impl IntoResponse {
    let customer_org: Option<i64> = extract_customer_org(security_context.as_ref());

    match state.repository.list(&query, customer_org).await {
        Ok((observers, total_count)) => {
            let response =
                PaginatedResponse::new(observers, query.page, query.page_size, total_count);
            (StatusCode::OK, Json(response)).into_response()
        },
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to list observers: {}", error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Get a single observer by ID.
///
/// GET /api/observers/:id
pub async fn get_observer(
    State(state): State<ObserverState>,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let customer_org: Option<i64> = None;

    match state.repository.get_by_id(id, customer_org).await {
        Ok(Some(observer)) => (StatusCode::OK, Json(observer)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "Observer not found" })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to get observer {}: {}", id, error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Create a new observer.
///
/// POST /api/observers
pub async fn create_observer(
    State(state): State<ObserverState>,
    OptionalSecurityContext(security_context): OptionalSecurityContext,
    Json(request): Json<CreateObserverRequest>,
) -> impl IntoResponse {
    // Validate request
    if request.name.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({ "error": "Name is required" })),
        )
            .into_response();
    }

    if request.actions.is_empty() {
        return (
            StatusCode::BAD_REQUEST,
            Json(serde_json::json!({ "error": "At least one action is required" })),
        )
            .into_response();
    }

    // Validate event_type if provided
    if let Some(ref event_type) = request.event_type {
        let valid_types = ["INSERT", "UPDATE", "DELETE", "CUSTOM"];
        if !valid_types.contains(&event_type.as_str()) {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": format!("Invalid event_type '{}'. Must be one of: {:?}", event_type, valid_types)
                })),
            )
                .into_response();
        }
    }

    let customer_org: Option<i64> = extract_customer_org(security_context.as_ref());
    let created_by: Option<&str> = extract_user_id(security_context.as_ref());

    match state.repository.create(&request, customer_org, created_by).await {
        Ok(observer) => (StatusCode::CREATED, Json(observer)).into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to create observer: {}", error_msg);
            let status = if error_msg.contains("already exists") {
                StatusCode::CONFLICT
            } else {
                StatusCode::INTERNAL_SERVER_ERROR
            };
            (status, Json(serde_json::json!({ "error": error_msg }))).into_response()
        },
    }
}

/// Update an existing observer.
///
/// PATCH /api/observers/:id
pub async fn update_observer(
    State(state): State<ObserverState>,
    OptionalSecurityContext(security_context): OptionalSecurityContext,
    Path(id): Path<Uuid>,
    Json(request): Json<UpdateObserverRequest>,
) -> impl IntoResponse {
    // Validate event_type if provided
    if let Some(ref event_type) = request.event_type {
        let valid_types = ["INSERT", "UPDATE", "DELETE", "CUSTOM"];
        if !valid_types.contains(&event_type.as_str()) {
            return (
                StatusCode::BAD_REQUEST,
                Json(serde_json::json!({
                    "error": format!("Invalid event_type '{}'. Must be one of: {:?}", event_type, valid_types)
                })),
            )
                .into_response();
        }
    }

    let customer_org: Option<i64> = extract_customer_org(security_context.as_ref());
    let updated_by: Option<&str> = extract_user_id(security_context.as_ref());

    match state.repository.update(id, &request, customer_org, updated_by).await {
        Ok(Some(observer)) => (StatusCode::OK, Json(observer)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "Observer not found" })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to update observer {}: {}", id, error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Delete an observer (soft delete).
///
/// DELETE /api/observers/:id
pub async fn delete_observer(
    State(state): State<ObserverState>,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let customer_org: Option<i64> = None;

    match state.repository.delete(id, customer_org).await {
        Ok(true) => StatusCode::NO_CONTENT.into_response(),
        Ok(false) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "Observer not found" })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to delete observer {}: {}", id, error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Get observer statistics.
///
/// GET /api/observers/stats
/// GET /api/observers/:id/stats
pub async fn get_observer_stats(
    State(state): State<ObserverState>,
    observer_id: Option<Path<Uuid>>,
) -> impl IntoResponse {
    let customer_org: Option<i64> = None;
    let id = observer_id.map(|p| p.0);

    match state.repository.get_stats(id, customer_org).await {
        Ok(stats) => (StatusCode::OK, Json(stats)).into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to get observer stats: {}", error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// List observer execution logs.
///
/// GET /api/observers/logs
/// GET /api/observers/:id/logs
pub async fn list_observer_logs(
    State(state): State<ObserverState>,
    Path(observer_id): Path<Option<Uuid>>,
    Query(mut query): Query<ListObserverLogsQuery>,
) -> impl IntoResponse {
    // If observer_id is in path, use it
    if let Some(id) = observer_id {
        query.observer_id = Some(id);
    }

    let customer_org: Option<i64> = None;

    match state.repository.list_logs(&query, customer_org).await {
        Ok((logs, total_count)) => {
            let response = PaginatedResponse::new(logs, query.page, query.page_size, total_count);
            (StatusCode::OK, Json(response)).into_response()
        },
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to list observer logs: {}", error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Enable an observer.
///
/// POST /api/observers/:id/enable
pub async fn enable_observer(
    State(state): State<ObserverState>,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let request = UpdateObserverRequest {
        enabled: Some(true),
        ..Default::default()
    };

    let customer_org: Option<i64> = None;
    let updated_by: Option<&str> = None;

    match state.repository.update(id, &request, customer_org, updated_by).await {
        Ok(Some(observer)) => (StatusCode::OK, Json(observer)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "Observer not found" })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to enable observer {}: {}", id, error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

/// Disable an observer.
///
/// POST /api/observers/:id/disable
pub async fn disable_observer(
    State(state): State<ObserverState>,
    Path(id): Path<Uuid>,
) -> impl IntoResponse {
    let request = UpdateObserverRequest {
        enabled: Some(false),
        ..Default::default()
    };

    let customer_org: Option<i64> = None;
    let updated_by: Option<&str> = None;

    match state.repository.update(id, &request, customer_org, updated_by).await {
        Ok(Some(observer)) => (StatusCode::OK, Json(observer)).into_response(),
        Ok(None) => (
            StatusCode::NOT_FOUND,
            Json(serde_json::json!({ "error": "Observer not found" })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to disable observer {}: {}", id, error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

// ============================================================================
// Runtime Health Check Handlers
// ============================================================================

use std::sync::Arc;

use tokio::sync::RwLock;

/// State for runtime health checks
#[derive(Clone)]
pub struct RuntimeHealthState {
    /// Reference to the observer runtime (wrapped in `RwLock` for thread safety)
    pub runtime: Arc<RwLock<super::ObserverRuntime>>,
}

/// Get observer runtime health status.
///
/// GET /api/observers/runtime/health
pub async fn get_runtime_health(State(state): State<RuntimeHealthState>) -> impl IntoResponse {
    let runtime = state.runtime.read().await;
    let health = runtime.health();

    let status = if health.running {
        StatusCode::OK
    } else {
        StatusCode::SERVICE_UNAVAILABLE
    };

    // Convert RuntimeHealth to JSON-serializable format
    let health_json = serde_json::json!({
        "running": health.running,
        "observer_count": health.observer_count,
        "last_checkpoint": health.last_checkpoint,
        "events_processed": health.events_processed,
        "errors": health.errors
    });

    (status, Json(health_json)).into_response()
}

/// Reload observers from database.
///
/// POST /api/observers/runtime/reload
pub async fn reload_observers(State(state): State<RuntimeHealthState>) -> impl IntoResponse {
    let runtime = state.runtime.read().await;

    match runtime.reload_observers().await {
        Ok(count) => (
            StatusCode::OK,
            Json(serde_json::json!({
                "message": "Observers reloaded successfully",
                "count": count
            })),
        )
            .into_response(),
        Err(e) => {
            let error_msg = e.to_string();
            tracing::error!("Failed to reload observers: {}", error_msg);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(serde_json::json!({ "error": error_msg })),
            )
                .into_response()
        },
    }
}

// ============================================================================
// Authentication Context Extraction
// ============================================================================

/// Extract customer/tenant organization ID from request context.
///
/// In a full implementation, this would use Axum extractors to pull from
/// the `SecurityContext` middleware. For now, returns None as a safe default.
/// In production, integrate with your auth middleware to extract from:
/// - X-Tenant-Id header
/// - JWT claims (`tenant_id` field)
/// - Session context
///
/// # Returns
///
/// Extract tenant/customer-org identifier from the authenticated security context.
///
/// Parses `SecurityContext::tenant_id` (a string) as `i64`.
/// Returns `None` if unauthenticated or if the tenant ID is absent or non-numeric.
#[must_use]
fn extract_customer_org(ctx: Option<&SecurityContext>) -> Option<i64> {
    ctx?.tenant_id.as_deref()?.parse::<i64>().ok()
}

/// Extract the authenticated user ID from the security context.
///
/// Returns `None` when the request is unauthenticated.
#[must_use]
fn extract_user_id(ctx: Option<&SecurityContext>) -> Option<&str> {
    Some(ctx?.user_id.as_str())
}