forked from sangria-graphql/sangria
/
AstSchemaMaterializer.scala
1015 lines (862 loc) · 36.3 KB
/
AstSchemaMaterializer.scala
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
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package sangria.schema
import language.{existentials, postfixOps}
import sangria.ast
import sangria.ast.{AstLocation, OperationType, TypeDefinition}
import sangria.execution.MaterializedSchemaValidationError
import sangria.parser.SourceMapper
import sangria.renderer.QueryRenderer
import sangria.util.Cache
import sangria.validation._
import scala.reflect.ClassTag
import scala.collection.Set
class AstSchemaMaterializer[Ctx] private (
val document: ast.Document,
builder: AstSchemaBuilder[Ctx]) {
import AstSchemaMaterializer.extractSchemaInfo
private val sdlOrigin = SDLOrigin(document)
private val typeDefCache = Cache.empty[(MatOrigin, String), Type with Named]
private val scalarAliasCache = Cache.empty[ScalarAlias[_, _], ScalarAlias[_, _]]
private lazy val typeDefs: Vector[ast.TypeDefinition] = document.definitions.collect {
case d: ast.TypeDefinition => d
}
private lazy val typeDefsMat: Vector[MaterializedType] =
typeDefs.map(MaterializedType(sdlOrigin, _))
private lazy val allDefinitions =
document.definitions ++ builder.additionalTypeExtensionDefs ++ builder.additionalDirectiveDefs
private lazy val additionalTypeDefsMap =
builder.additionalTypes.groupBy(_.name).map { case (k, v) => (k, v.head) }
private lazy val objectTypeExtensionDefs: Vector[ast.ObjectTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.ObjectTypeExtensionDefinition =>
d
}
private lazy val interfaceTypeExtensionDefs: Vector[ast.InterfaceTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.InterfaceTypeExtensionDefinition =>
d
}
private lazy val inputObjectTypeExtensionDefs: Vector[ast.InputObjectTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.InputObjectTypeExtensionDefinition =>
d
}
private lazy val unionTypeExtensionDefs: Vector[ast.UnionTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.UnionTypeExtensionDefinition =>
d
}
private lazy val enumTypeExtensionDefs: Vector[ast.EnumTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.EnumTypeExtensionDefinition =>
d
}
private lazy val scalarTypeExtensionDefs: Vector[ast.ScalarTypeExtensionDefinition] =
allDefinitions.collect { case d: ast.ScalarTypeExtensionDefinition =>
d
}
private lazy val schemaExtensionDefs: Vector[ast.SchemaExtensionDefinition] =
allDefinitions.collect { case d: ast.SchemaExtensionDefinition =>
d
}
private lazy val directiveDefs: Vector[ast.DirectiveDefinition] = allDefinitions.collect {
case d: ast.DirectiveDefinition => d
}
private lazy val directiveDefsMap = directiveDefs.groupBy(_.name)
private lazy val typeDefsMap = typeDefs.groupBy(_.name)
// maybe it would worth an effort to find more elegant way
private var existingDefsMat: Map[String, MaterializedType] = Map.empty
def extend[Val](schema: Schema[Ctx, Val]): Schema[Ctx, Val] = {
val existingOrigin = ExistingSchemaOrigin(schema)
val defErrors = validateExtensions(schema)
if (defErrors.nonEmpty) throw MaterializedSchemaValidationError(defErrors)
if (typeDefs.isEmpty &&
objectTypeExtensionDefs.isEmpty &&
interfaceTypeExtensionDefs.isEmpty &&
enumTypeExtensionDefs.isEmpty &&
scalarTypeExtensionDefs.isEmpty &&
inputObjectTypeExtensionDefs.isEmpty &&
unionTypeExtensionDefs.isEmpty)
schema
else {
existingDefsMat = schema.allTypes.mapValues(MaterializedType(existingOrigin, _)).toMap
val queryType = getTypeFromDef(existingOrigin, schema.query)
AstSchemaMaterializer.findOperationsTypes(
schemaExtensionDefs.flatMap(_.operationTypes),
document.sourceMapper,
true,
schema.mutation.isDefined,
schema.subscription.isDefined) match {
case Left(errors) => throw MaterializedSchemaValidationError(errors)
case Right((_, mutationExt, subscriptionExt)) =>
val mutationType =
mutationExt
.map(getObjectType(sdlOrigin, _).asInstanceOf[ObjectType[Ctx, Val]])
.orElse(schema.mutation)
.map(getTypeFromDef(existingOrigin, _))
val subscriptionType =
subscriptionExt
.map(getObjectType(sdlOrigin, _).asInstanceOf[ObjectType[Ctx, Val]])
.orElse(schema.subscription)
.map(getTypeFromDef(existingOrigin, _))
val directives = directiveDefs.flatMap(buildDirective(existingOrigin, _))
val (referenced, notReferenced) = findUnusedTypes()
builder.extendSchema[Val](
schema,
schemaExtensionDefs.toList,
queryType,
mutationType,
subscriptionType,
(notReferenced ++ findUnusedTypes(schema, referenced)).toList,
schema.directives.map(
builder.transformDirective(existingOrigin, _, this)) ++ directives,
this
)
}
}
}
lazy val build: Schema[Ctx, Any] = {
val defErrors = validateDefinitions
extractSchemaInfo(document, typeDefs, schemaExtensionDefs) match {
case Left(schemaErrors) => throw MaterializedSchemaValidationError(schemaErrors ++ defErrors)
case _ if defErrors.nonEmpty => throw MaterializedSchemaValidationError(defErrors)
case Right(schemaInfo) =>
val queryType = getObjectType(sdlOrigin, schemaInfo.query)
val mutationType = schemaInfo.mutation.map(getObjectType(sdlOrigin, _))
val subscriptionType = schemaInfo.subscription.map(getObjectType(sdlOrigin, _))
val directives = directiveDefs
.filterNot(d => Schema.isBuiltInDirective(d.name))
.flatMap(buildDirective(sdlOrigin, _))
builder.buildSchema(
schemaInfo.definition,
schemaExtensionDefs.toList,
queryType,
mutationType,
subscriptionType,
findUnusedTypes()._2.toList,
BuiltinDirectives ++ directives,
this
)
}
}
lazy val definitions: Vector[Named] = {
val defErrors = validateDefinitions
if (defErrors.nonEmpty) throw MaterializedSchemaValidationError(defErrors)
val directives = directiveDefs
.filterNot(d => Schema.isBuiltInDirective(d.name))
.flatMap(buildDirective(sdlOrigin, _))
val unused = findUnusedTypes()
unused._1.toVector.map(getNamedType(sdlOrigin, _, None)) ++ unused._2 ++ directives
}
def validateExtensions(schema: Schema[Ctx, _]): Vector[Violation] = {
val nestedErrors = Vector(
typeDefsMap.toVector.collect {
case (name, defs) if defs.size > 1 =>
NonUniqueTypeDefinitionViolation(
name,
document.sourceMapper,
defs.flatMap(_.location).toList)
case (name, defs) if schema.allTypes contains name =>
ExistingTypeViolation(name, document.sourceMapper, defs.flatMap(_.location).toList)
},
directiveDefsMap.toVector.collect {
case (name, defs) if defs.size > 1 =>
NonUniqueDirectiveDefinitionViolation(
name,
document.sourceMapper,
defs.flatMap(_.location).toList)
case (name, defs) if schema.directivesByName contains name =>
NonUniqueDirectiveDefinitionViolation(
name,
document.sourceMapper,
defs.flatMap(_.location).toList)
},
objectTypeExtensionDefs.flatMap(
validateExtensions[ObjectType[_, _], ast.ObjectTypeDefinition](schema, _, "object")),
interfaceTypeExtensionDefs.flatMap(
validateExtensions[InterfaceType[_, _], ast.InterfaceTypeDefinition](
schema,
_,
"interface")),
enumTypeExtensionDefs.flatMap(
validateExtensions[EnumType[_], ast.EnumTypeDefinition](schema, _, "enum")),
inputObjectTypeExtensionDefs.flatMap(
validateExtensions[InputObjectType[_], ast.InputObjectTypeDefinition](
schema,
_,
"input-object")),
scalarTypeExtensionDefs.flatMap(
validateExtensions[ScalarType[_], ast.ScalarTypeDefinition](schema, _, "scalar")),
unionTypeExtensionDefs.flatMap(
validateExtensions[UnionType[_], ast.UnionTypeDefinition](schema, _, "union"))
)
nestedErrors.flatten
}
private def validateExtensions[T1: ClassTag, T2: ClassTag](
schema: Schema[Ctx, _],
ext: ast.TypeExtensionDefinition,
typeKind: String): Option[Violation] = {
val instClass = implicitly[ClassTag[T1]].runtimeClass
val astClass = implicitly[ClassTag[T2]].runtimeClass
typeDefsMap.get(ext.name).map(_.head) match {
case Some(tpe) if astClass.isAssignableFrom(tpe.getClass) => None
case Some(tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
case None =>
schema.allTypes.get(ext.name) match {
case Some(tpe) if instClass.isAssignableFrom(tpe.getClass) => None
case Some(tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
case None => validateExtensionsAdditional(instClass, astClass, ext, typeKind)
}
}
}
def validateDefinitions: Vector[Violation] = {
val nestedErrors = Vector(
typeDefsMap.find(_._2.size > 1).toVector.map { case (name, defs) =>
NonUniqueTypeDefinitionViolation(
name,
document.sourceMapper,
defs.flatMap(_.location).toList)
},
directiveDefsMap.find(_._2.size > 1).toVector.map { case (name, defs) =>
NonUniqueDirectiveDefinitionViolation(
name,
document.sourceMapper,
defs.flatMap(_.location).toList)
},
objectTypeExtensionDefs.flatMap(
validateExtensionsAst[ObjectType[_, _], ast.ObjectTypeDefinition](_, "object")),
interfaceTypeExtensionDefs.flatMap(
validateExtensionsAst[InterfaceType[_, _], ast.InterfaceTypeDefinition](_, "interface")),
enumTypeExtensionDefs.flatMap(
validateExtensionsAst[EnumType[_], ast.EnumTypeDefinition](_, "enum")),
inputObjectTypeExtensionDefs.flatMap(
validateExtensionsAst[InputObjectType[_], ast.InputObjectTypeDefinition](
_,
"input-object")),
scalarTypeExtensionDefs.flatMap(
validateExtensionsAst[ScalarType[_], ast.ScalarTypeDefinition](_, "scalar")),
unionTypeExtensionDefs.flatMap(
validateExtensionsAst[UnionType[_], ast.UnionTypeDefinition](_, "union"))
)
nestedErrors.flatten
}
private def validateExtensionsAst[T1: ClassTag, T2: ClassTag](
ext: ast.TypeExtensionDefinition,
typeKind: String): Option[Violation] = {
val instClass = implicitly[ClassTag[T1]].runtimeClass
val astClass = implicitly[ClassTag[T2]].runtimeClass
typeDefsMap.get(ext.name).map(_.head) match {
case Some(tpe) if astClass.isAssignableFrom(tpe.getClass) => None
case Some(tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
case None => validateExtensionsAdditional(instClass, astClass, ext, typeKind)
}
}
private def validateExtensionsAdditional(
instClass: Class[_],
astClass: Class[_],
ext: ast.TypeExtensionDefinition,
typeKind: String) =
additionalTypeDefsMap.get(ext.name) match {
case Some(t) =>
t match {
case BuiltMaterializedTypeInst(_, tpe) if instClass.isAssignableFrom(tpe.getClass) => None
case BuiltMaterializedTypeInst(_, tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
case MaterializedTypeInst(_, tpe) if instClass.isAssignableFrom(tpe.getClass) => None
case MaterializedTypeInst(_, tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
case MaterializedTypeAst(_, tpe) if astClass.isAssignableFrom(tpe.getClass) => None
case MaterializedTypeAst(_, tpe) =>
Some(
TypeExtensionOnWrongKindViolation(
typeKind,
tpe.name,
document.sourceMapper,
ext.location.toList))
}
case None =>
Some(
TypeExtensionOnNonExistingTypeViolation(
ext.name,
document.sourceMapper,
ext.location.toList))
}
def findUnusedTypes(): (Set[String], Vector[Type with Named]) = {
resolveAllLazyFields()
val referenced = typeDefCache.mapToSet((_, v) => v.name)
val notReferenced =
typeDefs.filterNot(tpe => Schema.isBuiltInType(tpe.name) || referenced.contains(tpe.name))
val notReferencedAdd = builder.additionalTypes.filterNot(tpe =>
Schema.isBuiltInType(tpe.name) || referenced.contains(tpe.name))
referenced -> (notReferenced.map(tpe =>
getNamedType(sdlOrigin, tpe.name, tpe.location)) ++ notReferencedAdd.map(tpe =>
getNamedType(tpe.origin, tpe.name, tpe.location)))
}
def findUnusedTypes(schema: Schema[_, _], referenced: Set[String]): Vector[Type with Named] = {
val existingOrigin = ExistingSchemaOrigin(schema)
resolveAllLazyFields()
val notReferenced = schema.typeList.filterNot(tpe =>
Schema.isBuiltInType(tpe.name) || referenced.contains(tpe.name))
notReferenced.map(tpe => getTypeFromDef(existingOrigin, tpe))
}
// TODO: think about better solution
def resolveAllLazyFields(): Unit = {
var prevCount = 0
var newCount = 0
var iteration = 0
do {
prevCount = typeDefCache.size
iteration += 1
typeDefCache.forEachValue {
case o: ObjectLikeType[_, _] => o.fields
case o: InputObjectType[_] => o.fields
case _ => // do nothing
}
newCount = typeDefCache.size
} while (prevCount != newCount && iteration < 20)
}
def getTypeFromExistingType(origin: MatOrigin, tpe: OutputType[_]): OutputType[Any] = tpe match {
case ListType(ofType) => ListType(getTypeFromExistingType(origin, ofType))
case OptionType(ofType) => OptionType(getTypeFromExistingType(origin, ofType))
case t: Named => getTypeFromDef(origin, t)
}
def getInputTypeFromExistingType(origin: MatOrigin, tpe: InputType[_]): InputType[Any] =
tpe match {
case ListInputType(ofType) => ListInputType(getInputTypeFromExistingType(origin, ofType))
case OptionInputType(ofType) => OptionInputType(getInputTypeFromExistingType(origin, ofType))
case t: Named => getTypeFromDef(origin, t)
}
def getTypeFromDef[T <: Type with Named](origin: MatOrigin, tpe: T): T =
tpe match {
case alias: ScalarAlias[Any, Any] @unchecked =>
scalarAliasCache.getOrElseUpdate(alias, extendScalarAlias(origin, alias)).asInstanceOf[T]
case _ =>
getNamedType(origin, tpe.name, None).asInstanceOf[T]
}
def buildDirective(origin: MatOrigin, directive: ast.DirectiveDefinition) =
BuiltinDirectives
.find(_.name == directive.name)
.orElse(builder.buildDirective(
origin,
directive,
directive.arguments.flatMap(buildArgument(origin, Left(directive), None, _)) toList,
directive.locations.map(buildDirectiveLocation) toSet,
this
))
def getObjectType(origin: MatOrigin, tpe: ast.NamedType): ObjectType[Ctx, Any] =
getOutputType(origin, tpe, optional = false) match {
case obj: ObjectType[_, _] => obj.asInstanceOf[ObjectType[Ctx, Any]]
case _ =>
throw MaterializedSchemaValidationError(
Vector(
InvalidTypeUsageViolation(
"object",
QueryRenderer.render(tpe),
document.sourceMapper,
tpe.location.toList)))
}
def getScalarType(origin: MatOrigin, tpe: ast.NamedType): ScalarType[Any] =
getOutputType(origin, tpe, optional = false) match {
case obj: ScalarType[_] => obj.asInstanceOf[ScalarType[Any]]
case _ =>
throw MaterializedSchemaValidationError(
Vector(
InvalidTypeUsageViolation(
"scalar",
QueryRenderer.render(tpe),
document.sourceMapper,
tpe.location.toList)))
}
def getInterfaceType(origin: MatOrigin, tpe: ast.NamedType): InterfaceType[Ctx, Any] =
getOutputType(origin, tpe, optional = false) match {
case obj: InterfaceType[_, _] => obj.asInstanceOf[InterfaceType[Ctx, Any]]
case _ =>
throw MaterializedSchemaValidationError(
Vector(
InvalidTypeUsageViolation(
"interface",
QueryRenderer.render(tpe),
document.sourceMapper,
tpe.location.toList)))
}
def getInputType(
origin: MatOrigin,
tpe: ast.Type,
replacementNamedType: Option[InputType[_]] = None,
optional: Boolean = true): InputType[_] =
tpe match {
case ast.ListType(ofType, _) if optional =>
OptionInputType(ListInputType(getInputType(origin, ofType, replacementNamedType, true)))
case ast.ListType(ofType, _) =>
ListInputType(getInputType(origin, ofType, replacementNamedType, true))
case ast.NotNullType(ofType, _) => getInputType(origin, ofType, replacementNamedType, false)
case ast.NamedType(name, _) =>
replacementNamedType.getOrElse(getNamedType(origin, name, tpe.location)) match {
case input: InputType[_] if optional => OptionInputType(input)
case input: InputType[_] => input
case _ =>
throw MaterializedSchemaValidationError(
Vector(
InvalidTypeUsageViolation(
"input type",
QueryRenderer.render(tpe),
document.sourceMapper,
tpe.location.toList)))
}
}
def getOutputType(
origin: MatOrigin,
tpe: ast.Type,
replacementNamedType: Option[OutputType[_]] = None,
optional: Boolean = true): OutputType[_] =
tpe match {
case ast.ListType(ofType, _) if optional =>
OptionType(ListType(getOutputType(origin, ofType, replacementNamedType, true)))
case ast.ListType(ofType, _) =>
ListType(getOutputType(origin, ofType, replacementNamedType, true))
case ast.NotNullType(ofType, _) => getOutputType(origin, ofType, replacementNamedType, false)
case ast.NamedType(name, _) =>
replacementNamedType.getOrElse(getNamedType(origin, name, tpe.location)) match {
case out: OutputType[_] if optional => OptionType(out)
case out: OutputType[_] => out
case _ =>
throw MaterializedSchemaValidationError(
Vector(
InvalidTypeUsageViolation(
"output type",
QueryRenderer.render(tpe),
document.sourceMapper,
tpe.location.toList)))
}
}
def getNamedType(
origin: MatOrigin,
typeName: String,
location: Option[AstLocation]): Type with Named =
typeDefCache.getOrElseUpdate(
origin -> typeName,
Schema.getBuiltInType(typeName).getOrElse {
val existing = existingDefsMat.get(typeName).toVector
val sdl = typeDefsMat.filter(_.name == typeName)
val additional = builder.additionalTypes.filter(_.name == typeName).toVector
val allCandidates = existing ++ sdl ++ additional
val builtType =
if (allCandidates.size > 1) {
val resolved = builder.resolveNameConflict(
origin,
allCandidates ++
typeDefCache
.find((_, v) => v.name == typeName)
.map { case ((o, _), v) => BuiltMaterializedTypeInst(o, v) }
.toVector)
if (!resolved.isInstanceOf[BuiltMaterializedTypeInst] && typeDefCache.keyExists(
_._2 == resolved.name))
throw SchemaMaterializationException(
"Name conflict resolution produced already existing type name")
else
getNamedType(origin, resolved)
} else if (allCandidates.nonEmpty) {
getNamedType(origin, allCandidates.head)
} else None
builtType.getOrElse(
throw MaterializedSchemaValidationError(Vector(
UnknownTypeViolation(typeName, Seq.empty, document.sourceMapper, location.toList))))
}
)
def getNamedType(origin: MatOrigin, tpe: MaterializedType): Option[Type with Named] =
tpe match {
case BuiltMaterializedTypeInst(o, t) => Some(t)
case MaterializedTypeInst(o, t) => Some(extendType(o, t))
case MaterializedTypeAst(o, t) => buildType(o, t)
}
def buildType(origin: MatOrigin, definition: TypeDefinition): Option[Type with Named] =
definition match {
case d: ast.ObjectTypeDefinition => buildObjectDef(origin, d)
case d: ast.InterfaceTypeDefinition => buildInterfaceDef(origin, d)
case d: ast.UnionTypeDefinition => buildUnionDef(origin, d)
case d: ast.InputObjectTypeDefinition => buildInputObjectDef(origin, d)
case d: ast.ScalarTypeDefinition => buildScalarDef(origin, d)
case d: ast.EnumTypeDefinition => buildEnumDef(origin, d)
}
def extendType(origin: MatOrigin, existingType: Type with Named): Type with Named =
existingType match {
case tpe: ScalarType[_] =>
builder.transformScalarType(origin, findScalarExtensions(tpe.name), tpe, this)
case tpe: ScalarAlias[_, _] =>
extendScalarAlias(origin, tpe.asInstanceOf[ScalarAlias[Any, Any]])
case tpe: EnumType[_] => extendEnumType(origin, tpe)
case tpe: InputObjectType[_] => extendInputObjectType(origin, tpe)
case tpe: UnionType[Ctx] => extendUnionType(origin, tpe)
case tpe: ObjectType[Ctx, _] => extendObjectType(origin, tpe)
case tpe: InterfaceType[Ctx, _] => extendInterfaceType(origin, tpe)
}
def buildField(
origin: MatOrigin,
typeDefinition: Either[ast.TypeDefinition, ObjectLikeType[Ctx, _]],
extensions: Vector[ast.ObjectLikeTypeExtensionDefinition],
field: ast.FieldDefinition) = {
val args = field.arguments.flatMap(buildArgument(origin, typeDefinition, Some(field), _)) toList
val fieldType = builder.buildFieldType(origin, typeDefinition, extensions, field, args, this)
builder.buildField(origin, typeDefinition, extensions, field, fieldType, args, this)
}
def extendField(origin: MatOrigin, tpe: Option[ObjectLikeType[Ctx, _]], field: Field[Ctx, _]) = {
val f = field.asInstanceOf[Field[Ctx, Any]]
builder.extendField(
origin,
tpe,
f,
builder.extendFieldType(origin, tpe, f, this),
f.arguments.map(extendArgument(origin, tpe, f, _)),
this)
}
def extendArgument(
origin: MatOrigin,
tpe: Option[ObjectLikeType[Ctx, _]],
field: Field[Ctx, Any],
argument: Argument[_]) = {
val a = argument.asInstanceOf[Argument[Any]]
builder.extendArgument(
origin,
tpe,
field,
a,
builder.extendArgumentType(origin, tpe, field, a, this),
this)
}
def extendInputField(origin: MatOrigin, tpe: InputObjectType[_], field: InputField[_]) = {
val f = field.asInstanceOf[InputField[Any]]
builder.extendInputField(
origin,
tpe,
f,
builder.extendInputFieldType(origin, tpe, f, this),
this)
}
def buildObjectDef(origin: MatOrigin, tpe: ast.ObjectTypeDefinition) = {
val extensions = findObjectExtensions(tpe.name)
builder.buildObjectType(
origin,
tpe,
extensions.toList,
() => buildFields(origin, tpe, tpe.fields, extensions).toList,
buildInterfaces(origin, tpe.interfaces, extensions).toList,
this
)
}
def extendObjectType(origin: MatOrigin, tpe: ObjectType[Ctx, _]) = {
val extensions = findObjectExtensions(tpe.name)
builder.extendObjectType(
origin,
tpe,
extensions.toList,
() => extendFields(origin, tpe, extensions),
extendInterfaces(origin, tpe, extensions),
this)
}
def buildInterfaceDef(origin: MatOrigin, tpe: ast.InterfaceTypeDefinition) = {
val extensions = findInterfaceExtensions(tpe.name)
builder.buildInterfaceType(
origin,
tpe,
extensions.toList,
() => buildFields(origin, tpe, tpe.fields, extensions).toList,
buildInterfaces(origin, tpe.interfaces, extensions).toList,
this)
}
def extendEnumType(origin: MatOrigin, tpe: EnumType[_]) = {
val extensions = findEnumExtensions(tpe.name)
val extraValues = extensions.flatMap(_.values)
val extraDirs = extensions.flatMap(_.directives)
val ev = extraValues.flatMap(buildEnumValue(origin, Right(tpe), _, extensions))
val extendedType =
if (ev.nonEmpty || extraDirs.nonEmpty)
tpe.copy(values = tpe.values ++ ev, astDirectives = tpe.astDirectives ++ extraDirs)
else tpe
builder.transformEnumType(origin, extensions, extendedType, this)
}
def extendInputObjectType(origin: MatOrigin, tpe: InputObjectType[_]) = {
val extensions = findInputObjectExtensions(tpe.name)
val extraFields = extensions.flatMap(_.fields)
val fieldsFn = () => {
val ef = extraFields.flatMap(buildInputField(origin, Right(tpe), _, extensions)) toList
val f = tpe.fields.map(extendInputField(origin, tpe, _))
f ++ ef
}
builder.transformInputObjectType(origin, extensions, tpe, fieldsFn, this)
}
def extendInterfaceType(origin: MatOrigin, tpe: InterfaceType[Ctx, _]) = {
val extensions = findInterfaceExtensions(tpe.name)
builder.extendInterfaceType(
origin,
tpe,
extensions.toList,
() => extendFields(origin, tpe, extensions),
this)
}
def buildInterfaces(
origin: MatOrigin,
interfaces: Vector[ast.NamedType],
extensions: Vector[ast.ObjectLikeTypeExtensionDefinition]) = {
val extraInts = extensions.flatMap(_.interfaces)
val allInts = interfaces ++ extraInts
allInts.map(getInterfaceType(origin, _))
}
def extendInterfaces(
origin: MatOrigin,
tpe: ObjectType[Ctx, _],
extensions: Vector[ast.ObjectTypeExtensionDefinition]) = {
val extraInts = extensions.flatMap(_.interfaces)
val ei = extraInts.map(getInterfaceType(origin, _))
val oi = tpe.interfaces.map(getTypeFromDef(origin, _).asInstanceOf[InterfaceType[Ctx, Any]])
(ei ++ oi).toList
}
def buildFields(
origin: MatOrigin,
tpe: TypeDefinition,
fieldDefs: Vector[ast.FieldDefinition],
extensions: Vector[ast.ObjectLikeTypeExtensionDefinition]) = {
val extraFields = extensions.flatMap(_.fields)
val withExtensions = fieldDefs ++ extraFields
val addFields = builder.buildAdditionalFields(origin, extensions, tpe, this).flatMap {
case MaterializedFieldAst(o, ast) => buildField(o, Left(tpe), extensions, ast)
case MaterializedFieldInst(o, definition) => Some(extendField(o, None, definition))
}
withExtensions.flatMap(buildField(origin, Left(tpe), extensions, _)) ++ addFields
}
def extendFields(
origin: MatOrigin,
tpe: ObjectLikeType[Ctx, _],
extensions: Vector[ast.ObjectLikeTypeExtensionDefinition]) = {
val extraFields = extensions.flatMap(e => e.fields.map(e -> _))
val ef = extraFields.flatMap(f => buildField(origin, Right(tpe), extensions, f._2))
val of = tpe.uniqueFields.toList.map(extendField(origin, Some(tpe), _))
of ++ ef
}
def findObjectExtensions(typeName: String) =
objectTypeExtensionDefs.filter(_.name == typeName)
def findInterfaceExtensions(typeName: String) =
interfaceTypeExtensionDefs.filter(_.name == typeName)
def findScalarExtensions(typeName: String) =
scalarTypeExtensionDefs.filter(_.name == typeName)
def findInputObjectExtensions(typeName: String) =
inputObjectTypeExtensionDefs.filter(_.name == typeName)
def findUnionExtensions(typeName: String) =
unionTypeExtensionDefs.filter(_.name == typeName)
def findEnumExtensions(typeName: String) =
enumTypeExtensionDefs.filter(_.name == typeName)
def buildUnionDef(origin: MatOrigin, tpe: ast.UnionTypeDefinition) = {
val extensions = findUnionExtensions(tpe.name)
val extraTypes = extensions.flatMap(_.types)
val withExtensions = tpe.types ++ extraTypes
builder.buildUnionType(
origin,
extensions,
tpe,
withExtensions.map(getObjectType(origin, _)) toList,
this)
}
def extendUnionType(origin: MatOrigin, tpe: UnionType[Ctx]) = {
val extensions = findUnionExtensions(tpe.name)
val extraTypes = extensions.flatMap(_.types)
val t = tpe.types.map(getTypeFromDef(origin, _))
val et = extraTypes.map(getObjectType(origin, _)) toList
builder.extendUnionType(origin, extensions, tpe, t ++ et, this)
}
def extendScalarAlias(origin: MatOrigin, alias: ScalarAlias[Any, Any]) = {
val extensions = findScalarExtensions(alias.aliasFor.name)
builder.extendScalarAlias(
origin,
extensions,
alias,
getTypeFromDef(origin, alias.aliasFor),
this)
}
def buildInputObjectDef(origin: MatOrigin, tpe: ast.InputObjectTypeDefinition) = {
val extensions = findInputObjectExtensions(tpe.name)
val extraFields = extensions.flatMap(_.fields)
val withExtensions = tpe.fields ++ extraFields
builder.buildInputObjectType(
origin,
extensions,
tpe,
() => withExtensions.flatMap(buildInputField(origin, Left(tpe), _, extensions)) toList,
this)
}
def buildScalarDef(origin: MatOrigin, tpe: ast.ScalarTypeDefinition) = {
val extensions = findScalarExtensions(tpe.name)
builder.buildScalarType(origin, extensions, tpe, this)
}
private def buildEnumDef(origin: MatOrigin, tpe: ast.EnumTypeDefinition) = {
val extensions = findEnumExtensions(tpe.name)
val extraValues = extensions.flatMap(_.values)
val withExtensions = tpe.values ++ extraValues
builder.buildEnumType(
origin,
extensions,
tpe,
withExtensions.flatMap(buildEnumValue(origin, Left(tpe), _, extensions)) toList,
this)
}
private def buildEnumValue(
origin: MatOrigin,
typeDef: Either[ast.EnumTypeDefinition, EnumType[_]],
value: ast.EnumValueDefinition,
extensions: Vector[ast.EnumTypeExtensionDefinition]) =
builder.buildEnumValue(origin, extensions, typeDef, value, this)
def buildDefault(defaultValue: Option[ast.Value]) =
defaultValue.map(dv => dv -> sangria.marshalling.queryAst.queryAstToInput)
def buildArgument(
origin: MatOrigin,
typeDefinition: Either[ast.TypeSystemDefinition, ObjectLikeType[Ctx, _]],
fieldDef: Option[ast.FieldDefinition],
value: ast.InputValueDefinition) = {
val default = buildDefault(value.defaultValue)
val tpe = builder.buildArgumentType(origin, typeDefinition, fieldDef, value, default, this)
builder.buildArgument(origin, typeDefinition, fieldDef, value, tpe, default, this)
}
def buildInputField(
origin: MatOrigin,
typeDef: Either[ast.InputObjectTypeDefinition, InputObjectType[_]],
value: ast.InputValueDefinition,
extensions: Vector[ast.InputObjectTypeExtensionDefinition]) = {
val default = buildDefault(value.defaultValue)
val tpe = builder.buildInputFieldType(origin, extensions, typeDef, value, default, this)
builder.buildInputField(origin, extensions, typeDef, value, tpe, default, this)
}
def buildDirectiveLocation(loc: ast.DirectiveLocation) =
try DirectiveLocation.fromString(loc.name)
catch {
case e: MatchError =>
throw SchemaMaterializationException(s"Unknown directive location '${loc.name}'.")
}
}
object AstSchemaMaterializer {
case class SchemaInfo(
query: ast.NamedType,
mutation: Option[ast.NamedType],
subscription: Option[ast.NamedType],
definition: Option[ast.SchemaDefinition])
def extractSchemaInfo(
document: ast.Document,
typeDefs: Vector[ast.TypeDefinition],
extensions: Vector[ast.SchemaExtensionDefinition]): Either[Vector[Violation], SchemaInfo] = {
val schemas = document.definitions.collect { case s: ast.SchemaDefinition => s }
val schemaErrors =
if (schemas.size > 1)
Vector(
NonUniqueSchemaDefinitionViolation(
document.sourceMapper,
schemas.flatMap(_.location).toList))
else Vector.empty
if (schemas.nonEmpty) {
val validatedInfo =
schemas.map { schema =>
val allOperationTypes = schema.operationTypes ++ extensions.flatMap(_.operationTypes)
findOperationsTypes(allOperationTypes, document.sourceMapper, false, false, false)
.map { case (query, mutation, subscription) =>
SchemaInfo(query.get, mutation, subscription, Some(schema))
}
}
val typeErrors = validatedInfo.collect { case Left(errors) => errors }.flatten
if (schemaErrors.nonEmpty || typeErrors.nonEmpty) Left(schemaErrors ++ typeErrors)
else validatedInfo.head
} else {
typeDefs.find(_.name == "Query") match {
case None =>
Left(
schemaErrors :+ NoQueryTypeViolation(document.sourceMapper, document.location.toList))
case Some(_) if schemaErrors.nonEmpty =>
Left(schemaErrors)
case Some(query) =>
val mutation = typeDefs.find(_.name == "Mutation").map(t => ast.NamedType(t.name))
val subscription = typeDefs.find(_.name == "Subscription").map(t => ast.NamedType(t.name))
findOperationsTypes(
extensions.flatMap(_.operationTypes),
document.sourceMapper,
true,
mutation.isDefined,
subscription.isDefined).map { case (_, mutationExt, subscriptionExt) =>
SchemaInfo(
ast.NamedType(query.name),
mutationExt.orElse(mutation),
subscriptionExt.orElse(subscription),
None)
}
}
}
}
def findOperationsTypes(
allOperationTypes: Vector[ast.OperationTypeDefinition],
sourceMapper: Option[SourceMapper],
queryAlreadyExists: Boolean,
mutationAlreadyExists: Boolean,
subscriptionAlreadyExists: Boolean): Either[
Vector[Violation],
(Option[ast.NamedType], Option[ast.NamedType], Option[ast.NamedType])] = {
val queries = allOperationTypes.collect {
case ast.OperationTypeDefinition(OperationType.Query, tpe, _, _) => tpe
}
val mutations = allOperationTypes.collect {
case ast.OperationTypeDefinition(OperationType.Mutation, tpe, _, _) => tpe
}
val subscriptions = allOperationTypes.collect {
case ast.OperationTypeDefinition(OperationType.Subscription, tpe, _, _) => tpe
}
val qErrors =
if ((!queryAlreadyExists && queries.size != 1) || (queryAlreadyExists && queries.nonEmpty))
Vector(
NonUniqueRootTypeViolation("query", sourceMapper, queries.flatMap(_.location).toList))
else Vector.empty
val mErrors =
if ((!mutationAlreadyExists && mutations.size > 1) || (mutationAlreadyExists && mutations.nonEmpty))
qErrors :+ NonUniqueRootTypeViolation(
"mutation",
sourceMapper,
queries.flatMap(_.location).toList)
else qErrors
val sErrors =
if ((!subscriptionAlreadyExists && subscriptions.size > 1) || (subscriptionAlreadyExists && subscriptions.nonEmpty))
mErrors :+ NonUniqueRootTypeViolation(
"subscription",
sourceMapper,
queries.flatMap(_.location).toList)
else mErrors
if (sErrors.nonEmpty) Left(sErrors)
else Right((queries.headOption, mutations.headOption, subscriptions.headOption))
}
def buildSchema(document: ast.Document): Schema[Any, Any] =
buildSchema[Any](document, AstSchemaBuilder.default)