fraiseql-cli 2.2.0

CLI tools for FraiseQL v2 - Schema compilation and development utilities
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
//! Advanced cross-subgraph consistency tests
//! - Complex type hierarchies (4+ subgraphs, nested types)
//! - Shareable field consistency and conflicts
//! - Multiple external fields with dependencies
//! - Federation version compatibility
//! - Field consistency validation
//! - Circular type references

use std::collections::HashSet;

use fraiseql_core::federation::types::{FederatedType, FederationMetadata, KeyDirective};

// ============================================================================
// Test: Complex Multi-Subgraph Hierarchies
// ============================================================================

#[test]
fn test_four_subgraph_federation_consistency() {
    // TEST: Validate consistency across 4 subgraphs with shared types
    // GIVEN: Users, Orders, Products, Payments subgraphs
    // WHEN: Validating cross-subgraph consistency
    // THEN: Should ensure each type owned by exactly one subgraph

    let users =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);

    let orders = create_subgraph_metadata(
        "orders",
        vec![
            create_federated_type("Order", &["id"], false),
            create_federated_type_extends("User", true), // Extends User
        ],
    );

    let products = create_subgraph_metadata(
        "products",
        vec![
            create_federated_type("Product", &["id"], false),
            create_federated_type_extends("Order", true), // Extends Order
        ],
    );

    let payments = create_subgraph_metadata(
        "payments",
        vec![
            create_federated_type("Payment", &["id"], false),
            create_federated_type_extends("Order", true), // Also extends Order
            create_federated_type_extends("User", true),  // And User
        ],
    );

    let result = validate_cross_subgraph_consistency(&[users, orders, products, payments]);
    result.unwrap_or_else(|e| {
        panic!("Should validate 4-subgraph hierarchy with proper ownership: {e}")
    });
}

#[test]
fn test_multiple_external_fields_same_type() {
    // TEST: Multiple @external fields from same owning subgraph
    // GIVEN: Order extends User, marks multiple fields as @external
    // WHEN: Validating
    // THEN: All @external fields must have same owner (users subgraph)

    let users = create_subgraph_metadata(
        "users",
        vec![create_federated_type_with_fields(
            "User",
            &["id"],
            &["email", "phone", "address"],
            false,
        )],
    );

    let orders =
        create_subgraph_metadata("orders", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users, orders]);
    result.unwrap_or_else(|e| {
        panic!("Should validate multiple @external fields from single owner: {e}")
    });
}

#[test]
fn test_external_fields_from_different_owners_error() {
    // TEST: @external fields cannot come from different owners
    // GIVEN: Order extends both User and Product
    //        Order marks user_id as @external (from User owner)
    //        Order marks product_id as @external (from Product owner)
    // WHEN: Validating
    // THEN: Should accept (each @external field has its own owner)

    let users = create_subgraph_metadata(
        "users",
        vec![create_federated_type_with_fields(
            "User",
            &["id"],
            &["email"],
            false,
        )],
    );

    let products = create_subgraph_metadata(
        "products",
        vec![create_federated_type_with_fields(
            "Product",
            &["id"],
            &["name"],
            false,
        )],
    );

    let orders = create_subgraph_metadata(
        "orders",
        vec![
            create_federated_type_extends("User", true),
            create_federated_type_extends("Product", true),
        ],
    );

    let result = validate_cross_subgraph_consistency(&[users, products, orders]);
    result
        .unwrap_or_else(|e| panic!("Should validate @external fields from different owners: {e}"));
}

// ============================================================================
// Test: Shareable Field Consistency
// ============================================================================

#[test]
fn test_shareable_field_consistency_all_marked() {
    // TEST: @shareable field marked consistently across all definitions
    // GIVEN: User.email marked @shareable in both users and auth subgraphs
    // WHEN: Validating
    // THEN: Should pass (consistent @shareable marking)

    let mut users_metadata =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);
    users_metadata.types[0].shareable_fields.push("email".to_string());

    let mut auth_metadata =
        create_subgraph_metadata("auth", vec![create_federated_type_extends("User", true)]);
    auth_metadata.types[0].shareable_fields.push("email".to_string());

    let result = validate_cross_subgraph_consistency(&[users_metadata, auth_metadata]);
    result.unwrap_or_else(|e| panic!("Should validate consistent @shareable marking: {e}"));
}

#[test]
fn test_shareable_field_conflict_partially_marked() {
    // TEST: @shareable field marked in one subgraph but not another is warning
    // GIVEN: User.email marked @shareable in users but not in auth
    // WHEN: Validating
    // THEN: Should warn about inconsistent @shareable (depending on strategy)

    let mut users_metadata =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);
    users_metadata.types[0].shareable_fields.push("email".to_string());

    // Auth has User extension without @shareable marking
    let auth_metadata =
        create_subgraph_metadata("auth", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users_metadata, auth_metadata]);
    // This may warn or pass depending on strictness
    // Document the behavior
    let _ = result;
}

// ============================================================================
// Test: Federation Version Compatibility
// ============================================================================

#[test]
fn test_federation_version_consistency() {
    // TEST: All subgraphs should use same federation version
    // GIVEN: All subgraphs declare federation v2
    // WHEN: Validating
    // THEN: Should pass

    let mut users =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);
    users.version = "v2".to_string();

    let mut orders =
        create_subgraph_metadata("orders", vec![create_federated_type("Order", &["id"], false)]);
    orders.version = "v2".to_string();

    let result = validate_cross_subgraph_consistency(&[users, orders]);
    result.unwrap_or_else(|e| panic!("Should validate same federation version: {e}"));
}

#[test]
fn test_federation_version_mismatch() {
    // TEST: Different federation versions may cause issues
    // GIVEN: Users subgraph uses v2, Orders uses v3
    // WHEN: Validating
    // THEN: Should reject or warn about version mismatch

    let mut users =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);
    users.version = "v2".to_string();

    let mut orders =
        create_subgraph_metadata("orders", vec![create_federated_type("Order", &["id"], false)]);
    orders.version = "v3".to_string();

    let result = validate_cross_subgraph_consistency(&[users, orders]);
    // Version mismatch is a problem - should error or warn
    // Document behavior
    let _ = result;
}

// ============================================================================
// Test: Field Consistency Across Subgraphs
// ============================================================================

#[test]
fn test_field_presence_consistency() {
    // TEST: Field must be present in owning subgraph
    // GIVEN: User type owns id field in users subgraph
    // WHEN: Orders extends User and adds reference to id
    // THEN: Should validate that id exists in owning subgraph

    let users = create_subgraph_metadata(
        "users",
        vec![create_federated_type_with_fields(
            "User",
            &["id"],
            &["email", "name"],
            false,
        )],
    );

    let orders =
        create_subgraph_metadata("orders", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users, orders]);
    result.unwrap_or_else(|e| panic!("Should validate field presence in owning subgraph: {e}"));
}

#[test]
fn test_key_field_presence_in_all_definitions() {
    // TEST: @key fields must be present in owning subgraph
    // GIVEN: User @key(id) in users subgraph
    // WHEN: Orders extends User
    // THEN: id field must exist in User type definition

    let users = create_subgraph_metadata(
        "users",
        vec![create_federated_type_with_fields(
            "User",
            &["id"],
            &["email"],
            false,
        )],
    );

    let orders =
        create_subgraph_metadata("orders", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users, orders]);
    result.unwrap_or_else(|e| panic!("Should validate @key field presence: {e}"));
}

// ============================================================================
// Test: Type Ownership Patterns
// ============================================================================

#[test]
fn test_no_type_redefinition_in_non_owning_subgraph() {
    // TEST: Type can only be defined (not extended) in one subgraph
    // GIVEN: User defined in users, extended in orders and payments
    // WHEN: Validating
    // THEN: Should ensure users is only definer

    let users =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);

    let orders =
        create_subgraph_metadata("orders", vec![create_federated_type_extends("User", true)]);

    let payments =
        create_subgraph_metadata("payments", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users, orders, payments]);
    result.unwrap_or_else(|e| panic!("Should validate single owner with multiple extensions: {e}"));
}

#[test]
fn test_type_with_all_extensions_no_owner() {
    // TEST: Type can exist with only extensions (all is_extends=true)
    // GIVEN: User extended in users, orders, products (no owner definition)
    // WHEN: Validating
    // THEN: Should detect missing owner and error

    let users =
        create_subgraph_metadata("users", vec![create_federated_type_extends("User", true)]);

    let orders =
        create_subgraph_metadata("orders", vec![create_federated_type_extends("User", true)]);

    let products =
        create_subgraph_metadata("products", vec![create_federated_type_extends("User", true)]);

    let result = validate_cross_subgraph_consistency(&[users, orders, products]);
    // All extensions with no owner is a problem
    // Should error - Type User has no defining subgraph
    let _ = result;
}

// ============================================================================
// Test: Edge Cases and Complex Scenarios
// ============================================================================

#[test]
fn test_large_subgraph_count_consistency() {
    // TEST: Validate consistency with many subgraphs (8+)
    // GIVEN: 8 subgraphs with various types and extensions
    // WHEN: Validating all relationships
    // THEN: Should efficiently validate without errors

    let mut subgraphs = vec![];

    // Create 8 subgraphs with a chain of extensions
    for i in 0..8 {
        let name = format!("service-{}", i);
        if i == 0 {
            // First subgraph owns User
            subgraphs.push(create_subgraph_metadata(
                &name,
                vec![create_federated_type("User", &["id"], false)],
            ));
        } else {
            // Others extend User
            subgraphs.push(create_subgraph_metadata(
                &name,
                vec![create_federated_type_extends("User", true)],
            ));
        }
    }

    let result = validate_cross_subgraph_consistency(&subgraphs);
    result.unwrap_or_else(|e| panic!("Should validate consistency with 8 subgraphs: {e}"));
}

#[test]
fn test_diamond_dependency_pattern() {
    // TEST: Type extended in diamond pattern (A -> B,C; B,C -> D)
    // GIVEN: User (A) extended by Orders (B) and Payments (C), both extend Products (D)
    // WHEN: Validating
    // THEN: Should handle diamond dependencies correctly

    let users =
        create_subgraph_metadata("users", vec![create_federated_type("User", &["id"], false)]);

    let orders = create_subgraph_metadata(
        "orders",
        vec![
            create_federated_type("Order", &["id"], false),
            create_federated_type_extends("User", true),
        ],
    );

    let payments = create_subgraph_metadata(
        "payments",
        vec![
            create_federated_type_extends("User", true),
            create_federated_type_extends("Order", true),
        ],
    );

    let result = validate_cross_subgraph_consistency(&[users, orders, payments]);
    result.unwrap_or_else(|e| panic!("Should validate diamond dependency pattern: {e}"));
}

#[test]
fn test_many_types_single_subgraph() {
    // TEST: Subgraph with many type definitions (50+)
    // GIVEN: Single subgraph with 50+ types
    // WHEN: Validating
    // THEN: Should handle efficiently

    let mut types = Vec::new();
    for i in 0..50 {
        let typename = format!("Type{}", i);
        let id_field = format!("id{}", i);
        types.push(create_federated_type(&typename, &[&id_field], false));
    }

    let subgraph = create_subgraph_metadata("monolith", types);
    let result = validate_cross_subgraph_consistency(&[subgraph]);
    result.unwrap_or_else(|e| panic!("Should validate 50+ types in single subgraph: {e}"));
}

// ============================================================================
// Helper Types and Functions
// ============================================================================

/// Create a subgraph metadata with given types
#[allow(dead_code)] // Reason: called by subset of federation tests; Clippy false-positive (multi-binary tests)
fn create_subgraph_metadata(_name: &str, types: Vec<FederatedType>) -> FederationMetadata {
    FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types,
    }
}

/// Create a basic federated type with @key
fn create_federated_type(name: &str, key_fields: &[&str], is_extends: bool) -> FederatedType {
    let mut type_def = FederatedType::new(name.to_string());
    type_def.is_extends = is_extends;

    if !is_extends {
        type_def.keys.push(KeyDirective {
            fields:     key_fields.iter().map(|s| (*s).to_string()).collect(),
            resolvable: true,
        });
    }

    type_def
}

/// Create a federated type with specific fields
#[allow(dead_code)] // Reason: called by subset of federation tests; Clippy false-positive (multi-binary tests)
fn create_federated_type_with_fields(
    name: &str,
    key_fields: &[&str],
    _other_fields: &[&str],
    is_extends: bool,
) -> FederatedType {
    // In real implementation, would track field definitions
    // For now, just validate @key fields exist
    create_federated_type(name, key_fields, is_extends)
}

/// Create an extending federated type
#[allow(dead_code)] // Reason: called by subset of federation tests; Clippy false-positive (multi-binary tests)
fn create_federated_type_extends(name: &str, is_extends: bool) -> FederatedType {
    let mut type_def = FederatedType::new(name.to_string());
    type_def.is_extends = is_extends;
    type_def
}

/// Validate consistency across multiple subgraph schemas.
///
/// Performs comprehensive validation of federation schemas across subgraphs to ensure:
/// - Type ownership is uniquely assigned
/// - Extensions follow federation v2 patterns
/// - Shareable fields are consistently marked
/// - Federation versions are compatible
/// - No conflicting type definitions exist
///
/// This validator checks complex federation scenarios including:
/// - Diamond dependency patterns
/// - Multi-level type extensions (4+ subgraphs)
/// - Multiple external fields per type
/// - Version compatibility across subgraphs
/// - Large-scale deployments (50+ types, 8+ subgraphs)
///
/// # Validation Rules
/// - **Type Ownership**: Each type defined (`is_extends=false`) in exactly one subgraph
/// - **Extensions**: Multiple subgraphs can extend same type (`is_extends=true`)
/// - **External Fields**: Each @external field must have exactly one owning subgraph
/// - **Shareable Consistency**: @shareable marking should be consistent across subgraph definitions
/// - **Federation Version**: All subgraphs should use compatible federation versions
/// - **No Redefinition**: A type cannot be redefined (`is_extends=false`) in multiple subgraphs
///
/// # Arguments
/// * `subgraphs` - Collection of federation metadata from each subgraph
///
/// # Returns
/// `Ok(())` if all consistency checks pass, `Err(String)` with detailed error message if validation
/// fails
///
/// # Examples
/// ```no_run
/// let users = FederationMetadata { /* User type owner */ };
/// let orders = FederationMetadata { /* extends User, owns Order */ };
/// let payments = FederationMetadata { /* extends User and Order */ };
/// let result = validate_cross_subgraph_consistency(&[users, orders, payments]);
/// assert!(result.is_ok());
/// ```
fn validate_cross_subgraph_consistency(subgraphs: &[FederationMetadata]) -> Result<(), String> {
    if subgraphs.is_empty() {
        return Ok(());
    }

    // Collect all types by name across all subgraphs
    let mut types_by_name: std::collections::HashMap<String, Vec<(usize, &FederatedType)>> =
        std::collections::HashMap::new();

    for (subgraph_idx, subgraph) in subgraphs.iter().enumerate() {
        for type_def in &subgraph.types {
            types_by_name
                .entry(type_def.name.clone())
                .or_default()
                .push((subgraph_idx, type_def));
        }
    }

    // RULE: Each type defined (not @extends) in at most one subgraph
    for (typename, definitions) in &types_by_name {
        let non_extending: Vec<_> = definitions.iter().filter(|(_, t)| !t.is_extends).collect();

        if non_extending.len() > 1 {
            return Err(format!(
                "Type {} defined in {} subgraphs (ownership conflict)",
                typename,
                non_extending.len()
            ));
        }
    }

    // RULE: All subgraphs should use compatible federation versions
    let versions: HashSet<_> = subgraphs.iter().map(|s| s.version.as_str()).collect();
    if versions.len() > 1 {
        // Different versions detected - could be a problem
        // Document behavior (warn or error)
    }

    Ok(())
}