libgraphql-core 0.0.8

Core libraries provided by the `libgraphql` crate.
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
use crate::ast;
use crate::file_reader;
use crate::loc;
use crate::operation::OperationKind;
use crate::schema::Schema;
use crate::schema::TypeValidationError;
use crate::types::Directive;
use crate::types::EnumTypeBuilder;
use crate::types::GraphQLType;
use crate::types::InterfaceTypeBuilder;
use crate::types::InputObjectTypeBuilder;
use crate::types::NamedGraphQLTypeRef;
use crate::types::ObjectTypeBuilder;
use crate::types::Parameter;
use crate::types::ScalarTypeBuilder;
use crate::types::TypesMapBuilder;
use crate::types::UnionTypeBuilder;
use std::collections::HashMap;
use std::collections::HashSet;
use std::path::Path;
use std::path::PathBuf;
use std::sync::OnceLock;
use thiserror::Error;

type Result<T> = std::result::Result<T, SchemaBuildError>;

fn builtin_directive_names() -> &'static HashSet<&'static str> {
    static NAMES: OnceLock<HashSet<&'static str>> = OnceLock::new();
    NAMES.get_or_init(|| {
        HashSet::from([
            "skip",
            "include",
            "deprecated",
            "specifiedBy",
        ])
    })
}

#[derive(Debug, Clone, PartialEq)]
pub enum GraphQLOperationType {
    Query,
    Mutation,
    Subscription,
}

/// Utility for building a [Schema].
#[derive(Debug)]
pub struct SchemaBuilder {
    directive_defs: HashMap<String, Directive>,
    enum_builder: EnumTypeBuilder,
    inputobject_builder: InputObjectTypeBuilder,
    interface_builder: InterfaceTypeBuilder,
    query_type: Option<NamedTypeDefLocation>,
    mutation_type: Option<NamedTypeDefLocation>,
    object_builder: ObjectTypeBuilder,
    scalar_builder: ScalarTypeBuilder,
    subscription_type: Option<NamedTypeDefLocation>,
    types_map_builder: TypesMapBuilder,
    union_builder: UnionTypeBuilder,
}
impl SchemaBuilder {
    pub fn build(mut self) -> Result<Schema> {
        self.inject_missing_builtin_directives();

        self.enum_builder.finalize(&mut self.types_map_builder)?;
        self.inputobject_builder.finalize(&mut self.types_map_builder)?;
        self.interface_builder.finalize(&mut self.types_map_builder)?;
        self.object_builder.finalize(&mut self.types_map_builder)?;
        self.scalar_builder.finalize(&mut self.types_map_builder)?;
        self.union_builder.finalize(&mut self.types_map_builder)?;

        // Fun side-quest: Check types eagerly while visiting them. When there's a possibility that
        // a type error could be resolved (or manifested) later, track a
        //self.check_types()?;
        let types = self.types_map_builder.into_types_map()?;

        let query_typedefloc =
            if let Some(def) = self.query_type.take() {
                def
            } else {
                match types.get("Query") {
                    Some(GraphQLType::Object(obj_type)) => NamedTypeDefLocation {
                        def_location: obj_type.def_location().clone(),
                        type_name: "Query".to_string(),
                    },
                    _ => return Err(SchemaBuildError::NoQueryOperationTypeDefined),
                }
            };

        let mutation_type =
            if let Some(def) = self.mutation_type.take() {
                Some(def)
            } else {
                match types.get("Mutation") {
                    Some(GraphQLType::Object(obj_type)) => Some(NamedTypeDefLocation {
                        def_location: obj_type.def_location().clone(),
                        type_name: "Mutation".to_string(),
                    }),
                    _ => None,
                }
            };

        let subscription_type =
            if let Some(def) = self.subscription_type.take() {
                Some(def)
            } else {
                match types.get("Subscription") {
                    Some(GraphQLType::Object(obj_type)) => Some(NamedTypeDefLocation {
                        def_location: obj_type.def_location().clone(),
                        type_name: "Subscription".to_string(),
                    }),
                    _ => None,
                }
            };

        Ok(Schema {
            directive_defs: self.directive_defs,
            query_type: NamedGraphQLTypeRef::new(
                query_typedefloc.type_name,
                query_typedefloc.def_location,
            ),
            mutation_type: mutation_type.map(|t| NamedGraphQLTypeRef::new(
                t.type_name,
                t.def_location,
            )),
            subscription_type: subscription_type.map(|t| NamedGraphQLTypeRef::new(
                t.type_name,
                t.def_location,
            )),
            types,
        })
    }

    pub fn build_from_file(file_path: impl AsRef<Path>) -> Result<Schema> {
        Self::from_file(file_path).and_then(|builder| builder.build())
    }

    pub fn build_from_ast(
        file_path: Option<&Path>,
        ast_doc: crate::ast::schema::Document,
    ) -> Result<Schema> {
        Self::from_ast(file_path, ast_doc).and_then(|builder| builder.build())
    }

    pub fn build_from_str(
        file_path: Option<&Path>,
        content: impl AsRef<str>,
    ) -> Result<Schema> {
        Self::from_str(file_path, content).and_then(|builder| builder.build())
    }

    pub fn from_ast(
        file_path: Option<&Path>,
        ast_doc: crate::ast::schema::Document,
    ) -> Result<Self> {
        Self::new().load_ast(file_path, ast_doc)
    }

    pub fn from_file(file_path: impl AsRef<Path>) -> Result<Self> {
        Self::new()
            .load_file(file_path)
    }

    pub fn from_str(
        file_path: Option<&Path>,
        content: impl AsRef<str>,
    ) -> Result<Self> {
        Self::new().load_str(file_path, content)
    }

    pub fn load_file(
        self,
        file_path: impl AsRef<Path>,
    ) -> Result<Self> {
        self.load_files(vec![file_path])
    }

    pub fn load_ast(
        mut self,
        file_path: Option<&Path>,
        ast_doc: crate::ast::schema::Document,
    ) -> Result<Self> {
        for def in ast_doc.definitions {
            self.visit_ast_def(file_path, def)?;
        }
        Ok(self)
    }

    pub fn load_files(
        mut self,
        file_paths: Vec<impl AsRef<Path>>,
    ) -> Result<Self> {
        for file_path in file_paths {
            let file_path = file_path.as_ref();
            let file_content = file_reader::read_content(file_path)
                .map_err(|err| SchemaBuildError::SchemaFileReadError(
                    Box::new(err),
                ))?;
            self = self.load_str(
                Some(file_path),
                file_content.as_str(),
            )?;
        }
        Ok(self)
    }

    pub fn load_str(
        self,
        file_path: Option<&Path>,
        content: impl AsRef<str>,
    ) -> Result<Self> {
        let ast_doc =
            graphql_parser::schema::parse_schema::<String>(content.as_ref())
                .map_err(|err| SchemaBuildError::ParseError {
                    file: file_path.map(|p| p.to_path_buf()),
                    err: err.to_string(),
                })?.into_static();

        self.load_ast(file_path, ast_doc)
    }

    pub fn new() -> Self {
        let types_map_builder = TypesMapBuilder::new();

        Self {
            directive_defs: HashMap::new(),
            enum_builder: EnumTypeBuilder::new(),
            inputobject_builder: InputObjectTypeBuilder::new(),
            interface_builder: InterfaceTypeBuilder::new(),
            query_type: None,
            mutation_type: None,
            object_builder: ObjectTypeBuilder::new(),
            scalar_builder: ScalarTypeBuilder::new(),
            subscription_type: None,
            types_map_builder,
            union_builder: UnionTypeBuilder::new(),
        }
    }

    fn inject_missing_builtin_directives(&mut self) {
        if !self.directive_defs.contains_key("skip") {
            self.directive_defs.insert("skip".to_string(), Directive::Skip);
        }

        if !self.directive_defs.contains_key("include") {
            self.directive_defs.insert("include".to_string(), Directive::Include);
        }

        if !self.directive_defs.contains_key("deprecated") {
            self.directive_defs.insert("deprecated".to_string(), Directive::Deprecated);
        }

        if !self.directive_defs.contains_key("specifiedBy") {
            self.directive_defs.insert("specifiedBy".to_string(), Directive::SpecifiedBy);
        }
    }

    fn visit_ast_def(
        &mut self,
        file_path: Option<&Path>,
        def: ast::schema::Definition,
    ) -> Result<()> {
        use ast::schema::Definition;
        match def {
            Definition::SchemaDefinition(schema_def) =>
                self.visit_ast_schemablock_def(file_path, schema_def),
            Definition::TypeDefinition(type_def) =>
                self.visit_ast_type_def(file_path, type_def),
            Definition::TypeExtension(type_ext) =>
                self.visit_ast_type_extension(file_path, type_ext),
            Definition::DirectiveDefinition(directive_def) =>
                self.visit_ast_directive_def(file_path, directive_def),
        }
    }

    fn visit_ast_directive_def(
        &mut self,
        file_path: Option<&Path>,
        def: ast::schema::DirectiveDefinition,
    ) -> Result<()> {
        let directivedef_srcloc = loc::SourceLocation::from_schema_ast_position(
            file_path,
            &def.position,
        );

        if builtin_directive_names().contains(def.name.as_str()) {
            return Err(SchemaBuildError::RedefinitionOfBuiltinDirective {
                directive_name: def.name,
                location: directivedef_srcloc,
            })?;
        }

        if def.name.starts_with("__") {
            return Err(SchemaBuildError::InvalidDunderPrefixedDirectiveName {
                def_location: directivedef_srcloc,
                directive_name: def.name.to_string(),
            });
        }

        if let Some(Directive::Custom {
            def_location,
            ..
        }) = self.directive_defs.get(def.name.as_str()) {
            return Err(SchemaBuildError::DuplicateDirectiveDefinition {
                directive_name: def.name.clone(),
                location1: def_location.to_owned(),
                location2: directivedef_srcloc,
            })?;
        }

        self.directive_defs.insert(def.name.to_string(), Directive::Custom {
            def_location: directivedef_srcloc,
            description: def.description.to_owned(),
            name: def.name.to_string(),
            params: def.arguments.iter().map(|input_val| (
                input_val.name.to_string(),
                Parameter::from_ast(
                    file_path,
                    input_val,
                ),
            )).collect()
        });

        Ok(())
    }

    fn visit_ast_schemablock_def(
        &mut self,
        file_path: Option<&Path>,
        schema_def: ast::schema::SchemaDefinition,
    ) -> Result<()> {
        if let Some(type_name) = &schema_def.query {
            let typedef_loc = NamedTypeDefLocation {
                def_location: loc::SourceLocation::from_schema_ast_position(
                    file_path,
                    &schema_def.position,
                ),
                type_name: type_name.to_owned(),
            };
            if let Some(existing_typedef_loc) = &self.query_type {
                return Err(SchemaBuildError::DuplicateOperationDefinition {
                    operation: GraphQLOperationType::Query,
                    location1: existing_typedef_loc.clone(),
                    location2: typedef_loc,
                })?;
            }
            self.query_type = Some(typedef_loc);
        }

        if let Some(type_name) = &schema_def.mutation {
            let typedef_loc = NamedTypeDefLocation {
                def_location: loc::SourceLocation::from_schema_ast_position(
                    file_path,
                    &schema_def.position,
                ),
                type_name: type_name.to_owned(),
            };
            if let Some(existing_typedef_loc) = &self.mutation_type {
                return Err(SchemaBuildError::DuplicateOperationDefinition {
                    operation: GraphQLOperationType::Mutation,
                    location1: existing_typedef_loc.clone(),
                    location2: typedef_loc,
                })?;
            }
            self.mutation_type = Some(typedef_loc);
        }

        if let Some(type_name) = &schema_def.subscription {
            let typedef_loc = NamedTypeDefLocation {
                def_location: loc::SourceLocation::from_schema_ast_position(
                    file_path,
                    &schema_def.position,
                ),
                type_name: type_name.to_owned(),
            };
            if let Some(existing_typedef_loc) = &self.subscription_type {
                return Err(SchemaBuildError::DuplicateOperationDefinition {
                    operation: GraphQLOperationType::Subscription,
                    location1: existing_typedef_loc.clone(),
                    location2: typedef_loc,
                })?;
            }
            self.subscription_type = Some(typedef_loc);
        }

        // As per spec:
        //
        // > The query, mutation, and subscription root types must all be
        // > different types if provided.
        //
        // https://spec.graphql.org/October2021/#sel-FAHTRLCAACG0B57a
        if let (Some(query_type), Some(mut_type)) = (&self.query_type, &self.mutation_type)
            && query_type.type_name == mut_type.type_name {
            // Query and Mutation operations use the same type
            return Err(SchemaBuildError::NonUniqueOperationTypes {
                reused_type_name: query_type.type_name.to_owned(),
                operation1: OperationKind::Query,
                operation1_loc: query_type.def_location.to_owned(),
                operation2: OperationKind::Mutation,
                operation2_loc: mut_type.def_location.to_owned(),
            });
        }

        if let (Some(query_type), Some(sub_type)) = (&self.query_type, &self.subscription_type)
            && query_type.type_name == sub_type.type_name {
            // Query and Subscription operations use the same type
            return Err(SchemaBuildError::NonUniqueOperationTypes {
                reused_type_name: query_type.type_name.to_owned(),
                operation1: OperationKind::Query,
                operation1_loc: query_type.def_location.to_owned(),
                operation2: OperationKind::Subscription,
                operation2_loc: sub_type.def_location.to_owned(),
            });
        }

        if let (Some(mut_type), Some(sub_type)) = (&self.mutation_type, &self.subscription_type)
            && mut_type.type_name == sub_type.type_name {
            // Subscription and Mutation operations use the same type
            return Err(SchemaBuildError::NonUniqueOperationTypes {
                reused_type_name: mut_type.type_name.to_owned(),
                operation1: OperationKind::Mutation,
                operation1_loc: mut_type.def_location.to_owned(),
                operation2: OperationKind::Subscription,
                operation2_loc: sub_type.def_location.to_owned(),
            });
        }

        Ok(())
    }

    fn visit_ast_type_def(
        &mut self,
        file_path: Option<&Path>,
        type_def: ast::schema::TypeDefinition,
    ) -> Result<()> {
        match type_def {
            ast::schema::TypeDefinition::Enum(enum_def) =>
                self.enum_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &enum_def,
                ),

            ast::schema::TypeDefinition::InputObject(inputobj_def) =>
                self.inputobject_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &inputobj_def,
                ),

            ast::schema::TypeDefinition::Interface(iface_def) =>
                self.interface_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &iface_def,
                ),

            ast::schema::TypeDefinition::Scalar(scalar_def) =>
                self.scalar_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &scalar_def,
                ),

            ast::schema::TypeDefinition::Object(obj_def) =>
                self.object_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &obj_def,
                ),

            ast::schema::TypeDefinition::Union(union_def) =>
                self.union_builder.visit_type_def(
                    &mut self.types_map_builder,
                    file_path,
                    &union_def,
                ),
        }
    }

    fn visit_ast_type_extension(
        &mut self,
        file_path: Option<&Path>,
        ext: ast::schema::TypeExtension,
    ) -> Result<()> {
        use ast::schema::TypeExtension;
        match ext {
            TypeExtension::Enum(enum_ext) =>
                self.enum_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    enum_ext,
                ),

            TypeExtension::InputObject(inputobj_ext) =>
                self.inputobject_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    inputobj_ext,
                ),

            TypeExtension::Interface(iface_ext) =>
                self.interface_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    iface_ext,
                ),

            TypeExtension::Object(obj_ext) =>
                self.object_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    obj_ext,
                ),

            TypeExtension::Scalar(scalar_ext) =>
                self.scalar_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    scalar_ext,
                ),

            TypeExtension::Union(union_ext) =>
                self.union_builder.visit_type_extension(
                    &mut self.types_map_builder,
                    file_path,
                    union_ext,
                ),
        }
    }
}
impl Default for SchemaBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[derive(Debug, Error, PartialEq)]
pub enum SchemaBuildError {
    #[error("Multiple directives were defined with the same name")]
    DuplicateDirectiveDefinition {
        directive_name: String,
        location1: loc::SourceLocation,
        location2: loc::SourceLocation,
    },

    #[error("Multiple enum variants with the same name were defined on a single enum type")]
    DuplicateEnumValueDefinition {
        enum_name: String,
        enum_def_location: loc::SourceLocation,
        value_def1: loc::SourceLocation,
        value_def2: loc::SourceLocation,
    },

    #[error("Multiple fields with the same name were defined on a single object type")]
    DuplicateFieldNameDefinition {
        type_name: String,
        field_name: String,
        field_def1: loc::SourceLocation,
        field_def2: loc::SourceLocation,
    },

    #[error(
        "The `{type_name}` type declares that it implements the \
        `{duplicated_interface_name}` interface more than once"
    )]
    DuplicateInterfaceImplementsDeclaration {
        def_location: loc::SourceLocation,
        duplicated_interface_name: String,
        type_name: String,
    },

    #[error("Multiple definitions of the same operation were defined")]
    DuplicateOperationDefinition {
        operation: GraphQLOperationType,
        location1: NamedTypeDefLocation,
        location2: NamedTypeDefLocation,
    },

    #[error("Multiple GraphQL types with the same name were defined")]
    DuplicateTypeDefinition {
        type_name: String,
        def1: loc::SourceLocation,
        def2: loc::SourceLocation,
    },

    #[error("A union type specifies the same type as a member multiple times")]
    DuplicatedUnionMember {
        type_name: String,
        member1: loc::SourceLocation,
        member2: loc::SourceLocation,
    },

    #[error("Enum types must define one or more unique variants")]
    EnumWithNoVariants {
        type_name: String,
        location: loc::SourceLocation,
    },

    #[error("Attempted to extend a type that is not defined elsewhere")]
    ExtensionOfUndefinedType {
        type_name: String,
        extension_location: loc::SourceLocation,
    },

    #[error("Attempted to extend a type using a name that corresponds to a different kind of type")]
    InvalidExtensionType {
        schema_type: GraphQLType,
        extension_location: loc::SourceLocation,
    },

    #[error("Custom directive names must not start with `__`")]
    InvalidDunderPrefixedDirectiveName {
        def_location: loc::SourceLocation,
        directive_name: String,
    },

    #[error("Field names must not start with `__`")]
    InvalidDunderPrefixedFieldName {
        location: loc::SourceLocation,
        field_name: String,
        type_name: String,
    },

    #[error("Parameter names must not start with `__`")]
    InvalidDunderPrefixedParamName {
        location: loc::SourceLocation,
        field_name: String,
        param_name: String,
        type_name: String,
    },

    #[error("Type names must not start with `__`")]
    InvalidDunderPrefixedTypeName {
        def_location: loc::SourceLocation,
        type_name: String,
    },

    #[error(
        "Interface types may not declare that they implement themselves: The \
        `{interface_name}` interface does just that"
    )]
    InvalidSelfImplementingInterface {
        def_location: loc::SourceLocation,
        interface_name: String,
    },

    #[error("Attempted to build a schema that has no Query operation type defined")]
    NoQueryOperationTypeDefined,

    #[error(
        "The {operation1:?} and {operation2:?} root operation are defined with \
        the same GraphQL type, but this is not allowed in GraphQL. All root \
        operations must be defined with different types."
    )]
    NonUniqueOperationTypes {
        reused_type_name: String,
        operation1: OperationKind,
        operation1_loc: loc::SourceLocation,
        operation2: OperationKind,
        operation2_loc: loc::SourceLocation
    },

    #[error("Error parsing schema string")]
    ParseError {
        file: Option<PathBuf>,
        err: String,
    },

    #[error("Attempted to redefine a builtin directive")]
    RedefinitionOfBuiltinDirective {
        directive_name: String,
        location: loc::SourceLocation,
    },

    #[error("Failure while trying to read a schema file from disk")]
    SchemaFileReadError(Box<file_reader::ReadContentError>),

    #[error(
        "Encountered the following type-validation errors while building the \
        schema:\n\n{}",
        errors.iter()
            .map(|s| format!("  * {s}"))
            .collect::<Vec<_>>()
            .join("\n"),
    )]
    TypeValidationErrors {
        errors: Vec<TypeValidationError>,
    },
}

/// Represents the file location of a given type's definition in the schema.
#[derive(Clone, Debug, PartialEq)]
pub struct NamedTypeDefLocation {
    pub(crate) def_location: loc::SourceLocation,
    pub(crate) type_name: String,
}
impl NamedTypeDefLocation {
    pub fn def_location(&self) -> &loc::SourceLocation {
        &self.def_location
    }

    pub fn type_name(&self) -> &str {
        self.type_name.as_str()
    }
}