-
Notifications
You must be signed in to change notification settings - Fork 27
/
mapping.scala
476 lines (396 loc) · 18.1 KB
/
mapping.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
// Copyright (c) 2016-2020 Association of Universities for Research in Astronomy, Inc. (AURA)
// For license information see LICENSE or https://opensource.org/licenses/BSD-3-Clause
package edu.gemini.grackle
import scala.collection.Factory
import cats.Monad
import cats.data.{Ior, IorT}
import cats.implicits._
import fs2.{ Stream, Compiler }
import io.circe.{Encoder, Json}
import io.circe.syntax._
import org.tpolecat.sourcepos.SourcePos
import org.tpolecat.typename._
import Cursor.{AbstractCursor, Context, Env}
import Query.Select
import QueryCompiler.{ComponentElaborator, SelectElaborator, IntrospectionLevel}
import QueryInterpreter.mkErrorResult
import IntrospectionLevel._
trait QueryExecutor[F[_], T] { outer =>
def compileAndRun(text: String, name: Option[String] = None, untypedVars: Option[Json] = None, introspectionLevel: IntrospectionLevel = Full, env: Env = Env.empty)(
implicit sc: Compiler[F,F]
): F[T] =
compileAndRunOne(text, name, untypedVars, introspectionLevel, env)
def compileAndRunAll(text: String, name: Option[String] = None, untypedVars: Option[Json] = None, introspectionLevel: IntrospectionLevel = Full, env: Env = Env.empty): Stream[F,T]
def compileAndRunOne(text: String, name: Option[String] = None, untypedVars: Option[Json] = None, introspectionLevel: IntrospectionLevel = Full, env: Env = Env.empty)(
implicit sc: Compiler[F,F]
): F[T]
}
abstract class Mapping[F[_]] extends QueryExecutor[F, Json] {
implicit val M: Monad[F]
val schema: Schema
val typeMappings: List[TypeMapping]
def run(query: Query, rootTpe: Type, env: Env): Stream[F,Json] =
interpreter.run(query, rootTpe, env)
def run(op: Operation, env: Env = Env.empty): Stream[F,Json] =
run(op.query, op.rootTpe, env)
def compileAndRunOne(text: String, name: Option[String] = None, untypedVars: Option[Json] = None, introspectionLevel: IntrospectionLevel = Full, env: Env = Env.empty)(
implicit sc: Compiler[F,F]
): F[Json] =
compileAndRunAll(text, name, untypedVars, introspectionLevel, env).compile.toList.map {
case List(j) => j
case Nil => QueryInterpreter.mkError("Result stream was empty.").asJson
case js => QueryInterpreter.mkError(s"Result stream contained ${js.length} results; expected exactly one.").asJson
}
def compileAndRunAll(text: String, name: Option[String] = None, untypedVars: Option[Json] = None, introspectionLevel: IntrospectionLevel = Full, env: Env = Env.empty): Stream[F,Json] =
compiler.compile(text, name, untypedVars, introspectionLevel) match {
case Ior.Right(operation) =>
run(operation.query, operation.rootTpe, env)
case invalid =>
QueryInterpreter.mkInvalidResponse(invalid).pure[Stream[F,*]]
}
/** Yields a `Cursor` focused on the top level operation type of the query */
def defaultRootCursor(query: Query, tpe: Type, env: Env): F[Result[(Query, Cursor)]] =
Result((query, RootCursor(Context(tpe), None, env))).pure[F].widen
/**
* Root `Cursor` focussed on the top level operation of a query
*
* Construction of mapping-specific cursors is handled by delegation to
* `mkCursorForField which is typically overridden in `Mapping` subtypes.
*/
case class RootCursor(context: Context, parent: Option[Cursor], env: Env) extends AbstractCursor {
def withEnv(env0: Env): Cursor = copy(env = env.add(env0))
def focus: Any = ()
override def hasField(fieldName: String): Boolean =
fieldMapping(context, fieldName).isDefined
override def field(fieldName: String, resultName: Option[String]): Result[Cursor] =
mkCursorForField(this, fieldName, resultName)
}
/**
* Yields a `Cursor` suitable for traversing the query result corresponding to
* the `fieldName` child of `parent`.
*
* This method is typically overridden in and delegated to by `Mapping` subtypes.
*/
def mkCursorForField(parent: Cursor, fieldName: String, resultName: Option[String]): Result[Cursor] = {
val context = parent.context
val fieldContext = context.forFieldOrAttribute(fieldName, resultName)
def mkLeafCursor(focus: Any): Result[Cursor] =
LeafCursor(fieldContext, focus, Some(parent), parent.env).rightIor
fieldMapping(context, fieldName) match {
case Some(_ : RootEffect) =>
mkLeafCursor(parent.focus)
case Some(CursorField(_, f, _, _, _)) =>
f(parent).flatMap(res => mkLeafCursor(res))
case _ =>
mkErrorResult(s"No field '$fieldName' for type ${parent.tpe}")
}
}
def typeMapping(tpe: NamedType): Option[TypeMapping] =
typeMappingIndex.get(tpe.name)
private lazy val typeMappingIndex =
typeMappings.flatMap(tm => tm.tpe.asNamed.map(tpe => (tpe.name, tm)).toList).toMap
val validator: MappingValidator =
MappingValidator(this)
def objectMapping(context: Context): Option[ObjectMapping] =
context.tpe.underlyingObject.flatMap { obj =>
obj.asNamed.flatMap(typeMapping) match {
case Some(om: ObjectMapping) => Some(om)
case Some(pm: PrefixedMapping) =>
val revPath = context.path.reverse
pm.mappings.filter(m => revPath.endsWith(m._1)).maxByOption(_._1.length).map(_._2)
case _ => None
}
}
def fieldMapping(context: Context, fieldName: String): Option[FieldMapping] =
objectMapping(context).flatMap(_.fieldMapping(fieldName)).orElse {
context.tpe.underlyingObject match {
case Some(ot: ObjectType) =>
ot.interfaces.collectFirstSome(nt => fieldMapping(context.asType(nt), fieldName))
case _ => None
}
}
/** Yields the `RootEffect`, if any, associated with `fieldName`. */
def rootEffect(context: Context, fieldName: String): Option[RootEffect] =
fieldMapping(context, fieldName).collect {
case re: RootEffect => re
}
def leafMapping[T](tpe: Type): Option[LeafMapping[T]] =
typeMappings.collectFirst {
case lm@LeafMapping(tpe0, _) if tpe0 =:= tpe => lm.asInstanceOf[LeafMapping[T]]
}
/**
* True if the supplied type is a leaf with respect to the GraphQL schema
* or mapping, false otherwise.
*/
def isLeaf(tpe: Type): Boolean = tpe.underlying match {
case (_: ScalarType)|(_: EnumType) => true
case tpe => leafMapping(tpe).isDefined
}
def encoderForLeaf(tpe: Type): Option[Encoder[Any]] =
encoderMemo.get(tpe.dealias)
private lazy val encoderMemo: scala.collection.immutable.Map[Type, Encoder[Any]] = {
val intTypeEncoder: Encoder[Any] =
new Encoder[Any] {
def apply(i: Any): Json = i match {
case i: Int => Json.fromInt(i)
case l: Long => Json.fromLong(l)
case other => sys.error(s"Not an Int: $other")
}
}
val floatTypeEncoder: Encoder[Any] =
new Encoder[Any] {
def apply(f: Any): Json = f match {
case f: Float => Json.fromFloat(f).getOrElse(sys.error(s"Unrepresentable float $f"))
case d: Double => Json.fromDouble(d).getOrElse(sys.error(s"Unrepresentable double $d"))
case d: BigDecimal => Json.fromBigDecimal(d)
case other => sys.error(s"Not a Float: $other")
}
}
val definedEncoders: List[(Type, Encoder[Any])] =
typeMappings.collect { case lm: LeafMapping[_] => (lm.tpe.dealias -> lm.encoder.asInstanceOf[Encoder[Any]]) }
val defaultEncoders: List[(Type, Encoder[Any])] =
List(
ScalarType.StringType -> Encoder[String].asInstanceOf[Encoder[Any]],
ScalarType.IntType -> intTypeEncoder,
ScalarType.FloatType -> floatTypeEncoder,
ScalarType.BooleanType -> Encoder[Boolean].asInstanceOf[Encoder[Any]],
ScalarType.IDType -> Encoder[String].asInstanceOf[Encoder[Any]]
)
(definedEncoders ++ defaultEncoders).toMap
}
trait TypeMapping extends Product with Serializable {
def tpe: Type
def pos: SourcePos
}
case class PrimitiveMapping(tpe: Type)(implicit val pos: SourcePos) extends TypeMapping
abstract class ObjectMapping extends TypeMapping {
private lazy val fieldMappingIndex = fieldMappings.map(fm => (fm.fieldName, fm)).toMap
def fieldMappings: List[FieldMapping]
def fieldMapping(fieldName: String): Option[FieldMapping] = fieldMappingIndex.get(fieldName)
}
object ObjectMapping {
case class DefaultObjectMapping(tpe: Type, fieldMappings: List[FieldMapping])(
implicit val pos: SourcePos
) extends ObjectMapping
def apply(tpe: Type, fieldMappings: List[FieldMapping])(
implicit pos: SourcePos
): ObjectMapping =
DefaultObjectMapping(tpe, fieldMappings.map(_.withParent(tpe)))
}
case class PrefixedMapping(tpe: Type, mappings: List[(List[String], ObjectMapping)])(
implicit val pos: SourcePos
) extends TypeMapping
trait FieldMapping extends Product with Serializable {
def fieldName: String
def hidden: Boolean
def withParent(tpe: Type): FieldMapping
def pos: SourcePos
}
case class PrimitiveField(fieldName: String, hidden: Boolean = false)(implicit val pos: SourcePos) extends FieldMapping {
def withParent(tpe: Type): PrimitiveField = this
}
/**
* Root effects can perform an intial effect prior to computing the resulting
* `Cursor` and effective `Query`.
*
* Convenience methods are provided to cover the cases where only one of the
* query or the cursor are computed, and for where the computation is one-shot
* or a Stream. One-shot effects are used to perform initial effectful setup
* for a query or to perform the effect associated with a GraphQL mutation.
* Stream effects are used for GraphQL subscriptions.
*
* If only the query is computed the default root cursor for the mapping will
* be used. If only the cursor is computed the client query (after elaboration)
* is used unmodified ... in this case results of the performed effect can only
* be passed to the result construction stage via the environment associated
* with the returned cursor.
*/
case class RootEffect private (fieldName: String, effect: (Query, Path, Env) => Stream[F, Result[(Query, Cursor)]])(implicit val pos: SourcePos) extends FieldMapping {
def hidden = false
def withParent(tpe: Type): RootEffect = this
}
object RootEffect {
/**
* Yields a `RootEffect` which performs both an initial effect and yields an effect-specific query and
* corresponding root cursor.
*/
def apply(fieldName: String)(effect: (Query, Path, Env) => Stream[F, Result[(Query, Cursor)]])(implicit pos: SourcePos, di: DummyImplicit): RootEffect =
new RootEffect(fieldName, effect)
/**
* Yields a `RootEffect` which performs an initial effect and yields an effect-specific root cursor.
*/
def computeCursor(fieldName: String)(effect: (Query, Path, Env) => F[Result[Cursor]])(implicit pos: SourcePos): RootEffect =
new RootEffect(
fieldName,
(query, path, env) => Stream.eval(effect(query, path, env).map(_.map(c => (query, c))))
)
/**
* Yields a `RootEffect` which yields a stream of effect-specific root cursors.
*
* This form of effect is typically used to implement GraphQL subscriptions.
*/
def computeCursorStream(fieldName: String)(effect: (Query, Path, Env) => Stream[F, Result[Cursor]])(implicit pos: SourcePos): RootEffect =
new RootEffect(
fieldName,
(query, path, env) => effect(query, path, env).map(_.map(c => (query, c)))
)
/**
* Yields a `RootEffect` which performs an initial effect and yields an effect-specific query
* which is executed with respect to the default root cursor for the corresponding `Mapping`.
*/
def computeQuery(fieldName: String)(effect: (Query, Path, Env) => F[Result[Query]])(implicit pos: SourcePos): RootEffect =
new RootEffect(
fieldName,
(query, path, env) =>
Stream.eval(
(for {
q <- IorT(effect(query, path, env))
qc <- IorT(defaultRootCursor(q, path.rootTpe, env))
} yield qc).value
)
)
/**
* Yields a `RootEffect` which yields a stream of effect-specific queries
* which are executed with respect to the default root cursor for the
* corresponding `Mapping`.
*
* This form of effect is typically used to implement GraphQL subscriptions.
*/
def computeQueryStream(fieldName: String)(effect: (Query, Path, Env) => Stream[F, Result[Query]])(implicit pos: SourcePos): RootEffect =
new RootEffect(
fieldName,
(query, path, env) =>
effect(query, path, env).flatMap(rq =>
Stream.eval(
(for {
q <- IorT(rq.pure[F])
qc <- IorT(defaultRootCursor(q, path.rootTpe, env))
} yield qc).value
)
)
)
}
trait LeafMapping[T] extends TypeMapping {
def tpe: Type
def encoder: Encoder[T]
def scalaTypeName: String
def pos: SourcePos
}
object LeafMapping {
case class DefaultLeafMapping[T](tpe: Type, encoder: Encoder[T], scalaTypeName: String)(
implicit val pos: SourcePos
) extends LeafMapping[T]
def apply[T: TypeName](tpe: Type)(implicit encoder: Encoder[T], pos: SourcePos): LeafMapping[T] =
DefaultLeafMapping(tpe, encoder, typeName)
def unapply[T](lm: LeafMapping[T]): Option[(Type, Encoder[T])] =
Some((lm.tpe, lm.encoder))
}
case class CursorField[T](fieldName: String, f: Cursor => Result[T], encoder: Encoder[T], required: List[String], hidden: Boolean)(
implicit val pos: SourcePos
) extends FieldMapping {
def withParent(tpe: Type): CursorField[T] = this
}
object CursorField {
def apply[T](fieldName: String, f: Cursor => Result[T], required: List[String] = Nil, hidden: Boolean = false)(implicit encoder: Encoder[T], di: DummyImplicit): CursorField[T] =
new CursorField(fieldName, f, encoder, required, hidden)
}
case class Delegate(
fieldName: String,
interpreter: Mapping[F],
join: (Cursor, Query) => Result[Query] = ComponentElaborator.TrivialJoin
)(implicit val pos: SourcePos) extends FieldMapping {
def hidden = false
def withParent(tpe: Type): Delegate = this
}
val selectElaborator: SelectElaborator = new SelectElaborator(Map.empty[TypeRef, PartialFunction[Select, Result[Query]]])
lazy val componentElaborator = {
val componentMappings =
typeMappings.flatMap {
case om: ObjectMapping =>
om.fieldMappings.collect {
case Delegate(fieldName, mapping, join) =>
ComponentElaborator.ComponentMapping(schema.ref(om.tpe.toString), fieldName, mapping, join)
}
case _ => Nil
}
ComponentElaborator(componentMappings)
}
def compilerPhases: List[QueryCompiler.Phase] = List(selectElaborator, componentElaborator)
lazy val compiler = new QueryCompiler(schema, compilerPhases)
val interpreter: QueryInterpreter[F] = new QueryInterpreter(this)
/** Cursor positioned at a GraphQL result leaf */
case class LeafCursor(context: Context, focus: Any, parent: Option[Cursor], env: Env) extends Cursor {
def withEnv(env0: Env): Cursor = copy(env = env.add(env0))
def mkChild(context: Context = context, focus: Any = focus): LeafCursor =
LeafCursor(context, focus, Some(this), Env.empty)
def isLeaf: Boolean = tpe.isLeaf
def asLeaf: Result[Json] =
encoderForLeaf(tpe).map(enc => enc(focus).rightIor).getOrElse(mkErrorResult(
s"Cannot encode value $focus at ${context.path.reverse.mkString("/")} (of GraphQL type ${context.tpe}). Did you forget a LeafMapping?".stripMargin.trim
))
def preunique: Result[Cursor] = {
val listTpe = tpe.nonNull.list
focus match {
case _: List[_] => mkChild(context.asType(listTpe), focus).rightIor
case _ =>
mkErrorResult(s"Expected List type, found $focus for ${listTpe}")
}
}
def isList: Boolean =
tpe match {
case ListType(_) => true
case _ => false
}
def asList[C](factory: Factory[Cursor, C]): Result[C] = (tpe, focus) match {
case (ListType(tpe), it: List[_]) => it.view.map(f => mkChild(context.asType(tpe), focus = f)).to(factory).rightIor
case _ => mkErrorResult(s"Expected List type, found $tpe")
}
def listSize: Result[Int] = (tpe, focus) match {
case (ListType(_), it: List[_]) => it.size.rightIor
case _ => mkErrorResult(s"Expected List type, found $tpe")
}
def isNullable: Boolean =
tpe match {
case NullableType(_) => true
case _ => false
}
def asNullable: Result[Option[Cursor]] =
(tpe, focus) match {
case (NullableType(_), None) => None.rightIor
case (NullableType(tpe), Some(v)) => Some(mkChild(context.asType(tpe), focus = v)).rightIor
case _ => mkErrorResult(s"Not nullable at ${context.path}")
}
def isDefined: Result[Boolean] =
(tpe, focus) match {
case (NullableType(_), opt: Option[_]) => opt.isDefined.rightIor
case _ => mkErrorResult(s"Not nullable at ${context.path}")
}
def narrowsTo(subtpe: TypeRef): Boolean = false
def narrow(subtpe: TypeRef): Result[Cursor] =
mkErrorResult(s"Cannot narrow $tpe to $subtpe")
def hasField(fieldName: String): Boolean = false
def field(fieldName: String, resultName: Option[String]): Result[Cursor] =
mkErrorResult(s"Cannot select field '$fieldName' from leaf type $tpe")
}
}
abstract class ComposedMapping[F[_]](implicit val M: Monad[F]) extends Mapping[F] {
override def mkCursorForField(parent: Cursor, fieldName: String, resultName: Option[String]): Result[Cursor] = {
val context = parent.context
val fieldContext = context.forFieldOrAttribute(fieldName, resultName)
fieldMapping(context, fieldName) match {
case Some(_) =>
ComposedCursor(fieldContext, parent.env).rightIor
case _ =>
super.mkCursorForField(parent, fieldName, resultName)
}
}
case class ComposedCursor(context: Context, env: Env) extends AbstractCursor {
val focus = null
val parent = None
def withEnv(env0: Env): Cursor = copy(env = env.add(env0))
override def hasField(fieldName: String): Boolean =
fieldMapping(context, fieldName).isDefined
override def field(fieldName: String, resultName: Option[String]): Result[Cursor] =
mkCursorForField(this, fieldName, resultName)
}
}