fraiseql-server 2.0.0-alpha.6

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
//! Example Validation Tests
//!
//! Validates that all documented code examples and patterns work correctly.
//! These tests serve as both validation and documentation of correct error handling usage.
//!
//! # Test Organization
//!
//! - **Basic Examples** (6 tests): Fundamental error creation and HTTP status codes
//! - **Documentation Examples** (10 tests): Patterns from architecture documentation
//! - **Real-World Examples** (6 tests): Production scenarios with complete context
//!
//! # Covered Patterns
//!
//! 1. Error creation: `new()`, `validation()`, `parse()`, `database()`, etc.
//! 2. Error enrichment: `with_location()`, `with_path()`, `with_extensions()`
//! 3. Request tracing: `with_request_id()` for distributed tracing
//! 4. Error chaining: Builder pattern for combining metadata
//! 5. HTTP status codes: Complete mapping of error codes to status codes
//! 6. Recovery patterns: Identifying retryable vs non-retryable errors
//! 7. Complex scenarios: Federation, subscriptions, batch queries, partial errors
//!
//! # Running Tests
//!
//! ```bash
//! cargo test --test example_validation_test -- --nocapture
//! ```

#![cfg(test)]

use axum::http::StatusCode;
use fraiseql_server::error::{ErrorCode, ErrorExtensions, GraphQLError};

// ============================================================================
// SECTION 1: BASIC EXAMPLES (Fundamental error handling patterns)
// ============================================================================
// These tests demonstrate the most common error handling patterns:
// - Creating errors with specific codes
// - HTTP status code mapping
// - Basic error message construction
//
// Use these as a quick reference for error handling in handlers.

// ============================================================================
// Example 1: Basic Error Handling
// ============================================================================

#[test]
fn test_example_basic_error_handling() {
    // Example from docs showing basic error creation
    let error = GraphQLError::validation("Field 'email' is required for mutation 'createUser'");

    // Assertions match documentation
    assert_eq!(error.code, ErrorCode::ValidationError);
    assert_eq!(error.message, "Field 'email' is required for mutation 'createUser'");
    assert_eq!(error.code.status_code(), StatusCode::BAD_REQUEST);
}

// ============================================================================
// Example 2: Parse Error with Location
// ============================================================================

#[test]
fn test_example_parse_error_with_location() {
    // Example showing how to report parse errors with source location
    let error =
        GraphQLError::parse("Unexpected token '}' at line 1, column 15").with_location(1, 15);

    assert_eq!(error.code, ErrorCode::ParseError);
    assert!(error.locations.is_some());
    let locations = error.locations.unwrap();
    assert_eq!(locations[0].line, 1);
    assert_eq!(locations[0].column, 15);
}

// ============================================================================
// Documentation Example 3: Field Error with Path
// ============================================================================

#[test]
fn test_example_field_error_with_path() {
    // Example showing how to report field-level errors in responses
    let error = GraphQLError::validation("Cannot query field 'unknownField' on type 'User'")
        .with_path(vec!["user".to_string(), "profile".to_string()])
        .with_location(5, 10);

    assert_eq!(error.code, ErrorCode::ValidationError);
    assert!(error.path.is_some());
    let path = error.path.unwrap();
    assert_eq!(path.len(), 2);
    assert_eq!(path[0], "user");
    assert_eq!(path[1], "profile");
}

// ============================================================================
// Documentation Example 4: Authentication Error
// ============================================================================

#[test]
fn test_example_authentication_error() {
    // Example from docs: handling missing authentication
    let error = GraphQLError::unauthenticated();

    assert_eq!(error.code, ErrorCode::Unauthenticated);
    assert_eq!(error.code.status_code(), StatusCode::UNAUTHORIZED);
    assert_eq!(error.message, "Authentication required");
}

// ============================================================================
// Documentation Example 5: Authorization Error
// ============================================================================

#[test]
fn test_example_authorization_error() {
    // Example from docs: handling insufficient permissions
    let error = GraphQLError::forbidden();

    assert_eq!(error.code, ErrorCode::Forbidden);
    assert_eq!(error.code.status_code(), StatusCode::FORBIDDEN);
    assert_eq!(error.message, "Access denied");
}

// ============================================================================
// Documentation Example 6: Database Error
// ============================================================================

#[test]
fn test_example_database_error() {
    // Example showing database error handling
    let error = GraphQLError::database("Connection timeout: unable to reach database server");

    assert_eq!(error.code, ErrorCode::DatabaseError);
    assert_eq!(error.code.status_code(), StatusCode::INTERNAL_SERVER_ERROR);
}

// ============================================================================
// Documentation Example 7: Timeout Error
// ============================================================================

#[test]
fn test_example_timeout_error() {
    // Example showing timeout error with helper
    let error = GraphQLError::timeout("Query execution");

    assert_eq!(error.code, ErrorCode::Timeout);
    assert_eq!(error.code.status_code(), StatusCode::REQUEST_TIMEOUT);
    assert!(error.message.contains("exceeded timeout"));
}

// ============================================================================
// Documentation Example 8: Rate Limit Error
// ============================================================================

#[test]
fn test_example_rate_limit_error() {
    // Example showing rate limiting error
    let error = GraphQLError::rate_limited("Exceeded 1000 requests per minute");

    assert_eq!(error.code, ErrorCode::RateLimitExceeded);
    assert_eq!(error.code.status_code(), StatusCode::TOO_MANY_REQUESTS);
}

// ============================================================================
// Documentation Example 9: Request ID for Distributed Tracing
// ============================================================================

#[test]
fn test_example_request_id_tracing() {
    // Example from docs showing request ID for distributed tracing
    let error = GraphQLError::database("Connection error").with_request_id("req-abc-123-xyz");

    assert!(error.extensions.is_some());
    let ext = error.extensions.unwrap();
    assert_eq!(ext.request_id, Some("req-abc-123-xyz".to_string()));
}

// ============================================================================
// Documentation Example 10: Error with Extensions Metadata
// ============================================================================

#[test]
fn test_example_error_with_extensions() {
    // Example showing how to add custom metadata via extensions
    let extensions = ErrorExtensions {
        category:   Some("DATABASE".to_string()),
        status:     Some(500),
        request_id: Some("req-db-001".to_string()),
    };

    let error = GraphQLError::database("Connection pool exhausted").with_extensions(extensions);

    assert!(error.extensions.is_some());
    let ext = error.extensions.unwrap();
    assert_eq!(ext.category, Some("DATABASE".to_string()));
    assert_eq!(ext.status, Some(500));
    assert_eq!(ext.request_id, Some("req-db-001".to_string()));
}

// ============================================================================
// Documentation Example 11: Error Chaining Pattern
// ============================================================================

#[test]
fn test_example_error_chaining() {
    // Example showing how to chain error builders
    let error = GraphQLError::validation("Argument type mismatch")
        .with_location(2, 5)
        .with_path(vec!["user".to_string(), "age".to_string()])
        .with_request_id("req-val-456");

    assert_eq!(error.code, ErrorCode::ValidationError);
    assert!(error.locations.is_some());
    assert!(error.path.is_some());
    assert!(error.extensions.is_some());
}

// ============================================================================
// Documentation Example 12: All Error Codes and Status Codes
// ============================================================================

#[test]
fn test_example_error_code_status_mapping() {
    // Example showing complete status code mapping for reference
    struct ErrorMapping {
        code:   ErrorCode,
        status: StatusCode,
    }

    let mappings = [
        ErrorMapping {
            code:   ErrorCode::ValidationError,
            status: StatusCode::BAD_REQUEST,
        },
        ErrorMapping {
            code:   ErrorCode::ParseError,
            status: StatusCode::BAD_REQUEST,
        },
        ErrorMapping {
            code:   ErrorCode::RequestError,
            status: StatusCode::BAD_REQUEST,
        },
        ErrorMapping {
            code:   ErrorCode::Unauthenticated,
            status: StatusCode::UNAUTHORIZED,
        },
        ErrorMapping {
            code:   ErrorCode::Forbidden,
            status: StatusCode::FORBIDDEN,
        },
        ErrorMapping {
            code:   ErrorCode::NotFound,
            status: StatusCode::NOT_FOUND,
        },
        ErrorMapping {
            code:   ErrorCode::Timeout,
            status: StatusCode::REQUEST_TIMEOUT,
        },
        ErrorMapping {
            code:   ErrorCode::RateLimitExceeded,
            status: StatusCode::TOO_MANY_REQUESTS,
        },
        ErrorMapping {
            code:   ErrorCode::DatabaseError,
            status: StatusCode::INTERNAL_SERVER_ERROR,
        },
        ErrorMapping {
            code:   ErrorCode::InternalServerError,
            status: StatusCode::INTERNAL_SERVER_ERROR,
        },
    ];

    // Verify all mappings match documentation
    for mapping in &mappings {
        let error = GraphQLError::new("test", mapping.code);
        assert_eq!(
            error.code.status_code(),
            mapping.status,
            "Status code mismatch for {:?}",
            mapping.code
        );
    }
}

// ============================================================================
// Documentation Example 13: Multiple Errors in Response
// ============================================================================

#[test]
fn test_example_multiple_errors_in_response() {
    // Example showing multiple errors in a single GraphQL response
    let errors = [
        GraphQLError::validation("Field 'email' is required")
            .with_path(vec!["user".to_string(), "email".to_string()]),
        GraphQLError::validation("Field 'age' must be >= 18")
            .with_path(vec!["user".to_string(), "age".to_string()]),
    ];

    assert_eq!(errors.len(), 2);
    assert!(errors.iter().all(|e| e.code == ErrorCode::ValidationError));
    assert!(errors[0].path.is_some());
    assert!(errors[1].path.is_some());
}

// ============================================================================
// Documentation Example 14: Common Error Patterns in Handlers
// ============================================================================

#[test]
fn test_example_handler_error_patterns() {
    // Example patterns commonly used in HTTP handlers

    // Pattern 1: Validation error from request
    {
        let error =
            GraphQLError::request("Invalid variable type").with_request_id("req-handler-001");
        assert_eq!(error.code, ErrorCode::RequestError);
        assert!(error.extensions.is_some());
    }

    // Pattern 2: Authorization check failure
    {
        let error = GraphQLError::forbidden();
        assert_eq!(error.code, ErrorCode::Forbidden);
    }

    // Pattern 3: Not found error
    {
        let error = GraphQLError::not_found("User with ID 123 not found");
        assert_eq!(error.code, ErrorCode::NotFound);
    }

    // Pattern 4: Internal error with context
    {
        let error = GraphQLError::internal("Unexpected error in field resolver");
        assert_eq!(error.code, ErrorCode::InternalServerError);
    }
}

// ============================================================================
// Documentation Example 15: Security Error Examples
// ============================================================================

#[test]
fn test_example_security_error_patterns() {
    // Examples of security-related errors

    // SQL injection attempt
    {
        let error = GraphQLError::request("Invalid input: SQL keywords detected");
        assert_eq!(error.code, ErrorCode::RequestError);
        assert_eq!(error.code.status_code(), StatusCode::BAD_REQUEST);
    }

    // XSS attempt
    {
        let error = GraphQLError::request("Invalid input: HTML/script tags not allowed");
        assert_eq!(error.code, ErrorCode::RequestError);
    }

    // Rate limiting for brute force protection
    {
        let error = GraphQLError::rate_limited("Too many failed login attempts");
        assert_eq!(error.code, ErrorCode::RateLimitExceeded);
        assert_eq!(error.code.status_code(), StatusCode::TOO_MANY_REQUESTS);
    }
}

// ============================================================================
// Documentation Example 16: Error Recovery Patterns
// ============================================================================

#[test]
fn test_example_error_recovery_patterns() {
    // Examples showing error patterns for client recovery

    // Retryable error (timeout)
    {
        let error = GraphQLError::timeout("Query execution");
        let status = error.code.status_code();
        // Timeout is retryable
        assert_eq!(status, StatusCode::REQUEST_TIMEOUT);
    }

    // Retryable error (service unavailable)
    {
        let error = GraphQLError::internal("Service temporarily unavailable");
        let status = error.code.status_code();
        // Internal server errors may be retryable
        assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
    }

    // Non-retryable error (validation)
    {
        let error = GraphQLError::validation("Invalid field type");
        let status = error.code.status_code();
        // Validation errors should not be retried
        assert_eq!(status, StatusCode::BAD_REQUEST);
    }

    // Non-retryable error (authorization)
    {
        let error = GraphQLError::forbidden();
        let status = error.code.status_code();
        // Authorization errors should not be retried
        assert_eq!(status, StatusCode::FORBIDDEN);
    }
}

// ============================================================================
// Real-World Example: End-to-End Error Handling in Resolver
// ============================================================================

#[test]
fn test_example_resolver_error_handling() {
    // Real example: Error handling in a GraphQL resolver

    // Scenario: User query resolver
    // 1. Database lookup fails
    let db_error = GraphQLError::database("Failed to query user table")
        .with_path(vec!["user".to_string()])
        .with_request_id("req-resolver-001");

    assert_eq!(db_error.code, ErrorCode::DatabaseError);
    assert_eq!(db_error.code.status_code(), StatusCode::INTERNAL_SERVER_ERROR);

    // 2. Authorization check fails
    let auth_error = GraphQLError::forbidden()
        .with_path(vec!["user".to_string(), "email".to_string()])
        .with_request_id("req-resolver-001");

    assert_eq!(auth_error.code, ErrorCode::Forbidden);
    assert_eq!(auth_error.code.status_code(), StatusCode::FORBIDDEN);

    // 3. Validation error in arguments
    let validation_error = GraphQLError::validation("Argument 'id' must be positive")
        .with_location(3, 20)
        .with_request_id("req-resolver-001");

    assert_eq!(validation_error.code, ErrorCode::ValidationError);
    assert_eq!(validation_error.code.status_code(), StatusCode::BAD_REQUEST);
}

// ============================================================================
// Real-World Example: Federation Error Handling
// ============================================================================

#[test]
fn test_example_federation_error_handling() {
    // Example: Error handling across federated subgraphs

    // Scenario: Cross-subgraph query with partial failure
    // Subgraph 1 (Users) succeeds, Subgraph 2 (Orders) times out

    let orders_timeout = GraphQLError::timeout("Orders subgraph")
        .with_path(vec!["user".to_string(), "orders".to_string()])
        .with_request_id("req-fed-001");

    assert_eq!(orders_timeout.code, ErrorCode::Timeout);
    assert_eq!(orders_timeout.code.status_code(), StatusCode::REQUEST_TIMEOUT);

    // Client can retry just the Orders subgraph using request ID
    assert!(orders_timeout.extensions.is_some());
    let ext = orders_timeout.extensions.unwrap();
    assert_eq!(ext.request_id, Some("req-fed-001".to_string()));
}

// ============================================================================
// Real-World Example: GraphQL Response with Errors and Partial Data
// ============================================================================

#[test]
fn test_example_graphql_response_with_partial_errors() {
    // Example: Proper GraphQL error response for partial failures

    // Scenario: Query returns data but some fields have errors
    // {
    //   "data": {
    //     "user": { "id": "1", "name": "Alice" },
    //     "posts": null  // null because field had error
    //   },
    //   "errors": [
    //     {
    //       "message": "Cannot access field 'posts' without permission",
    //       "code": "FORBIDDEN",
    //       "path": ["user", "posts"]
    //     }
    //   ]
    // }

    let partial_error =
        GraphQLError::forbidden().with_path(vec!["user".to_string(), "posts".to_string()]);

    assert_eq!(partial_error.code, ErrorCode::Forbidden);
    assert!(partial_error.path.is_some());
    let path = partial_error.path.unwrap();
    assert_eq!(path[0], "user");
    assert_eq!(path[1], "posts");
}

// ============================================================================
// Real-World Example: Batch Query Error Handling
// ============================================================================

#[test]
fn test_example_batch_query_error_handling() {
    // Example: Error handling for batched queries

    // Batch of 3 queries:
    // Query 1: Valid, succeeds
    // Query 2: Syntax error
    // Query 3: Authorization error

    let query2_error = GraphQLError::parse("Unexpected token '}' in query 2")
        .with_location(5, 15)
        .with_request_id("req-batch-001");

    let query3_error = GraphQLError::forbidden().with_request_id("req-batch-001");

    // All errors share same request ID for batch correlation
    assert_eq!(query2_error.code, ErrorCode::ParseError);
    assert_eq!(query3_error.code, ErrorCode::Forbidden);

    let ext2 = query2_error.extensions.unwrap_or(ErrorExtensions {
        category:   None,
        status:     None,
        request_id: Some("req-batch-001".to_string()),
    });
    let ext3 = query3_error.extensions.unwrap_or(ErrorExtensions {
        category:   None,
        status:     None,
        request_id: Some("req-batch-001".to_string()),
    });

    // Both reference same request ID
    assert_eq!(ext2.request_id, Some("req-batch-001".to_string()));
    assert_eq!(ext3.request_id, Some("req-batch-001".to_string()));
}

// ============================================================================
// Real-World Example: Subscription Error Handling
// ============================================================================

#[test]
fn test_example_subscription_error_handling() {
    // Example: Error handling for subscriptions

    // Scenario: Subscription authentication fails
    let auth_error = GraphQLError::unauthenticated().with_request_id("req-sub-001");

    assert_eq!(auth_error.code, ErrorCode::Unauthenticated);
    assert_eq!(auth_error.code.status_code(), StatusCode::UNAUTHORIZED);

    // Scenario: Too many subscriptions from client
    let resource_error =
        GraphQLError::rate_limited("Client already has 100 active subscriptions, maximum is 100")
            .with_request_id("req-sub-002");

    assert_eq!(resource_error.code, ErrorCode::RateLimitExceeded);
    assert_eq!(resource_error.code.status_code(), StatusCode::TOO_MANY_REQUESTS);
}

// ============================================================================
// Example: Complete Error Context Pattern
// ============================================================================

#[test]
fn test_example_complete_error_context() {
    // Production pattern: Rich error context for debugging

    let error = GraphQLError::database("Connection to primary replica failed after 3 retries")
        .with_location(10, 5) // Line and column in query
        .with_path(vec!["orders".to_string(), "items".to_string()]) // Field path
        .with_request_id("req-abc-xyz-123") // For correlation
        .with_extensions(ErrorExtensions {
            category:   Some("DATABASE_REPLICA".to_string()),
            status:     Some(503),
            request_id: Some("req-abc-xyz-123".to_string()),
        });

    // All context present for debugging
    assert_eq!(error.code, ErrorCode::DatabaseError);
    assert!(error.locations.is_some());
    assert!(error.path.is_some());
    assert!(error.extensions.is_some());

    // Verify each component
    assert_eq!(error.locations.unwrap()[0].line, 10);
    assert_eq!(error.path.unwrap()[0], "orders");
    assert_eq!(error.extensions.unwrap().category, Some("DATABASE_REPLICA".to_string()));
}