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
//! HTTP Server End-to-End Tests
//!
//! Tests complete HTTP request/response flow:
//! 1. HTTP server starts and binds to port
//! 2. Client makes HTTP requests
//! 3. Server processes requests (parsing, validation, execution)
//! 4. Responses returned in correct format
//! 5. Error handling works correctly
//!
//! These are TRUE E2E tests with actual HTTP server running.
//!
//! ## Running Tests
//!
//! By default, tests connect to `http://localhost:8000`. Set the
//! `FRAISEQL_TEST_URL` environment variable to test against a different server:
//!
//! ```bash
//! # Test against Docker E2E server
//! FRAISEQL_TEST_URL=http://localhost:9001 cargo test -p fraiseql-server --test http_server_e2e_test -- --include-ignored
//! ```
//!
//! **Execution engine:** none
//! **Infrastructure:** none
//! **Parallelism:** safe
#![allow(clippy::unwrap_used)] // Reason: test code, panics acceptable
#![allow(clippy::cast_precision_loss)] // Reason: test metrics use usize/u64→f64 for reporting
#![allow(clippy::cast_sign_loss)] // Reason: test data uses small positive integers
#![allow(clippy::cast_possible_truncation)] // Reason: test data values are small and bounded
#![allow(clippy::cast_possible_wrap)] // Reason: test data values are small and bounded
#![allow(clippy::cast_lossless)] // Reason: test code readability
#![allow(clippy::missing_panics_doc)] // Reason: test helper functions, panics are expected
#![allow(clippy::missing_errors_doc)] // Reason: test helper functions
#![allow(missing_docs)] // Reason: test code does not require documentation
#![allow(clippy::items_after_statements)] // Reason: test helpers defined near use site
#![allow(clippy::used_underscore_binding)] // Reason: test variables prefixed with _ by convention
#![allow(clippy::needless_pass_by_value)] // Reason: test helper signatures follow test patterns

mod test_helpers;

use std::env;

use reqwest::StatusCode;
use test_helpers::*;

/// Get the base URL for testing. Defaults to localhost:8000, but can be
/// overridden with `FRAISEQL_TEST_URL` environment variable.
fn get_test_base_url() -> String {
    env::var("FRAISEQL_TEST_URL").unwrap_or_else(|_| "http://localhost:8000".to_string())
}

/// Returns `true` if `FRAISEQL_TEST_URL` is set, indicating a FraiseQL server
/// is available for E2E testing. Tests that require a running server should
/// call this and return early if it returns `false`.
fn fraiseql_server_available() -> bool {
    env::var("FRAISEQL_TEST_URL").is_ok()
}

/// Test that health endpoint responds correctly
#[tokio::test]
async fn test_health_endpoint_responds() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Test health endpoint
    let response = client.get(format!("{}/health", base_url)).send().await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::OK);
            let json = resp
                .json::<serde_json::Value>()
                .await
                .expect("health response should be valid JSON");
            assert_health_response(&json);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test that metrics endpoint responds with Prometheus format (requires bearer token)
#[tokio::test]
async fn test_metrics_endpoint_responds() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();
    let token = get_metrics_token();

    let response = client
        .get(format!("{}/metrics", base_url))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::OK);
            let content_type = resp
                .headers()
                .get("content-type")
                .expect("metrics response should have Content-Type header");
            let ct_str = content_type.to_str().unwrap();
            assert!(
                ct_str.contains("text/plain") || ct_str.contains("application/openmetrics"),
                "metrics Content-Type should be Prometheus format, got: {ct_str}"
            );

            let text = resp.text().await.expect("metrics response should have a body");
            assert!(
                text.contains("fraiseql_graphql_queries_total"),
                "metrics body should contain Prometheus metric names"
            );
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test that metrics JSON endpoint responds correctly (requires bearer token)
#[tokio::test]
async fn test_metrics_json_endpoint_responds() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();
    let token = get_metrics_token();

    let response = client
        .get(format!("{}/metrics/json", base_url))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::OK);

            let json = resp
                .json::<serde_json::Value>()
                .await
                .expect("metrics JSON response should be valid JSON");
            assert_metrics_response(&json);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test that metrics endpoint rejects requests without token
#[tokio::test]
async fn test_metrics_endpoint_requires_auth() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Request without Authorization header
    let response = client.get(format!("{}/metrics", base_url)).send().await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test that metrics endpoint rejects invalid token
#[tokio::test]
async fn test_metrics_endpoint_rejects_invalid_token() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let response = client
        .get(format!("{}/metrics", base_url))
        .header("Authorization", "Bearer wrong-token")
        .send()
        .await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::FORBIDDEN);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test that invalid paths return 404
#[tokio::test]
async fn test_invalid_path_returns_404() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let response = client.get(format!("{}/invalid/path", base_url)).send().await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::NOT_FOUND);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test GraphQL endpoint accepts POST requests
#[tokio::test]
async fn test_graphql_endpoint_accepts_post() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Use a real query from our schema (users list query)
    let request = create_graphql_request("{ users { id name } }", None, None);

    let response = client.post(format!("{}/graphql", base_url)).json(&request).send().await;

    match response {
        Ok(resp) => {
            assert_eq!(resp.status(), StatusCode::OK);
            let json = resp
                .json::<serde_json::Value>()
                .await
                .expect("GraphQL response should be valid JSON");
            assert_graphql_response(&json);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test GraphQL endpoint rejects GET requests
#[tokio::test]
async fn test_graphql_endpoint_rejects_get() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let response = client.get(format!("{}/graphql", base_url)).send().await;

    match response {
        Ok(resp) => {
            // Should reject GET with 405 or similar
            assert_ne!(resp.status(), StatusCode::OK);
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test response includes correct headers
#[tokio::test]
async fn test_response_headers_correct() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Use a real query from our schema
    let request = create_graphql_request("{ users { id name } }", None, None);

    let response = client.post(format!("{}/graphql", base_url)).json(&request).send().await;

    match response {
        Ok(resp) => {
            // Should have Content-Type header
            let content_type = resp.headers().get("content-type");
            assert!(content_type.is_some());

            if let Some(ct) = content_type {
                let ct_str = ct.to_str().unwrap_or("");
                assert!(ct_str.contains("application/json"));
            }
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test empty query returns validation error
#[tokio::test]
async fn test_empty_query_returns_error() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let request = create_graphql_request("", None, None);

    let response = client.post(format!("{}/graphql", base_url)).json(&request).send().await;

    match response {
        Ok(resp) => {
            // Server may return 400 Bad Request or 200 OK with errors in body
            // Both are valid ways to handle empty query
            let status = resp.status();
            assert!(
                status == StatusCode::OK || status == StatusCode::BAD_REQUEST,
                "Expected OK or BAD_REQUEST, got {}",
                status
            );

            let body = resp.json::<serde_json::Value>().await;
            if let Ok(json) = body {
                // Should have errors if 200 response
                if status == StatusCode::OK {
                    assert!(json.get("errors").is_some());
                }
            }
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test malformed JSON returns bad request
#[tokio::test]
async fn test_malformed_json_returns_error() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let response = client
        .post(format!("{}/graphql", base_url))
        .body("{invalid json")
        .header("Content-Type", "application/json")
        .send()
        .await;

    match response {
        Ok(resp) => {
            // Should return 400 or 422
            assert!(resp.status().is_client_error());
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test introspection endpoint responds
#[tokio::test]
async fn test_introspection_endpoint_responds() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    let response = client.post(format!("{}/introspection", base_url)).send().await;

    match response {
        Ok(resp) => {
            let status = resp.status();
            assert!(
                status == StatusCode::OK
                    || status == StatusCode::BAD_REQUEST
                    || status == StatusCode::METHOD_NOT_ALLOWED,
                "Introspection should return 200, 400, or 405; got {status}"
            );
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

/// Test concurrent requests to health endpoint
#[tokio::test]
async fn test_concurrent_health_requests() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Create 10 concurrent requests
    let futures: Vec<_> = (0..10)
        .map(|_| {
            let client = client.clone();
            let url = format!("{}/health", base_url);
            async move { client.get(url).send().await }
        })
        .collect();

    let results = futures::future::join_all(futures).await;

    let successful = results.iter().filter(|r| r.is_ok()).count();

    // All 10 concurrent health checks should succeed
    assert_eq!(
        successful, 10,
        "all concurrent health requests should succeed, got {successful}/10"
    );
}

/// Test response content type consistency
#[tokio::test]
async fn test_content_type_consistency() {
    if !fraiseql_server_available() {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    }
    let client = create_test_client();
    let base_url = get_test_base_url();

    // Test GraphQL endpoint with a real query
    let request = create_graphql_request("{ users { id name } }", None, None);
    let response = client.post(format!("{}/graphql", base_url)).json(&request).send().await;

    match response {
        Ok(resp) => {
            let content_type = resp
                .headers()
                .get("content-type")
                .expect("GraphQL response should have Content-Type header");
            let ct_str = content_type.to_str().unwrap();
            assert!(
                ct_str.contains("application/json"),
                "GraphQL response Content-Type should be application/json, got: {ct_str}"
            );
        },
        Err(e) => {
            eprintln!("Warning: Could not connect to server: {}", e);
        },
    }
}

// Note: These tests assume a FraiseQL server is running on localhost:8000
// In CI/CD, you would typically:
// 1. Start the server in a test harness
// 2. Run these tests against it
// 3. Tear down the server
//
// Example with test harness:
// #[tokio::test]
// async fn test_with_server() {
//     let server = TestServer::start().await;
//     let client = create_test_client();
//
//     let response = client.get(server.health_url()).send().await;
//     assert!(response.is_ok());
//
//     server.shutdown().await;
// }