@effect-gql/opentelemetry 0.1.0 → 1.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/index.d.cts ADDED
@@ -0,0 +1,416 @@
1
+ import { GraphQLExtension, ExtensionsService, MiddlewareRegistration, GraphQLSchemaBuilder } from '@effect-gql/core';
2
+ import { GraphQLResolveInfo, ResponsePath, GraphQLSchema } from 'graphql';
3
+ import { Effect, Context, Layer } from 'effect';
4
+ import { HttpServerRequest, HttpRouter } from '@effect/platform';
5
+ import { MakeGraphQLRouterOptions } from '@effect-gql/core/server';
6
+
7
+ /**
8
+ * Configuration for the GraphQL tracing extension
9
+ */
10
+ interface TracingExtensionConfig {
11
+ /**
12
+ * Include the query source in span attributes.
13
+ * Default: false (for security - queries may contain sensitive data)
14
+ */
15
+ readonly includeQuery?: boolean;
16
+ /**
17
+ * Include variables in span attributes.
18
+ * Default: false (for security - variables may contain sensitive data)
19
+ */
20
+ readonly includeVariables?: boolean;
21
+ /**
22
+ * Add trace ID and span ID to the GraphQL response extensions.
23
+ * Useful for correlating client requests with backend traces.
24
+ * Default: false
25
+ */
26
+ readonly exposeTraceIdInResponse?: boolean;
27
+ /**
28
+ * Custom attributes to add to all spans.
29
+ */
30
+ readonly customAttributes?: Record<string, string | number | boolean>;
31
+ }
32
+ /**
33
+ * Creates a GraphQL extension that adds OpenTelemetry tracing to all execution phases.
34
+ *
35
+ * This extension:
36
+ * - Creates spans for parse, validate phases
37
+ * - Annotates the current span with operation metadata during execution
38
+ * - Optionally exposes trace ID in response extensions
39
+ *
40
+ * Requires an OpenTelemetry tracer to be provided via Effect's tracing layer
41
+ * (e.g., `@effect/opentelemetry` NodeSdk.layer or OtlpTracer.layer).
42
+ *
43
+ * @example
44
+ * ```typescript
45
+ * import { tracingExtension } from "@effect-gql/opentelemetry"
46
+ *
47
+ * const builder = GraphQLSchemaBuilder.empty.pipe(
48
+ * extension(tracingExtension({
49
+ * exposeTraceIdInResponse: true
50
+ * })),
51
+ * query("hello", { ... })
52
+ * )
53
+ * ```
54
+ */
55
+ declare const tracingExtension: (config?: TracingExtensionConfig) => GraphQLExtension<ExtensionsService>;
56
+
57
+ /**
58
+ * Configuration for resolver tracing middleware
59
+ */
60
+ interface ResolverTracingConfig {
61
+ /**
62
+ * Minimum field depth to trace.
63
+ * Depth 0 = root fields (Query.*, Mutation.*).
64
+ * Default: 0 (trace all fields)
65
+ */
66
+ readonly minDepth?: number;
67
+ /**
68
+ * Maximum field depth to trace.
69
+ * Default: Infinity (no limit)
70
+ */
71
+ readonly maxDepth?: number;
72
+ /**
73
+ * Field patterns to exclude from tracing.
74
+ * Patterns are matched against "TypeName.fieldName".
75
+ *
76
+ * @example
77
+ * // Exclude introspection and internal fields
78
+ * excludePatterns: [/^Query\.__/, /\.id$/]
79
+ */
80
+ readonly excludePatterns?: readonly RegExp[];
81
+ /**
82
+ * Whether to include field arguments in span attributes.
83
+ * Default: false (for security - args may contain sensitive data)
84
+ */
85
+ readonly includeArgs?: boolean;
86
+ /**
87
+ * Whether to include parent type in span attributes.
88
+ * Default: true
89
+ */
90
+ readonly includeParentType?: boolean;
91
+ /**
92
+ * Whether to trace introspection fields (__schema, __type, etc.).
93
+ * Default: false
94
+ */
95
+ readonly traceIntrospection?: boolean;
96
+ /**
97
+ * Custom span name generator.
98
+ * Default: "graphql.resolve TypeName.fieldName"
99
+ */
100
+ readonly spanNameGenerator?: (info: GraphQLResolveInfo) => string;
101
+ }
102
+ /**
103
+ * Creates middleware that wraps each resolver in an OpenTelemetry span.
104
+ *
105
+ * Each resolver execution creates a child span with GraphQL-specific attributes:
106
+ * - `graphql.field.name`: The field being resolved
107
+ * - `graphql.field.path`: Full path to the field (e.g., "Query.users.0.posts")
108
+ * - `graphql.field.type`: The return type of the field
109
+ * - `graphql.parent.type`: The parent type name
110
+ * - `graphql.operation.name`: The operation name (if available)
111
+ * - `error`: Set to true if the resolver fails
112
+ * - `error.type`: Error type/class name
113
+ * - `error.message`: Error message
114
+ *
115
+ * Requires an OpenTelemetry tracer to be provided via Effect's tracing layer.
116
+ *
117
+ * @example
118
+ * ```typescript
119
+ * import { resolverTracingMiddleware } from "@effect-gql/opentelemetry"
120
+ *
121
+ * const builder = GraphQLSchemaBuilder.empty.pipe(
122
+ * middleware(resolverTracingMiddleware({
123
+ * minDepth: 0,
124
+ * excludePatterns: [/^Query\.__/],
125
+ * includeArgs: false
126
+ * })),
127
+ * query("users", { ... })
128
+ * )
129
+ * ```
130
+ */
131
+ declare const resolverTracingMiddleware: (config?: ResolverTracingConfig) => MiddlewareRegistration<never>;
132
+
133
+ /**
134
+ * W3C Trace Context header names
135
+ * @see https://www.w3.org/TR/trace-context/
136
+ */
137
+ declare const TRACEPARENT_HEADER = "traceparent";
138
+ declare const TRACESTATE_HEADER = "tracestate";
139
+ /**
140
+ * Parsed W3C Trace Context from incoming HTTP headers
141
+ */
142
+ interface TraceContext {
143
+ /**
144
+ * Version of the trace context format (always "00" for current spec)
145
+ */
146
+ readonly version: string;
147
+ /**
148
+ * Trace ID - 32 character lowercase hex string
149
+ */
150
+ readonly traceId: string;
151
+ /**
152
+ * Parent Span ID - 16 character lowercase hex string
153
+ */
154
+ readonly parentSpanId: string;
155
+ /**
156
+ * Trace flags - determines if trace is sampled
157
+ * Bit 0 (0x01) = sampled flag
158
+ */
159
+ readonly traceFlags: number;
160
+ /**
161
+ * Optional trace state from upstream services
162
+ */
163
+ readonly traceState?: string;
164
+ }
165
+ declare const TraceContextTag_base: Context.TagClass<TraceContextTag, "@effect-gql/opentelemetry/TraceContext", TraceContext>;
166
+ /**
167
+ * Context tag for TraceContext
168
+ */
169
+ declare class TraceContextTag extends TraceContextTag_base {
170
+ }
171
+ /**
172
+ * Parse a W3C traceparent header value.
173
+ *
174
+ * Format: {version}-{trace-id}-{parent-id}-{trace-flags}
175
+ * Example: 00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01
176
+ *
177
+ * @see https://www.w3.org/TR/trace-context/#traceparent-header
178
+ *
179
+ * @param header - The traceparent header value
180
+ * @returns Parsed trace context or null if invalid
181
+ */
182
+ declare const parseTraceParent: (header: string) => TraceContext | null;
183
+ /**
184
+ * Check if a trace context is sampled (should be recorded)
185
+ */
186
+ declare const isSampled: (context: TraceContext) => boolean;
187
+ /**
188
+ * Extract trace context from HTTP request headers.
189
+ *
190
+ * Looks for the W3C Trace Context headers:
191
+ * - `traceparent`: Required, contains trace ID, span ID, and flags
192
+ * - `tracestate`: Optional, vendor-specific trace data
193
+ *
194
+ * @example
195
+ * ```typescript
196
+ * const context = yield* extractTraceContext
197
+ * if (context) {
198
+ * console.log(`Continuing trace: ${context.traceId}`)
199
+ * }
200
+ * ```
201
+ */
202
+ declare const extractTraceContext: Effect.Effect<TraceContext | null, never, HttpServerRequest.HttpServerRequest>;
203
+ /**
204
+ * Format a trace context as a traceparent header value
205
+ */
206
+ declare const formatTraceParent: (context: TraceContext) => string;
207
+
208
+ /**
209
+ * Convert a GraphQL response path to a string representation.
210
+ *
211
+ * @example
212
+ * // For path: Query -> users -> 0 -> posts -> 1 -> title
213
+ * // Returns: "Query.users.0.posts.1.title"
214
+ */
215
+ declare const pathToString: (path: ResponsePath | undefined) => string;
216
+ /**
217
+ * Get the depth of a field in the query tree.
218
+ * Root fields (Query.*, Mutation.*) have depth 0.
219
+ */
220
+ declare const getFieldDepth: (info: GraphQLResolveInfo) => number;
221
+ /**
222
+ * Check if a field is an introspection field (__schema, __type, etc.)
223
+ */
224
+ declare const isIntrospectionField: (info: GraphQLResolveInfo) => boolean;
225
+
226
+ /**
227
+ * Options for the traced GraphQL router
228
+ */
229
+ interface TracedRouterOptions extends MakeGraphQLRouterOptions {
230
+ /**
231
+ * Name for the root HTTP span.
232
+ * Default: "graphql.http"
233
+ */
234
+ readonly rootSpanName?: string;
235
+ /**
236
+ * Additional attributes to add to the root span.
237
+ */
238
+ readonly rootSpanAttributes?: Record<string, string | number | boolean>;
239
+ /**
240
+ * Whether to propagate trace context from incoming HTTP headers.
241
+ * Uses W3C Trace Context (traceparent header).
242
+ * Default: true
243
+ */
244
+ readonly propagateContext?: boolean;
245
+ }
246
+ /**
247
+ * Creates a GraphQL router with OpenTelemetry tracing at the HTTP level.
248
+ *
249
+ * This wraps the standard makeGraphQLRouter to:
250
+ * 1. Extract trace context from incoming HTTP headers (W3C Trace Context)
251
+ * 2. Create a root span for the entire HTTP request
252
+ * 3. Propagate trace context to child spans created by extensions/middleware
253
+ *
254
+ * **Span Hierarchy:**
255
+ * ```
256
+ * graphql.http (created by this router)
257
+ * ├── graphql.parse (from tracing extension)
258
+ * ├── graphql.validate (from tracing extension)
259
+ * └── graphql.resolve Query.* (from tracing middleware)
260
+ * ```
261
+ *
262
+ * @example
263
+ * ```typescript
264
+ * import { makeTracedGraphQLRouter } from "@effect-gql/opentelemetry"
265
+ * import { NodeSdk } from "@effect/opentelemetry"
266
+ *
267
+ * const router = makeTracedGraphQLRouter(schema, serviceLayer, {
268
+ * path: "/graphql",
269
+ * graphiql: { path: "/graphiql" },
270
+ * rootSpanName: "graphql.http",
271
+ * rootSpanAttributes: {
272
+ * "service.name": "my-api"
273
+ * }
274
+ * })
275
+ *
276
+ * // Provide OpenTelemetry layer when serving
277
+ * const TracingLayer = NodeSdk.layer(() => ({
278
+ * resource: { serviceName: "my-graphql-api" },
279
+ * spanProcessor: new BatchSpanProcessor(new OTLPTraceExporter())
280
+ * }))
281
+ * ```
282
+ *
283
+ * @param schema - The GraphQL schema
284
+ * @param layer - Effect layer providing services required by resolvers
285
+ * @param options - Router and tracing configuration
286
+ * @returns An HttpRouter with tracing enabled
287
+ */
288
+ declare const makeTracedGraphQLRouter: <R>(schema: GraphQLSchema, layer: Layer.Layer<R>, options?: TracedRouterOptions) => HttpRouter.HttpRouter<never, never>;
289
+ /**
290
+ * Wrap an existing HttpRouter with OpenTelemetry tracing.
291
+ *
292
+ * This is useful when you already have a router and want to add
293
+ * request-level tracing without recreating it.
294
+ *
295
+ * @example
296
+ * ```typescript
297
+ * import { toRouter } from "@effect-gql/core/server"
298
+ * import { withTracedRouter } from "@effect-gql/opentelemetry"
299
+ *
300
+ * const baseRouter = toRouter(builder, serviceLayer)
301
+ * const tracedRouter = withTracedRouter(baseRouter, {
302
+ * rootSpanName: "graphql.http"
303
+ * })
304
+ * ```
305
+ */
306
+ declare const withTracedRouter: (router: HttpRouter.HttpRouter<any, any>, options?: {
307
+ rootSpanName?: string;
308
+ rootSpanAttributes?: Record<string, string | number | boolean>;
309
+ propagateContext?: boolean;
310
+ }) => HttpRouter.HttpRouter<any, any>;
311
+
312
+ /**
313
+ * @effect-gql/opentelemetry
314
+ *
315
+ * OpenTelemetry tracing integration for Effect GraphQL.
316
+ *
317
+ * Provides distributed tracing using Effect's native OpenTelemetry support.
318
+ * Works with any OpenTelemetry-compatible backend (Jaeger, Tempo, Honeycomb, etc.).
319
+ *
320
+ * @example
321
+ * ```typescript
322
+ * import { GraphQLSchemaBuilder } from "@effect-gql/core"
323
+ * import { serve } from "@effect-gql/node"
324
+ * import { withTracing } from "@effect-gql/opentelemetry"
325
+ * import { NodeSdk } from "@effect/opentelemetry"
326
+ * import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base"
327
+ * import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"
328
+ *
329
+ * // Add tracing to schema
330
+ * const builder = GraphQLSchemaBuilder.empty
331
+ * .query("users", { ... })
332
+ * .pipe(withTracing({
333
+ * extension: { exposeTraceIdInResponse: true },
334
+ * resolver: { excludePatterns: [/^Query\.__/] }
335
+ * }))
336
+ *
337
+ * // Configure OpenTelemetry
338
+ * const TracingLayer = NodeSdk.layer(() => ({
339
+ * resource: { serviceName: "my-graphql-api" },
340
+ * spanProcessor: new BatchSpanProcessor(
341
+ * new OTLPTraceExporter({ url: "http://localhost:4318/v1/traces" })
342
+ * )
343
+ * }))
344
+ *
345
+ * // Serve with tracing
346
+ * serve(builder, TracingLayer.pipe(Layer.merge(serviceLayer)))
347
+ * ```
348
+ *
349
+ * @packageDocumentation
350
+ */
351
+
352
+ /**
353
+ * Complete configuration for GraphQL tracing
354
+ */
355
+ interface GraphQLTracingConfig {
356
+ /**
357
+ * Configuration for phase-level tracing (parse, validate, execute).
358
+ * Uses the Extensions system.
359
+ */
360
+ readonly extension?: TracingExtensionConfig;
361
+ /**
362
+ * Configuration for resolver-level tracing.
363
+ * Uses the Middleware system.
364
+ */
365
+ readonly resolver?: ResolverTracingConfig;
366
+ }
367
+ /**
368
+ * Add OpenTelemetry tracing to a GraphQL schema builder.
369
+ *
370
+ * This is a convenience function that registers both the tracing extension
371
+ * (for phase-level spans) and resolver middleware (for field-level spans).
372
+ *
373
+ * **Span Hierarchy:**
374
+ * ```
375
+ * graphql.request (if using traced router)
376
+ * ├── graphql.parse
377
+ * ├── graphql.validate
378
+ * └── graphql.execute
379
+ * ├── graphql.resolve Query.users
380
+ * ├── graphql.resolve User.posts
381
+ * └── graphql.resolve Post.author
382
+ * ```
383
+ *
384
+ * **Requirements:**
385
+ * - An OpenTelemetry tracer must be provided via Effect's tracing layer
386
+ * - Use `@effect/opentelemetry` NodeSdk.layer or OtlpTracer.layer
387
+ *
388
+ * @example
389
+ * ```typescript
390
+ * import { GraphQLSchemaBuilder } from "@effect-gql/core"
391
+ * import { withTracing } from "@effect-gql/opentelemetry"
392
+ *
393
+ * const builder = GraphQLSchemaBuilder.empty
394
+ * .query("hello", {
395
+ * type: S.String,
396
+ * resolve: () => Effect.succeed("world")
397
+ * })
398
+ * .pipe(withTracing({
399
+ * extension: {
400
+ * exposeTraceIdInResponse: true, // Add traceId to response extensions
401
+ * includeQuery: false, // Don't include query in spans (security)
402
+ * },
403
+ * resolver: {
404
+ * minDepth: 0, // Trace all resolvers
405
+ * excludePatterns: [/^Query\.__/], // Skip introspection
406
+ * includeArgs: false, // Don't include args (security)
407
+ * }
408
+ * }))
409
+ * ```
410
+ *
411
+ * @param config - Optional tracing configuration
412
+ * @returns A function that adds tracing to a GraphQLSchemaBuilder
413
+ */
414
+ declare const withTracing: <R>(config?: GraphQLTracingConfig) => (builder: GraphQLSchemaBuilder<R>) => GraphQLSchemaBuilder<R>;
415
+
416
+ export { type GraphQLTracingConfig, type ResolverTracingConfig, TRACEPARENT_HEADER, TRACESTATE_HEADER, type TraceContext, TraceContextTag, type TracedRouterOptions, type TracingExtensionConfig, extractTraceContext, formatTraceParent, getFieldDepth, isIntrospectionField, isSampled, makeTracedGraphQLRouter, parseTraceParent, pathToString, resolverTracingMiddleware, tracingExtension, withTracedRouter, withTracing };