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
//! Concurrent Load Tests for FraiseQL Server
//!
//! Tests performance and correctness under concurrent request loads:
//! 1. Multiple concurrent HTTP requests
//! 2. Performance under sustained load
//! 3. Resource management (connection pooling)
//! 4. Error handling under load
//! 5. Throughput and latency measurements
//!
//! **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::{
    sync::{
        Arc,
        atomic::{AtomicU64, Ordering},
    },
    time::Instant,
};

use test_helpers::*;

/// Get base URL for load tests. Uses `FRAISEQL_TEST_URL` or defaults to `http://localhost:8000`.
fn get_load_test_url() -> Option<String> {
    std::env::var("FRAISEQL_TEST_URL").ok()
}

/// Test 10 concurrent requests to health endpoint
#[tokio::test]
async fn test_10_concurrent_health_requests() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let success_count = Arc::new(AtomicU64::new(0));

    let futures: Vec<_> = (0..10)
        .map(|_| {
            let client = client.clone();
            let url = format!("{}/health", base_url);
            let success = success_count.clone();

            async move {
                if let Ok(resp) = client.get(url).send().await {
                    if resp.status().is_success() {
                        success.fetch_add(1, Ordering::Relaxed);
                    }
                } else {
                    // Server not running
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let successful = success_count.load(Ordering::Relaxed);
    if successful > 0 {
        assert!(successful >= 1);
    }
}

/// Test 50 concurrent GraphQL queries
#[tokio::test]
async fn test_50_concurrent_graphql_queries() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let success_count = Arc::new(AtomicU64::new(0));
    let error_count = Arc::new(AtomicU64::new(0));

    let futures: Vec<_> = (0..50)
        .map(|i| {
            let client = client.clone();
            let url = format!("{}/graphql", base_url);
            let success = success_count.clone();
            let errors = error_count.clone();

            async move {
                let request = create_graphql_request(
                    "query { __typename }",
                    None,
                    Some(&format!("Query{}", i)),
                );

                match client.post(&url).json(&request).send().await {
                    Ok(resp) => {
                        if resp.status().is_success() {
                            success.fetch_add(1, Ordering::Relaxed);
                        } else {
                            errors.fetch_add(1, Ordering::Relaxed);
                        }
                    },
                    Err(_) => {
                        errors.fetch_add(1, Ordering::Relaxed);
                    },
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let successful = success_count.load(Ordering::Relaxed);
    let failed = error_count.load(Ordering::Relaxed);

    if successful > 0 {
        // If any succeeded, we should have at least 1
        assert!(successful >= 1);
    }

    // Should not crash under load - verify we ran the test
    // At least some requests should have been made
    assert!(successful + failed > 0, "No requests were processed");
}

/// Test 100 concurrent requests with varying endpoints
#[tokio::test]
async fn test_100_concurrent_mixed_endpoints() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let success_count = Arc::new(AtomicU64::new(0));

    let futures: Vec<_> = (0..100)
        .map(|i| {
            let client = client.clone();
            let success = success_count.clone();
            let base_url = base_url.clone();

            async move {
                let result = match i % 3 {
                    0 => {
                        // Health endpoint
                        client.get(format!("{}/health", base_url)).send().await
                    },
                    1 => {
                        // Metrics endpoint
                        client.get(format!("{}/metrics", base_url)).send().await
                    },
                    _ => {
                        // GraphQL endpoint
                        let request = create_graphql_request("{ __typename }", None, None);
                        client.post(format!("{}/graphql", base_url)).json(&request).send().await
                    },
                };

                if let Ok(resp) = result {
                    if resp.status().is_success() {
                        success.fetch_add(1, Ordering::Relaxed);
                    }
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let successful = success_count.load(Ordering::Relaxed);
    if successful > 0 {
        assert!(successful >= 1);
    }
}

/// Test throughput of health endpoint
#[tokio::test]
async fn test_health_endpoint_throughput() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();

    let start = Instant::now();
    let mut count = 0u64;

    // Fire requests as fast as possible for 1 second
    while start.elapsed().as_secs() < 1 {
        match client.get(format!("{}/health", base_url)).send().await {
            Ok(_) => count += 1,
            Err(_) => break, // Server not running
        }
    }

    if count > 0 {
        println!("Health endpoint throughput: {} req/s", count);
        assert!(count > 0);
    }
}

/// Test latency distribution under load
#[tokio::test]
async fn test_latency_distribution() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let latencies = Arc::new(tokio::sync::Mutex::new(Vec::new()));

    let futures: Vec<_> = (0..20)
        .map(|_| {
            let client = client.clone();
            let url = format!("{}/health", base_url);
            let latencies = latencies.clone();

            async move {
                let start = Instant::now();
                if client.get(&url).send().await.is_ok() {
                    let latency_ms = start.elapsed().as_millis() as u64;
                    let mut lats = latencies.lock().await;
                    lats.push(latency_ms);
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let lats = latencies.lock().await;
    if !lats.is_empty() {
        let min = lats.iter().min().copied().unwrap_or(0);
        let max = lats.iter().max().copied().unwrap_or(0);
        let avg = lats.iter().sum::<u64>() / lats.len() as u64;

        println!("Latency - Min: {}ms, Max: {}ms, Avg: {}ms", min, max, avg);

        // Latency should be reasonable (< 1s)
        assert!(max < 1000);
    }
}

/// Test sustained load for 10 seconds
#[tokio::test]
async fn test_sustained_load() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let request_count = Arc::new(AtomicU64::new(0));
    let start = Instant::now();

    let futures: Vec<_> = (0..5)
        .map(|_| {
            let client = client.clone();
            let count = request_count.clone();
            let base_url = base_url.clone();

            async move {
                let start = Instant::now();
                // Keep making requests for test duration
                while start.elapsed().as_secs() < 2 {
                    let request = create_graphql_request("{ __typename }", None, None);
                    if client
                        .post(format!("{}/graphql", base_url))
                        .json(&request)
                        .send()
                        .await
                        .is_ok()
                    {
                        count.fetch_add(1, Ordering::Relaxed);
                    }
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let total_requests = request_count.load(Ordering::Relaxed);
    let duration_secs = start.elapsed().as_secs_f64();

    if total_requests > 0 {
        let throughput = total_requests as f64 / duration_secs;
        println!(
            "Sustained load - Total: {}, Throughput: {:.1} req/s",
            total_requests, throughput
        );
        assert!(total_requests > 0);
    }
}

/// Test error handling under concurrent load
#[tokio::test]
async fn test_error_handling_under_load() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let success_count = Arc::new(AtomicU64::new(0));
    let error_count = Arc::new(AtomicU64::new(0));

    let futures: Vec<_> = (0..30)
        .map(|i| {
            let client = client.clone();
            let success = success_count.clone();
            let errors = error_count.clone();
            let base_url = base_url.clone();

            async move {
                let request = if i % 2 == 0 {
                    // Valid query
                    create_graphql_request("{ __typename }", None, None)
                } else {
                    // Invalid query (too deep)
                    create_graphql_request("{ a { b { c { d { e { f { g } } } } } } }", None, None)
                };

                match client.post(format!("{}/graphql", base_url)).json(&request).send().await {
                    Ok(resp) => {
                        if resp.status().is_success() {
                            success.fetch_add(1, Ordering::Relaxed);
                        } else {
                            errors.fetch_add(1, Ordering::Relaxed);
                        }
                    },
                    Err(_) => {
                        errors.fetch_add(1, Ordering::Relaxed);
                    },
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let successful = success_count.load(Ordering::Relaxed);
    let failed = error_count.load(Ordering::Relaxed);

    if successful > 0 {
        // Should handle both valid and invalid queries
        println!("Success: {}, Errors: {}", successful, failed);
    }
}

/// Test connection pool behavior under load
#[tokio::test]
async fn test_connection_pool_stability() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let slow_requests = Arc::new(AtomicU64::new(0));
    let fast_requests = Arc::new(AtomicU64::new(0));
    let slow_threshold_ms = 100u128;

    let futures: Vec<_> = (0..40)
        .map(|_| {
            let client = client.clone();
            let url = format!("{}/health", base_url);
            let slow = slow_requests.clone();
            let fast = fast_requests.clone();

            async move {
                let start = Instant::now();
                if client.get(&url).send().await.is_ok() {
                    let latency = start.elapsed().as_millis();
                    if latency > slow_threshold_ms {
                        slow.fetch_add(1, Ordering::Relaxed);
                    } else {
                        fast.fetch_add(1, Ordering::Relaxed);
                    }
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let fast = fast_requests.load(Ordering::Relaxed);
    let slow = slow_requests.load(Ordering::Relaxed);
    let total = fast + slow;

    if total > 0 {
        let slow_percentage = (slow as f64 / total as f64) * 100.0;
        println!(
            "Request latency - Fast (<{}ms): {:.1}%, Slow: {:.1}%",
            slow_threshold_ms,
            100.0 - slow_percentage,
            slow_percentage
        );

        // Most requests should be fast - only assert if this looks like a FraiseQL server
        // (other services on port 8000 may have different latency characteristics)
        if fast > 0 {
            assert!(
                fast > slow,
                "Connection pool stability test expects most requests to be fast (<100ms)"
            );
        }
    }
}

/// Test graceful degradation under extreme load
#[tokio::test]
async fn test_extreme_concurrent_load() {
    let Some(base_url) = get_load_test_url() else {
        eprintln!("skipped: FRAISEQL_TEST_URL not set");
        return;
    };
    let client = create_test_client();
    let success_count = Arc::new(AtomicU64::new(0));

    // Try 200 concurrent requests
    let futures: Vec<_> = (0..200)
        .map(|_| {
            let client = client.clone();
            let url = format!("{}/health", base_url);
            let success = success_count.clone();

            async move {
                if client.get(&url).send().await.is_ok() {
                    success.fetch_add(1, Ordering::Relaxed);
                }
            }
        })
        .collect();

    futures::future::join_all(futures).await;

    let successful = success_count.load(Ordering::Relaxed);
    if successful > 0 {
        println!("Extreme load - Successfully handled {}/200 requests", successful);
        assert!(successful >= 1);
    }
}