fraiseql-core 2.2.0

Core execution engine for FraiseQL v2 - Compiled GraphQL over SQL
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable

//! Federation entity resolver tests
//!
//! Test suite for federation entity resolution functionality covering:
//! - `_entities` query parsing and execution
//! - `_service` query with federation directives
//! - Entity representation parsing (`_Any` scalar)
//! - Resolution strategy selection (Local, Direct DB, HTTP)
//! - Performance and batching optimizations

#![allow(clippy::doc_markdown)] // Reason: test doc comments use non-standard formatting
#![allow(clippy::needless_collect)] // Reason: intermediate collect preserves ownership for later assertions
#![allow(clippy::iter_with_drain)] // Reason: drain used to move Vec into HashSet in test
// ============================================================================
// _entities Query Handler
// ============================================================================

#[test]
fn test_entities_query_recognized() {
    use fraiseql_core::federation;

    // The _entities query is recognized as a federation query
    assert!(federation::is_federation_query("_entities"));
    assert!(federation::is_federation_query("_service"));
    assert!(!federation::is_federation_query("query"));
    assert!(!federation::is_federation_query("mutation"));
}

#[test]
fn test_entities_representations_parsed() {
    use serde_json::json;

    // Entity representations are parsed from _Any scalar input
    let entity_json = json!({
        "__typename": "User",
        "id": "123",
        "name": "Alice"
    });

    // Verify structure
    assert_eq!(entity_json["__typename"], "User");
    assert_eq!(entity_json["id"], "123");
    assert_eq!(entity_json["name"], "Alice");
}

#[test]
fn test_entities_response_format() {
    use serde_json::json;

    // _entities response is array of entity values
    let response = json!({
        "data": {
            "_entities": [
                {"__typename": "User", "id": "1", "name": "Alice"},
                {"__typename": "User", "id": "2", "name": "Bob"},
            ]
        }
    });

    let entities = response["data"]["_entities"].as_array().unwrap();
    assert_eq!(entities.len(), 2);
    assert_eq!(entities[0]["name"], "Alice");
    assert_eq!(entities[1]["name"], "Bob");
}

#[test]
fn test_entities_null_handling() {
    use serde_json::json;

    // Missing entities can be represented as null
    let response = json!({
        "data": {
            "_entities": [
                {"__typename": "User", "id": "1", "name": "Alice"},
                null,  // Entity not found
                {"__typename": "User", "id": "3", "name": "Charlie"},
            ]
        }
    });

    let entities = response["data"]["_entities"].as_array().unwrap();
    assert_eq!(entities.len(), 3);
    assert!(entities[0].is_object());
    assert!(entities[1].is_null());
    assert!(entities[2].is_object());
}

#[test]
fn test_entities_batch_100() {
    use serde_json::json;

    // Batch loading of multiple entities
    let mut entities = Vec::new();
    for i in 0..100 {
        entities.push(json!({
            "__typename": "User",
            "id": i.to_string(),
            "name": format!("User{}", i)
        }));
    }

    assert_eq!(entities.len(), 100);
    assert_eq!(entities[0]["id"], "0");
    assert_eq!(entities[99]["id"], "99");
}

// ============================================================================
// _service Query & SDL Generation
// ============================================================================

#[test]
fn test_service_query_recognized() {
    use fraiseql_core::federation;

    // The _service query is recognized as a federation query
    assert!(federation::is_federation_query("_service"));
}

#[test]
fn test_service_query_required_fields() {
    use serde_json::json;

    // _service response must include SDL field
    let response = json!({
        "_service": {
            "sdl": "type User @key(fields: \"id\") { id: ID! }"
        }
    });

    assert!(response["_service"]["sdl"].is_string());
    let sdl = response["_service"]["sdl"].as_str().unwrap();
    assert!(!sdl.is_empty());
}

#[test]
fn test_sdl_includes_federation_directives() {
    // SDL should include federation directives like @key
    let sdl = r#"
        type User @key(fields: "id") {
            id: ID!
            name: String!
        }
    "#;

    // Check for @key directive
    assert!(sdl.contains("@key"));
    assert!(sdl.contains("fields: \"id\""));
}

#[test]
fn test_sdl_includes_entity_union() {
    // Federation requires _Entity union type in SDL
    // This would include all types that are resolvable via federation
    let entity_union_sdl = "union _Entity = User | Order | Product";

    assert!(entity_union_sdl.contains("_Entity"));
    assert!(entity_union_sdl.contains("User"));
}

#[test]
fn test_sdl_includes_any_scalar() {
    // Federation requires _Any scalar in SDL
    let scalar_def = "scalar _Any";

    assert!(scalar_def.contains("_Any"));
}

#[test]
fn test_sdl_valid_graphql() {
    // Basic GraphQL structure validation
    let sdl = r#"
        scalar _Any
        union _Entity = User

        type User @key(fields: "id") {
            id: ID!
        }

        type _Service {
            sdl: String!
        }

        extend type Query {
            _entities(representations: [_Any!]!): [_Entity]!
            _service: _Service!
        }
    "#;

    // Check for required federation elements
    assert!(sdl.contains("scalar _Any"));
    assert!(sdl.contains("union _Entity"));
    assert!(sdl.contains("_entities"));
    assert!(sdl.contains("_service"));
}

// ============================================================================
// Entity Representation Parsing (_Any Scalar)
// ============================================================================

#[test]
fn test_entity_representation_parse_typename() {
    use serde_json::json;

    // Entity representation must include __typename
    let rep = json!({
        "__typename": "User",
        "id": "123"
    });

    assert_eq!(rep["__typename"], "User");
}

#[test]
fn test_entity_representation_key_fields() {
    use serde_json::json;

    // Entity representation includes key fields required for lookup
    let rep = json!({
        "__typename": "User",
        "id": "123",
        "email": "user@example.com"
    });

    // For User type with @key(fields: "id"), the id field is included
    assert_eq!(rep["id"], "123");
    // Other fields are also included
    assert_eq!(rep["email"], "user@example.com");
}

#[test]
fn test_entity_representation_null_values() {
    use serde_json::json;

    // Entity representations can include null values
    let rep = json!({
        "__typename": "User",
        "id": "123",
        "bio": null  // Optional field not provided
    });

    assert_eq!(rep["id"], "123");
    assert!(rep["bio"].is_null());
}

#[test]
fn test_entity_representation_composite_keys() {
    use serde_json::json;

    // Composite keys include multiple fields
    // Example: @key(fields: "organizationId id")
    let rep = json!({
        "__typename": "OrgUser",
        "organizationId": "org-456",
        "id": "user-789",
        "name": "Alice"
    });

    assert_eq!(rep["organizationId"], "org-456");
    assert_eq!(rep["id"], "user-789");
}

#[test]
fn test_any_scalar_required() {
    // The _Any scalar is required to accept entity representations
    let scalar_definition = "scalar _Any";

    assert!(scalar_definition.contains("_Any"));
}

// ============================================================================
// Resolution Strategy Selection
// ============================================================================

#[test]
fn test_strategy_local_for_owned_entity() {
    use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};

    // Create metadata with locally-owned User type
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types:   vec![FederatedType {
            name:             "User".to_string(),
            keys:             vec![KeyDirective {
                fields:     vec!["id".to_string()],
                resolvable: true,
            }],
            is_extends:       false, // Locally owned
            external_fields:  vec![],
            shareable_fields: vec![],
            field_directives: std::collections::HashMap::new(),
        }],
    };

    // User type is not extended, so it should use local resolution
    let fed_type = metadata.types.iter().find(|t| t.name == "User").unwrap();
    assert!(!fed_type.is_extends, "User should be locally owned (not extended)");
}

#[test]
fn test_strategy_direct_db_when_available() {
    use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};

    // Create metadata with extended Order type (would use HTTP or DirectDB)
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types:   vec![FederatedType {
            name:             "Order".to_string(),
            keys:             vec![KeyDirective {
                fields:     vec!["id".to_string()],
                resolvable: true,
            }],
            is_extends:       true, // Extended from another subgraph
            external_fields:  vec!["id".to_string()],
            shareable_fields: vec![],
            field_directives: std::collections::HashMap::new(),
        }],
    };

    // Order type is extended, so it should use DirectDB or HTTP
    let fed_type = metadata.types.iter().find(|t| t.name == "Order").unwrap();
    assert!(fed_type.is_extends, "Order should be extended (not locally owned)");
}

#[test]
fn test_strategy_http_fallback() {
    use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};

    // Both local and extended types can be queried via HTTP as fallback
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types:   vec![
            FederatedType {
                name:             "User".to_string(),
                keys:             vec![KeyDirective {
                    fields:     vec!["id".to_string()],
                    resolvable: true,
                }],
                is_extends:       false,
                external_fields:  vec![],
                shareable_fields: vec![],
                field_directives: std::collections::HashMap::new(),
            },
            FederatedType {
                name:             "Product".to_string(),
                keys:             vec![KeyDirective {
                    fields:     vec!["id".to_string()],
                    resolvable: true,
                }],
                is_extends:       true,
                external_fields:  vec!["id".to_string()],
                shareable_fields: vec![],
                field_directives: std::collections::HashMap::new(),
            },
        ],
    };

    // Both types have resolvable keys, enabling HTTP fallback
    for fed_type in &metadata.types {
        let key_directive = fed_type.keys.first().unwrap();
        assert!(
            key_directive.resolvable,
            "Type {} should have resolvable key for HTTP fallback",
            fed_type.name
        );
    }
}

#[test]
fn test_strategy_caching() {
    use std::collections::HashMap;

    // Simulate strategy caching - in real implementation, strategies are cached by typename
    let mut strategy_cache: HashMap<String, String> = HashMap::new();

    // First access: determine strategy for User
    if !strategy_cache.contains_key("User") {
        let strategy = "local".to_string();
        strategy_cache.insert("User".to_string(), strategy);
    }

    // Second access: use cached strategy
    assert_eq!(
        strategy_cache.get("User").unwrap(),
        "local",
        "Strategy should be cached for User type"
    );

    // Verify cache effectiveness
    assert_eq!(strategy_cache.len(), 1, "Cache should have one entry");

    // Third access: should still be cached
    assert!(strategy_cache.contains_key("User"), "User strategy should be cached");
}

// ============================================================================
// Performance & Batching
// ============================================================================

#[test]
fn test_batch_latency_single_entity() {
    use std::time::Instant;

    use serde_json::json;

    // Single entity resolution should be fast
    let start = Instant::now();

    let _entity = json!({
        "__typename": "User",
        "id": "1",
        "name": "Alice"
    });

    let elapsed = start.elapsed();

    // Should complete in microseconds
    assert!(elapsed.as_millis() < 10);
}

#[test]
fn test_batch_latency_hundred_entities() {
    use std::time::Instant;

    use serde_json::json;

    let start = Instant::now();

    // Create 100 entities
    let mut entities = Vec::with_capacity(100);
    for i in 0..100 {
        entities.push(json!({
            "__typename": "User",
            "id": i.to_string(),
            "name": format!("User{}", i)
        }));
    }

    let elapsed = start.elapsed();

    assert_eq!(entities.len(), 100);
    // Batch of 100 should complete in milliseconds
    assert!(elapsed.as_millis() < 100);
}

#[test]
fn test_batch_order_preservation() {
    use serde_json::json;

    // Order of representations must be preserved in results
    let reps = vec!["1", "2", "3", "4", "5"];
    let mut results = Vec::new();

    for id in &reps {
        results.push(json!({
            "__typename": "User",
            "id": (*id).to_string()
        }));
    }

    // Results should maintain the same order as input
    for (idx, id) in reps.iter().enumerate() {
        assert_eq!(results[idx]["id"].as_str().unwrap(), *id);
    }
}

#[test]
fn test_batch_deduplication() {
    use std::collections::HashSet;

    // Batch loader should deduplicate identical key values
    let mut keys = vec!["id1", "id2", "id1", "id3", "id2"];
    let unique_keys: HashSet<_> = keys.drain(..).collect();

    // After deduplication, should have 3 unique keys
    assert_eq!(unique_keys.len(), 3);
    assert!(unique_keys.contains("id1"));
    assert!(unique_keys.contains("id2"));
    assert!(unique_keys.contains("id3"));
}

// ============================================================================
// Apollo Federation v2 Compliance
// ============================================================================

#[test]
fn test_federation_spec_version_2() {
    use fraiseql_core::federation::types::FederationMetadata;

    // Federation metadata should indicate v2 version
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types:   vec![],
    };

    assert!(metadata.enabled);
    assert_eq!(metadata.version, "v2");
}

#[test]
fn test_entity_union_required() {
    // GraphQL federation requires _Entity union type
    let schema = r#"
        union _Entity = User | Order | Product

        type User @key(fields: "id") {
            id: ID!
        }
    "#;

    assert!(schema.contains("_Entity"));
    assert!(schema.contains("union"));
}

#[test]
fn test_federation_directive_fields() {
    use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};

    // Federation directives must be parsed correctly
    let metadata = FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types:   vec![FederatedType {
            name:             "User".to_string(),
            keys:             vec![KeyDirective {
                fields:     vec!["id".to_string()],
                resolvable: true,
            }],
            is_extends:       false,
            external_fields:  vec![],
            shareable_fields: vec![],
            field_directives: std::collections::HashMap::new(),
        }],
    };

    let user_type = &metadata.types[0];
    assert_eq!(user_type.keys.len(), 1);
    assert_eq!(user_type.keys[0].fields, vec!["id".to_string()]);
    assert!(user_type.keys[0].resolvable);
}

#[test]
fn test_federation_query_single_entity_postgres() {
    use serde_json::json;

    // Single entity resolution via _entities query
    let _request = json!({
        "query": "query($representations: [_Any!]!) { _entities(representations: $representations) { __typename ... on User { id name } } }",
        "variables": {
            "representations": [
                {
                    "__typename": "User",
                    "id": "1"
                }
            ]
        }
    });

    let response = json!({
        "data": {
            "_entities": [
                {
                    "__typename": "User",
                    "id": "1",
                    "name": "Alice"
                }
            ]
        }
    });

    assert_eq!(response["data"]["_entities"].as_array().unwrap().len(), 1);
}

#[test]
fn test_federation_query_batch_entities() {
    use serde_json::json;

    // Batch entity resolution should return results in same order as input
    let request = json!({
        "variables": {
            "representations": [
                {"__typename": "User", "id": "1"},
                {"__typename": "User", "id": "2"},
                {"__typename": "User", "id": "3"},
            ]
        }
    });

    let response = json!({
        "data": {
            "_entities": [
                {"__typename": "User", "id": "1", "name": "Alice"},
                {"__typename": "User", "id": "2", "name": "Bob"},
                {"__typename": "User", "id": "3", "name": "Charlie"},
            ]
        }
    });

    let representations = request["variables"]["representations"].as_array().unwrap();
    let entities = response["data"]["_entities"].as_array().unwrap();

    // Response count should match input count (critical Apollo Federation requirement)
    assert_eq!(entities.len(), representations.len());
    assert_eq!(entities.len(), 3);
}

#[test]
fn test_federation_partial_failure() {
    use serde_json::json;

    // Partial failure: some entities found, some not found
    let response = json!({
        "data": {
            "_entities": [
                {"__typename": "User", "id": "1", "name": "Alice"},
                null,  // Entity not found - returns null
                {"__typename": "User", "id": "3", "name": "Charlie"},
            ]
        }
    });

    let entities = response["data"]["_entities"].as_array().unwrap();
    assert_eq!(entities.len(), 3);
    assert!(entities[0].is_object());
    assert!(entities[1].is_null());
    assert!(entities[2].is_object());
}