fraiseql-core 2.17.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
//! Non-null completion of a response — GraphQL § 6.4.4 (*Handling Execution Errors*, #1522),
//! and the result coercion of an enum whose members store values (§ 3.9, #1580).
//!
//! A field the schema publishes as non-null (`String!`, `[Edge!]!`) must never be answered
//! with `null`. When the stored value is missing or `null`, § 6.4.4 makes it a **field
//! error**: the error is added to `errors` with the field's response path, and the `null`
//! propagates to the nearest ancestor position that allows it (a nullable field or list
//! item), up to `data` itself when every position above is non-null.
//!
//! Before this nothing checked it: a row with no `name` came back `{"name": null}` under a
//! `String!`, and a typed client generated from the schema crashed on a value it was told
//! could not occur.
//!
//! # The types are the ones introspection publishes
//!
//! The rule is applied against [`IntrospectionBuilder::build`], the same model `__schema`
//! and `__type` answer from, so what the runtime enforces is exactly what it advertises:
//! the relay `Connection`/`Edge` wrappers, the translations siblings of localized fields
//! and the root operation types included. A type or field that model does not carry is
//! passed through unadjudicated, the governing rule of the validators next door.
//!
//! # One pass, after execution
//!
//! Completion runs once over a root field's finished value, guided by the operation's
//! selection set (aliases are response keys; inline fragments apply when their type
//! condition matches the object's `__typename`; `@skip`/`@include` are evaluated against the
//! request's variables), rather than inside each projector. Every read path — regular,
//! relay, composed, node, federation `_entities`, aggregates, mutation payloads and
//! subscription events — produces a value of the published type, so one walk over that
//! value is the one place the rule can be applied to all of them alike.

use std::{
    cell::OnceCell,
    collections::{HashMap, HashSet},
};

use ahash::AHashMap;
use serde_json::{Map, Value};

use crate::{
    graphql::{DirectiveEvaluator, FieldSelection},
    schema::{CompiledSchema, IntrospectionBuilder, IntrospectionType, TypeKind},
};

/// How deep the walk follows a response before passing the rest through. A response is
/// depth-limited upstream (GATE 1); this bounds a hand-built one.
const MAX_COMPLETION_DEPTH: usize = 64;

/// An output type reference, wrappers included: `[Edge!]!` is
/// `NonNull(List(NonNull(Named("Edge"))))`.
#[derive(Debug, Clone, PartialEq, Eq)]
enum TypeRef {
    NonNull(Box<TypeRef>),
    List(Box<TypeRef>),
    /// An enum: its value is checked against the members (§ 3.9 result coercion).
    Enum(String),
    Named(String),
}

impl TypeRef {
    fn from_introspection(t: &IntrospectionType) -> Option<Self> {
        match t.kind {
            TypeKind::NonNull => {
                Some(Self::NonNull(Box::new(Self::from_introspection(t.of_type.as_deref()?)?)))
            },
            TypeKind::List => {
                Some(Self::List(Box::new(Self::from_introspection(t.of_type.as_deref()?)?)))
            },
            TypeKind::Enum => t.name.clone().map(Self::Enum),
            _ => t.name.clone().map(Self::Named),
        }
    }
}

/// The output types of a schema, as introspection publishes them: every object and
/// interface's fields with their wrapped types, and every abstract type's possible types.
///
/// Every response is completed against these, a lookup per object and per field, so the
/// maps hash with `ahash`. They hold the schema's own names and are built once, so no
/// request can grow them.
#[derive(Debug, Clone, Default)]
pub struct OutputTypes {
    /// Object and interface type name → field name → published type.
    fields:   AHashMap<String, AHashMap<String, TypeRef>>,
    /// Interface and union type name → the object types it may resolve to.
    possible: AHashMap<String, HashSet<String>>,
    /// Enum type name → its members by stored value (#1580): a stored value is served as
    /// its member's name, and one that is no member's is a field error.
    enums:    AHashMap<String, EnumMembers>,
}

/// An enum's members by the value each is stored as: a string (its name, or a string
/// value) or an integer.
#[derive(Debug, Clone)]
struct EnumMembers {
    strings:    AHashMap<String, String>,
    ints:       AHashMap<i64, String>,
    definition: crate::schema::EnumDefinition,
}

impl EnumMembers {
    fn of(e: &crate::schema::EnumDefinition) -> Self {
        let mut strings = AHashMap::new();
        let mut ints = AHashMap::new();
        for v in &e.values {
            match &v.value {
                Some(crate::schema::StoredEnumValue::Int(n)) => {
                    ints.insert(*n, v.name.clone());
                },
                Some(crate::schema::StoredEnumValue::String(s)) => {
                    strings.insert(s.clone(), v.name.clone());
                },
                None => {
                    strings.insert(v.name.clone(), v.name.clone());
                },
            }
        }
        Self {
            strings,
            ints,
            definition: e.clone(),
        }
    }

    /// The member `stored` is the stored value of.
    fn member_of(&self, stored: &Value) -> Option<&String> {
        match stored {
            Value::String(s) => self.strings.get(s.as_str()),
            Value::Number(n) => n.as_i64().and_then(|n| self.ints.get(&n)),
            _ => None,
        }
    }
}

impl OutputTypes {
    /// The output types `schema` publishes through introspection.
    #[must_use]
    pub fn from_schema(schema: &CompiledSchema) -> Self {
        let introspection = IntrospectionBuilder::build(schema);
        let mut types = Self::default();
        for t in &introspection.types {
            let Some(name) = &t.name else {
                continue;
            };
            if let Some(fields) = &t.fields {
                let fields = fields
                    .iter()
                    .filter_map(|f| {
                        TypeRef::from_introspection(&f.field_type).map(|r| (f.name.clone(), r))
                    })
                    .collect();
                types.fields.insert(name.clone(), fields);
            }
            if let Some(possible) = &t.possible_types {
                types
                    .possible
                    .insert(name.clone(), possible.iter().map(|p| p.name.clone()).collect());
            }
        }
        for e in &schema.enums {
            types.enums.insert(e.name.clone(), EnumMembers::of(e));
        }
        #[cfg(feature = "federation")]
        types.add_federation(schema);
        types
    }

    /// The federation entry point the subgraph SDL publishes (`_entities(representations:
    /// [_Any!]!): [_Entity]!`, `union _Entity` of the entity types), which introspection
    /// does not carry.
    #[cfg(feature = "federation")]
    fn add_federation(&mut self, schema: &CompiledSchema) {
        let Some(metadata) = schema.federation_metadata() else {
            return;
        };
        let entity = TypeRef::Named("_Entity".to_string());
        self.fields.entry("Query".to_string()).or_default().insert(
            "_entities".to_string(),
            TypeRef::NonNull(Box::new(TypeRef::List(Box::new(entity)))),
        );
        self.possible
            .insert("_Entity".to_string(), metadata.types.iter().map(|t| t.name.clone()).collect());
    }

    /// The published fields of `type_name`, and the name as the schema spells it.
    fn type_fields(&self, type_name: &str) -> Option<(&str, &AHashMap<String, TypeRef>)> {
        self.fields
            .get_key_value(type_name)
            .map(|(name, fields)| (name.as_str(), fields))
    }

    /// Complete `response["data"]` (§ 6.4.4): each root field of `selections` on
    /// `root_type`, in place. A violation nulls the nearest nullable position, or `data`,
    /// and adds an entry to `response["errors"]`.
    ///
    /// `selections` is the operation's root selection set with fragment spreads expanded
    /// and directives not yet evaluated; `variables` (the request's, an object) evaluates
    /// them.
    pub fn complete(
        &self,
        response: &mut Value,
        root_type: &str,
        selections: &[FieldSelection],
        variables: Option<&Value>,
    ) {
        let walk = Walk::new(self, variables);
        let mut errors = Vec::new();
        let Some(data) = response.get_mut("data").and_then(Value::as_object_mut) else {
            return;
        };
        let mut null_data = false;
        let mut path = Vec::new();
        if let Some((root_type, fields)) = self.type_fields(root_type) {
            walk.for_each_field(selections, root_type, &mut |sel| {
                let Some(field_ref) = fields.get(&sel.name) else {
                    return;
                };
                let key = sel.response_key();
                let Some(value) = data.get_mut(key) else {
                    return;
                };
                path.push(Step::Key(key));
                let label = Label::Field(root_type, &sel.name);
                if walk.position(value, field_ref, sel, label, &mut path, &mut errors, 0).is_err() {
                    null_data = true;
                }
                path.pop();
            });
        }
        if null_data {
            response["data"] = Value::Null;
        }
        if errors.is_empty() {
            return;
        }
        match response.get_mut("errors").and_then(Value::as_array_mut) {
            Some(existing) => existing.extend(errors),
            None => {
                if let Some(object) = response.as_object_mut() {
                    object.insert("errors".to_string(), Value::Array(errors));
                }
            },
        }
    }
}

impl OutputTypes {
    /// Complete one value of `type_name` at a nullable position (§ 6.4.4), against the
    /// sub-selection `selections` (spreads expanded, directives evaluated): the value, or
    /// `null` when a violation propagated to it, and the errors, their paths rooted at
    /// `root_key`. A subscription event is one: every subscription field is nullable.
    #[must_use]
    pub fn complete_value(
        &self,
        mut value: Value,
        type_name: &str,
        selections: &[FieldSelection],
        root_key: &str,
    ) -> (Value, Vec<Value>) {
        let walk = Walk::new(self, None);
        let sel = FieldSelection {
            name:          root_key.to_string(),
            alias:         None,
            arguments:     Vec::new(),
            nested_fields: selections.to_vec(),
            directives:    Vec::new(),
        };
        let mut errors = Vec::new();
        let mut path = vec![Step::Key(root_key)];
        let field_ref = TypeRef::Named(type_name.to_string());
        if walk
            .position(
                &mut value,
                &field_ref,
                &sel,
                Label::Root(root_key),
                &mut path,
                &mut errors,
                0,
            )
            .is_err()
        {
            value = Value::Null;
        }
        (value, errors)
    }
}

/// A non-null violation below, to be absorbed by the nearest nullable position.
struct Propagate;

/// One step of a response path, borrowed from the walk. Rendered only into an error.
#[derive(Clone, Copy)]
enum Step<'a> {
    Key(&'a str),
    Index(usize),
}

/// The field an error names: `Type.field`, or a root key on its own. Rendered only into an
/// error.
#[derive(Clone, Copy)]
enum Label<'a> {
    Field(&'a str, &'a str),
    Root(&'a str),
}

impl std::fmt::Display for Label<'_> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Field(owner, field) => write!(f, "{owner}.{field}"),
            Self::Root(key) => f.write_str(key),
        }
    }
}

/// The § 6.4.4 field error for a `null` at a non-null position.
fn violation(label: Label<'_>, path: &[Step<'_>]) -> Value {
    serde_json::json!({
        "message": format!("Cannot return null for non-nullable field {label}."),
        "path": response_path(path),
    })
}

/// The field error for a stored value of an enum position that is no member's stored value.
fn not_a_member(
    label: Label<'_>,
    path: &[Step<'_>],
    stored: &Value,
    members: &EnumMembers,
) -> Value {
    serde_json::json!({
        "message": members.definition.not_a_member_message(stored, &label),
        "path": response_path(path),
    })
}

fn response_path(path: &[Step<'_>]) -> Vec<Value> {
    path.iter()
        .map(|step| match *step {
            Step::Key(key) => Value::String(key.to_string()),
            Step::Index(index) => Value::from(index),
        })
        .collect()
}

/// One completion: the types and the request's variables.
///
/// Completion runs on every response, so the walk allocates nothing unless it records an
/// error: values are completed in place, the path and the field label are borrowed and
/// rendered only into an error, and the variables become the map directives are evaluated
/// against only when a selection carries a directive.
struct Walk<'a> {
    types:               &'a OutputTypes,
    variables:           Option<&'a Value>,
    directive_variables: OnceCell<HashMap<String, Value>>,
}

impl<'a> Walk<'a> {
    const fn new(types: &'a OutputTypes, variables: Option<&'a Value>) -> Self {
        Self {
            types,
            variables,
            directive_variables: OnceCell::new(),
        }
    }

    /// Whether `@skip`/`@include` keep `sel`.
    fn included(&self, sel: &FieldSelection) -> bool {
        if sel.directives.is_empty() {
            return true;
        }
        let variables = self.directive_variables.get_or_init(|| {
            self.variables
                .and_then(Value::as_object)
                .map(|map| map.iter().map(|(k, v)| (k.clone(), v.clone())).collect())
                .unwrap_or_default()
        });
        // A directive that cannot be evaluated was refused before execution; included is
        // the reading that adjudicates the most.
        DirectiveEvaluator::evaluate_directives(sel, variables).unwrap_or(true)
    }

    /// Visit the fields `selections` selects on an object of type `type_name`: inline
    /// fragments whose condition the type satisfies are lifted, fields excluded by
    /// `@skip`/`@include` and meta-fields are skipped.
    fn for_each_field<'s>(
        &self,
        selections: &'s [FieldSelection],
        type_name: &str,
        visit: &mut impl FnMut(&'s FieldSelection),
    ) {
        for sel in selections {
            if !self.included(sel) {
                continue;
            }
            if let Some(condition) = sel.name.strip_prefix("...on ") {
                if self.satisfies(type_name, condition.trim()) {
                    self.for_each_field(&sel.nested_fields, type_name, visit);
                }
                continue;
            }
            if sel.name.starts_with("...") || sel.name.starts_with("__") {
                continue;
            }
            visit(sel);
        }
    }

    /// Whether an object of type `type_name` matches a fragment on `condition`.
    fn satisfies(&self, type_name: &str, condition: &str) -> bool {
        condition == type_name
            || self.types.possible.get(condition).is_some_and(|p| p.contains(type_name))
    }

    /// Complete `value`, in place, at a position of type `field_ref`.
    ///
    /// `Err(Propagate)` when the position is non-null and its value is `null`, whether it
    /// arrived so (an error is recorded here, at `path`) or became so by a violation below
    /// (already recorded there). A nullable position absorbs a violation below by becoming
    /// `null`.
    #[allow(clippy::too_many_arguments)] // Reason: one recursive step of one walk; a struct would hold the same state
    fn position<'s>(
        &self,
        value: &mut Value,
        field_ref: &TypeRef,
        sel: &'s FieldSelection,
        label: Label<'s>,
        path: &mut Vec<Step<'s>>,
        errors: &mut Vec<Value>,
        depth: usize,
    ) -> Result<(), Propagate>
    where
        'a: 's,
    {
        match field_ref {
            TypeRef::NonNull(inner) => {
                self.nullable(value, inner, sel, label, path, errors, depth)?;
                if value.is_null() {
                    errors.push(violation(label, path));
                    return Err(Propagate);
                }
                Ok(())
            },
            other => {
                if self.nullable(value, other, sel, label, path, errors, depth).is_err() {
                    *value = Value::Null;
                }
                Ok(())
            },
        }
    }

    /// Complete a value, in place, at a nullable position: `Err(Propagate)` when a
    /// non-null violation below makes it `null`.
    #[allow(clippy::too_many_arguments)] // Reason: as `position`
    fn nullable<'s>(
        &self,
        value: &mut Value,
        field_ref: &TypeRef,
        sel: &'s FieldSelection,
        label: Label<'s>,
        path: &mut Vec<Step<'s>>,
        errors: &mut Vec<Value>,
        depth: usize,
    ) -> Result<(), Propagate>
    where
        'a: 's,
    {
        if value.is_null() || depth > MAX_COMPLETION_DEPTH {
            return Ok(());
        }
        match field_ref {
            TypeRef::NonNull(_) => self.position(value, field_ref, sel, label, path, errors, depth),
            // A stored value is served as its member's name (#1580), and a value that is no
            // member's is a field error, never served (§ 3.9 result coercion).
            TypeRef::Enum(name) => {
                let Some(members) = self.types.enums.get(name.as_str()) else {
                    return Ok(());
                };
                let Some(member) = members.member_of(value) else {
                    errors.push(not_a_member(label, path, value, members));
                    return Err(Propagate);
                };
                if value.as_str() != Some(member.as_str()) {
                    *value = Value::String(member.clone());
                }
                Ok(())
            },
            TypeRef::List(inner) => {
                let Value::Array(items) = value else {
                    return Ok(());
                };
                // Every item is completed, so every violation is reported, before one
                // that propagated nulls the list.
                let mut propagated = false;
                for (index, item) in items.iter_mut().enumerate() {
                    path.push(Step::Index(index));
                    if self.position(item, inner, sel, label, path, errors, depth + 1).is_err() {
                        propagated = true;
                    }
                    path.pop();
                }
                if propagated { Err(Propagate) } else { Ok(()) }
            },
            TypeRef::Named(name) => match value {
                Value::Object(map) => self.object(map, name, sel, path, errors, depth),
                _ => Ok(()),
            },
        }
    }

    /// Complete an object value of declared type `declared`, in place, against `sel`'s
    /// sub-selection.
    fn object<'s>(
        &self,
        map: &mut Map<String, Value>,
        declared: &str,
        sel: &'s FieldSelection,
        path: &mut Vec<Step<'s>>,
        errors: &mut Vec<Value>,
        depth: usize,
    ) -> Result<(), Propagate>
    where
        'a: 's,
    {
        // The object is of the type its `__typename` names, when that is a type the schema
        // publishes: an abstract type's variant, or the error type a failed mutation
        // resolves to under a bare success return type. Without one, the declared type's
        // own fields (an interface's) are all that can be adjudicated.
        let types = self.types;
        let Some((concrete, fields)) = map
            .get("__typename")
            .and_then(Value::as_str)
            .and_then(|t| types.type_fields(t))
            .or_else(|| types.type_fields(declared))
        else {
            return Ok(());
        };
        // Every field is completed, so every violation is reported, before one that
        // propagated nulls the object.
        let mut propagated = false;
        self.for_each_field(&sel.nested_fields, concrete, &mut |child| {
            let Some(field_ref) = fields.get(&child.name) else {
                return;
            };
            let key = child.response_key();
            path.push(Step::Key(key));
            let label = Label::Field(concrete, &child.name);
            // Completed in place, never removed and re-inserted: the response keeps the
            // document's field order (§ 6.3). An absent field is completed as `null` and
            // stays absent.
            let completed = match map.get_mut(key) {
                Some(value) => {
                    self.position(value, field_ref, child, label, path, errors, depth + 1)
                },
                None => self.position(
                    &mut Value::Null,
                    field_ref,
                    child,
                    label,
                    path,
                    errors,
                    depth + 1,
                ),
            };
            path.pop();
            if completed.is_err() {
                propagated = true;
            }
        });
        if propagated { Err(Propagate) } else { Ok(()) }
    }
}

#[cfg(test)]
mod tests;