graphql_federated_graph/
federated_graph.rs

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
mod debug;
mod directives;
mod entity;
mod enum_definitions;
mod enum_values;
mod ids;
mod objects;
mod root_operation_types;
mod scalar_definitions;
mod r#type;
mod view;

use crate::directives::*;

pub use self::{
    directives::*,
    entity::*,
    enum_definitions::EnumDefinitionRecord,
    enum_values::{EnumValue, EnumValueRecord},
    ids::*,
    r#type::{Definition, Type},
    root_operation_types::RootOperationTypes,
    scalar_definitions::ScalarDefinitionRecord,
    view::{View, ViewNested},
};
use enum_definitions::EnumDefinition;
use scalar_definitions::ScalarDefinition;
pub use wrapping::Wrapping;

use std::ops::Range;

#[derive(Clone)]
pub struct FederatedGraph {
    pub subgraphs: Vec<Subgraph>,
    pub root_operation_types: RootOperationTypes,
    pub objects: Vec<Object>,
    pub interfaces: Vec<Interface>,
    pub fields: Vec<Field>,

    pub scalar_definitions: Vec<ScalarDefinitionRecord>,
    pub enum_definitions: Vec<EnumDefinitionRecord>,
    pub unions: Vec<Union>,
    pub input_objects: Vec<InputObject>,
    pub enum_values: Vec<EnumValueRecord>,

    /// All [input value definitions](http://spec.graphql.org/October2021/#InputValueDefinition) in the federated graph. Concretely, these are arguments of output fields, and input object fields.
    pub input_value_definitions: Vec<InputValueDefinition>,

    /// All the strings in the federated graph, deduplicated.
    pub strings: Vec<String>,
}

impl FederatedGraph {
    /// Instantiate a [FederatedGraph] from a federated schema string
    #[cfg(feature = "from_sdl")]
    pub fn from_sdl(sdl: &str) -> Result<Self, crate::DomainError> {
        crate::from_sdl::from_sdl(sdl)
    }

    pub fn definition_name(&self, definition: Definition) -> &str {
        let name_id = match definition {
            Definition::Scalar(scalar_id) => self[scalar_id].name,
            Definition::Object(object_id) => self.at(object_id).name,
            Definition::Interface(interface_id) => self.at(interface_id).name,
            Definition::Union(union_id) => self[union_id].name,
            Definition::Enum(enum_id) => self[enum_id].name,
            Definition::InputObject(input_object_id) => self[input_object_id].name,
        };

        &self[name_id]
    }

    pub fn iter_interfaces(&self) -> impl ExactSizeIterator<Item = View<InterfaceId, &Interface>> {
        (0..self.interfaces.len()).map(|idx| self.view(InterfaceId::from(idx)))
    }

    pub fn iter_objects(&self) -> impl ExactSizeIterator<Item = View<ObjectId, &Object>> {
        (0..self.objects.len()).map(|idx| self.view(ObjectId::from(idx)))
    }

    pub fn iter_scalar_definitions(&self) -> impl Iterator<Item = ScalarDefinition<'_>> {
        self.scalar_definitions
            .iter()
            .enumerate()
            .map(|(idx, _)| self.at(ScalarDefinitionId::from(idx)))
    }

    pub fn iter_enum_definitions(&self) -> impl Iterator<Item = EnumDefinition<'_>> {
        self.enum_definitions
            .iter()
            .enumerate()
            .map(|(idx, _)| self.at(EnumDefinitionId::from(idx)))
    }
}

#[derive(Clone)]
pub struct Subgraph {
    pub name: StringId,
    pub url: StringId,
}

#[derive(Clone)]
pub struct Union {
    pub name: StringId,
    pub description: Option<StringId>,
    pub members: Vec<ObjectId>,
    pub directives: Vec<Directive>,
}

#[derive(Clone)]
pub struct InputObject {
    pub name: StringId,
    pub description: Option<StringId>,
    pub fields: InputValueDefinitions,
    pub directives: Vec<Directive>,
}

#[derive(Default, Clone, PartialEq, PartialOrd, Debug)]
#[allow(clippy::enum_variant_names)]
pub enum Value {
    #[default]
    Null,
    String(StringId),
    Int(i64),
    Float(f64),
    Boolean(bool),
    /// Different from `String`.
    ///
    /// `@tag(name: "SOMETHING")` vs `@tag(name: SOMETHING)`
    ///
    /// FIXME: This is currently required because we do not keep accurate track of the directives in use in the schema, but we should strive towards removing UnboundEnumValue in favour of EnumValue.
    UnboundEnumValue(StringId),
    EnumValue(EnumValueId),
    Object(Box<[(StringId, Value)]>),
    List(Box<[Value]>),
}

#[derive(Clone)]
pub struct Object {
    pub name: StringId,
    pub directives: Vec<Directive>,
    pub description: Option<StringId>,
    pub implements_interfaces: Vec<InterfaceId>,
    pub fields: Fields,
}

#[derive(Clone)]
pub struct Interface {
    pub name: StringId,
    pub directives: Vec<Directive>,
    pub description: Option<StringId>,
    pub implements_interfaces: Vec<InterfaceId>,
    pub fields: Fields,
}

#[derive(Clone)]
pub struct Field {
    pub parent_entity_id: EntityDefinitionId,
    pub name: StringId,
    pub description: Option<StringId>,
    pub r#type: Type,
    pub arguments: InputValueDefinitions,
    pub directives: Vec<Directive>,
}

impl Value {
    pub fn is_list(&self) -> bool {
        matches!(self, Value::List(_))
    }

    pub fn is_null(&self) -> bool {
        matches!(self, Value::Null)
    }
}

#[derive(Clone, PartialEq)]
pub struct InputValueDefinition {
    pub name: StringId,
    pub r#type: Type,
    pub directives: Vec<Directive>,
    pub description: Option<StringId>,
    pub default: Option<Value>,
}

/// Represents an `@provides` directive on a field in a subgraph.
#[derive(Clone)]
pub struct FieldProvides {
    pub subgraph_id: SubgraphId,
    pub fields: SelectionSet,
}

/// Represents an `@requires` directive on a field in a subgraph.
#[derive(Clone)]
pub struct FieldRequires {
    pub subgraph_id: SubgraphId,
    pub fields: SelectionSet,
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct SelectionSet(pub Vec<Selection>);

impl From<Vec<Selection>> for SelectionSet {
    fn from(selections: Vec<Selection>) -> Self {
        SelectionSet(selections)
    }
}

impl FromIterator<Selection> for SelectionSet {
    fn from_iter<I: IntoIterator<Item = Selection>>(iter: I) -> Self {
        SelectionSet(iter.into_iter().collect())
    }
}

impl std::ops::Deref for SelectionSet {
    type Target = Vec<Selection>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl std::ops::DerefMut for SelectionSet {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl SelectionSet {
    pub fn find_field(&self, field_id: FieldId) -> Option<&FieldSelection> {
        for selection in &self.0 {
            match selection {
                Selection::Field(field) => {
                    if field.field_id == field_id {
                        return Some(field);
                    }
                }
                Selection::InlineFragment { subselection, .. } => {
                    if let Some(found) = subselection.find_field(field_id) {
                        return Some(found);
                    }
                }
            }
        }
        None
    }
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub enum Selection {
    Field(FieldSelection),
    InlineFragment { on: Definition, subselection: SelectionSet },
}

#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct FieldSelection {
    pub field_id: FieldId,
    pub arguments: Vec<(InputValueDefinitionId, Value)>,
    pub subselection: SelectionSet,
}

#[derive(Clone, Debug)]
pub struct Key {
    /// The subgraph that can resolve the entity with the fields in [Key::fields].
    pub subgraph_id: SubgraphId,

    /// Corresponds to the fields argument in an `@key` directive.
    pub fields: SelectionSet,

    /// Correspond to the `@join__type(isInterfaceObject: true)` directive argument.
    pub is_interface_object: bool,

    pub resolvable: bool,
}

impl Default for FederatedGraph {
    fn default() -> Self {
        FederatedGraph {
            scalar_definitions: Vec::new(),
            enum_definitions: Vec::new(),
            subgraphs: Vec::new(),
            interfaces: Vec::new(),
            unions: Vec::new(),
            input_objects: Vec::new(),
            enum_values: Vec::new(),
            input_value_definitions: Vec::new(),

            root_operation_types: RootOperationTypes {
                query: ObjectId::from(0),
                mutation: None,
                subscription: None,
            },
            objects: vec![Object {
                name: StringId::from(0),
                description: None,
                directives: Vec::new(),
                implements_interfaces: Vec::new(),
                fields: FieldId::from(0)..FieldId::from(2),
            }],
            fields: vec![
                Field {
                    name: StringId::from(1),
                    r#type: Type {
                        wrapping: Default::default(),
                        definition: Definition::Scalar(0usize.into()),
                    },
                    parent_entity_id: EntityDefinitionId::Object(ObjectId::from(0)),
                    arguments: NO_INPUT_VALUE_DEFINITION,
                    description: None,
                    directives: Vec::new(),
                },
                Field {
                    name: StringId::from(2),
                    r#type: Type {
                        wrapping: Default::default(),
                        definition: Definition::Scalar(0usize.into()),
                    },
                    parent_entity_id: EntityDefinitionId::Object(ObjectId::from(0)),
                    arguments: NO_INPUT_VALUE_DEFINITION,
                    description: None,
                    directives: Vec::new(),
                },
            ],
            strings: ["Query", "__type", "__schema"]
                .into_iter()
                .map(|string| string.to_owned())
                .collect(),
        }
    }
}

impl std::ops::Index<InputValueDefinitions> for FederatedGraph {
    type Output = [InputValueDefinition];

    fn index(&self, index: InputValueDefinitions) -> &Self::Output {
        let (start, len) = index;
        &self.input_value_definitions[usize::from(start)..(usize::from(start) + len)]
    }
}

impl std::ops::Index<Fields> for FederatedGraph {
    type Output = [Field];

    fn index(&self, index: Fields) -> &Self::Output {
        &self.fields[usize::from(index.start)..usize::from(index.end)]
    }
}

pub type InputValueDefinitionSet = Vec<InputValueDefinitionSetItem>;

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, PartialOrd)]
pub struct InputValueDefinitionSetItem {
    pub input_value_definition: InputValueDefinitionId,
    pub subselection: InputValueDefinitionSet,
}

/// A (start, end) range in FederatedGraph::fields.
pub type Fields = Range<FieldId>;
/// A (start, len) range in FederatedSchema.
pub type InputValueDefinitions = (InputValueDefinitionId, usize);

pub const NO_INPUT_VALUE_DEFINITION: InputValueDefinitions = (InputValueDefinitionId::const_from_usize(0), 0);
pub const NO_FIELDS: Fields = Range {
    start: FieldId::const_from_usize(0),
    end: FieldId::const_from_usize(0),
};

pub type FieldSet = Vec<FieldSetItem>;

#[derive(Clone, PartialEq, PartialOrd)]
pub struct FieldSetItem {
    pub field: FieldId,
    pub arguments: Vec<(InputValueDefinitionId, Value)>,
    pub subselection: FieldSet,
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn override_label() {
        assert!("".parse::<OverrideLabel>().is_err());
        assert!("percent(heh)".parse::<OverrideLabel>().is_err());
        assert!("percent(30".parse::<OverrideLabel>().is_err());

        assert_eq!(
            "percent(30)".parse::<OverrideLabel>().unwrap().as_percent().unwrap(),
            30
        );
    }
}