-
Notifications
You must be signed in to change notification settings - Fork 3
/
Planner.scala
309 lines (269 loc) · 10.7 KB
/
Planner.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
/*
* Copyright 2022 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 gql.resolver._
import cats.implicits._
import cats.data._
import gql.PreparedQuery.PreparedDataField
import gql.PreparedQuery.PreparedFragField
import gql.PreparedQuery.PreparedLeaf
import gql.PreparedQuery.PreparedList
import gql.PreparedQuery.PreparedOption
import gql.PreparedQuery.Selection
import scala.collection.immutable.TreeSet
import cats._
import scala.io.AnsiColor
trait Planner[F[_]] { self =>
def plan(naive: Planner.NodeTree): F[Planner.NodeTree]
def mapK[G[_]](fk: F ~> G): Planner[G] =
new Planner[G] {
def plan(naive: Planner.NodeTree): G[Planner.NodeTree] = fk(self.plan(naive))
}
}
object Planner {
final case class Node(
name: String,
end: Double,
cost: Double,
elemCost: Double,
children: List[Node],
batcher: Option[BatchResolver.ResolverKey],
edgeId: PreparedQuery.EdgeId
) {
lazy val start = end - cost
}
def costForPrepared[F[_]: Statistics](p: PreparedQuery.Prepared[F, Any], currentCost: Double)(implicit F: Monad[F]): F[List[Node]] =
p match {
case PreparedLeaf(_, _) => F.pure(Nil)
case Selection(fields) => costForFields[F](currentCost, fields).map(_.toList)
case PreparedList(cont, _) => costForCont[F](cont.edges.toList, cont.cont, currentCost)
case PreparedOption(cont) => costForCont[F](cont.edges.toList, cont.cont, currentCost)
}
def costForEdges[F[_]](pes: List[PreparedQuery.PreparedEdge.Edge[F]], cont: PreparedQuery.Prepared[F, Any], currentCost: Double)(implicit
stats: Statistics[F],
F: Monad[F]
): F[List[Node]] =
pes match {
case Nil => costForPrepared[F](cont, currentCost)
case x :: xs =>
val resolverKey = x.resolver match {
case PreparedQuery.PreparedResolver.Batch(BatchResolver(id, _)) => Some(id)
case _ => None
}
stats
.getStatsOpt(x.statisticsName)
.map {
case None => Statistics.Stats(100d, 5d)
case Some(x) => x
}
.flatMap { s =>
val end = currentCost + s.initialCost
val childrenF = costForEdges[F](xs, cont, end).map(_.toList)
childrenF.map { children =>
List(
Node(
x.statisticsName,
end,
s.initialCost,
s.extraElementCost,
children.toList,
resolverKey,
x.id
)
)
}
}
}
def costForCont[F[_]: Statistics: Monad](
edges: List[PreparedQuery.PreparedEdge[F]],
cont: PreparedQuery.Prepared[F, Any],
currentCost: Double
): F[List[Node]] =
costForEdges[F](
edges.toList.collect { case e: PreparedQuery.PreparedEdge.Edge[F] => e },
cont,
currentCost
)
def costForFields[F[_]](
currentCost: Double,
prepared: NonEmptyList[PreparedQuery.PreparedField[F, Any]]
)(implicit
F: Monad[F],
stats: Statistics[F]
): F[List[Node]] = {
prepared.toList.flatTraverse {
case PreparedDataField(_, _, _, cont) => costForCont[F](cont.edges.toList, cont.cont, currentCost)
case PreparedFragField(_, _, _, selection) => costForFields[F](currentCost, selection.fields)
}
}
def costTree[F[_]: Monad](
prepared: NonEmptyList[PreparedQuery.PreparedField[F, Any]]
)(implicit stats: Statistics[F]): F[NodeTree] =
costForFields[F](0d, prepared).map(xs => NodeTree(xs.toList))
def apply[F[_]](implicit F: Applicative[F]) = new Planner[F] {
def plan(tree: NodeTree): F[NodeTree] = {
tree.root.toNel match {
case None => F.pure(tree.set(tree.root))
case Some(_) =>
val flatNodes = tree.flattened
val orderedFlatNodes = flatNodes.sortBy(_.end).reverse
val m = orderedFlatNodes.head.end
// go through every node sorted by end decending
// if the node has a batching name, move node to lastest possible batch (frees up most space for parents to move)
def go(
remaining: List[Node],
handled: Map[PreparedQuery.EdgeId, Node],
batchMap: Map[BatchResolver.ResolverKey, Eval[TreeSet[Double]]]
): Map[PreparedQuery.EdgeId, Node] =
remaining match {
case Nil => handled
case r :: rs =>
// the maximum amount we can move down is the child with smallest start
val maxEnd: Double = r.children match {
case Nil => m
case x :: xs =>
// use the already resolved if possible
val children = NonEmptyList(x, xs)
children.map(c => handled.get(c.edgeId).getOrElse(c).start).minimum
}
val (newEnd, newMap) =
r.batcher match {
// No batching, free up as much space as possible for parents to move
case None => (maxEnd, batchMap)
case Some(bn) =>
// Find nodes that we may move to:
// All nodes that end no later than the earliest of our children but end later than us
val compat =
batchMap
.get(bn)
.flatMap { m =>
val o = if (m.value.contains(maxEnd)) Some(maxEnd) else m.value.maxBefore(maxEnd)
o.filter(_ >= r.end)
}
.getOrElse(maxEnd)
val newSet =
batchMap.get(bn) match {
case None => Eval.later(TreeSet(r.end))
case Some(s) => s.map(_ + r.end)
}
val newMap = batchMap + (bn -> newSet)
(compat, newMap)
}
go(rs, handled + (r.edgeId -> r.copy(end = newEnd)), newMap)
}
val plannedMap = go(orderedFlatNodes.toList, Map.empty, Map.empty)
def reConstruct(ns: List[PreparedQuery.EdgeId]): Eval[List[Node]] = Eval.defer {
ns.traverse { n =>
val newN = plannedMap(n)
val newChildrenF = reConstruct(newN.children.map(_.edgeId)).map(_.toList)
newChildrenF.map(x => newN.copy(children = x))
}
}
F.pure(tree.set(reConstruct(tree.root.map(_.edgeId)).value))
}
}
}
final case class NodeTree(
root: List[Node],
source: Option[NodeTree] = None
) {
def set(newRoot: List[Node]): NodeTree =
NodeTree(newRoot, Some(this))
lazy val flattened: List[Node] = {
def go(xs: List[Node]): Eval[List[Node]] = Eval.defer {
xs.flatTraverse {
case n @ Node(_, _, _, _, Nil, _, _) => Eval.now(List(n))
case n @ Node(_, _, _, _, xs, _, _) => go(xs).map(n :: _)
}
}
go(root).value
}
lazy val batches: List[(BatchResolver.ResolverKey, NonEmptyChain[PreparedQuery.EdgeId])] =
flattened
.map(n => (n.batcher, n))
.collect { case (Some(batcherKey), node) => (batcherKey, node) }
.groupByNec { case (_, node) => node.end }
.toList
.flatMap { case (_, endGroup) =>
endGroup
.groupBy { case (batcherKey, _) => batcherKey }
.toSortedMap
.toList
.map { case (batcherKey, batch) =>
batcherKey -> batch.map { case (_, node) => node.edgeId }
}
}
def totalCost: Double = {
val thisFlat = flattened
val thisFlattenedMap = thisFlat.map(n => n.edgeId -> n).toMap
val thisBatches = batches.filter { case (_, edges) => edges.size > 1 }
val naiveCost = thisFlat.map(_.cost).sum
val batchSubtraction = thisBatches.map { case (_, xs) =>
// cost * (size - 1 )
thisFlattenedMap(xs.head).cost * (xs.size - 1)
}.sum
naiveCost - batchSubtraction
}
def show(showImprovement: Boolean = false, ansiColors: Boolean = false) = {
val (default, displaced) =
if (showImprovement)
source match {
case Some(x) => (x, Some(this))
case None => (this, None)
}
else (this, None)
val maxEnd = displaced.getOrElse(default).flattened.maxByOption(_.end).map(_.end).getOrElse(0d)
val (red, green, blue, reset) =
if (ansiColors) (AnsiColor.RED_B, AnsiColor.GREEN_B, AnsiColor.BLUE_B, AnsiColor.RESET)
else ("", "", "", "")
val prefix =
if (ansiColors)
displaced.as {
s"""|
|${red}old field schedule$reset
|${green}new field offset (deferral of execution)$reset
|""".stripMargin
}.mkString
else ""
val per = math.max((maxEnd / 40d), 1)
def go(default: List[Node], displacement: Map[PreparedQuery.EdgeId, Node]): String = {
default
.sortBy(_.edgeId.id)
.map { n =>
val disp = displacement.get(n.edgeId)
val basePrefix = " " * (n.start / per).toInt
val showDisp = disp
.filter(_.end.toInt != n.end.toInt)
.map { d =>
val pushedPrefix = blue + ">" * ((d.start - n.start) / per).toInt + green
s"$basePrefix${pushedPrefix}name: ${d.name}, cost: ${d.cost}, end: ${d.end}$reset"
}
val showHere =
s"$basePrefix${if (showDisp.isDefined) red else ""}name: ${n.name}, cost: ${n.cost}, end: ${n.end}$reset"
val all = showHere + showDisp.map("\n" + _).mkString
val children = go(n.children, disp.map(_.children.map(x => x.edgeId -> x).toMap).getOrElse(Map.empty))
all + "\n" + children
}
.mkString("")
}
prefix +
go(default.root, displaced.map(_.root.map(x => x.edgeId -> x).toMap).getOrElse(Map.empty))
}
}
object NodeTree {
implicit lazy val showForNodeTree: Show[NodeTree] = Show.show[NodeTree](_.show(showImprovement = true))
}
}