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
//! HTTP @requires enforcement tests
//! - Required fields present in entity representations before HTTP call
//! - Error messages when required fields missing
//! - Query augmentation to include required fields in _entities query
//! - Both single and batch entity resolution

#![allow(clippy::unwrap_used)] // Reason: test code, panics are acceptable
#![allow(clippy::default_trait_access)] // Reason: test setup uses Default::default() for brevity
#![allow(clippy::iter_on_single_items)] // Reason: test uses single-element iter for pattern uniformity
use fraiseql_core::federation::types::{
    EntityRepresentation, FederatedType, FederationMetadata, FieldFederationDirectives,
    FieldPathSelection, KeyDirective,
};
use serde_json::json;

// ============================================================================
// Test: HTTP @requires Validation Before Remote Call
// ============================================================================

#[test]
fn test_http_requires_validation_missing_field() {
    // TEST: Should fail if required field is missing from representation
    // GIVEN: User.orders requires "email", but representation has only id
    // WHEN: We validate before HTTP resolution
    // THEN: Should return error without making HTTP call

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });
    user_type.set_field_directives(
        "orders".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["email".to_string()],
            typename: "User".to_string(),
        }),
    );

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

    // Entity representation missing email
    let repr = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: Default::default(),
        all_fields: [("id".to_string(), json!("123"))].iter().cloned().collect(),
    };

    // Should fail because email (required by orders) is missing
    let result = validate_http_requires(&metadata, "User", &["orders"], &repr);
    assert!(result.is_err(), "Should fail when required field missing from representation");
    let err = result.unwrap_err();
    assert!(
        err.to_lowercase().contains("email") || err.to_lowercase().contains("requires"),
        "Error should mention missing field: {}",
        err
    );
}

#[test]
fn test_http_requires_validation_field_present() {
    // TEST: Should pass if all required fields are present
    // GIVEN: User.orders requires "email", representation has it
    // WHEN: We validate before HTTP resolution
    // THEN: Should succeed (HTTP call can proceed)

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });
    user_type.set_field_directives(
        "orders".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["email".to_string()],
            typename: "User".to_string(),
        }),
    );

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

    // Entity representation has email
    let repr = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("123")),
            ("email".to_string(), json!("user@example.com")),
        ]
        .iter()
        .cloned()
        .collect(),
    };

    let result = validate_http_requires(&metadata, "User", &["orders"], &repr);
    assert!(result.is_ok(), "Should pass when required fields present");
}

#[test]
fn test_http_requires_validation_multiple_fields() {
    // TEST: Multiple @requires directives must all be satisfied
    // GIVEN: Order.shippingEstimate requires both weight and dimensions
    // WHEN: We validate before HTTP resolution
    // THEN: All required fields must be present

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });
    order_type.set_field_directives(
        "shippingEstimate".to_string(),
        FieldFederationDirectives::new()
            .add_requires(FieldPathSelection {
                path:     vec!["weight".to_string()],
                typename: "Order".to_string(),
            })
            .add_requires(FieldPathSelection {
                path:     vec!["dimensions".to_string()],
                typename: "Order".to_string(),
            }),
    );

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

    // Has weight but missing dimensions
    let repr_missing_dimensions = EntityRepresentation {
        typename:   "Order".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("456")),
            ("weight".to_string(), json!(2.5)),
        ]
        .iter()
        .cloned()
        .collect(),
    };

    let result =
        validate_http_requires(&metadata, "Order", &["shippingEstimate"], &repr_missing_dimensions);
    assert!(result.is_err(), "Should fail when any required field is missing");

    // Has both required fields
    let repr_complete = EntityRepresentation {
        typename:   "Order".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("456")),
            ("weight".to_string(), json!(2.5)),
            ("dimensions".to_string(), json!("10x10x10")),
        ]
        .iter()
        .cloned()
        .collect(),
    };

    let result = validate_http_requires(&metadata, "Order", &["shippingEstimate"], &repr_complete);
    assert!(result.is_ok(), "Should pass when all required fields present");
}

#[test]
fn test_http_requires_batch_validation() {
    // TEST: Multiple representations in batch must all have required fields
    // GIVEN: Batch of 3 User entities, 1 missing required email field
    // WHEN: We validate batch before HTTP _entities call
    // THEN: Should fail because one entity is missing required field

    let mut user_type = FederatedType::new("User".to_string());
    user_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });
    user_type.set_field_directives(
        "profile".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["email".to_string()],
            typename: "User".to_string(),
        }),
    );

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

    let repr1 = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("1")),
            ("email".to_string(), json!("user1@example.com")),
        ]
        .iter()
        .cloned()
        .collect(),
    };

    let repr2 = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("2")),
            // Missing email!
        ]
        .iter()
        .cloned()
        .collect(),
    };

    let repr3 = EntityRepresentation {
        typename:   "User".to_string(),
        key_fields: Default::default(),
        all_fields: [
            ("id".to_string(), json!("3")),
            ("email".to_string(), json!("user3@example.com")),
        ]
        .iter()
        .cloned()
        .collect(),
    };

    // Validate each representation individually
    assert!(
        validate_http_requires(&metadata, "User", &["profile"], &repr1).is_ok(),
        "First representation should pass"
    );
    assert!(
        validate_http_requires(&metadata, "User", &["profile"], &repr2).is_err(),
        "Second representation should fail (missing email)"
    );
    assert!(
        validate_http_requires(&metadata, "User", &["profile"], &repr3).is_ok(),
        "Third representation should pass"
    );
}

// ============================================================================
// Test: Query Augmentation for Required Fields
// ============================================================================

#[test]
fn test_http_query_includes_required_fields() {
    // TEST: HTTP _entities query should include required fields
    // GIVEN: Requesting Order.shippingEstimate which requires weight
    // WHEN: We build the query
    // THEN: Query should include weight in inline fragments

    let mut order_type = FederatedType::new("Order".to_string());
    order_type.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });
    order_type.set_field_directives(
        "shippingEstimate".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["weight".to_string()],
            typename: "Order".to_string(),
        }),
    );

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

    // Build augmented field list
    let requested_fields = vec!["shippingEstimate".to_string()];
    let augmented_fields = compute_augmented_fields(&metadata, "Order", &requested_fields);

    // Should include both requested field and required field
    assert!(
        augmented_fields.contains(&"shippingEstimate".to_string()),
        "Should include requested field"
    );
    assert!(
        augmented_fields.contains(&"weight".to_string()),
        "Should include required field weight"
    );
}

#[test]
fn test_http_query_deduplicates_fields() {
    // TEST: Query should not duplicate fields
    // GIVEN: Multiple fields that require overlapping dependencies
    // WHEN: We augment the field list
    // THEN: Fields should be deduplicated

    let mut type_def = FederatedType::new("Order".to_string());
    type_def.keys.push(KeyDirective {
        fields:     vec!["id".to_string()],
        resolvable: true,
    });

    // Both fields require weight
    type_def.set_field_directives(
        "shippingEstimate".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["weight".to_string()],
            typename: "Order".to_string(),
        }),
    );

    type_def.set_field_directives(
        "taxAmount".to_string(),
        FieldFederationDirectives::new().add_requires(FieldPathSelection {
            path:     vec!["weight".to_string()],
            typename: "Order".to_string(),
        }),
    );

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

    let requested_fields = vec!["shippingEstimate".to_string(), "taxAmount".to_string()];
    let augmented_fields = compute_augmented_fields(&metadata, "Order", &requested_fields);

    // Count occurrences of "weight"
    let weight_count = augmented_fields.iter().filter(|f| f == &"weight").count();
    assert_eq!(weight_count, 1, "Field weight should appear only once");
}

// ============================================================================
// Helper functions for HTTP @requires enforcement
// ============================================================================

/// Validate @requires directives for HTTP entity resolution
///
/// Before making HTTP calls to remote subgraphs, verifies that all fields
/// required by @requires directives are present in the entity representation
/// received from the Apollo Router or federation gateway.
///
/// # Arguments
/// * `metadata` - Federation metadata containing type and directive definitions
/// * `typename` - Name of the type being resolved (e.g., "User", "Order")
/// * `fields` - Field names being requested for HTTP resolution
/// * `representation` - Entity representation from gateway with available fields
///
/// # Returns
/// `Ok(())` if all required fields are present, `Err` with details if not
///
/// # Example
/// ```no_run
/// // User.orders requires "email", but representation only has id
/// let result = validate_http_requires(&metadata, "User", &["orders"], &repr);
/// // Returns Err: "HTTP Validation Error: Required field missing..."
/// ```
fn validate_http_requires(
    metadata: &FederationMetadata,
    typename: &str,
    fields: &[&str],
    representation: &EntityRepresentation,
) -> Result<(), String> {
    // Find the type in metadata
    let federated_type = metadata
        .types
        .iter()
        .find(|t| t.name == typename)
        .ok_or_else(|| format!("Type {} not found in federation metadata", typename))?;

    // Check @requires for each requested field
    for field in fields {
        if let Some(directives) = federated_type.get_field_directives(field) {
            // Verify all required fields are present in representation
            for required in &directives.requires {
                let field_path = required.path.join(".");
                if !representation.has_field(&field_path) {
                    return Err(format!(
                        "HTTP Validation Error: Required field missing\n\
                         Type: {}\n\
                         Field: {}\n\
                         Required: {}\n\
                         Issue: HTTP resolution of {}.{} requires '{}' but it is missing from entity representation\n\
                         Suggestion: Ensure '{}' is included in entity representation from gateway",
                        typename, field, field_path, typename, field, field_path, field_path
                    ));
                }
            }
        }
    }

    Ok(())
}

/// Compute augmented field list including required fields
///
/// When building an HTTP _entities query for a remote subgraph, computes the
/// complete set of fields needed by augmenting requested fields with any fields
/// required by @requires directives.
///
/// # Arguments
/// * `metadata` - Federation metadata with type and directive information
/// * `typename` - Type name to compute fields for
/// * `fields` - Originally requested field names
///
/// # Returns
/// Vector of all field names needed (requested + required), deduplicated
///
/// # Example
/// ```no_run
/// // Requesting Order.shippingEstimate which requires Order.weight
/// let fields = vec!["shippingEstimate".to_string()];
/// let augmented = compute_augmented_fields(&metadata, "Order", &fields);
/// // Returns: ["shippingEstimate", "weight"]
/// ```
fn compute_augmented_fields(
    metadata: &FederationMetadata,
    typename: &str,
    fields: &[String],
) -> Vec<String> {
    let mut augmented = fields.to_vec();

    // Find the type and add all required fields
    if let Some(federated_type) = metadata.types.iter().find(|t| t.name == typename) {
        for field in fields {
            if let Some(directives) = federated_type.get_field_directives(field) {
                for required in &directives.requires {
                    // Add all components of the required field path
                    augmented.extend(required.path.clone());
                }
            }
        }
    }

    // Deduplicate while preserving insertion order
    let mut seen = std::collections::HashSet::new();
    augmented.retain(|f| seen.insert(f.clone()));

    augmented
}