fraiseql-core 2.7.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
//! Shared fixtures and helpers for federation tests.

#![allow(
    clippy::unwrap_used,
    clippy::print_stdout,
    clippy::print_stderr,
    clippy::missing_assert_message
)] // Reason: test code, panics are acceptable
#![allow(clippy::cast_possible_truncation)] // Reason: test step counts cast usize→u32; test sizes never exceed u32::MAX
#![allow(clippy::map_unwrap_or)] // Reason: test readability preferred over method chain refactoring
use std::{collections::HashMap, sync::Arc, time::Duration};

use fraiseql_core::{
    db::{postgres::PostgresAdapter, traits::DatabaseAdapter},
    federation::{
        mutation_executor::FederationMutationExecutor,
        types::{EntityRepresentation, FederatedType, FederationMetadata, KeyDirective},
    },
};
use serde_json::{Value, json};

/// Connect to the harness Postgres and (re)provision `table` from `column_ddl`
/// (e.g. `["id text", "amount integer"]`), seeded from `rows`. Returns the
/// connected adapter.
///
/// Returns `None` when no Postgres is configured (`DATABASE_URL` unset and no
/// local-testcontainers spawn) so the caller skips cleanly on the non-DB
/// preflight leg; the bound `Service` is returned alongside the adapter so a
/// locally-spawned container, if any, is held for the test's lifetime.
///
/// Seed values come from each row's matching column name (the first token of the
/// DDL); strings/numbers/bools render as the obvious SQL literal, missing/`Null`
/// as SQL `NULL`. Seed data is test-controlled, so it is inline-rendered and run
/// via `execute_raw_query`.
pub async fn pg_entity_fixture(
    table: &str,
    column_ddl: &[&str],
    rows: &[HashMap<String, Value>],
) -> Option<(fraiseql_test_support::Service, Arc<PostgresAdapter>)> {
    let (pg, adapter) = pg_adapter().await?;

    adapter
        .execute_raw_query(&format!(r#"DROP TABLE IF EXISTS "{table}" CASCADE"#))
        .await
        .expect("drop fixture table");
    adapter
        .execute_raw_query(&format!(r#"CREATE TABLE "{table}" ({})"#, column_ddl.join(", ")))
        .await
        .expect("create fixture table");

    let col_names: Vec<&str> = column_ddl
        .iter()
        .map(|c| c.split_whitespace().next().expect("non-empty column ddl"))
        .collect();
    let col_list = col_names.iter().map(|c| format!("\"{c}\"")).collect::<Vec<_>>().join(", ");
    for row in rows {
        let vals = col_names
            .iter()
            .map(|c| sql_literal(row.get(*c)))
            .collect::<Vec<_>>()
            .join(", ");
        adapter
            .execute_raw_query(&format!(r#"INSERT INTO "{table}" ({col_list}) VALUES ({vals})"#))
            .await
            .expect("seed fixture row");
    }

    Some((pg, adapter))
}

/// Connect to the harness Postgres, returning the adapter with no table
/// provisioned. `None` when no Postgres is configured (skip on the non-DB
/// preflight leg); the bound `Service` is returned so a locally-spawned
/// container, if any, is held for the test's lifetime.
pub async fn pg_adapter() -> Option<(fraiseql_test_support::Service, Arc<PostgresAdapter>)> {
    let pg = fraiseql_test_support::postgres().await?;
    let adapter = PostgresAdapter::new(pg.url()).await.expect("connect to harness postgres");
    Some((pg, Arc::new(adapter)))
}

/// Build a column→value map (a seed row, or a representation's key fields).
pub fn row(pairs: &[(&str, Value)]) -> HashMap<String, Value> {
    pairs.iter().map(|(k, v)| ((*k).to_string(), v.clone())).collect()
}

/// Build an `EntityRepresentation` for `typename` from its key (column, value) pairs.
pub fn rep(typename: &str, keys: &[(&str, Value)]) -> EntityRepresentation {
    let key_fields = row(keys);
    EntityRepresentation {
        typename: typename.to_string(),
        all_fields: key_fields.clone(),
        key_fields,
    }
}

/// Render a JSON value as a SQL literal for test seed data (test-controlled).
fn sql_literal(value: Option<&Value>) -> String {
    match value {
        Some(Value::String(s)) => format!("'{}'", s.replace('\'', "''")),
        Some(Value::Number(n)) => n.to_string(),
        Some(Value::Bool(b)) => b.to_string(),
        Some(Value::Null) | None => "NULL".to_string(),
        Some(other) => format!("'{}'", other.to_string().replace('\'', "''")),
    }
}

// =============================================================================
// Mutation Executor Fixture (real PostgreSQL)
// =============================================================================

/// Connect to the harness Postgres, provision each `(table, column_ddl)` as a
/// fresh empty table, and return a [`FederationMutationExecutor`] over the real
/// adapter.
///
/// `FederationMutationExecutor::execute_local_mutation` builds a plain
/// `INSERT`/`UPDATE`/`DELETE` against the lowercased entity type name and runs
/// it via `execute_raw_query`, so each test provisions exactly the columns its
/// variables reference. The table name is lowercased here to match the builder
/// (`quote_postgres_identifier(typename.to_lowercase())`), so callers can pass
/// either case without drift. `execute_extended_mutation` never touches the
/// adapter, so its tests pass an empty `tables` slice.
///
/// Returns `None` when no Postgres is configured (`DATABASE_URL` unset and no
/// local-testcontainers spawn) so the caller skips cleanly on the non-DB
/// preflight leg; the bound `Service` is returned alongside the executor so a
/// locally-spawned container, if any, is held for the test's lifetime.
pub async fn pg_mutation_executor(
    metadata: FederationMetadata,
    tables: &[(&str, &[&str])],
) -> Option<(fraiseql_test_support::Service, FederationMutationExecutor<PostgresAdapter>)> {
    let (pg, adapter) = pg_adapter().await?;

    for (table, column_ddl) in tables {
        let table = table.to_lowercase();
        adapter
            .execute_raw_query(&format!(r#"DROP TABLE IF EXISTS "{table}" CASCADE"#))
            .await
            .expect("drop mutation table");
        adapter
            .execute_raw_query(&format!(r#"CREATE TABLE "{table}" ({})"#, column_ddl.join(", ")))
            .await
            .expect("create mutation table");
    }

    Some((pg, FederationMutationExecutor::new(adapter, metadata)))
}

// =============================================================================
// FederationMetadata Builders
// =============================================================================

/// Create a `FederationMetadata` with a single owned type with one key field.
pub fn metadata_single_key(type_name: &str, key_field: &str) -> FederationMetadata {
    FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![FederatedType {
            name:                type_name.to_string(),
            keys:                vec![KeyDirective {
                fields:     vec![key_field.to_string()],
                resolvable: true,
            }],
            is_extends:          false,
            external_fields:     vec![],
            shareable_fields:    vec![],
            inaccessible_fields: vec![],
            field_directives:    std::collections::HashMap::new(),
            type_shareable:      false,
        }],
        remote_subscription_fields: std::collections::HashMap::new(),
    }
}

/// Create a `FederationMetadata` with a single extended type.
pub fn metadata_extended_type(
    type_name: &str,
    key_field: &str,
    external_fields: &[&str],
    shareable_fields: &[&str],
) -> FederationMetadata {
    FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![FederatedType {
            name:                type_name.to_string(),
            keys:                vec![KeyDirective {
                fields:     vec![key_field.to_string()],
                resolvable: true,
            }],
            is_extends:          true,
            external_fields:     external_fields.iter().map(|s| (*s).to_string()).collect(),
            shareable_fields:    shareable_fields.iter().map(|s| (*s).to_string()).collect(),
            inaccessible_fields: vec![],
            field_directives:    std::collections::HashMap::new(),
            type_shareable:      false,
        }],
        remote_subscription_fields: std::collections::HashMap::new(),
    }
}

/// Create a `FederationMetadata` with a composite key.
pub fn metadata_composite_key(type_name: &str, key_fields: &[&str]) -> FederationMetadata {
    FederationMetadata {
        enabled: true,
        version: "v2".to_string(),
        types: vec![FederatedType {
            name:                type_name.to_string(),
            keys:                vec![KeyDirective {
                fields:     key_fields.iter().map(|s| (*s).to_string()).collect(),
                resolvable: true,
            }],
            is_extends:          false,
            external_fields:     vec![],
            shareable_fields:    vec![],
            inaccessible_fields: vec![],
            field_directives:    std::collections::HashMap::new(),
            type_shareable:      false,
        }],
        remote_subscription_fields: std::collections::HashMap::new(),
    }
}

// =============================================================================
// @requires Enforcement Helper
// =============================================================================

/// Enforce @requires directives at runtime.
///
/// Validates that all fields required by the @requires directives are present
/// in the entity representation.
pub fn enforce_requires(
    metadata: &FederationMetadata,
    typename: &str,
    fields: &[&str],
    representation: &EntityRepresentation,
) -> std::result::Result<(), String> {
    let federated_type = metadata
        .types
        .iter()
        .find(|t| t.name == typename)
        .ok_or_else(|| format!("Type {} not found in federation metadata", typename))?;

    for field in fields {
        if let Some(directives) = federated_type.get_field_directives(field) {
            for required in &directives.requires {
                let field_path = required.path.join(".");
                if !representation.has_field(&field_path) {
                    return Err(format!(
                        "Validation Error: Required field missing\n\
                         Type: {}\n\
                         Field: {}\n\
                         Required: {}\n\
                         Issue: Field '{}' requires '{}' but it is missing from entity \
                         representation\n\
                         Suggestion: Ensure '{}' is requested from the owning subgraph",
                        typename, field, field_path, field, field_path, field_path
                    ));
                }
            }
        }
    }

    Ok(())
}

// =============================================================================
// Docker Network Infrastructure
// =============================================================================

pub const APOLLO_GATEWAY_URL: &str = "http://localhost:4000/graphql";
pub const USERS_SUBGRAPH_URL: &str = "http://localhost:4001/graphql";
pub const ORDERS_SUBGRAPH_URL: &str = "http://localhost:4002/graphql";
pub const PRODUCTS_SUBGRAPH_URL: &str = "http://localhost:4003/graphql";

/// Wait for a service to be ready with health check.
pub async fn wait_for_service(
    url: &str,
    max_retries: u32,
) -> std::result::Result<(), Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let mut retries = 0;

    loop {
        match client
            .post(url)
            .json(&json!({ "query": "{ __typename }" }))
            .timeout(Duration::from_secs(5))
            .send()
            .await
        {
            Ok(response) if response.status().is_success() => {
                println!("✓ Service ready: {}", url);
                return Ok(());
            },
            Ok(response) => {
                println!("✗ Service {} returned status: {}", url, response.status());
            },
            Err(e) => {
                println!("✗ Service {} connection failed: {}", url, e);
            },
        }

        retries += 1;
        if retries >= max_retries {
            return Err(format!(
                "Service {} failed to become ready after {} retries",
                url, max_retries
            )
            .into());
        }

        tokio::time::sleep(Duration::from_secs(2)).await;
    }
}

/// Execute a GraphQL query against a service.
pub async fn graphql_query(
    url: &str,
    query: &str,
) -> std::result::Result<Value, Box<dyn std::error::Error>> {
    let client = reqwest::Client::new();
    let response = client
        .post(url)
        .json(&json!({ "query": query }))
        .timeout(Duration::from_secs(10))
        .send()
        .await?;

    let body: Value = response.json().await?;
    Ok(body)
}

/// Extract data from a GraphQL response.
pub fn extract_data(response: &Value) -> Option<&Value> {
    response.get("data")
}

/// Check for GraphQL errors.
pub fn has_errors(response: &Value) -> bool {
    response.get("errors").is_some()
}

/// Get error messages from a GraphQL response.
pub fn get_error_messages(response: &Value) -> String {
    response
        .get("errors")
        .and_then(|e| e.as_array())
        .map(|arr| {
            arr.iter()
                .filter_map(|err| err.get("message")?.as_str())
                .collect::<Vec<_>>()
                .join("; ")
        })
        .unwrap_or_else(|| "Unknown error".to_string())
}

/// Setup test fixtures — ensures 2-subgraph services are ready.
pub async fn setup_federation_tests() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("\n=== Setting up 2-subgraph federation tests ===\n");

    println!("Waiting for users subgraph...");
    wait_for_service(USERS_SUBGRAPH_URL, 30).await?;

    println!("Waiting for orders subgraph...");
    wait_for_service(ORDERS_SUBGRAPH_URL, 30).await?;

    println!("Waiting for Apollo Router gateway...");
    wait_for_service(APOLLO_GATEWAY_URL, 30).await?;

    println!("\n✓ All services ready for 2-subgraph federation tests\n");
    Ok(())
}

/// Setup helper for 3-subgraph federation tests (users -> orders -> products).
pub async fn setup_three_subgraph_tests() -> std::result::Result<(), Box<dyn std::error::Error>> {
    println!("\n=== Setting up 3-subgraph federation tests ===\n");

    println!("Waiting for users subgraph (port 4001)...");
    wait_for_service(USERS_SUBGRAPH_URL, 30).await?;

    println!("Waiting for orders subgraph (port 4002)...");
    wait_for_service(ORDERS_SUBGRAPH_URL, 30).await?;

    println!("Waiting for products subgraph (port 4003)...");
    wait_for_service(PRODUCTS_SUBGRAPH_URL, 30).await?;

    println!("Waiting for Apollo Router gateway...");
    wait_for_service(APOLLO_GATEWAY_URL, 30).await?;

    println!("\n✓ All 3 subgraphs + gateway ready for federation tests\n");
    Ok(())
}

// =============================================================================
// Saga Test Helpers
// =============================================================================

use fraiseql_core::federation::{
    saga_compensator::SagaCompensator,
    saga_coordinator::{CompensationStrategy, SagaCoordinator, SagaStep},
    saga_executor::SagaExecutor,
};
use uuid::Uuid;

/// Test saga scenario builder for E2E testing.
pub struct TestSagaScenario {
    pub step_count:            usize,
    pub compensation_strategy: CompensationStrategy,
}

impl TestSagaScenario {
    pub const fn new(step_count: usize) -> Self {
        Self {
            step_count,
            compensation_strategy: CompensationStrategy::Automatic,
        }
    }

    #[allow(dead_code)] // Reason: builder method used by subset of saga tests; Clippy false-positive (multi-binary)
    pub const fn with_strategy(mut self, strategy: CompensationStrategy) -> Self {
        self.compensation_strategy = strategy;
        self
    }

    pub fn build_steps(&self) -> Vec<SagaStep> {
        (1..=self.step_count as u32)
            .map(|i| {
                let subgraph = format!("service-{}", i % 3 + 1);
                let mutation = format!("mutation{}", i);
                let compensation = format!("compensation{}", i);

                SagaStep::new(
                    i,
                    &subgraph,
                    format!("Entity{}", i),
                    &mutation,
                    json!({
                        "step": i,
                        "data": format!("input_{}", i)
                    }),
                    &compensation,
                    json!({
                        "step": i,
                        "rollback": true
                    }),
                )
            })
            .collect()
    }
}

/// Create coordinator and execute saga creation.
pub async fn execute_saga_scenario(scenario: TestSagaScenario) -> (Vec<SagaStep>, Uuid) {
    let coordinator = SagaCoordinator::new(scenario.compensation_strategy);
    let steps = scenario.build_steps();
    let saga_id = coordinator.create_saga(steps.clone()).await.expect("Failed to create saga");
    (steps, saga_id)
}

/// Execute all steps of a saga.
pub async fn execute_all_steps(saga_id: Uuid, step_count: usize) {
    execute_all_steps_with_failure(saga_id, step_count, None).await;
}

/// Execute steps with optional failure injection at a specific step.
pub async fn execute_all_steps_with_failure(
    saga_id: Uuid,
    step_count: usize,
    fail_at_step: Option<u32>,
) {
    let executor = SagaExecutor::new();

    for step_number in 1..=step_count as u32 {
        let mutation_name = format!("mutation{}", step_number);
        let subgraph = format!("service-{}", step_number % 3 + 1);

        if Some(step_number) == fail_at_step {
            break;
        }

        let result = executor
            .execute_step(
                saga_id,
                step_number,
                &mutation_name,
                &json!({"step": step_number}),
                &subgraph,
            )
            .await;

        assert!(result.is_ok(), "Step {} execution failed", step_number);
        let step_result = result.unwrap();
        assert_eq!(step_result.step_number, step_number);
        assert!(step_result.success, "Step {} should succeed", step_number);
        assert!(step_result.data.is_some(), "Step {} should return data", step_number);
    }
}

/// Execute compensation for a saga in reverse order.
pub async fn execute_compensation(saga_id: Uuid, completed_step_count: usize) {
    let compensator = SagaCompensator::new();

    for step_number in (1..=completed_step_count as u32).rev() {
        let compensation_mutation = format!("compensation{}", step_number);
        let subgraph = format!("service-{}", step_number % 3 + 1);
        let result = compensator
            .compensate_step(
                saga_id,
                step_number,
                &compensation_mutation,
                &json!({"step": step_number}),
                &subgraph,
            )
            .await;

        assert!(result.is_ok(), "Compensation step {} failed", step_number);
        let comp_result = result.unwrap();
        assert_eq!(comp_result.step_number, step_number);
    }
}