-
Notifications
You must be signed in to change notification settings - Fork 3
/
PreparedQuery.scala
772 lines (689 loc) · 30.3 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
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
object PreparedQuery {
sealed trait Prepared[F[_], A]
sealed trait PreparedField[F[_], A]
final case class PreparedDataField[F[_], I, T](
id: Int,
name: String,
alias: Option[String],
cont: PreparedCont[F]
) extends PreparedField[F, I]
final case class PreparedFragField[F[_], A](
id: Int,
typename: String,
specify: Any => Option[A],
selection: Selection[F, A]
) extends PreparedField[F, A]
final case class FragmentDefinition[F[_], A](
name: String,
typeCondition: String,
specify: Any => Option[A],
fields: NonEmptyList[PreparedField[F, A]]
)
final case class EdgeId(id: Int) extends AnyVal
final case class PreparedEdge[F[_]](
id: EdgeId,
resolver: Resolver[F, Any, Any],
statisticsName: String
)
final case class PreparedCont[F[_]](
edges: NonEmptyChain[PreparedEdge[F]],
cont: Prepared[F, Any]
)
final case class Selection[F[_], A](fields: NonEmptyList[PreparedField[F, A]]) extends Prepared[F, A]
final case class PreparedList[F[_], A](of: Prepared[F, A], toSeq: Any => Seq[A]) extends Prepared[F, A]
final case class PreparedOption[F[_], A](of: Prepared[F, A]) extends Prepared[F, A]
final case class PreparedLeaf[F[_], A](name: String, encode: A => Json) extends Prepared[F, A]
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
}
}
sealed trait PrepEdge {
def name: String
}
object PrepEdge {
final case class ASTEdge(edge: SchemaShape.ValidationEdge) extends PrepEdge {
def name: String = edge.name
}
final case class FragmentEdge(name: String) extends PrepEdge
}
final case class PrepCursor(position: Chain[PrepEdge]) {
def add(edge: PrepEdge): PrepCursor = PrepCursor(position append edge)
def pop: PrepCursor = PrepCursor(Chain.fromOption(position.initLast).flatMap { case (xs, _) => xs })
}
object PrepCursor {
val empty: PrepCursor = PrepCursor(Chain.empty)
}
final case class Prep(
cycleSet: Set[String],
nextId: Int,
cursor: PrepCursor
)
object Prep {
val empty: Prep = Prep(Set.empty, 1, PrepCursor.empty)
}
object InArr {
def unapply[A](p: In[A]): Option[(In[A], Seq[?] => Either[String, A])] =
p.asInstanceOf[In[A]] match {
case x: InArr[?, A] => Some((x.of.asInstanceOf[In[A]], x.fromSeq.asInstanceOf[Seq[?] => Either[String, A]]))
case _ => None
}
}
object InOpt {
def unapply[A](p: In[A]): Option[In[A]] =
p.asInstanceOf[In[Option[A]]] match {
case x: InOpt[A] => Some(x.of.asInstanceOf[In[A]])
case _ => None
}
}
object OutArr {
def unapply[G[_], A](p: Out[G, A]): Option[(Out[G, A], Any => Seq[A])] =
p.asInstanceOf[Out[G, A]] match {
case x: OutArr[G, ?, A] => Some((x.of.asInstanceOf[Out[G, A]], x.toSeq.asInstanceOf[Any => Seq[A]]))
case _ => None
}
}
object OutOpt {
def unapply[G[_], A](p: Out[G, A]): Option[Out[G, A]] =
p.asInstanceOf[Out[G, Option[A]]] match {
case x: OutOpt[G, A] => Some(x.of.asInstanceOf[Out[G, A]])
case _ => None
}
}
def flattenResolvers[F[_]: Monad, G[_]](parentName: String, resolver: Resolver[G, Any, Any])(implicit
S: Stateful[F, Prep]
): F[(NonEmptyChain[PreparedEdge[G]], String)] =
resolver match {
case BatchResolver(id, _) =>
nextId[F].map(nid => (NonEmptyChain.of(PreparedEdge(EdgeId(nid), resolver, s"batch_${id.id}")), parentName))
case EffectResolver(_) =>
val thisName = s"${parentName}_effect"
nextId[F].map(nid => (NonEmptyChain.of(PreparedEdge(EdgeId(nid), resolver, thisName)), thisName))
case PureResolver(_) =>
val thisName = s"${parentName}_pure"
nextId[F].map(nid => (NonEmptyChain.of(PreparedEdge(EdgeId(nid), resolver, thisName)), thisName))
case FallibleResolver(_) =>
val thisName = s"${parentName}_fallible"
nextId[F].map(nid => (NonEmptyChain.of(PreparedEdge(EdgeId(nid), resolver, thisName)), thisName))
case StreamResolver(_) =>
val thisName = s"${parentName}_stream"
nextId[F].map(nid => (NonEmptyChain.of(PreparedEdge(EdgeId(nid), resolver, thisName)), thisName))
case CompositionResolver(left, right) =>
flattenResolvers[F, G](parentName, left.asInstanceOf[Resolver[G, Any, Any]])
.flatMap { case (ys, newParentName) =>
flattenResolvers[F, G](newParentName, right.asInstanceOf[Resolver[G, Any, Any]])
.map { case (zs, outName) => (ys ++ zs, outName) }
}
}
def underlyingOutputTypename[G[_]](ot: Out[G, ?]): String = (ot: @unchecked) match {
case Enum(name, _, _) => name
case Union(name, _, _) => name
case Interface(name, _, _, _) => name
case Type(name, _, _, _) => name
case Scalar(name, _, _, _) => name
case OutOpt(of) => underlyingOutputTypename(of)
case OutArr(of, _) => underlyingOutputTypename(of)
}
def friendlyName[G[_], A](ot: Out[G, A]): String = (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) => s"(${friendlyName(of)} | null)"
case OutArr(of, _) => s"[${friendlyName(of)}]"
}
def nextId[F[_]: Monad](implicit S: Stateful[F, Prep]) =
S.inspect(_.nextId) <* S.modify(x => x.copy(nextId = x.nextId + 1))
def raise[F[_], A](s: String, caret: Option[Caret])(implicit S: Stateful[F, Prep], F: MonadError[F, PositionalError]): F[A] =
S.get.map(state => PositionalError(state.cursor, caret.toList, s)).flatMap(F.raiseError[A])
def raiseOpt[F[_], A](o: Option[A], s: String, caret: Option[Caret])(implicit
S: Stateful[F, Prep],
F: MonadError[F, 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
S: Stateful[F, Prep],
F: MonadError[F, PositionalError]
): F[A] =
e match {
case Left(value) => raise[F, A](value, caret)
case Right(value) => F.pure(value)
}
def ambientEdge[F[_]: Monad, A](edge: PrepEdge)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
S.inspect(_.cursor).flatMap { c =>
S.modify(_.copy(cursor = c.add(edge))) *> fa <* S.modify(_.copy(cursor = c))
}
def ambientField[F[_]: Monad, A](name: String)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
ambientEdge[F, A](PrepEdge.ASTEdge(SchemaShape.ValidationEdge.Field(name)))(fa)
def ambientOutputType[F[_]: Monad, A](name: String)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
ambientEdge[F, A](PrepEdge.ASTEdge(SchemaShape.ValidationEdge.OutputType(name)))(fa)
def ambientArg[F[_]: Monad, A](name: String)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
ambientEdge[F, A](PrepEdge.ASTEdge(SchemaShape.ValidationEdge.Arg(name)))(fa)
def ambientInputType[F[_]: Monad, A](name: String)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
ambientEdge[F, A](PrepEdge.ASTEdge(SchemaShape.ValidationEdge.InputType(name)))(fa)
def ambientFragment[F[_]: Monad, A](name: String)(fa: F[A])(implicit S: Stateful[F, Prep]): F[A] =
ambientEdge[F, A](PrepEdge.FragmentEdge(name))(fa)
def prepareSelections[F[_], G[_]](
ol: Selectable[G, Any],
s: P.SelectionSet,
variableMap: VariableMap[Any],
fragments: Map[String, Pos[P.FragmentDefinition]],
currentTypename: String,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
G: Applicative[G],
S: Stateful[F, Prep],
F: MonadError[F, PositionalError],
D: Defer[F]
): F[NonEmptyList[PreparedField[G, Any]]] = D.defer {
val syntheticTypename =
Field[G, Any, String, Unit](
Applicative[Arg].unit,
FallibleResolver[G, (Any, Unit), String] { case (input, _) =>
// TODO this code shares much with the subtype interfaces below in matchType
val typename = ol match {
case Type(name, _, _, _) => Some(name)
case Union(_, types, _) =>
types.collectFirstSome { variant => variant.specify(input) as variant.tpe.value.name }
case Interface(name, _, _, _) =>
// Only look for concrete types; that is; `Type`s
discoveryState.implementations
.get(name)
.toList
.flatMap(_.values.toList)
.collectFirstSome {
case (Type(name, _, _, _), spec) => spec(input) as name
case _ => None
}
}
G.pure(typename.toRightIor("typename could not be determined, this is an implementation error"))
},
Eval.now(gql.ast.stringScalar)
)
val schemaMap = ol.fieldMap + ("__typename" -> syntheticTypename)
s.selections.traverse[F, PreparedField[G, Any]] {
case Pos(caret, P.Selection.FieldSelection(field)) =>
(schemaMap.get(field.name): @unchecked) match {
case None => raise(s"unknown field name ${field.name}", Some(caret))
case Some(f: Field[G, Any, Any, Any] @unchecked) =>
ambientField(field.name) {
prepareField[F, G](field, caret, f, variableMap, fragments, currentTypename, discoveryState)
}
}
case Pos(caret, P.Selection.InlineFragmentSelection(f)) =>
f.typeCondition match {
case None => raise(s"inline fragment must have a type condition", Some(caret))
case Some(typeCnd) =>
matchType[F, G](typeCnd, ol, caret, discoveryState).flatMap { case (ol, specialize) =>
prepareSelections[F, G](ol, f.selectionSet, variableMap, fragments, typeCnd, discoveryState)
.map(Selection(_))
.flatMap[PreparedField[G, Any]](s => nextId[F].map(id => PreparedFragField(id, typeCnd, specialize, s)))
}
}
case Pos(caret, P.Selection.FragmentSpreadSelection(f)) =>
fragments.get(f.fragmentName) match {
case None => raise(s"unknown fragment name ${f.fragmentName}", Some(caret))
case Some(fd) =>
ambientFragment(f.fragmentName) {
prepareFragment[F, G](ol, fd, variableMap, fragments, fd.value.typeCnd, discoveryState)
.flatMap[PreparedField[G, Any]] { fd =>
nextId[F].map(id => PreparedFragField(id, fd.typeCondition, fd.specify, Selection(fd.fields)))
}
}
}
}
}
type VariableMap[A] = Map[String, (In[A], A)]
def closeFieldParameters[F[_], G[_]](
gqlField: P.Field,
caret: Caret,
field: Field[G, Any, Any, Any],
variableMap: VariableMap[Any]
)(implicit
S: Stateful[F, Prep],
F: MonadError[F, PositionalError]
): F[Resolver[G, Any, Any]] = {
val provided = gqlField.arguments.toList.flatMap(_.nel.toList)
val Field(args, resolve, _, _) = field
// 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))
val decObj = args match {
case PureArg(value) if provided.isEmpty => value.fold(raise(_, None), F.pure(_))
case PureArg(_) =>
raise(s"field ${gqlField.name} does not accept arguments", Some(caret))
case nea @ NonEmptyArg(_, _) =>
parseInputObj[F, Any](argObj, nea, Some(variableMap), ambigiousEnum = false)
}
decObj.map(a => resolve.contramap[Any]((_, a)))
}
def prepareField[F[_], G[_]: Applicative](
gqlField: P.Field,
caret: Caret,
field: Field[G, Any, Any, Any],
variableMap: VariableMap[Any],
fragments: Map[String, Pos[P.FragmentDefinition]],
currentTypename: String,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
S: Stateful[F, Prep],
F: MonadError[F, PositionalError],
D: Defer[F]
): F[PreparedField[G, Any]] = {
closeFieldParameters[F, G](gqlField, caret, field, variableMap).flatMap { resolve =>
val tpe = field.output.value
val ss = gqlField.selectionSet.value
val selCaret = gqlField.selectionSet.caret
val tn = underlyingOutputTypename(field.output.value)
def typePrep(t: Out[G, Any]): F[Prepared[G, Any]] =
(t, ss) match {
case (OutArr(inner, toSeq), _) => typePrep(inner).map(PreparedList(_, toSeq))
case (OutOpt(inner), _) => typePrep(inner).map(PreparedOption(_))
case (ol: Selectable[G, Any], Some(ss)) =>
prepareSelections[F, G](ol, ss, variableMap, fragments, tn, discoveryState)
.map(Selection(_))
case (e: Enum[G, Any], None) =>
F.pure(PreparedLeaf(e.name, x => Json.fromString(e.revm(x))))
case (s: Scalar[G, Any], None) =>
F.pure(PreparedLeaf(s.name, x => s.encoder(x).asJson))
case (o, Some(_)) => raise(s"type ${friendlyName[G, Any](o)} cannot have selections", Some(selCaret))
case (o, None) => raise(s"object like type ${friendlyName[G, Any](o)} must have a selection", Some(selCaret))
}
val prepF: F[Prepared[G, Any]] = typePrep(tpe)
prepF.flatMap { p =>
nextId[F].flatMap { id =>
flattenResolvers[F, G](s"${currentTypename}_${gqlField.name}", resolve).map { case (edges, _) =>
val pc = PreparedCont(edges, p)
PreparedDataField(id, gqlField.name, gqlField.alias, pc)
}
}
}
}
}
// name is the type in the pattern match case
// sel is the type we match on
// sel match { case x if x.name == name => ... }
def matchType[F[_], G[_]](
name: String,
sel: Selectable[G, Any],
caret: Caret,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit F: MonadError[F, PositionalError], S: Stateful[F, Prep]): F[(Selectable[G, Any], Any => Option[Any])] =
if (sel.name == name) F.pure((sel, Some(_)))
else {
sel match {
case Type(n, _, _, _) =>
raise(s"tried to match with type $name on type object type $n", Some(caret))
// What types implement this interface?
case i @ Interface(n, _, _, _) =>
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),
s"$name does not implement interface $n, possible implementations are ${m.keySet.mkString(", ")}",
caret.some
)
}
case u @ Union(n, _, _) =>
raiseOpt(
u.instanceMap
.get(name)
.map(i => (i.tpe.value.asInstanceOf[Type[G, Any]], i.specify)),
s"$name is not a member of the union $n, possible members are ${u.instanceMap.keySet.mkString(", ")}",
caret.some
)
}
}
def prepareFragment[F[_], G[_]: Applicative](
ol: Selectable[G, Any],
f: Pos[P.FragmentDefinition],
variableMap: VariableMap[Any],
fragments: Map[String, Pos[P.FragmentDefinition]],
currentTypename: String,
discoveryState: SchemaShape.DiscoveryState[G]
)(implicit
S: Stateful[F, Prep],
F: MonadError[F, PositionalError],
D: Defer[F]
): F[FragmentDefinition[G, Any]] =
D.defer {
S.get.flatMap {
case c if c.cycleSet(f.value.name) => raise(s"fragment by name ${f.value.name} is cyclic", Some(f.caret))
case _ =>
val beforeF: F[Unit] = S.modify(s => s.copy(cycleSet = s.cycleSet + f.value.name))
val afterF: F[Unit] = S.modify(s => s.copy(cycleSet = s.cycleSet - f.value.name))
val programF: F[FragmentDefinition[G, Any]] =
matchType[F, G](f.value.typeCnd, ol, f.caret, discoveryState)
.flatMap { case (t, specify) =>
prepareSelections[F, G](t, f.value.selectionSet, variableMap, fragments, currentTypename, discoveryState)
.map(FragmentDefinition(f.value.name, f.value.typeCnd, specify, _))
}
beforeF *> programF <* afterF
}
}
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]): String = (in: @unchecked) match {
case InArr(of, _) => s"list of ${inName(of)}"
case Enum(name, _, _) => name
case Scalar(name, _, _, _) => name
case InOpt(of) => s"optional of ${inName(of)}"
case Input(name, _, _) => name
}
def parseInputObj[F[_], A](
v: P.Value.ObjectValue,
fields: NonEmptyArg[A],
variableMap: Option[VariableMap[A]],
ambigiousEnum: Boolean
)(implicit
F: MonadError[F, PositionalError],
S: Stateful[F, Prep]
): F[A] = {
val xs = v.v
val m = xs.toMap
val required = fields.nec.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.mkString_(", ")}", None)
tooMuchF >> parseArg[F, A](fields, m, variableMap, ambigiousEnum)
}
def parseInput[F[_], A](v: P.Value, tpe: In[A], variableMap: Option[VariableMap[A]], ambigiousEnum: Boolean)(implicit
F: MonadError[F, PositionalError],
S: Stateful[F, Prep]
): F[A] =
(tpe, v) match {
case (_, P.Value.VariableValue(v)) =>
variableMap match {
case None => raise(s"variable $v may not occur here", None)
case Some(vm) =>
vm.get(v) match {
case None => raise(s"variable $v is not defined", None)
case Some((varType, a)) =>
def cmpTpe[A](lhs: In[A], rhs: In[A]): F[Unit] =
(lhs, rhs) match {
case (InArr(expected, _), InArr(other, _)) => cmpTpe(expected, other)
case (Enum(name, _, _), Enum(otherName, _, _)) =>
if (name == otherName) F.unit
else raise(s"expected enum $name for variable $v, but got enum $otherName", None)
case (Scalar(name, _, _, _), Scalar(otherName, _, _, _)) =>
if (name == otherName) F.unit
else raise(s"expected scalar $name for variable $v, but got scalar $otherName", None)
case (InOpt(expected), InOpt(other)) => cmpTpe(expected, other)
case (Input(name, _, _), Input(otherName, _, _)) =>
if (name == otherName) F.unit
else raise(s"expected input $name for variable $v, but got input $otherName", None)
case _ =>
raise(s"expected ${inName(lhs)} type for variable $v, but got ${inName(rhs)}", None)
}
cmpTpe(tpe, varType).as(a)
}
}
case (e @ Enum(name, _, _), v) =>
ambientInputType(name) {
val fa: F[String] = v match {
case P.Value.EnumValue(s) => F.pure(s)
case P.Value.StringValue(s) if ambigiousEnum => F.pure(s)
case _ =>
raise(s"enum value expected for $name, but got ${pValueName(v)}", None)
}
fa.flatMap { s =>
e.m.lookup(s) match {
case Some(x) => F.pure(x)
case None =>
val names = e.m.keys.toList
raise(
s"enum value $s does not occur in enum type $name, possible enum values are ${names.mkString_(", ")}",
None
)
}
}
}
case (Scalar(name, _, decoder, _), x) =>
ambientInputType(name) {
parserValueToValue[F](x).flatMap(x => raiseEither(decoder(x), None))
}
case (Input(name, fields, _), o: P.Value.ObjectValue) =>
ambientInputType(name) {
parseInputObj[F, A](o, fields, variableMap, ambigiousEnum)
}
case (InArr(of, dec), P.Value.ListValue(xs)) =>
xs.traverse(parseInput[F, A](_, of, variableMap, ambigiousEnum)).flatMap(dec(_).fold(raise(_, None), F.pure(_)))
case (InOpt(_), P.Value.NullValue) => F.pure(None.asInstanceOf[A])
case (InOpt(of), x) => parseInput[F, A](x, of, variableMap, ambigiousEnum).map(Some(_).asInstanceOf[A])
case (i, _) => raise(s"expected ${inName(i)} type, but got ${pValueName(v)}", None)
}
def parseArgValue[F[_], A](a: ArgValue[A], input: Map[String, P.Value], variableMap: Option[VariableMap[A]], ambigiousEnum: Boolean)(
implicit
F: MonadError[F, PositionalError],
S: Stateful[F, Prep]
) = {
val fa =
input.get(a.name) match {
case None =>
a.defaultValue match {
case None =>
a.input.value match {
case InOpt(_) => F.pure(P.Value.NullValue)
case _ =>
raise[F, P.Value](s"required input ${a.name} was not provided and has no default value", None)
}
// TODO this value being parsed can probably be cached, since the default is the same for every query
case Some(dv) => F.pure(valueToParserValue(dv))
}
case Some(x) => F.pure(x)
}
ambientArg(a.name) {
fa.flatMap(parseInput[F, A](_, a.input.value, variableMap, ambigiousEnum))
}
}
def parseArg[F[_], A](arg: Arg[A], input: Map[String, P.Value], variableMap: Option[VariableMap[A]], ambigiousEnum: Boolean)(implicit
F: MonadError[F, PositionalError],
S: Stateful[F, Prep]
): F[A] = {
// All provided fields are of the correct type
// All required fields are either defiend or defaulted
val fieldsF: F[Chain[(String, Any)]] =
arg.entries.traverse { a =>
parseArgValue[F, Any](
a.asInstanceOf[ArgValue[Any]],
input,
variableMap.asInstanceOf[Option[VariableMap[Any]]],
ambigiousEnum
)
.tupleLeft(a.name)
}
fieldsF
.map(_.toList.toMap)
.flatMap(arg.decode(_).fold(raise(_, None), F.pure(_)))
}
def parserValueToValue[F[_]](v: P.Value)(implicit
F: MonadError[F, PositionalError],
S: Stateful[F, Prep]
): F[Value] =
v match {
case NullValue => F.pure(Value.NullValue)
case FloatValue(v) => F.pure(Value.FloatValue(v))
case P.Value.EnumValue(v) => F.pure(Value.EnumValue(v))
case ListValue(v) =>
v.toVector.traverse(parserValueToValue[F]).map(Value.ArrayValue(_))
case IntValue(v) => F.pure(Value.IntValue(v))
case VariableValue(v) => raise[F, Value](s"variable $v may not occur here", None)
case ObjectValue(v) =>
v.traverse { case (k, v) =>
parserValueToValue[F](v).tupleLeft(k)
}.map(xs => Value.ObjectValue(xs.toMap))
case BooleanValue(v) => F.pure(Value.BooleanValue(v))
case StringValue(v) => F.pure(Value.StringValue(v))
}
def valueToParserValue(v: Value): P.Value =
v match {
case Value.BooleanValue(v) => P.Value.BooleanValue(v)
case Value.StringValue(v) => P.Value.StringValue(v)
case Value.IntValue(v) => P.Value.IntValue(v)
case Value.ObjectValue(fields) => P.Value.ObjectValue(fields.toList.map { case (k, v) => k -> valueToParserValue(v) })
case Value.ArrayValue(v) => P.Value.ListValue(v.toList.map(valueToParserValue))
case Value.EnumValue(v) => P.Value.EnumValue(v)
case Value.NullValue => P.Value.NullValue
case Value.FloatValue(v) => P.Value.FloatValue(v)
}
def getOperationDefinition[F[_]](
ops: List[Pos[P.OperationDefinition]],
operationName: Option[String]
)(implicit F: MonadError[F, (String, List[Caret])]): F[P.OperationDefinition] =
(ops, operationName) match {
case (Nil, _) => F.raiseError((s"no operations provided", Nil))
case (x :: Nil, _) => F.pure(x.value)
case (xs, _) if xs.exists {
case Pos(_, _: P.OperationDefinition.Simple) => true
case _ => false
} =>
F.raiseError((s"exactly one operation must be suplied for shorthand queries", xs.map(_.caret)))
case (xs, None) =>
F.raiseError((s"operation name must be supplied for multiple operations"), xs.map(_.caret))
case (xs, Some(name)) =>
val o = xs.collectFirst { case Pos(_, d: P.OperationDefinition.Detailed) if d.name.contains(name) => d }
F.fromOption(o, (s"unable to find operation $name", xs.map(_.caret)))
}
def operationType(od: P.OperationDefinition) =
od match {
case P.OperationDefinition.Simple(_) => P.OperationType.Query
case P.OperationDefinition.Detailed(ot, _, _, _, _) => ot
}
// TODO add another phase after finding the OperationDefinition and before this,
// that checks all that variables have been used
def prepareParts[F[_], G[_]: Applicative](
op: P.OperationDefinition,
frags: List[Pos[P.FragmentDefinition]],
schema: Schema[G, ?, ?, ?],
variableMap: Map[String, Json]
)(implicit
S: Stateful[F, Prep],
F: MonadError[F, PositionalError],
D: Defer[F]
): F[(P.OperationType, NonEmptyList[PreparedField[G, Any]])] = {
val ot = operationType(op)
val rootSchema: F[Type[G, Any]] =
ot match {
// We sneak the introspection query in here
case P.OperationType.Query =>
val i: NonEmptyList[(String, Field[G, Unit, ?, ?])] = schema.shape.introspection
val q = schema.shape.query.asInstanceOf[Type[G, Any]]
F.pure(q.copy(fields = q.fields concatNel i.map { case (k, v) => k -> v.contramap[Any](_ => ()) }))
case P.OperationType.Mutation =>
raiseOpt(schema.shape.mutation.map(_.asInstanceOf[Type[G, Any]]), "no mutation defined in schema", None)
case P.OperationType.Subscription =>
raiseOpt(schema.shape.subscription.map(_.asInstanceOf[Type[G, Any]]), "no subscription defined in schema", None)
}
val rootTypename =
ot match {
case P.OperationType.Query => "Query"
case P.OperationType.Mutation => "Mutation"
case P.OperationType.Subscription => "Subscription"
}
val selF = op match {
case P.OperationDefinition.Simple(sel) => F.pure((sel, Map.empty[String, (In[Any], Any)]))
case P.OperationDefinition.Detailed(_, _, vdsO, _, sel) =>
val varMapF =
vdsO.toList
.flatMap(_.nel.toList)
.traverse { case Pos(caret, vd) =>
def getTpe(p: P.Type, optional: Boolean = true): F[In[Any]] = {
def opt(tpe: In[Any]): In[Any] =
if (optional) ast.InOpt(tpe).asInstanceOf[In[Any]] else tpe
p match {
case P.Type.Named(name) =>
raiseOpt(schema.shape.discover.inputs.get(name).asInstanceOf[Option[In[Any]]], s"type $name does not exist", None)
.map(opt)
case P.Type.List(of) =>
getTpe(of).map(ast.InArr[Any, Any](_, _.asRight).asInstanceOf[In[Any]]).map(opt)
case P.Type.NonNull(of) => getTpe(of, false)
}
}
getTpe(vd.tpe).flatMap { tpe =>
val resolvedInput =
(variableMap.get(vd.name), vd.defaultValue) match {
case (Some(j), _) =>
parseInput[F, Any](valueToParserValue(Value.fromJson(j)), tpe, None, ambigiousEnum = true)
case (None, Some(default)) =>
parseInput[F, Any](default, tpe, None, ambigiousEnum = false)
case (None, None) =>
tpe match {
case InOpt(_) => F.pure(None.asInstanceOf[Any])
case _ =>
raise[F, Any](s"Variable '$$${vd.name}' is required but was not provided.", Some(caret))
}
}
resolvedInput.map(v => vd.name -> ((tpe, v)))
}
}
.map(_.toMap)
varMapF.tupleLeft(sel)
}
selF.flatMap { case (sel, vm) =>
val fa = rootSchema.flatMap { root =>
prepareSelections[F, G](
root.asInstanceOf[Type[G, Any]],
sel,
vm,
frags.map(f => f.value.name -> f).toMap,
rootTypename,
schema.shape.discover
)
}
fa tupleLeft ot
}
}
type H[A] = StateT[EitherT[Eval, PositionalError, *], Prep, A]
def prepare[F[_]: Applicative](
executabels: NonEmptyList[P.ExecutableDefinition],
schema: Schema[F, ?, ?, ?],
variableMap: Map[String, Json],
operationName: Option[String]
): Either[PositionalError, (P.OperationType, NonEmptyList[PreparedField[F, Any]])] = {
val (ops, frags) = executabels.toList.partitionEither {
case P.ExecutableDefinition.Operation(op) => Left(op)
case P.ExecutableDefinition.Fragment(frag) => Right(frag)
}
getOperationDefinition[Either[(String, List[Caret]), *]](ops, operationName) match {
case Left((e, carets)) => Left(PositionalError(PrepCursor.empty, carets, e))
case Right(op) =>
prepareParts[H, F](op, frags, schema, variableMap)
.runA(Prep.empty)
.value
.value
}
}
}