/
DgsGraphQLMetricsInstrumentation.kt
390 lines (347 loc) · 16 KB
/
DgsGraphQLMetricsInstrumentation.kt
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
package com.netflix.graphql.dgs.metrics.micrometer
import com.netflix.graphql.dgs.Internal
import com.netflix.graphql.dgs.internal.DgsSchemaProvider
import com.netflix.graphql.dgs.metrics.DgsMetrics.GqlMetric
import com.netflix.graphql.dgs.metrics.DgsMetrics.GqlTag
import com.netflix.graphql.dgs.metrics.micrometer.tagging.DgsGraphQLMetricsTagsProvider
import com.netflix.graphql.dgs.metrics.micrometer.utils.QuerySignatureRepository
import com.netflix.graphql.types.errors.ErrorType
import graphql.ExecutionInput
import graphql.ExecutionResult
import graphql.GraphQLError
import graphql.InvalidSyntaxError
import graphql.analysis.QueryTraverser
import graphql.analysis.QueryVisitorFieldEnvironment
import graphql.analysis.QueryVisitorStub
import graphql.execution.instrumentation.*
import graphql.execution.instrumentation.SimpleInstrumentationContext.whenCompleted
import graphql.execution.instrumentation.parameters.InstrumentationCreateStateParameters
import graphql.execution.instrumentation.parameters.InstrumentationExecuteOperationParameters
import graphql.execution.instrumentation.parameters.InstrumentationExecutionParameters
import graphql.execution.instrumentation.parameters.InstrumentationFieldFetchParameters
import graphql.execution.instrumentation.parameters.InstrumentationValidationParameters
import graphql.schema.DataFetcher
import graphql.schema.GraphQLNonNull
import graphql.schema.GraphQLObjectType
import graphql.validation.ValidationError
import io.micrometer.core.instrument.MeterRegistry
import io.micrometer.core.instrument.Tag
import io.micrometer.core.instrument.Tags
import io.micrometer.core.instrument.Timer
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.*
import java.util.Optional
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CompletionStage
class DgsGraphQLMetricsInstrumentation(
private val schemaProvider: DgsSchemaProvider,
private val registrySupplier: DgsMeterRegistrySupplier,
private val tagsProvider: DgsGraphQLMetricsTagsProvider,
private val properties: DgsGraphQLMetricsProperties,
private val limitedTagMetricResolver: LimitedTagMetricResolver,
private val optQuerySignatureRepository: Optional<QuerySignatureRepository> = Optional.empty()
) : SimpleInstrumentation() {
companion object {
private val log: Logger = LoggerFactory.getLogger(DgsGraphQLMetricsInstrumentation::class.java)
}
override fun createState(parameters: InstrumentationCreateStateParameters): InstrumentationState {
return MetricsInstrumentationState(
registrySupplier.get(),
limitedTagMetricResolver
)
}
override fun beginExecution(
parameters: InstrumentationExecutionParameters,
state: InstrumentationState
): InstrumentationContext<ExecutionResult> {
val miState: MetricsInstrumentationState = state as MetricsInstrumentationState
miState.startTimer()
miState.operationName = Optional.ofNullable(parameters.operation)
miState.isIntrospectionQuery = QueryUtils.isIntrospectionQuery(parameters.executionInput)
return object : SimpleInstrumentationContext<ExecutionResult>() {
override fun onDispatched(result: CompletableFuture<ExecutionResult>?) {
super.onDispatched(result)
}
override fun onCompleted(result: ExecutionResult, exc: Throwable?) {
miState.stopTimer(
properties.autotime
.builder(GqlMetric.QUERY.key)
.tags(tagsProvider.getContextualTags())
.tags(tagsProvider.getExecutionTags(parameters, result, exc))
.tags(miState.tags())
)
}
}
}
override fun instrumentExecutionResult(
executionResult: ExecutionResult,
parameters: InstrumentationExecutionParameters,
state: InstrumentationState
): CompletableFuture<ExecutionResult> {
val miState: MetricsInstrumentationState = state as MetricsInstrumentationState
val tags =
Tags.empty()
.and(tagsProvider.getContextualTags())
.and(tagsProvider.getExecutionTags(parameters, executionResult, null))
.and(miState.tags())
ErrorUtils
.sanitizeErrorPaths(executionResult)
.forEach {
registrySupplier
.get()
.counter(
GqlMetric.ERROR.key,
tags.and(GqlTag.PATH.key, it.path)
.and(GqlTag.ERROR_CODE.key, it.type)
.and(GqlTag.ERROR_DETAIL.key, it.detail)
).increment()
}
return CompletableFuture.completedFuture(executionResult)
}
override fun instrumentDataFetcher(
dataFetcher: DataFetcher<*>,
parameters: InstrumentationFieldFetchParameters,
state: InstrumentationState
): DataFetcher<*> {
val miState: MetricsInstrumentationState = state as MetricsInstrumentationState
val gqlField = TagUtils.resolveDataFetcherTagValue(parameters)
if (parameters.isTrivialDataFetcher ||
miState.isIntrospectionQuery ||
TagUtils.shouldIgnoreTag(gqlField) ||
!schemaProvider.isFieldInstrumentationEnabled(gqlField)
) {
return dataFetcher
}
return DataFetcher { environment ->
val registry = registrySupplier.get()
val baseTags =
Tags.of(GqlTag.FIELD.key, gqlField)
.and(tagsProvider.getContextualTags())
.and(miState.tags())
val sampler = Timer.start(registry)
try {
val result = dataFetcher.get(environment)
if (result is CompletionStage<*>) {
result.whenComplete { _, error ->
recordDataFetcherMetrics(
registry,
sampler,
parameters,
error,
baseTags
)
}
} else {
recordDataFetcherMetrics(registry, sampler, parameters, null, baseTags)
}
result
} catch (throwable: Throwable) {
recordDataFetcherMetrics(registry, sampler, parameters, throwable, baseTags)
throw throwable
}
}
}
/**
* Port the implementation from MaxQueryComplexityInstrumentation in graphql-java and store the computed complexity
* in the MetricsInstrumentationState for access to add tags to metrics.
*/
override fun beginValidation(
parameters: InstrumentationValidationParameters,
state: InstrumentationState
): InstrumentationContext<List<ValidationError>> {
return whenCompleted { errors, throwable ->
if (errors != null && errors.isNotEmpty() || throwable != null) {
return@whenCompleted
}
val miState: MetricsInstrumentationState = state as MetricsInstrumentationState
if (parameters.document != null) {
miState.querySignature = optQuerySignatureRepository.flatMap { it.get(parameters.document, parameters) }
}
}
}
override fun beginExecuteOperation(
parameters: InstrumentationExecuteOperationParameters,
state: InstrumentationState
): InstrumentationContext<ExecutionResult> {
val miState: MetricsInstrumentationState = state as MetricsInstrumentationState
if (parameters.executionContext.getRoot<Any>() == null) {
miState.operation = Optional.of(parameters.executionContext.operationDefinition.operation.name.uppercase())
if (!miState.operationName.isPresent) {
miState.operationName = Optional.ofNullable(parameters.executionContext.operationDefinition?.name)
}
}
miState.queryComplexity = ComplexityUtils.resolveComplexity(parameters)
return super.beginExecuteOperation(parameters)
}
private fun recordDataFetcherMetrics(
registry: MeterRegistry,
timerSampler: Timer.Sample,
parameters: InstrumentationFieldFetchParameters,
error: Throwable?,
baseTags: Iterable<Tag>
) {
val recordedTags = Tags
.of(baseTags)
.and(tagsProvider.getFieldFetchTags(parameters, error))
timerSampler.stop(
properties
.autotime
.builder(GqlMetric.RESOLVER.key)
.tags(recordedTags)
.register(registry)
)
}
class MetricsInstrumentationState(
private val registry: MeterRegistry,
private val limitedTagMetricResolver: LimitedTagMetricResolver
) : InstrumentationState {
private var timerSample: Optional<Timer.Sample> = Optional.empty()
var isIntrospectionQuery = false
var queryComplexity: Optional<Int> = Optional.empty()
var operation: Optional<String> = Optional.empty()
var operationName: Optional<String> = Optional.empty()
var querySignature: Optional<QuerySignatureRepository.QuerySignature> = Optional.empty()
fun startTimer() {
this.timerSample = Optional.of(Timer.start(this.registry))
}
fun stopTimer(timer: Timer.Builder) {
this.timerSample.ifPresent { it.stop(timer.register(this.registry)) }
}
@Internal
fun tags(): Tags {
return Tags
.of(
GqlTag.QUERY_COMPLEXITY.key,
queryComplexity.map { it.toString() }.orElse(TagUtils.TAG_VALUE_NONE)
)
.and(
GqlTag.OPERATION.key,
operation.map { it.uppercase() }.orElse(TagUtils.TAG_VALUE_NONE)
)
.and(
limitedTagMetricResolver.tags(
GqlTag.OPERATION_NAME.key,
operationName.orElse(TagUtils.TAG_VALUE_ANONYMOUS)
)
)
.and(
limitedTagMetricResolver.tags(
GqlTag.QUERY_SIG_HASH.key,
querySignature.map { it.hash }.orElse(TagUtils.TAG_VALUE_NONE)
)
)
}
}
internal object QueryUtils {
fun isIntrospectionQuery(input: ExecutionInput): Boolean {
return input.query.contains("query IntrospectionQuery") || input.operationName == "IntrospectionQuery"
}
}
internal object ComplexityUtils {
private val queryComplexityBuckets = listOf(5, 10, 25, 50, 100, 200, 500, 1000, 2000, 5000, 10000)
fun resolveComplexity(parameters: InstrumentationExecuteOperationParameters): Optional<Int> {
try {
val queryTraverser: QueryTraverser = newQueryTraverser(parameters)
val valuesByParent: MutableMap<QueryVisitorFieldEnvironment?, Int?> =
LinkedHashMap<QueryVisitorFieldEnvironment?, Int?>()
queryTraverser.visitPostOrder(object : QueryVisitorStub() {
override fun visitField(env: QueryVisitorFieldEnvironment?) {
val childComplexity = valuesByParent.getOrDefault(env, 0)
val value = calculateComplexity(env!!, childComplexity!!)
valuesByParent.compute(env.parentEnvironment) { _, oldValue -> Optional.ofNullable(oldValue).orElse(0) + value }
}
})
val totalComplexity = valuesByParent.getOrDefault(null, 0)
return Optional.ofNullable(queryComplexityBuckets.filter { totalComplexity!! < it }.minOrNull())
} catch (error: Throwable) {
log.error("Unable to compute the query complexity!", error)
return Optional.empty()
}
}
/**
* Port from MaxQueryComplexityInstrumentation in graphql-java
*/
fun calculateComplexity(
queryVisitorFieldEnvironment: QueryVisitorFieldEnvironment,
childComplexity: Int,
fieldComplexityCalculator: (Int) -> Int = { cx -> 1 + cx }
): Int {
if (queryVisitorFieldEnvironment.isTypeNameIntrospectionField) {
return 0
}
return fieldComplexityCalculator(childComplexity)
}
private fun newQueryTraverser(parameters: InstrumentationExecuteOperationParameters): QueryTraverser {
return QueryTraverser
.newQueryTraverser()
.schema(parameters.executionContext.graphQLSchema)
.document(parameters.executionContext.document)
.operationName(parameters.executionContext.operationDefinition.name)
.variables(parameters.executionContext.variables)
.build()
}
}
internal object TagUtils {
private val instrumentationIgnores = setOf("__typename", "__Schema", "__Type")
const val TAG_VALUE_ANONYMOUS = "anonymous"
const val TAG_VALUE_NONE = "none"
const val TAG_VALUE_UNKNOWN = "unknown"
fun resolveDataFetcherTagValue(parameters: InstrumentationFieldFetchParameters): String {
val type = parameters.executionStepInfo.parent.type
val parentType = if (type is GraphQLNonNull) {
type.wrappedType as GraphQLObjectType
} else {
type as GraphQLObjectType
}
return "${parentType.name}.${parameters.executionStepInfo.field.singleField.name}"
}
fun shouldIgnoreTag(tag: String): Boolean {
return instrumentationIgnores.find { tag.contains(it) } != null
}
}
internal object ErrorUtils {
fun sanitizeErrorPaths(executionResult: ExecutionResult): Collection<ErrorTagValues> {
var dedupeErrorPaths: Map<String, ErrorTagValues> = emptyMap()
executionResult.errors.forEach { error ->
val errorPath: List<Any>
val errorType: String
val errorDetail = errorDetailExtension(error)
when (error) {
is ValidationError -> {
errorPath = error.queryPath ?: emptyList()
errorType = ErrorType.BAD_REQUEST.name
}
is InvalidSyntaxError -> {
errorPath = emptyList()
errorType = ErrorType.BAD_REQUEST.name
}
else -> {
errorPath = error.path ?: emptyList()
errorType = errorTypeExtension(error)
}
}
val sanitizedPath = errorPath.map { iter ->
if (iter.toString().toIntOrNull() != null) "number"
else iter.toString()
}.toString()
// in case of batch loaders, eliminate duplicate instances of the same error at different indices
if (!dedupeErrorPaths.contains(sanitizedPath)) {
dedupeErrorPaths = dedupeErrorPaths
.plus(Pair(sanitizedPath, ErrorTagValues(sanitizedPath, errorType, errorDetail)))
}
}
return dedupeErrorPaths.values
}
private fun <T : GraphQLError> errorTypeExtension(error: T): String {
return extension(error, "errorType", TagUtils.TAG_VALUE_UNKNOWN)
}
private fun <T : GraphQLError> errorDetailExtension(error: T): String {
return extension(error, "errorDetail", TagUtils.TAG_VALUE_NONE)
}
private fun <T : GraphQLError> extension(error: T, key: String, default: String): String {
return error.extensions?.get(key)?.toString() ?: default
}
internal data class ErrorTagValues(val path: String, val type: String, val detail: String)
}
}