-
Notifications
You must be signed in to change notification settings - Fork 3
/
PreparedQuery.scala
1377 lines (1251 loc) · 57 KB
/
PreparedQuery.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
/*
* Copyright 2023 Valdemar Grange
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package gql
import cats.implicits._
import cats.data._
import cats.mtl._
import cats._
import io.circe._
import gql.parser.{QueryParser => P, Pos}
import P.Value._
import gql.ast._
import gql.resolver._
import cats.parse.Caret
import gql.parser.QueryParser
object PreparedQuery {
sealed trait PreparedField[F[_], A]
sealed trait Prepared[F[_], I]
final case class PreparedCont[F[_], I, A](
edges: PreparedStep[F, I, A],
cont: Prepared[F, A]
)
final case class Selection[F[_], I](fields: NonEmptyList[PreparedField[F, I]]) extends Prepared[F, I]
final case class PreparedList[F[_], A, C, B](of: PreparedCont[F, A, B], toSeq: C => Seq[A]) extends Prepared[F, C]
final case class PreparedOption[F[_], I, O](of: PreparedCont[F, I, O]) extends Prepared[F, Option[I]]
final case class PreparedLeaf[F[_], I](name: String, encode: I => Json) extends Prepared[F, I]
final case class PreparedDataField[F[_], A](
name: String,
alias: Option[String],
cont: PreparedCont[F, A, ?]
) extends PreparedField[F, A] {
lazy val outputName = alias.getOrElse(name)
}
final case class PreparedSpecification[F[_], I, A](
typename: String,
specify: I => Option[A],
selection: NonEmptyList[PreparedDataField[F, A]]
) extends PreparedField[F, I]
sealed trait PreparedStep[F[_], -I, +O]
final case class PreparedMeta(
variables: VariableMap,
alias: Option[String],
args: Option[P.Arguments]
)
object PreparedStep {
final case class Lift[F[_], I, O](f: I => O) extends AnyRef with PreparedStep[F, I, O]
final case class EmbedEffect[F[_], I](stableUniqueEdgeName: UniqueEdgeCursor) extends AnyRef with PreparedStep[F, F[I], I]
final case class EmbedStream[F[_], I](stableUniqueEdgeName: UniqueEdgeCursor) extends AnyRef with PreparedStep[F, fs2.Stream[F, I], I]
final case class EmbedError[F[_], I]() extends AnyRef with PreparedStep[F, Ior[String, I], I]
final case class Compose[F[_], I, A, O](left: PreparedStep[F, I, A], right: PreparedStep[F, A, O])
extends AnyRef
with PreparedStep[F, I, O]
final case class Skip[F[_], I, O](compute: PreparedStep[F, I, O]) extends AnyRef with PreparedStep[F, Either[I, O], O]
final case class GetMeta[F[_], I](meta: PreparedMeta) extends AnyRef with PreparedStep[F, I, Meta]
final case class First[F[_], I, O, C](step: PreparedStep[F, I, O]) extends AnyRef with PreparedStep[F, (I, C), (O, C)]
final case class Batch[F[_], K, V](id: Step.BatchKey[K, V], globalEdgeId: UniqueBatchInstance[K, V])
extends AnyRef
with PreparedStep[F, Set[K], Map[K, V]]
}
final case class UniqueBatchInstance[K, V](id: Int) extends AnyVal
final case class UniqueEdgeCursor(path: NonEmptyChain[String]) {
def append(name: String): UniqueEdgeCursor = UniqueEdgeCursor(path append name)
lazy val asString: String = path.mkString_(".")
}
object UniqueEdgeCursor {
def apply(name: String): UniqueEdgeCursor = UniqueEdgeCursor(NonEmptyChain.one(name))
}
final case class PositionalError(position: PrepCursor, caret: List[Caret], message: String) {
lazy val asGraphQL: JsonObject = {
import io.circe.syntax._
Map(
"message" -> Some(message.asJson),
"locations" -> caret.map(c => Json.obj("line" -> c.line.asJson, "column" -> c.col.asJson)).toNel.map(_.asJson),
"path" -> NonEmptyChain.fromChain(position.position.map(_.name)).map(_.asJson)
).collect { case (k, Some(v)) => k -> v }.asJsonObject
}
}
final case class PrepCursor(position: Chain[Validation.Edge]) {
def add(edge: Validation.Edge): PrepCursor = PrepCursor(position append edge)
}
object PrepCursor {
val empty: PrepCursor = PrepCursor(Chain.empty)
}
final case class Prep(
cycleSet: Set[String],
cursor: PrepCursor
) {
def addEdge(edge: Validation.Edge): Prep = copy(cursor = cursor add edge)
def addCycle(s: String): Prep = copy(cycleSet = cycleSet + s)
}
object Prep {
val empty: Prep = Prep(Set.empty, PrepCursor.empty)
}
type UsedArgs = Set[String]
type Used[F[_], A] = WriterT[F, UsedArgs, A]
object Used {
def apply[F[_]](implicit F: MonadError[F, NonEmptyChain[PositionalError]]) =
MonadError[Used[F, *], NonEmptyChain[PositionalError]]
def liftF[F[_]: Applicative, A](fa: F[A]) = WriterT.liftF[F, UsedArgs, A](fa)
}
def compileStep[F[_]: Parallel, G[_], I, O](step: Step[G, I, O], cursor: UniqueEdgeCursor, meta: PreparedMeta)(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]]
): Used[F, State[Int, PreparedStep[G, I, O]]] = {
def pure[A](a: A): Used[F, State[Int, A]] =
Used[F].pure(State.pure(a))
def rec[I2, O2](step: Step[G, I2, O2], edge: String): Used[F, State[Int, PreparedStep[G, I2, O2]]] =
compileStep[F, G, I2, O2](step, cursor append edge, meta)
step match {
case Step.Alg.Lift(f) => pure(PreparedStep.Lift(f))
case Step.Alg.EmbedError() => pure(PreparedStep.EmbedError[G, O]())
case alg: Step.Alg.Compose[?, i, a, o] =>
val left = rec[i, a](alg.left, "left")
val right = rec[a, o](alg.right, "right")
(left, right).parMapN((_, _).tupled).map(_.map { case (l, r) => PreparedStep.Compose[G, i, a, o](l, r) })
case _: Step.Alg.EmbedEffect[?, i] => pure(PreparedStep.EmbedEffect[G, i](cursor))
case _: Step.Alg.EmbedStream[?, i] => pure(PreparedStep.EmbedStream[G, i](cursor))
case alg: Step.Alg.Skip[g, i, ?] =>
rec[i, O](alg.compute, "skip").map(_.map(s => PreparedStep.Skip(s)))
case Step.Alg.GetMeta() => pure(PreparedStep.GetMeta(meta))
case alg: Step.Alg.Batch[?, k, v] =>
Used[F].pure(State { (i: Int) =>
(i + 1, PreparedStep.Batch[G, k, v](alg.id, UniqueBatchInstance(i)))
})
case alg: Step.Alg.First[?, i, o, c] =>
rec[i, o](alg.step, "first").map(_.map(s => PreparedStep.First[G, i, o, c](s)))
case alg: Step.Alg.Argument[?, a] =>
val fa = Used
.liftF(decodeFieldArgs[F, G, a](alg.arg, meta.args, meta.variables))
.map[PreparedStep[G, I, O]](o => PreparedStep.Lift[G, I, O](_ => o)) <*
WriterT.tell(alg.arg.entries.map(_.name).toList.toSet)
fa.map(State.pure(_))
}
}
def collectFields[G[_]](step: Step[G, ?, ?]): Chain[Arg[Any]] =
step match {
case Step.Alg.Argument(a) => Chain.one(a)
case Step.Alg.First(s) => collectFields(s)
case Step.Alg.Skip(s) => collectFields(s)
case Step.Alg.Compose(l, r) => collectFields(l) ++ collectFields(r)
case _ => Chain.empty
}
def friendlyName[G[_], A](ot: Out[G, A], inOption: Boolean = false): String = {
val suffix = if (inOption) "" else "!"
val prefix = (ot: @unchecked) match {
case Scalar(name, _, _, _) => name
case Enum(name, _, _) => name
case Type(name, _, _, _) => name
case Union(name, _, _) => name
case Interface(name, _, _, _) => name
case OutOpt(of, _) => friendlyName(of, inOption = true)
case OutArr(of, _, _) => s"[${friendlyName(of)}]"
}
prefix + suffix
}
def raise[F[_], A](s: String, caret: Option[Caret])(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]]
): F[A] =
L.ask.map(state => NonEmptyChain.one(PositionalError(state.cursor, caret.toList, s))).flatMap(F.raiseError[A])
def raiseOpt[F[_], A](o: Option[A], s: String, caret: Option[Caret])(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]]
): F[A] =
o.map(_.pure[F]).getOrElse(raise[F, A](s, caret))
def raiseEither[F[_], A](e: Either[String, A], caret: Option[Caret])(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]]
): F[A] =
e match {
case Left(value) => raise[F, A](value, caret)
case Right(value) => F.pure(value)
}
def ambientEdge[F[_], A](edge: Validation.Edge)(fa: F[A])(implicit L: Local[F, Prep]): F[A] =
L.local(fa)(_ addEdge edge)
def ambientField[F[_], A](name: String)(fa: F[A])(implicit L: Local[F, Prep]): F[A] =
ambientEdge[F, A](Validation.Edge.Field(name))(fa)
def ambientArg[F[_], A](name: String)(fa: F[A])(implicit L: Local[F, Prep]): F[A] =
ambientEdge[F, A](Validation.Edge.Arg(name))(fa)
def ambientIndex[F[_], A](i: Int)(fa: F[A])(implicit L: Local[F, Prep]): F[A] =
ambientEdge[F, A](Validation.Edge.Index(i))(fa)
def ambientInputType[F[_], A](name: String)(fa: F[A])(implicit L: Local[F, Prep]): F[A] =
ambientEdge[F, A](Validation.Edge.InputType(name))(fa)
def modifyError[F[_], A](f: PositionalError => PositionalError)(fa: F[A])(implicit F: MonadError[F, NonEmptyChain[PositionalError]]) =
F.adaptError(fa)(_.map(f))
def appendMessage[F[_], A](message: String)(fa: F[A])(implicit F: MonadError[F, NonEmptyChain[PositionalError]]) =
modifyError[F, A](d => d.copy(message = d.message + "\n" + message))(fa)
def typenameField[A](typename: String) = {
import gql.dsl._
lift[fs2.Pure, A](_ => typename)
}
def inFragment[F[_], A](
fragmentName: String,
fragments: Map[String, Pos[P.FragmentDefinition]],
caret: Option[Caret]
)(
faf: Pos[P.FragmentDefinition] => F[A]
)(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[A] =
D.defer {
L.ask.flatMap[A] {
case c if c.cycleSet(fragmentName) =>
raise(s"Fragment by '$fragmentName' is cyclic. Hint: graphql queries must be finite.", caret)
case _ =>
fragments.get(fragmentName) match {
case None => raise(s"Unknown fragment name '$fragmentName'.", caret)
case Some(f) => L.local(faf(f))(_ addCycle fragmentName)
}
}
}
sealed trait SimplifiedType[G[_]] { def selections: List[SelectionInfo[G]] }
object SimplifiedType {
final case class List[G[_]](t: SimplifiedType[G]) extends SimplifiedType[G] { def selections = t.selections }
final case class Option[G[_]](t: SimplifiedType[G]) extends SimplifiedType[G] { def selections = t.selections }
final case class Scalar[G[_]](name: String) extends SimplifiedType[G] { def selections = Nil }
final case class Enum[G[_]](name: String) extends SimplifiedType[G] { def selections = Nil }
final case class Selectable[G[_]](name: String, selection: NonEmptyList[SelectionInfo[G]]) extends SimplifiedType[G] {
def selections = selection.toList
}
}
def getSimplifiedTypeString[G[_]](st: SimplifiedType[G], inOption: Boolean = false): String = {
val optPart = if (inOption) "" else "!"
val n = st match {
case SimplifiedType.List(t) => s"[${getSimplifiedTypeString(t)}]"
case SimplifiedType.Option(t) => getSimplifiedTypeString(t, inOption = true)
case SimplifiedType.Scalar(name) => name
case SimplifiedType.Enum(name) => name
case SimplifiedType.Selectable(name, _) => name
}
n + optPart
}
final case class FieldInfo[G[_]](
name: String,
alias: Option[String],
args: Option[P.Arguments],
tpe: SimplifiedType[G],
caret: Caret,
path: PrepCursor
) {
lazy val outputName: String = alias.getOrElse(name)
}
object FieldInfo {
def apply[F[_]: Functor, G[_]](name: String, alias: Option[String], args: Option[P.Arguments], tpe: SimplifiedType[G], caret: Caret)(
implicit L: Local[F, Prep]
): F[FieldInfo[G]] =
L.ask.map(_.cursor).map(FieldInfo(name, alias, args, tpe, caret, _))
}
def collectFieldInfo[F[_]: Parallel, G[_]](
af: AbstractField[G, ?],
f: P.Field,
caret: Caret,
variableMap: VariableMap,
fragments: Map[String, Pos[P.FragmentDefinition]],
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
G: Applicative[G],
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[FieldInfo[G]] = ambientField(f.name) {
// Verify arguments by decoding them
val decF = af.arg.traverse_ { case a: Arg[a] => decodeFieldArgs[F, G, a](a, f.arguments, variableMap).void }
// Verify subselection
val c = f.selectionSet.caret
def verifySubsel(t: Out[G, ?]): F[SimplifiedType[G]] =
(t, f.selectionSet.value) match {
case (arr: OutArr[G, ?, ?, ?], _) => verifySubsel(arr.of).map(SimplifiedType.List(_))
case (opt: OutOpt[G, ?, ?], _) => verifySubsel(opt.of).map(SimplifiedType.Option(_))
case (ol: Selectable[G, ?], Some(ss)) =>
collectSelectionInfo[F, G](ol, ss, variableMap, fragments, discoveryState)
.map(xs => SimplifiedType.Selectable(ol.name, xs))
case (e: Enum[?], None) => F.pure(SimplifiedType.Enum(e.name))
case (s: Scalar[?], None) => F.pure(SimplifiedType.Scalar(s.name))
case (o, Some(_)) => raise(s"Type `${friendlyName(o)}` cannot have selections.", Some(c))
case (o, None) => raise(s"Object like type `${friendlyName(o)}` must have a selection.", Some(c))
}
decF &> verifySubsel(af.output.value).flatMap(FieldInfo[F, G](f.name, f.alias, f.arguments, _, caret))
}
final case class SelectionInfo[G[_]](
s: Selectable[G, ?],
fields: NonEmptyList[FieldInfo[G]],
fragmentName: Option[String]
)
def collectSelectionInfo[F[_]: Parallel, G[_]](
s: Selectable[G, ?],
ss: P.SelectionSet,
variableMap: VariableMap,
fragments: Map[String, Pos[P.FragmentDefinition]],
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
G: Applicative[G],
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[NonEmptyList[SelectionInfo[G]]] = D.defer {
val fields = ss.selections.collect { case Pos(caret, P.Selection.FieldSelection(field)) => (caret, field) }
val actualFields: Map[String, AbstractField[G, ?]] =
s.abstractFieldMap + ("__typename" -> AbstractField(None, Eval.now(stringScalar), None))
val validateFieldsF: F[List[SelectionInfo[G]]] = fields
.parTraverse { case (caret, field) =>
actualFields.get(field.name) match {
case None => raise[F, FieldInfo[G]](s"Field '${field.name}' is not a member of `${s.name}`.", Some(caret))
case Some(f) => collectFieldInfo[F, G](f, field, caret, variableMap, fragments, discoveryState)
}
}
.map(_.toNel.toList.map(SelectionInfo(s, _, None)))
val realInlines =
ss.selections
.collect { case Pos(caret, P.Selection.InlineFragmentSelection(f)) => (caret, f) }
.parFlatTraverse { case (caret, f) =>
f.typeCondition.traverse(matchType[F, G](_, s, caret, discoveryState)).map(_.getOrElse(s)).flatMap { t =>
collectSelectionInfo[F, G](t, f.selectionSet, variableMap, fragments, discoveryState).map(_.toList)
}
}
val realFragments =
ss.selections
.collect { case Pos(caret, P.Selection.FragmentSpreadSelection(f)) => (caret, f) }
.parFlatTraverse { case (caret, f) =>
val fn = f.fragmentName
inFragment(fn, fragments, caret.some) { case Pos(caret, f) =>
matchType[F, G](f.typeCnd, s, caret, discoveryState).flatMap { t =>
collectSelectionInfo[F, G](t, f.selectionSet, variableMap, fragments, discoveryState)
.map(_.toList.map(_.copy(fragmentName = Some(fn))))
}
}
}
(validateFieldsF :: realInlines :: realFragments :: Nil).parFlatSequence
// Unfortunate, but is always safe here since nel is input
.map(_.toNel.get)
}
def fieldName[G[_]](f: FieldInfo[G]): String =
s"'${f.alias.getOrElse(f.name)}'${f.alias.map(x => s" (alias for '$x')").mkString}"
def compareValues[F[_]: Parallel](av: P.Value, bv: P.Value, caret: Option[Caret])(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
): F[Unit] = {
(av, bv) match {
case (P.Value.VariableValue(avv), P.Value.VariableValue(bvv)) =>
if (avv === bvv) F.unit
else raise[F, Unit](s"Variable '$avv' and '$bvv' are not equal.", caret)
case (P.Value.IntValue(ai), P.Value.IntValue(bi)) =>
if (ai === bi) F.unit
else raise[F, Unit](s"Int '$ai' and '$bi' are not equal.", caret)
case (P.Value.FloatValue(af), P.Value.FloatValue(bf)) =>
if (af === bf) F.unit
else raise[F, Unit](s"Float '$af' and '$bf' are not equal.", caret)
case (P.Value.StringValue(as), P.Value.StringValue(bs)) =>
if (as === bs) F.unit
else raise[F, Unit](s"String '$as' and '$bs' are not equal.", caret)
case (P.Value.BooleanValue(ab), P.Value.BooleanValue(bb)) =>
if (ab === bb) F.unit
else raise[F, Unit](s"Boolean '$ab' and '$bb' are not equal.", caret)
case (P.Value.EnumValue(ae), P.Value.EnumValue(be)) =>
if (ae === be) F.unit
else raise[F, Unit](s"Enum '$ae' and '$be' are not equal.", caret)
case (P.Value.NullValue, P.Value.NullValue) => F.unit
case (P.Value.ListValue(al), P.Value.ListValue(bl)) =>
if (al.length === bl.length) {
al.zip(bl).zipWithIndex.parTraverse_ { case ((a, b), i) => ambientIndex(i)(compareValues[F](a, b, caret)) }
} else
raise[F, Unit](s"Lists are not af same size. Found list of length ${al.length} versus list of length ${bl.length}.", caret)
case (P.Value.ObjectValue(ao), P.Value.ObjectValue(bo)) =>
if (ao.length =!= bo.length)
raise[F, Unit](
s"Objects are not af same size. Found object of length ${ao.length} versus object of length ${bo.length}.",
caret
)
else {
def checkUniqueness(xs: List[(String, P.Value)]) =
xs.groupMap { case (k, _) => k } { case (_, v) => v }
.toList
.parTraverse {
case (k, v :: Nil) => F.pure(k -> v)
case (k, _) => raise[F, (String, P.Value)](s"Key '$k' is not unique in object.", caret)
}
.map(_.toMap)
(checkUniqueness(ao), checkUniqueness(bo)).parTupled.flatMap { case (amap, bmap) =>
// TODO test that verifies that order does not matter
(amap align bmap).toList.parTraverse_ {
case (k, Ior.Left(_)) => raise[F, Unit](s"Key '$k' is missing in object.", caret)
case (k, Ior.Right(_)) => raise[F, Unit](s"Key '$k' is missing in object.", caret)
case (k, Ior.Both(l, r)) => ambientArg(k)(compareValues[F](l, r, caret))
}
}
}
case _ => raise[F, Unit](s"Values are not same type, got ${pValueName(av)} and ${pValueName(bv)}.", caret)
}
}
def compareArguments[F[_]: Parallel](name: String, aa: P.Arguments, ba: P.Arguments, caret: Option[Caret])(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
) = {
def checkUniqueness(x: P.Arguments): F[Map[String, QueryParser.Argument]] =
x.nel.toList
.groupBy(_.name)
.toList
.parTraverse {
case (k, v :: Nil) => F.pure(k -> v)
case (k, _) =>
raise[F, (String, P.Argument)](s"Argument '$k' of field $name was not unique.", caret)
}
.map(_.toMap)
(checkUniqueness(aa), checkUniqueness(ba)).parTupled.flatMap { case (amap, bmap) =>
(amap align bmap).toList.parTraverse_ {
case (k, Ior.Left(_)) =>
raise[F, Unit](s"Field $name is already selected with argument '$k', but no argument was given here.", caret)
case (k, Ior.Right(_)) =>
raise[F, Unit](s"Field $name is already selected without argument '$k', but an argument was given here.", caret)
case (k, Ior.Both(l, r)) => ambientArg(k)(compareValues[F](l.value, r.value, caret))
}
}
}
// https://spec.graphql.org/draft/#sec-Field-Selection-Merging.Formal-Specification
def checkFieldsMerge[F[_]: Parallel, G[_]](a: FieldInfo[G], asi: SelectionInfo[G], b: FieldInfo[G], bsi: SelectionInfo[G])(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
) = {
sealed trait EitherObject
object EitherObject {
case object FirstIsObject extends EitherObject
case object SecondIsObject extends EitherObject
case object NeitherIsObject extends EitherObject
case object BothAreObjects extends EitherObject
}
lazy val objectPair = (asi.s, bsi.s) match {
case (_: Type[G, ?], _: Type[G, ?]) => EitherObject.BothAreObjects
case (_: Type[G, ?], _) => EitherObject.FirstIsObject
case (_, _: Type[G, ?]) => EitherObject.SecondIsObject
case _ => EitherObject.NeitherIsObject
}
val parentNameSame = asi.s.name === bsi.s.name
lazy val aIn = s"${fieldName(a)} in type `${asi.s.name}`"
lazy val bIn = s"${fieldName(b)} in type `${bsi.s.name}`"
lazy val whyMerge = {
val why1 = if (parentNameSame) Some("they have the same parent type") else None
val why2 = objectPair match {
case EitherObject.FirstIsObject => Some(s"the second field ${fieldName(a)} is not an object but the first was")
case EitherObject.SecondIsObject => Some(s"the first field ${fieldName(b)} is not an object but the second was")
case EitherObject.NeitherIsObject => Some(s"neither field ${fieldName(a)} nor ${fieldName(b)} are objects")
case EitherObject.BothAreObjects => None
}
List(why1, why2).collect { case Some(err) => err }.mkString(" and ") + "."
}
// 2. in FieldsInSetCanMerge
val thoroughCheckF = if (parentNameSame || objectPair != EitherObject.BothAreObjects) {
val argsF = (a.args, b.args) match {
case (None, None) => F.unit
case (Some(_), None) => raise[F, Unit](s"A selection of field ${fieldName(a)} has arguments, while another doesn't.", Some(b.caret))
case (None, Some(_)) => raise[F, Unit](s"A selection of field ${fieldName(a)} has arguments, while another doesn't.", Some(b.caret))
case (Some(aa), Some(ba)) => compareArguments[F](fieldName(a), aa, ba, Some(b.caret))
}
val nameSameF =
if (a.name === b.name) F.unit
else {
raise[F, Unit](
s"Field $aIn and $bIn must have the same name (not alias) when they are merged.",
Some(a.caret)
)
}
appendMessage(s"They were merged since $whyMerge") {
argsF &> nameSameF
}
} else F.unit
// 1. in FieldsInSetCanMerge
val shapeCheckF = checkSimplifiedTypeShape[F, G](a.tpe, b.tpe, a.caret)
thoroughCheckF &> shapeCheckF
}
// There's a bug here that will allow fewer valid queries than the spec allows.
// In the spec, when two fields are not to be considered equal in regards to arguments and aliasing
// (i.e. they are not to be merged), they should only be structurally equal.
// However, during structural equality checking, we can start to check the arguments again if two fields are defined in the same type.
//
// A new version of this function has two outcomes for every field name:
// Either at-least one field is defined on a non-object type and all types must be fully equal (structural, arguments and alias)
// Or all fields are defined on object types and only fields that are defied on the same type must be fully equal (structural, arguments and alias)
// Fields between different types should just be structurally equal.
//
// It should be very feasible to implement this efficiently (i.e O(n)).
def checkSelectionsMerge[F[_]: Parallel, G[_]](xs: NonEmptyList[SelectionInfo[G]])(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
): F[Unit] = {
val ys: NonEmptyList[NonEmptyList[(SelectionInfo[G], FieldInfo[G])]] =
xs.flatMap(si => si.fields tupleLeft si)
.groupByNem { case (_, f) => f.outputName }
.toNel
.map { case (_, v) => v }
ys.parTraverse_ { zs =>
val mergeFieldsF = {
val (siHead, fiHead) = zs.head
zs.tail.parTraverse_ { case (si, fi) => checkFieldsMerge[F, G](fiHead, siHead, fi, si) }
}
mergeFieldsF >>
zs.toList.flatMap { case (_, fi) => fi.tpe.selections }.toNel.traverse_(checkSelectionsMerge[F, G])
}
}
// Optimization: we don't check selections recursively since checkSelectionsMerge traverses the whole tree
// We only need to check the immidiate children and will eventually have checked the whole tree
def checkSimplifiedTypeShape[F[_]: Parallel, G[_]](a: SimplifiedType[G], b: SimplifiedType[G], caret: Caret)(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
): F[Unit] = {
(a, b) match {
case (SimplifiedType.List(l), SimplifiedType.List(r)) => checkSimplifiedTypeShape[F, G](l, r, caret)
case (SimplifiedType.Option(l), SimplifiedType.Option(r)) => checkSimplifiedTypeShape[F, G](l, r, caret)
// It turns out we don't care if more fields are selected in one object than the other
case (SimplifiedType.Selectable(_, _), SimplifiedType.Selectable(_, _)) => F.unit
// case (SimplifiedType.Selectable(_, l), SimplifiedType.Selectable(_, r)) => F.unit
// val lComb = l.flatMap(x => x.fields tupleLeft x).groupByNem { case (_, f) => f.outputName }
// val rComb = r.flatMap(x => x.fields tupleLeft x).groupByNem { case (_, f) => f.outputName }
// (lComb align rComb).toNel.parTraverse_ {
// case (_, Ior.Both(_, _)) => F.unit
// case (k, Ior.Left(_)) => raise[F, Unit](s"Field '$k' was missing when verifying shape equivalence.", Some(caret))
// case (k, Ior.Right(_)) => raise[F, Unit](s"Field '$k' was missing when verifying shape equivalence.", Some(caret))
// }
case (SimplifiedType.Enum(l), SimplifiedType.Enum(r)) =>
if (l === r) F.unit
else raise[F, Unit](s"Enums are not the same, got '$l' and '$r'.", Some(caret))
case (SimplifiedType.Scalar(l), SimplifiedType.Scalar(r)) =>
if (l === r) F.unit
else raise[F, Unit](s"Scalars are not the same, got '$l' and '$r'.", Some(caret))
case _ =>
raise[F, Unit](s"Types are not the same, got ${getSimplifiedTypeString(a)} and ${getSimplifiedTypeString(b)}.", Some(caret))
}
}
final case class FoundImplementation[G[_], A, B](
tpe: Type[G, B],
specify: A => Option[B]
)
def findImplementations[G[_], A](
s: Selectable[G, A],
discoveryState: SchemaShape.DiscoveryState[G]
): List[FoundImplementation[G, A, ?]] = s match {
case t: Type[G, ?] => List(FoundImplementation(t, Some(_)))
case u: Union[G, ?] =>
u.types.toList.map { case x: gql.ast.Variant[G, A, b] =>
FoundImplementation(x.tpe.value, x.specify)
}
case it @ Interface(_, _, _, _) =>
val m: Map[String, SchemaShape.InterfaceImpl[G, A]] =
discoveryState.implementations
.get(it.name)
.getOrElse(Map.empty)
.collect { case (k, v: SchemaShape.InterfaceImpl[G, A] @unchecked) => (k, v) }
m.values.toList
.collect { case ti: SchemaShape.InterfaceImpl.TypeImpl[G, A, b] => FoundImplementation(ti.t, ti.specify) }
}
final case class MergedFieldInfo[G[_]](
name: String,
alias: Option[String],
args: Option[P.Arguments],
selections: List[SelectionInfo[G]],
// TODO these two should probably be lists
caret: Caret,
path: PrepCursor
)
final case class PairedFieldSelection[G[_], A](
info: MergedFieldInfo[G],
field: Field[G, A, ?]
)
final case class MergedImplementation[G[_], A, B](
leaf: Type[G, B],
selections: NonEmptyList[PairedFieldSelection[G, B]],
specify: A => Option[B]
)
def mergeImplementations[F[_]: Parallel, G[_], A](
base: Selectable[G, A],
sels: NonEmptyList[SelectionInfo[G]],
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
): F[NonEmptyList[MergedImplementation[G, A, ?]]] = {
// We need to find all implementations of the base type
val concreteBaseMap = findImplementations[G, A](base, discoveryState).map(x => x.tpe.name -> x).toMap
val concreteBase = concreteBaseMap.toList
val nestedSelections: List[(String, NonEmptyList[FieldInfo[G]])] = sels.toList.flatMap { sel =>
/* The set of typenames that implement whatever we're selecting on
* ```graphql
* interface A {
* name: String
* }
*
* {
* ...
* ... on A {
* name
* }
* }
* ```
* In this case, we have a selection on `A`, so we must figure out what types implement `A`
* and then for every type `T` that implements `A`, we must find the field `name` and select it on `T`.
*/
val concreteIntersections = findImplementations(sel.s, discoveryState)
.map { case FoundImplementation(t, _) => t.name }
concreteIntersections tupleRight sel.fields
}
// TODO field merging can be optimized significantly by deduplicating fragment spreads
// (if two fields are in the same fragment (maybe also the same position)?)
/*
* Now we must merge all fields that are selected on the same type.
*
* Merge fields at this level only.
* We cannot merge fields globally, because we need to know the base type
* And even if we looked for the base type, we might as well do resolver/step preparation and argument parsing
* since that would require us to walk the tree again.
*/
type Typename = String
type FieldName = String
// There may be more than one field with the same name
// This is fine, but we need to merge their implementations
val grouped: Map[Typename, NonEmptyMap[FieldName, NonEmptyList[FieldInfo[G]]]] = nestedSelections
.groupMap { case (k, _) => k } { case (_, vs) => vs }
.collect { case (k, x :: xs) => k -> NonEmptyList(x, xs).flatten.groupByNem(_.outputName) }
val merged = grouped.fmap(_.fmap { fields =>
val sels = fields.map(_.tpe.selections).reduce
MergedFieldInfo(
fields.head.name,
fields.head.alias,
fields.head.args,
sels,
fields.head.caret,
fields.head.path
)
})
val collected: F[List[MergedImplementation[G, A, ?]]] = concreteBase.parFlatTraverse { case (k, (fi: FoundImplementation[G, A, b])) =>
val t = fi.tpe
val specify = fi.specify
merged.get(k).toList.traverse { fields =>
fields.toNonEmptyList
.parTraverse { f =>
if (f.name === "__typename") F.pure(PairedFieldSelection[G, b](f, typenameField[b](t.name)))
else {
t.fieldMap.get(f.name) match {
case None =>
raise[F, PairedFieldSelection[G, b]](s"Could not find field '${f.name}' on type `${t.name}`.", None)
case Some(field) => F.pure(PairedFieldSelection[G, b](f, field))
}
}
}
.map(fields => MergedImplementation[G, A, b](t, fields, specify))
}
}
collected.flatMap { xs =>
xs.toNel match {
case Some(x) => F.pure(x)
case None =>
raise[F, NonEmptyList[MergedImplementation[G, A, ?]]](
s"Could not find any implementations of `${base.name}` in the selection set.",
None
)
}
}
}
def decodeFieldArgs[F[_]: Parallel, G[_], A](
a: Arg[A],
args: Option[P.Arguments],
variableMap: VariableMap
)(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]]
): F[A] = {
val provided = args.toList.flatMap(_.nel.toList)
// Treat input arguments as an object
// Decode the args as-if an input
val argObj =
P.Value.ObjectValue(provided.map(a => a.name -> a.value))
parseInputObj[F, A](argObj, a, Some(variableMap), ambigiousEnum = false)
}
def prepareField[F[_]: Parallel, G[_]: Applicative, I, T](
fi: MergedFieldInfo[G],
field: Field[G, I, T],
currentTypename: String,
variableMap: VariableMap,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[State[Int, PreparedDataField[G, I]]] = D.defer {
val tpe = field.output.value
val selCaret = fi.caret
val name = fi.name
val step = field.resolve.underlying
val rootUniqueName = UniqueEdgeCursor(s"${currentTypename}_$name")
val meta: PreparedMeta = PreparedMeta(
variableMap,
fi.alias,
fi.args
)
def compileCont[A](t: Out[G, A], cursor: UniqueEdgeCursor): Used[F, State[Int, Prepared[G, A]]] =
(t, fi.selections.toNel) match {
case (out: gql.ast.OutArr[g, a, c, b], _) =>
val innerStep: Step[G, a, b] = out.resolver.underlying
val nc = cursor append "array"
val compiledStep = compileStep[F, G, a, b](innerStep, nc, meta)
val compiledCont = compileCont[b](out.of, nc)
(compiledStep, compiledCont)
.parMapN((_, _).tupled)
.map(_.map { case (s, c) =>
PreparedList(PreparedCont(s, c), out.toSeq)
})
case (out: gql.ast.OutOpt[g, a, b], _) =>
val innerStep: Step[G, a, b] = out.resolver.underlying
val nc = cursor append "option"
val compiledStep = compileStep[F, G, a, b](innerStep, nc, meta)
val compiledCont = compileCont[b](out.of, nc)
(compiledStep, compiledCont)
.parMapN((_, _).tupled)
.map(_.map { case (s, c) =>
PreparedOption(PreparedCont(s, c))
})
case (s: Selectable[G, a], Some(ss)) =>
Used.liftF {
prepareSelectable[F, G, a](s, ss, variableMap, discoveryState)
.map(_.map(Selection(_)))
}
case (e: Enum[a], None) =>
Used[F].pure(State.pure(PreparedLeaf(e.name, x => Json.fromString(e.revm(x)))))
case (s: Scalar[a], None) =>
Used[F].pure(State.pure(PreparedLeaf(s.name, x => s.encoder(x).asJson)))
case (o, Some(_)) =>
Used.liftF(raise(s"Type `${friendlyName(o)}` cannot have selections.", Some(selCaret)))
case (o, None) =>
Used.liftF(raise(s"Object like type `${friendlyName(o)}` must have a selection.", Some(selCaret)))
}
val usedF = (
compileStep[F, G, I, T](step, rootUniqueName, meta),
compileCont(tpe, rootUniqueName)
).parMapN((_, _).tupled)
.map(_.map { case (s, c) =>
val pc = PreparedCont(s, c)
PreparedDataField(name, fi.alias, pc)
})
usedF.run
.flatMap { case (used, a) =>
val provided = fi.args.toList.flatMap(_.nel.toList).map(_.name).toSet
val tooMany = provided -- used
if (tooMany.isEmpty) F.pure(a)
else raise(s"Field '$name' does not accept the arguments ${tooMany.map(s => s"'$s'").toList.mkString_(", ")}", Some(selCaret))
}
}
def prepareSelectable[F[_]: Parallel, G[_], A](
s: Selectable[G, A],
sis: NonEmptyList[SelectionInfo[G]],
variableMap: VariableMap,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
G: Applicative[G],
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[State[Int, NonEmptyList[PreparedSpecification[G, A, ?]]]] = {
mergeImplementations[F, G, A](s, sis, discoveryState).flatMap { impls =>
impls
.parTraverse[F, State[Int, PreparedSpecification[G, A, ?]]] { case impl: MergedImplementation[G, A, b] =>
val fa: F[NonEmptyList[State[Int, PreparedDataField[G, b]]]] = impl.selections.parTraverse { sel =>
sel.field match {
case field: Field[G, b2, t] =>
prepareField[F, G, b, t](sel.info, field, impl.leaf.name, variableMap, discoveryState)
}
}
fa.map(_.sequence.map(xs => PreparedSpecification[G, A, b](s.name, impl.specify, xs)))
}
.map(_.sequence)
}
}
def prepareSelectableRoot[F[_]: Parallel, G[_], A](
s: Selectable[G, A],
ss: P.SelectionSet,
variableMap: VariableMap,
fragments: Map[String, Pos[P.FragmentDefinition]],
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
G: Applicative[G],
L: Local[F, Prep],
F: MonadError[F, NonEmptyChain[PositionalError]],
D: Defer[F]
): F[NonEmptyList[PreparedSpecification[G, A, ?]]] = {
collectSelectionInfo[F, G](s, ss, variableMap, fragments, discoveryState).flatMap { root =>
checkSelectionsMerge[F, G](root) >>
prepareSelectable[F, G, A](s, root, variableMap, discoveryState)
.map(_.runA(0).value)
}
}
type VariableMap = Map[String, Either[P.Value, Json]]
def matchType[F[_], G[_]](
name: String,
sel: Selectable[G, ?],
caret: Caret,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit F: MonadError[F, NonEmptyChain[PositionalError]], L: Local[F, Prep]): F[Selectable[G, ?]] =
if (sel.name == name) F.pure(sel)
else {
sel match {
case t @ Type(n, _, _, _) =>
// Check downcast
t.implementsMap.get(name).map(_.value) match {
case None => raise(s"Tried to match with type `$name` on type object type `$n`.", Some(caret))
case Some(i) => F.pure(i)
}
// What types implement this interface?
// We can both downcast and up-match
case i @ Interface(n, _, _, _) =>
i.implementsMap.get(name).map(_.value) match {
case Some(i) => F.pure(i)
case None =>
raiseOpt(
discoveryState.implementations.get(i.name),
s"The interface `${i.name}` is not implemented by any type.",
caret.some
).flatMap { m =>
raiseOpt(
m.get(name).map {
case t: SchemaShape.InterfaceImpl.TypeImpl[G @unchecked, ?, ?] => t.t
case i: SchemaShape.InterfaceImpl.OtherInterface[G @unchecked, ?] => i.i
},
s"`$name` does not implement interface `$n`, possible implementations are ${m.keySet.mkString(", ")}.",
caret.some
)
}
}
// Can match to any type or any of it's types' interfacees
case u @ Union(n, _, _) =>
u.instanceMap
.get(name) match {
case Some(i) => F.pure(i.tpe.value)
case None =>
u.types.toList
.map(_.tpe.value)
.collectFirstSome(_.implementsMap.get(name)) match {
case None =>
raise(
s"`$name` is not a member of the union `$n` (or any of the union's types' implemented interfaces), possible members are ${u.instanceMap.keySet
.mkString(", ")}.",
caret.some
)
case Some(x) => F.pure(x.value)
}
}
}
}
def pValueName(v: P.Value): String =
v match {
case ObjectValue(_) => "object"
case StringValue(_) => "string"
case ListValue(_) => "list"
case P.Value.EnumValue(_) => "enum"
case BooleanValue(_) => "boolean"
case NullValue => "null"
case FloatValue(_) => "float"
case IntValue(_) => "int"
case VariableValue(_) => "variable"
}
def inName[A](in: In[A], inOption: Boolean = false): String = {
val suffix = if (inOption) "" else "!"
val rec = (in: @unchecked) match {
case InArr(of, _) => s"[${inName(of)}]"
case Enum(name, _, _) => name
case Scalar(name, _, _, _) => name
case InOpt(of) => s"${inName(of, inOption = true)}"
case Input(name, _, _) => name
}
rec + suffix
}
def parseInputObj[F[_]: Parallel, A](
v: P.Value.ObjectValue,
fields: Arg[A],
variableMap: Option[VariableMap],
ambigiousEnum: Boolean
)(implicit
F: MonadError[F, NonEmptyChain[PositionalError]],
L: Local[F, Prep]
): F[A] = {
val xs = v.v
val m = xs.toMap
val required = fields.entries.map(x => x.name -> x).toList.toMap
// All provided fields are defined
val tooMuch = m.keySet -- required.keySet
val tooMuchF =
if (tooMuch.isEmpty) F.unit
else raise[F, Unit](s"Too many fields provided, unknown fields are ${tooMuch.toList.map(x => s"'$x'").mkString_(", ")}.", None)