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
use indexmap::IndexMap;

use crate::dynamic::{
    base::{BaseContainer, BaseField},
    schema::SchemaInner,
    InputObject, Interface, SchemaError, Type,
};

impl SchemaInner {
    pub(crate) fn check(&self) -> Result<(), SchemaError> {
        self.check_types_exists()?;
        self.check_root_types()?;
        self.check_objects()?;
        self.check_input_objects()?;
        self.check_interfaces()?;
        self.check_unions()?;
        Ok(())
    }

    fn check_root_types(&self) -> Result<(), SchemaError> {
        if let Some(ty) = self.types.get(&self.env.registry.query_type) {
            if !matches!(ty, Type::Object(_)) {
                return Err("The query root must be an object".into());
            }
        }

        if let Some(mutation_type) = &self.env.registry.mutation_type {
            if let Some(ty) = self.types.get(mutation_type) {
                if !matches!(ty, Type::Object(_)) {
                    return Err("The mutation root must be an object".into());
                }
            }
        }

        if let Some(subscription_type) = &self.env.registry.subscription_type {
            if let Some(ty) = self.types.get(subscription_type) {
                if !matches!(ty, Type::Subscription(_)) {
                    return Err("The subsciprtion root must be an subscription object".into());
                }
            }
        }

        Ok(())
    }

    fn check_types_exists(&self) -> Result<(), SchemaError> {
        fn check<I: IntoIterator<Item = T>, T: AsRef<str>>(
            types: &IndexMap<String, Type>,
            type_names: I,
        ) -> Result<(), SchemaError> {
            for name in type_names {
                if !types.contains_key(name.as_ref()) {
                    return Err(format!("Type \"{0}\" not found", name.as_ref()).into());
                }
            }
            Ok(())
        }

        check(
            &self.types,
            std::iter::once(self.env.registry.query_type.as_str())
                .chain(self.env.registry.mutation_type.as_deref()),
        )?;

        for ty in self.types.values() {
            match ty {
                Type::Object(obj) => check(
                    &self.types,
                    obj.fields
                        .values()
                        .map(|field| {
                            std::iter::once(field.ty.type_name())
                                .chain(field.arguments.values().map(|arg| arg.ty.type_name()))
                        })
                        .flatten()
                        .chain(obj.implements.iter().map(AsRef::as_ref)),
                )?,
                Type::InputObject(obj) => {
                    check(
                        &self.types,
                        obj.fields.values().map(|field| field.ty.type_name()),
                    )?;
                }
                Type::Interface(interface) => check(
                    &self.types,
                    interface
                        .fields
                        .values()
                        .map(|field| {
                            std::iter::once(field.ty.type_name())
                                .chain(field.arguments.values().map(|arg| arg.ty.type_name()))
                        })
                        .flatten(),
                )?,
                Type::Union(union) => check(&self.types, &union.possible_types)?,
                Type::Subscription(subscription) => check(
                    &self.types,
                    subscription
                        .fields
                        .values()
                        .map(|field| {
                            std::iter::once(field.ty.type_name())
                                .chain(field.arguments.values().map(|arg| arg.ty.type_name()))
                        })
                        .flatten(),
                )?,
                Type::Scalar(_) | Type::Enum(_) => {}
            }
        }

        Ok(())
    }

    fn check_objects(&self) -> Result<(), SchemaError> {
        // https://spec.graphql.org/October2021/#sec-Objects.Type-Validation
        for ty in self.types.values() {
            if let Type::Object(obj) = ty {
                // An Object type must define one or more fields.
                if obj.fields.is_empty() {
                    return Err(
                        format!("Object \"{}\" must define one or more fields", obj.name).into(),
                    );
                }

                for field in obj.fields.values() {
                    // The field must not have a name which begins with the characters "__" (two
                    // underscores)
                    if field.name.starts_with("__") {
                        return Err(format!("Field \"{}.{}\" must not have a name which begins with the characters \"__\" (two underscores)", obj.name, field.name).into());
                    }

                    // The field must return a type where IsOutputType(fieldType) returns true.
                    if let Some(ty) = self.types.get(field.ty.type_name()) {
                        if !ty.is_output_type() {
                            return Err(format!(
                                "Field \"{}.{}\" must return a output type",
                                obj.name, field.name
                            )
                            .into());
                        }
                    }

                    for arg in field.arguments.values() {
                        // The argument must not have a name which begins with the characters "__"
                        // (two underscores).
                        if arg.name.starts_with("__") {
                            return Err(format!("Argument \"{}.{}.{}\" must not have a name which begins with the characters \"__\" (two underscores)", obj.name, field.name, arg.name).into());
                        }

                        // The argument must accept a type where
                        // IsInputType(argumentType) returns true.
                        if let Some(ty) = self.types.get(arg.ty.type_name()) {
                            if !ty.is_input_type() {
                                return Err(format!(
                                    "Argument \"{}.{}.{}\" must accept a input type",
                                    obj.name, field.name, arg.name
                                )
                                .into());
                            }
                        }
                    }
                }

                for interface_name in &obj.implements {
                    if let Some(ty) = self.types.get(interface_name) {
                        let interface = ty.as_interface().ok_or_else(|| {
                            format!("Type \"{}\" is not interface", interface_name)
                        })?;
                        check_is_valid_implementation(obj, interface)?;
                    }
                }
            }
        }

        Ok(())
    }

    fn check_input_objects(&self) -> Result<(), SchemaError> {
        // https://spec.graphql.org/October2021/#sec-Input-Objects.Type-Validation
        for ty in self.types.values() {
            if let Type::InputObject(obj) = ty {
                for field in obj.fields.values() {
                    // The field must not have a name which begins with the characters "__" (two
                    // underscores)
                    if field.name.starts_with("__") {
                        return Err(format!("Field \"{}.{}\" must not have a name which begins with the characters \"__\" (two underscores)", obj.name, field.name).into());
                    }

                    // The input field must accept a type where IsInputType(inputFieldType) returns
                    // true.
                    if let Some(ty) = self.types.get(field.ty.type_name()) {
                        if !ty.is_input_type() {
                            return Err(format!(
                                "Field \"{}.{}\" must accept a input type",
                                obj.name, field.name
                            )
                            .into());
                        }
                    }

                    if obj.oneof {
                        // The type of the input field must be nullable.
                        if !field.ty.is_nullable() {
                            return Err(format!(
                                "Field \"{}.{}\" must be nullable",
                                obj.name, field.name
                            )
                            .into());
                        }

                        // The input field must not have a default value.
                        if field.default_value.is_some() {
                            return Err(format!(
                                "Field \"{}.{}\" must not have a default value",
                                obj.name, field.name
                            )
                            .into());
                        }
                    }
                }

                // If an Input Object references itself either directly or
                // through referenced Input Objects, at least one of the
                // fields in the chain of references must be either a
                // nullable or a List type.
                self.check_input_object_reference(&obj.name, &obj)?;
            }
        }

        Ok(())
    }

    fn check_input_object_reference(
        &self,
        current: &str,
        obj: &InputObject,
    ) -> Result<(), SchemaError> {
        for field in obj.fields.values() {
            if field.ty.type_name() == current {
                if !field.ty.is_named() && !field.ty.is_list() {
                    return Err(format!("\"{}\" references itself either directly or through referenced Input Objects, at least one of the fields in the chain of references must be either a nullable or a List type.", current).into());
                }
            } else if let Some(obj) = self
                .types
                .get(field.ty.type_name())
                .and_then(Type::as_input_object)
            {
                self.check_input_object_reference(current, obj)?;
            }
        }

        Ok(())
    }

    fn check_interfaces(&self) -> Result<(), SchemaError> {
        // https://spec.graphql.org/October2021/#sec-Interfaces.Type-Validation
        for ty in self.types.values() {
            if let Type::Interface(interface) = ty {
                for field in interface.fields.values() {
                    // The field must not have a name which begins with the characters "__" (two
                    // underscores)
                    if field.name.starts_with("__") {
                        return Err(format!("Field \"{}.{}\" must not have a name which begins with the characters \"__\" (two underscores)", interface.name, field.name).into());
                    }

                    // The field must return a type where IsOutputType(fieldType) returns true.
                    if let Some(ty) = self.types.get(field.ty.type_name()) {
                        if !ty.is_output_type() {
                            return Err(format!(
                                "Field \"{}.{}\" must return a output type",
                                interface.name, field.name
                            )
                            .into());
                        }
                    }

                    // The field must return a type where IsOutputType(fieldType) returns true.
                    if let Some(ty) = self.types.get(field.ty.type_name()) {
                        if !ty.is_output_type() {
                            return Err(format!(
                                "Field \"{}.{}\" must return a output type",
                                interface.name, field.name
                            )
                            .into());
                        }
                    }

                    for arg in field.arguments.values() {
                        // The argument must not have a name which begins with the characters "__"
                        // (two underscores).
                        if arg.name.starts_with("__") {
                            return Err(format!("Argument \"{}.{}.{}\" must not have a name which begins with the characters \"__\" (two underscores)", interface.name, field.name, arg.name).into());
                        }

                        // The argument must accept a type where
                        // IsInputType(argumentType) returns true.
                        if let Some(ty) = self.types.get(arg.ty.type_name()) {
                            if !ty.is_input_type() {
                                return Err(format!(
                                    "Argument \"{}.{}.{}\" must accept a input type",
                                    interface.name, field.name, arg.name
                                )
                                .into());
                            }
                        }
                    }

                    // An interface type may declare that it implements one or more unique
                    // interfaces, but may not implement itself.
                    if interface.implements.contains(&interface.name) {
                        return Err(format!(
                            "Interface \"{}\" may not implement itself",
                            interface.name
                        )
                        .into());
                    }

                    // An interface type must be a super-set of all interfaces
                    // it implements
                    for interface_name in &interface.implements {
                        if let Some(ty) = self.types.get(interface_name) {
                            let implemenented_type = ty.as_interface().ok_or_else(|| {
                                format!("Type \"{}\" is not interface", interface_name)
                            })?;
                            check_is_valid_implementation(interface, implemenented_type)?;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    fn check_unions(&self) -> Result<(), SchemaError> {
        // https://spec.graphql.org/October2021/#sec-Unions.Type-Validation
        for ty in self.types.values() {
            if let Type::Union(union) = ty {
                // The member types of a Union type must all be Object base
                // types; Scalar, Interface and Union types must not be member
                // types of a Union. Similarly, wrapping types must not be
                // member types of a Union.
                for type_name in &union.possible_types {
                    if let Some(ty) = self.types.get(type_name) {
                        if ty.as_object().is_none() {
                            return Err(format!(
                                "Member \"{}\" of union \"{}\" is not an object",
                                type_name, union.name
                            )
                            .into());
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

fn check_is_valid_implementation(
    implementing_type: &impl BaseContainer,
    implemented_type: &Interface,
) -> Result<(), SchemaError> {
    for field in implemented_type.fields.values() {
        let impl_field = implementing_type.field(&field.name).ok_or_else(|| {
            format!(
                "{} \"{}\" requires field \"{}\" defined by interface \"{}\"",
                implementing_type.graphql_type(),
                implementing_type.name(),
                field.name,
                implemented_type.name
            )
        })?;

        for arg in field.arguments.values() {
            let impl_arg = match impl_field.argument(&arg.name) {
                Some(impl_arg) => impl_arg,
                None if !arg.ty.is_nullable() => {
                    return Err(format!(
                        "Field \"{}.{}\" requires argument \"{}\" defined by interface \"{}.{}\"",
                        implementing_type.name(),
                        field.name,
                        arg.name,
                        implemented_type.name,
                        field.name,
                    )
                    .into());
                }
                None => continue,
            };

            if !arg.ty.is_subtype(&impl_arg.ty) {
                return Err(format!(
                    "Argument \"{}.{}.{}\" is not sub-type of \"{}.{}.{}\"",
                    implemented_type.name,
                    field.name,
                    arg.name,
                    implementing_type.name(),
                    field.name,
                    arg.name
                )
                .into());
            }
        }

        // field must return a type which is equal to or a sub-type of (covariant) the
        // return type of implementedField field’s return type
        if !impl_field.ty().is_subtype(&field.ty) {
            return Err(format!(
                "Field \"{}.{}\" is not sub-type of \"{}.{}\"",
                implementing_type.name(),
                field.name,
                implemented_type.name,
                field.name,
            )
            .into());
        }
    }

    Ok(())
}