@effect-gql/opentelemetry 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +7 -0
- package/dist/context-propagation.d.ts +78 -0
- package/dist/context-propagation.d.ts.map +1 -0
- package/dist/context-propagation.js +125 -0
- package/dist/context-propagation.js.map +1 -0
- package/dist/index.d.ts +111 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +120 -0
- package/dist/index.js.map +1 -0
- package/dist/traced-router.d.ts +90 -0
- package/dist/traced-router.d.ts.map +1 -0
- package/dist/traced-router.js +154 -0
- package/dist/traced-router.js.map +1 -0
- package/dist/tracing-extension.d.ts +52 -0
- package/dist/tracing-extension.d.ts.map +1 -0
- package/dist/tracing-extension.js +110 -0
- package/dist/tracing-extension.js.map +1 -0
- package/dist/tracing-middleware.d.ts +78 -0
- package/dist/tracing-middleware.d.ts.map +1 -0
- package/dist/tracing-middleware.js +96 -0
- package/dist/tracing-middleware.js.map +1 -0
- package/dist/utils.d.ts +19 -0
- package/dist/utils.d.ts.map +1 -0
- package/dist/utils.js +47 -0
- package/dist/utils.js.map +1 -0
- package/package.json +50 -0
- package/src/context-propagation.ts +177 -0
- package/src/index.ts +139 -0
- package/src/traced-router.ts +240 -0
- package/src/tracing-extension.ts +175 -0
- package/src/tracing-middleware.ts +177 -0
- package/src/utils.ts +48 -0
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
import { Effect, Option } from "effect"
|
|
2
|
+
import type { DocumentNode, ExecutionResult, GraphQLError, OperationDefinitionNode } from "graphql"
|
|
3
|
+
import type { GraphQLExtension, ExecutionArgs } from "@effect-gql/core"
|
|
4
|
+
import { ExtensionsService } from "@effect-gql/core"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for the GraphQL tracing extension
|
|
8
|
+
*/
|
|
9
|
+
export interface TracingExtensionConfig {
|
|
10
|
+
/**
|
|
11
|
+
* Include the query source in span attributes.
|
|
12
|
+
* Default: false (for security - queries may contain sensitive data)
|
|
13
|
+
*/
|
|
14
|
+
readonly includeQuery?: boolean
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Include variables in span attributes.
|
|
18
|
+
* Default: false (for security - variables may contain sensitive data)
|
|
19
|
+
*/
|
|
20
|
+
readonly includeVariables?: boolean
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Add trace ID and span ID to the GraphQL response extensions.
|
|
24
|
+
* Useful for correlating client requests with backend traces.
|
|
25
|
+
* Default: false
|
|
26
|
+
*/
|
|
27
|
+
readonly exposeTraceIdInResponse?: boolean
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* Custom attributes to add to all spans.
|
|
31
|
+
*/
|
|
32
|
+
readonly customAttributes?: Record<string, string | number | boolean>
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Extract the operation name from a parsed GraphQL document
|
|
37
|
+
*/
|
|
38
|
+
const getOperationName = (document: DocumentNode): string | undefined => {
|
|
39
|
+
for (const definition of document.definitions) {
|
|
40
|
+
if (definition.kind === "OperationDefinition") {
|
|
41
|
+
return definition.name?.value
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return undefined
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Extract the operation type (query, mutation, subscription) from a parsed document
|
|
49
|
+
*/
|
|
50
|
+
const getOperationType = (document: DocumentNode): string => {
|
|
51
|
+
for (const definition of document.definitions) {
|
|
52
|
+
if (definition.kind === "OperationDefinition") {
|
|
53
|
+
return (definition as OperationDefinitionNode).operation
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return "unknown"
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Creates a GraphQL extension that adds OpenTelemetry tracing to all execution phases.
|
|
61
|
+
*
|
|
62
|
+
* This extension:
|
|
63
|
+
* - Creates spans for parse, validate phases
|
|
64
|
+
* - Annotates the current span with operation metadata during execution
|
|
65
|
+
* - Optionally exposes trace ID in response extensions
|
|
66
|
+
*
|
|
67
|
+
* Requires an OpenTelemetry tracer to be provided via Effect's tracing layer
|
|
68
|
+
* (e.g., `@effect/opentelemetry` NodeSdk.layer or OtlpTracer.layer).
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```typescript
|
|
72
|
+
* import { tracingExtension } from "@effect-gql/opentelemetry"
|
|
73
|
+
*
|
|
74
|
+
* const builder = GraphQLSchemaBuilder.empty.pipe(
|
|
75
|
+
* extension(tracingExtension({
|
|
76
|
+
* exposeTraceIdInResponse: true
|
|
77
|
+
* })),
|
|
78
|
+
* query("hello", { ... })
|
|
79
|
+
* )
|
|
80
|
+
* ```
|
|
81
|
+
*/
|
|
82
|
+
export const tracingExtension = (
|
|
83
|
+
config?: TracingExtensionConfig
|
|
84
|
+
): GraphQLExtension<ExtensionsService> => ({
|
|
85
|
+
name: "opentelemetry-tracing",
|
|
86
|
+
description: "Adds OpenTelemetry tracing to GraphQL execution phases",
|
|
87
|
+
|
|
88
|
+
onParse: (source: string, document: DocumentNode) =>
|
|
89
|
+
Effect.withSpan("graphql.parse")(
|
|
90
|
+
Effect.gen(function* () {
|
|
91
|
+
const operationName = getOperationName(document) ?? "anonymous"
|
|
92
|
+
yield* Effect.annotateCurrentSpan("graphql.document.name", operationName)
|
|
93
|
+
yield* Effect.annotateCurrentSpan(
|
|
94
|
+
"graphql.document.operation_count",
|
|
95
|
+
document.definitions.filter((d) => d.kind === "OperationDefinition").length
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
if (config?.includeQuery) {
|
|
99
|
+
yield* Effect.annotateCurrentSpan("graphql.source", source)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Add custom attributes if provided
|
|
103
|
+
if (config?.customAttributes) {
|
|
104
|
+
for (const [key, value] of Object.entries(config.customAttributes)) {
|
|
105
|
+
yield* Effect.annotateCurrentSpan(key, value)
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
})
|
|
109
|
+
),
|
|
110
|
+
|
|
111
|
+
onValidate: (document: DocumentNode, errors: readonly GraphQLError[]) =>
|
|
112
|
+
Effect.withSpan("graphql.validate")(
|
|
113
|
+
Effect.gen(function* () {
|
|
114
|
+
yield* Effect.annotateCurrentSpan("graphql.validation.error_count", errors.length)
|
|
115
|
+
|
|
116
|
+
if (errors.length > 0) {
|
|
117
|
+
yield* Effect.annotateCurrentSpan(
|
|
118
|
+
"graphql.validation.errors",
|
|
119
|
+
JSON.stringify(errors.map((e) => e.message))
|
|
120
|
+
)
|
|
121
|
+
yield* Effect.annotateCurrentSpan("error", true)
|
|
122
|
+
}
|
|
123
|
+
})
|
|
124
|
+
),
|
|
125
|
+
|
|
126
|
+
onExecuteStart: (args: ExecutionArgs) =>
|
|
127
|
+
Effect.gen(function* () {
|
|
128
|
+
const operationName = args.operationName ?? getOperationName(args.document) ?? "anonymous"
|
|
129
|
+
const operationType = getOperationType(args.document)
|
|
130
|
+
|
|
131
|
+
yield* Effect.annotateCurrentSpan("graphql.operation.name", operationName)
|
|
132
|
+
yield* Effect.annotateCurrentSpan("graphql.operation.type", operationType)
|
|
133
|
+
|
|
134
|
+
if (config?.includeVariables && args.variableValues) {
|
|
135
|
+
yield* Effect.annotateCurrentSpan("graphql.variables", JSON.stringify(args.variableValues))
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Expose trace ID in response extensions if configured
|
|
139
|
+
if (config?.exposeTraceIdInResponse) {
|
|
140
|
+
const currentSpanOption = yield* Effect.option(Effect.currentSpan)
|
|
141
|
+
if (Option.isSome(currentSpanOption)) {
|
|
142
|
+
const span = currentSpanOption.value
|
|
143
|
+
const ext = yield* ExtensionsService
|
|
144
|
+
yield* ext.set("tracing", {
|
|
145
|
+
traceId: span.traceId,
|
|
146
|
+
spanId: span.spanId,
|
|
147
|
+
})
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}),
|
|
151
|
+
|
|
152
|
+
onExecuteEnd: (result: ExecutionResult) =>
|
|
153
|
+
Effect.gen(function* () {
|
|
154
|
+
const hasErrors = result.errors !== undefined && result.errors.length > 0
|
|
155
|
+
|
|
156
|
+
yield* Effect.annotateCurrentSpan("graphql.response.has_errors", hasErrors)
|
|
157
|
+
yield* Effect.annotateCurrentSpan(
|
|
158
|
+
"graphql.response.has_data",
|
|
159
|
+
result.data !== null && result.data !== undefined
|
|
160
|
+
)
|
|
161
|
+
|
|
162
|
+
if (hasErrors) {
|
|
163
|
+
yield* Effect.annotateCurrentSpan("error", true)
|
|
164
|
+
yield* Effect.annotateCurrentSpan(
|
|
165
|
+
"graphql.errors",
|
|
166
|
+
JSON.stringify(
|
|
167
|
+
result.errors!.map((e) => ({
|
|
168
|
+
message: e.message,
|
|
169
|
+
path: e.path,
|
|
170
|
+
}))
|
|
171
|
+
)
|
|
172
|
+
)
|
|
173
|
+
}
|
|
174
|
+
}),
|
|
175
|
+
})
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
import { Effect } from "effect"
|
|
2
|
+
import type { GraphQLResolveInfo } from "graphql"
|
|
3
|
+
import type { MiddlewareRegistration, MiddlewareContext } from "@effect-gql/core"
|
|
4
|
+
import { pathToString, getFieldDepth, isIntrospectionField } from "./utils"
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Configuration for resolver tracing middleware
|
|
8
|
+
*/
|
|
9
|
+
export interface ResolverTracingConfig {
|
|
10
|
+
/**
|
|
11
|
+
* Minimum field depth to trace.
|
|
12
|
+
* Depth 0 = root fields (Query.*, Mutation.*).
|
|
13
|
+
* Default: 0 (trace all fields)
|
|
14
|
+
*/
|
|
15
|
+
readonly minDepth?: number
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Maximum field depth to trace.
|
|
19
|
+
* Default: Infinity (no limit)
|
|
20
|
+
*/
|
|
21
|
+
readonly maxDepth?: number
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Field patterns to exclude from tracing.
|
|
25
|
+
* Patterns are matched against "TypeName.fieldName".
|
|
26
|
+
*
|
|
27
|
+
* @example
|
|
28
|
+
* // Exclude introspection and internal fields
|
|
29
|
+
* excludePatterns: [/^Query\.__/, /\.id$/]
|
|
30
|
+
*/
|
|
31
|
+
readonly excludePatterns?: readonly RegExp[]
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Whether to include field arguments in span attributes.
|
|
35
|
+
* Default: false (for security - args may contain sensitive data)
|
|
36
|
+
*/
|
|
37
|
+
readonly includeArgs?: boolean
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Whether to include parent type in span attributes.
|
|
41
|
+
* Default: true
|
|
42
|
+
*/
|
|
43
|
+
readonly includeParentType?: boolean
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Whether to trace introspection fields (__schema, __type, etc.).
|
|
47
|
+
* Default: false
|
|
48
|
+
*/
|
|
49
|
+
readonly traceIntrospection?: boolean
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Custom span name generator.
|
|
53
|
+
* Default: "graphql.resolve TypeName.fieldName"
|
|
54
|
+
*/
|
|
55
|
+
readonly spanNameGenerator?: (info: GraphQLResolveInfo) => string
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Check if a field should be traced based on configuration
|
|
60
|
+
*/
|
|
61
|
+
const shouldTraceField = (info: GraphQLResolveInfo, config?: ResolverTracingConfig): boolean => {
|
|
62
|
+
// Skip introspection fields unless explicitly enabled
|
|
63
|
+
if (!config?.traceIntrospection && isIntrospectionField(info)) {
|
|
64
|
+
return false
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const depth = getFieldDepth(info)
|
|
68
|
+
|
|
69
|
+
// Check depth bounds
|
|
70
|
+
if (config?.minDepth !== undefined && depth < config.minDepth) {
|
|
71
|
+
return false
|
|
72
|
+
}
|
|
73
|
+
if (config?.maxDepth !== undefined && depth > config.maxDepth) {
|
|
74
|
+
return false
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
// Check exclude patterns
|
|
78
|
+
if (config?.excludePatterns) {
|
|
79
|
+
const fieldPath = `${info.parentType.name}.${info.fieldName}`
|
|
80
|
+
for (const pattern of config.excludePatterns) {
|
|
81
|
+
if (pattern.test(fieldPath)) {
|
|
82
|
+
return false
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
return true
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Creates middleware that wraps each resolver in an OpenTelemetry span.
|
|
92
|
+
*
|
|
93
|
+
* Each resolver execution creates a child span with GraphQL-specific attributes:
|
|
94
|
+
* - `graphql.field.name`: The field being resolved
|
|
95
|
+
* - `graphql.field.path`: Full path to the field (e.g., "Query.users.0.posts")
|
|
96
|
+
* - `graphql.field.type`: The return type of the field
|
|
97
|
+
* - `graphql.parent.type`: The parent type name
|
|
98
|
+
* - `graphql.operation.name`: The operation name (if available)
|
|
99
|
+
* - `error`: Set to true if the resolver fails
|
|
100
|
+
* - `error.type`: Error type/class name
|
|
101
|
+
* - `error.message`: Error message
|
|
102
|
+
*
|
|
103
|
+
* Requires an OpenTelemetry tracer to be provided via Effect's tracing layer.
|
|
104
|
+
*
|
|
105
|
+
* @example
|
|
106
|
+
* ```typescript
|
|
107
|
+
* import { resolverTracingMiddleware } from "@effect-gql/opentelemetry"
|
|
108
|
+
*
|
|
109
|
+
* const builder = GraphQLSchemaBuilder.empty.pipe(
|
|
110
|
+
* middleware(resolverTracingMiddleware({
|
|
111
|
+
* minDepth: 0,
|
|
112
|
+
* excludePatterns: [/^Query\.__/],
|
|
113
|
+
* includeArgs: false
|
|
114
|
+
* })),
|
|
115
|
+
* query("users", { ... })
|
|
116
|
+
* )
|
|
117
|
+
* ```
|
|
118
|
+
*/
|
|
119
|
+
export const resolverTracingMiddleware = (
|
|
120
|
+
config?: ResolverTracingConfig
|
|
121
|
+
): MiddlewareRegistration<never> => ({
|
|
122
|
+
name: "opentelemetry-resolver-tracing",
|
|
123
|
+
description: "Wraps resolvers in OpenTelemetry spans",
|
|
124
|
+
|
|
125
|
+
match: (info: GraphQLResolveInfo) => shouldTraceField(info, config),
|
|
126
|
+
|
|
127
|
+
apply: <A, E, R>(
|
|
128
|
+
effect: Effect.Effect<A, E, R>,
|
|
129
|
+
context: MiddlewareContext
|
|
130
|
+
): Effect.Effect<A, E, R> => {
|
|
131
|
+
const { info } = context
|
|
132
|
+
|
|
133
|
+
const spanName = config?.spanNameGenerator
|
|
134
|
+
? config.spanNameGenerator(info)
|
|
135
|
+
: `graphql.resolve ${info.parentType.name}.${info.fieldName}`
|
|
136
|
+
|
|
137
|
+
return Effect.withSpan(spanName)(
|
|
138
|
+
Effect.gen(function* () {
|
|
139
|
+
// Add standard attributes
|
|
140
|
+
yield* Effect.annotateCurrentSpan("graphql.field.name", info.fieldName)
|
|
141
|
+
yield* Effect.annotateCurrentSpan("graphql.field.path", pathToString(info.path))
|
|
142
|
+
yield* Effect.annotateCurrentSpan("graphql.field.type", String(info.returnType))
|
|
143
|
+
|
|
144
|
+
if (config?.includeParentType !== false) {
|
|
145
|
+
yield* Effect.annotateCurrentSpan("graphql.parent.type", info.parentType.name)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
if (info.operation?.name?.value) {
|
|
149
|
+
yield* Effect.annotateCurrentSpan("graphql.operation.name", info.operation.name.value)
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (config?.includeArgs && context.args && Object.keys(context.args).length > 0) {
|
|
153
|
+
yield* Effect.annotateCurrentSpan("graphql.field.args", JSON.stringify(context.args))
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Execute resolver and handle errors
|
|
157
|
+
const result = yield* effect.pipe(
|
|
158
|
+
Effect.tapError((error) =>
|
|
159
|
+
Effect.gen(function* () {
|
|
160
|
+
yield* Effect.annotateCurrentSpan("error", true)
|
|
161
|
+
yield* Effect.annotateCurrentSpan(
|
|
162
|
+
"error.type",
|
|
163
|
+
error instanceof Error ? error.constructor.name : "Error"
|
|
164
|
+
)
|
|
165
|
+
yield* Effect.annotateCurrentSpan(
|
|
166
|
+
"error.message",
|
|
167
|
+
error instanceof Error ? error.message : String(error)
|
|
168
|
+
)
|
|
169
|
+
})
|
|
170
|
+
)
|
|
171
|
+
)
|
|
172
|
+
|
|
173
|
+
return result
|
|
174
|
+
})
|
|
175
|
+
) as Effect.Effect<A, E, R>
|
|
176
|
+
},
|
|
177
|
+
})
|
package/src/utils.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { GraphQLResolveInfo, ResponsePath } from "graphql"
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Convert a GraphQL response path to a string representation.
|
|
5
|
+
*
|
|
6
|
+
* @example
|
|
7
|
+
* // For path: Query -> users -> 0 -> posts -> 1 -> title
|
|
8
|
+
* // Returns: "Query.users.0.posts.1.title"
|
|
9
|
+
*/
|
|
10
|
+
export const pathToString = (path: ResponsePath | undefined): string => {
|
|
11
|
+
if (!path) return ""
|
|
12
|
+
|
|
13
|
+
const segments: (string | number)[] = []
|
|
14
|
+
let current: ResponsePath | undefined = path
|
|
15
|
+
|
|
16
|
+
while (current) {
|
|
17
|
+
segments.unshift(current.key)
|
|
18
|
+
current = current.prev
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
return segments.join(".")
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Get the depth of a field in the query tree.
|
|
26
|
+
* Root fields (Query.*, Mutation.*) have depth 0.
|
|
27
|
+
*/
|
|
28
|
+
export const getFieldDepth = (info: GraphQLResolveInfo): number => {
|
|
29
|
+
let depth = 0
|
|
30
|
+
let current: ResponsePath | undefined = info.path
|
|
31
|
+
|
|
32
|
+
while (current?.prev) {
|
|
33
|
+
// Skip array indices in depth calculation
|
|
34
|
+
if (typeof current.key === "string") {
|
|
35
|
+
depth++
|
|
36
|
+
}
|
|
37
|
+
current = current.prev
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
return depth
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Check if a field is an introspection field (__schema, __type, etc.)
|
|
45
|
+
*/
|
|
46
|
+
export const isIntrospectionField = (info: GraphQLResolveInfo): boolean => {
|
|
47
|
+
return info.fieldName.startsWith("__")
|
|
48
|
+
}
|