fraiseql-core 2.12.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
//! `__schema` query response construction.
//!
//! Builds the Query, Mutation, and Subscription root introspection types, and
//! the `IntrospectionBuilder` and `IntrospectionResponses` public entry points.

use std::{collections::HashMap, sync::Arc};

use super::{
    super::{CompiledSchema, MutationDefinition, QueryDefinition, SubscriptionDefinition},
    directive_builder::{build_custom_directives, builtin_directives},
    field_resolver::{build_arg_input_value, type_ref},
    type_resolver::{
        build_enum_type, build_input_object_type, build_interface_type, build_object_type,
        build_union_type, builtin_scalars,
    },
    types::{
        IntrospectionField, IntrospectionInputValue, IntrospectionSchema, IntrospectionType,
        IntrospectionTypeRef, TypeKind,
    },
};

// =============================================================================
// IntrospectionBuilder
// =============================================================================

/// Builds introspection schema from compiled schema.
#[must_use = "call .build() to construct the final value"]
pub struct IntrospectionBuilder;

impl IntrospectionBuilder {
    /// Build complete introspection schema from compiled schema.
    #[must_use]
    pub fn build(schema: &CompiledSchema) -> IntrospectionSchema {
        let mut types = Vec::new();

        // Add built-in scalar types
        types.extend(builtin_scalars());

        // Add user-defined types
        for type_def in &schema.types {
            types.push(build_object_type(type_def));
        }

        // Add enum types
        for enum_def in &schema.enums {
            types.push(build_enum_type(enum_def));
        }

        // Add input object types
        for input_def in &schema.input_types {
            types.push(build_input_object_type(input_def));
        }

        // Add interface types
        for interface_def in &schema.interfaces {
            types.push(build_interface_type(interface_def, schema));
        }

        // Add union types
        for union_def in &schema.unions {
            types.push(build_union_type(union_def));
        }

        // Add Query root type
        types.push(build_query_type(schema));

        // Add Mutation root type if mutations exist
        if !schema.mutations.is_empty() {
            types.push(build_mutation_type(schema));
        }

        // Add Subscription root type if subscriptions exist
        if !schema.subscriptions.is_empty() {
            types.push(build_subscription_type(schema));
        }

        // Build directives: built-in + custom
        let mut directives = builtin_directives();
        directives.extend(build_custom_directives(&schema.directives));

        IntrospectionSchema {
            description: Some("FraiseQL GraphQL Schema".to_string()),
            types,
            query_type: IntrospectionTypeRef {
                name: "Query".to_string(),
            },
            mutation_type: if schema.mutations.is_empty() {
                None
            } else {
                Some(IntrospectionTypeRef {
                    name: "Mutation".to_string(),
                })
            },
            subscription_type: if schema.subscriptions.is_empty() {
                None
            } else {
                Some(IntrospectionTypeRef {
                    name: "Subscription".to_string(),
                })
            },
            directives,
        }
    }

    /// Build a lookup map for `__type(name:)` queries.
    #[must_use]
    pub fn build_type_map(schema: &IntrospectionSchema) -> HashMap<String, IntrospectionType> {
        let mut map = HashMap::new();
        for t in &schema.types {
            if let Some(ref name) = t.name {
                map.insert(name.clone(), t.clone());
            }
        }
        map
    }

    /// Expose `type_ref` as an associated function for use in tests.
    #[must_use]
    pub fn type_ref(name: &str) -> IntrospectionType {
        type_ref(name)
    }
}

// =============================================================================
// Root type builders
// =============================================================================

/// Build Query root type.
fn build_query_type(schema: &CompiledSchema) -> IntrospectionType {
    let mut fields: Vec<IntrospectionField> =
        schema.queries.iter().map(|q| build_query_field(q, schema)).collect();

    // Inject synthetic `node(id: ID!): Node` field when relay types exist.
    let has_relay_types =
        schema.types.iter().any(|t| t.relay) || schema.interfaces.iter().any(|i| i.name == "Node");
    if has_relay_types && !fields.iter().any(|f| f.name == "node") {
        fields.push(build_node_query_field());
    }

    IntrospectionType {
        kind:               TypeKind::Object,
        name:               Some("Query".to_string()),
        description:        Some("Root query type".to_string()),
        fields:             Some(fields),
        interfaces:         Some(vec![]),
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    }
}

/// Build Mutation root type.
fn build_mutation_type(schema: &CompiledSchema) -> IntrospectionType {
    let fields: Vec<IntrospectionField> =
        schema.mutations.iter().map(|m| build_mutation_field(m, schema)).collect();

    IntrospectionType {
        kind:               TypeKind::Object,
        name:               Some("Mutation".to_string()),
        description:        Some("Root mutation type".to_string()),
        fields:             Some(fields),
        interfaces:         Some(vec![]),
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    }
}

/// Build Subscription root type.
fn build_subscription_type(schema: &CompiledSchema) -> IntrospectionType {
    let fields: Vec<IntrospectionField> = schema
        .subscriptions
        .iter()
        .map(|s| build_subscription_field(s, schema))
        .collect();

    IntrospectionType {
        kind:               TypeKind::Object,
        name:               Some("Subscription".to_string()),
        description:        Some("Root subscription type".to_string()),
        fields:             Some(fields),
        interfaces:         Some(vec![]),
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    }
}

// =============================================================================
// Operation field builders
// =============================================================================

/// Build query field introspection.
fn build_query_field(query: &QueryDefinition, schema: &CompiledSchema) -> IntrospectionField {
    // Relay connection queries expose `XxxConnection` as their return type
    // (always non-null) and add the four standard cursor arguments.
    if query.relay {
        return build_relay_query_field(query, schema);
    }

    let return_type = type_ref(&query.return_type);
    let return_type = if query.returns_list {
        IntrospectionType {
            kind:               TypeKind::List,
            name:               None,
            description:        None,
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       None,
            of_type:            Some(Box::new(return_type)),
            specified_by_u_r_l: None,
        }
    } else {
        return_type
    };

    let return_type = if query.nullable {
        return_type
    } else {
        IntrospectionType {
            kind:               TypeKind::NonNull,
            name:               None,
            description:        None,
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       None,
            of_type:            Some(Box::new(return_type)),
            specified_by_u_r_l: None,
        }
    };

    // Build arguments, including the auto-wired `where`/`orderBy`/`limit`/`offset`
    // arguments derived from `auto_params` so introspection matches the `_service`
    // SDL and generated clients.
    let args: Vec<IntrospectionInputValue> =
        query.graphql_arguments().iter().map(build_arg_input_value).collect();

    IntrospectionField {
        name: schema.display_name(&query.name),
        description: query.description.clone(),
        args,
        field_type: return_type,
        is_deprecated: query.is_deprecated(),
        deprecation_reason: query.deprecation_reason().map(ToString::to_string),
    }
}

/// Build introspection for a Relay connection query.
///
/// Relay connection queries differ from normal list queries:
/// - Return type is `XxxConnection!` (non-null), not `[Xxx!]!`
/// - Arguments are `first: Int, after: String, last: Int, before: String` (instead of
///   `limit`/`offset`)
fn build_relay_query_field(query: &QueryDefinition, schema: &CompiledSchema) -> IntrospectionField {
    let connection_type = format!("{}Connection", query.return_type);

    // Return type: XxxConnection! (always non-null)
    let return_type = IntrospectionType {
        kind:               TypeKind::NonNull,
        name:               None,
        description:        None,
        fields:             None,
        interfaces:         None,
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            Some(Box::new(type_ref(&connection_type))),
        specified_by_u_r_l: None,
    };

    // Standard Relay cursor arguments.
    let nullable_int = || IntrospectionType {
        kind:               TypeKind::Scalar,
        name:               Some("Int".to_string()),
        description:        None,
        fields:             None,
        interfaces:         None,
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    };
    let nullable_string = || IntrospectionType {
        kind:               TypeKind::Scalar,
        name:               Some("String".to_string()),
        description:        None,
        fields:             None,
        interfaces:         None,
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    };
    let relay_args = vec![
        IntrospectionInputValue {
            name:               "first".to_string(),
            description:        Some("Return the first N items.".to_string()),
            input_type:         nullable_int(),
            default_value:      None,
            is_deprecated:      false,
            deprecation_reason: None,
            validation_rules:   vec![],
        },
        IntrospectionInputValue {
            name:               "after".to_string(),
            description:        Some("Cursor: return items after this position.".to_string()),
            input_type:         nullable_string(),
            default_value:      None,
            is_deprecated:      false,
            deprecation_reason: None,
            validation_rules:   vec![],
        },
        IntrospectionInputValue {
            name:               "last".to_string(),
            description:        Some("Return the last N items.".to_string()),
            input_type:         nullable_int(),
            default_value:      None,
            is_deprecated:      false,
            deprecation_reason: None,
            validation_rules:   vec![],
        },
        IntrospectionInputValue {
            name:               "before".to_string(),
            description:        Some("Cursor: return items before this position.".to_string()),
            input_type:         nullable_string(),
            default_value:      None,
            is_deprecated:      false,
            deprecation_reason: None,
            validation_rules:   vec![],
        },
    ];

    IntrospectionField {
        name:               schema.display_name(&query.name),
        description:        query.description.clone(),
        args:               relay_args,
        field_type:         return_type,
        is_deprecated:      query.is_deprecated(),
        deprecation_reason: query.deprecation_reason().map(ToString::to_string),
    }
}

/// Build the synthetic `node(id: ID!): Node` field for the Query root type.
///
/// Injected automatically when the schema contains Relay types (relay=true).
fn build_node_query_field() -> IntrospectionField {
    // Return type: Node (nullable per Relay spec — unknown id returns null).
    // Kind must be INTERFACE because Node is declared as an interface type,
    // not an OBJECT. Relay's compiler uses this to dispatch `... on User` fragments.
    let return_type = IntrospectionType {
        kind:               TypeKind::Interface,
        name:               Some("Node".to_string()),
        description:        None,
        fields:             None,
        interfaces:         None,
        possible_types:     None,
        enum_values:        None,
        input_fields:       None,
        of_type:            None,
        specified_by_u_r_l: None,
    };

    // Argument: id: ID! (non-null)
    let id_arg = IntrospectionInputValue {
        name:               "id".to_string(),
        description:        Some("Globally unique opaque identifier.".to_string()),
        input_type:         IntrospectionType {
            kind:               TypeKind::NonNull,
            name:               None,
            description:        None,
            fields:             None,
            interfaces:         None,
            possible_types:     None,
            enum_values:        None,
            input_fields:       None,
            of_type:            Some(Box::new(type_ref("ID"))),
            specified_by_u_r_l: None,
        },
        default_value:      None,
        is_deprecated:      false,
        deprecation_reason: None,
        validation_rules:   vec![],
    };

    IntrospectionField {
        name:               "node".to_string(),
        description:        Some(
            "Fetch any object that implements the Node interface by its global ID.".to_string(),
        ),
        args:               vec![id_arg],
        field_type:         return_type,
        is_deprecated:      false,
        deprecation_reason: None,
    }
}

/// Build mutation field introspection.
fn build_mutation_field(
    mutation: &MutationDefinition,
    schema: &CompiledSchema,
) -> IntrospectionField {
    // Mutations always return a single object (not a list)
    let return_type = type_ref(&mutation.return_type);

    // Build arguments
    let args: Vec<IntrospectionInputValue> =
        mutation.arguments.iter().map(build_arg_input_value).collect();

    IntrospectionField {
        name: schema.display_name(&mutation.name),
        description: mutation.description.clone(),
        args,
        field_type: return_type,
        is_deprecated: mutation.is_deprecated(),
        deprecation_reason: mutation.deprecation_reason().map(ToString::to_string),
    }
}

/// Build subscription field introspection.
fn build_subscription_field(
    subscription: &SubscriptionDefinition,
    schema: &CompiledSchema,
) -> IntrospectionField {
    // Subscriptions typically return a single item per event
    let return_type = type_ref(&subscription.return_type);

    // Build arguments
    let args: Vec<IntrospectionInputValue> =
        subscription.arguments.iter().map(build_arg_input_value).collect();

    IntrospectionField {
        name: schema.display_name(&subscription.name),
        description: subscription.description.clone(),
        args,
        field_type: return_type,
        is_deprecated: subscription.is_deprecated(),
        deprecation_reason: subscription.deprecation_reason().map(ToString::to_string),
    }
}

// =============================================================================
// IntrospectionResponses
// =============================================================================

/// Pre-built introspection responses for fast serving.
///
/// Responses are stored as `Arc<serde_json::Value>` so cloning is O(1)
/// (introspection queries are frequent but the schema is immutable).
#[derive(Debug, Clone)]
pub struct IntrospectionResponses {
    /// Full `__schema` response JSON.
    pub schema_response: Arc<serde_json::Value>,
    /// Map of type name -> `__type` response JSON.
    pub type_responses:  HashMap<String, Arc<serde_json::Value>>,
}

impl IntrospectionResponses {
    /// Build introspection responses from compiled schema.
    ///
    /// This is called once at server startup and cached.
    #[must_use]
    pub fn build(schema: &CompiledSchema) -> Self {
        let introspection = IntrospectionBuilder::build(schema);
        let type_map = IntrospectionBuilder::build_type_map(&introspection);

        // Build __schema response
        let schema_response = Arc::new(serde_json::json!({
            "data": {
                "__schema": introspection
            }
        }));

        // Build __type responses for each type
        let mut type_responses = HashMap::new();
        for (name, t) in type_map {
            let response = Arc::new(serde_json::json!({
                "data": {
                    "__type": t
                }
            }));
            type_responses.insert(name, response);
        }

        Self {
            schema_response,
            type_responses,
        }
    }

    /// Filter `@inaccessible` fields from introspection responses.
    ///
    /// Removes fields listed as inaccessible from both `__type` and `__schema`
    /// responses. This is a DX defence-in-depth measure — Apollo Router uses
    /// `_service { sdl }`, not live introspection, so hiding fields here protects
    /// tooling that queries the subgraph directly.
    ///
    /// Does NOT affect data responses or `_entities` results.
    pub fn filter_inaccessible(&mut self, inaccessible: &HashMap<String, Vec<String>>) {
        if inaccessible.is_empty() {
            return;
        }

        // Filter __type responses
        for (type_name, field_names) in inaccessible {
            if let Some(response) = self.type_responses.get_mut(type_name) {
                let mut val = response.as_ref().clone();
                if let Some(fields) =
                    val.pointer_mut("/data/__type/fields").and_then(|v| v.as_array_mut())
                {
                    fields.retain(|f| {
                        f.get("name")
                            .and_then(|n| n.as_str())
                            .is_none_or(|name| !field_names.contains(&name.to_string()))
                    });
                }
                *response = Arc::new(val);
            }
        }

        // Filter __schema response (types array contains the same fields)
        let mut schema_val = self.schema_response.as_ref().clone();
        if let Some(types) =
            schema_val.pointer_mut("/data/__schema/types").and_then(|v| v.as_array_mut())
        {
            for type_val in types.iter_mut() {
                let type_name = type_val.get("name").and_then(|n| n.as_str()).unwrap_or("");
                if let Some(field_names) = inaccessible.get(type_name) {
                    if let Some(fields) = type_val.get_mut("fields").and_then(|v| v.as_array_mut())
                    {
                        fields.retain(|f| {
                            f.get("name")
                                .and_then(|n| n.as_str())
                                .is_none_or(|name| !field_names.contains(&name.to_string()))
                        });
                    }
                }
            }
        }
        self.schema_response = Arc::new(schema_val);
    }

    /// Get response for `__type(name: "...")` query.
    #[must_use]
    pub fn get_type_response(&self, type_name: &str) -> serde_json::Value {
        self.type_responses.get(type_name).map_or_else(
            || {
                serde_json::json!({
                    "data": {
                        "__type": null
                    }
                })
            },
            |v| v.as_ref().clone(),
        )
    }
}