@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 643 lines 20.4 KB
Raw
1 /**
2 * Bridges Effect tracing into OpenTelemetry by installing an Effect `Tracer`
3 * that creates OpenTelemetry spans, records attributes, events, links, errors,
4 * and status, and keeps OpenTelemetry context active while traced effects run.
5 * Use this module when an application already has an OpenTelemetry
6 * `TracerProvider`, or when the Node and Web SDK layers should expose Effect
7 * spans to OTLP, console, or other OpenTelemetry-compatible exporters.
8 *
9 * The layer constructors wire Effect's tracer service to either the global
10 * OpenTelemetry tracer provider or an explicitly provided `OtelTracer`. This
11 * module does not create exporters or span processors by itself, so spans are
12 * exported only when the provider has been configured by the application or by
13 * the Node/Web SDK layers. Effect parents take precedence over active
14 * OpenTelemetry spans. Use `Effect.withParentSpan` to inherit Effect-installed
15 * ambient spans.
16 * `makeExternalSpan` and `withSpanContext` continue incoming remote traces.
17 * Preserve `traceFlags` and `traceState` when building external spans; otherwise
18 * sampling defaults to sampled and trace state cannot be propagated.
19 *
20 * @stability unstable
21 * @since 4.0.0
22 */
23 import * as Otel from "@opentelemetry/api"
24 import * as Cause from "effect/Cause"
25 import type * as Clock from "effect/Clock"
26 import * as Context from "effect/Context"
27 import * as Effect from "effect/Effect"
28 import * as Exit from "effect/Exit"
29 import { constTrue, dual } from "effect/Function"
30 import * as Layer from "effect/Layer"
31 import * as Option from "effect/Option"
32 import * as Predicate from "effect/Predicate"
33 import * as Tracer from "effect/Tracer"
34 import * as Version from "effect/Version"
35 import { nanosToHrTime, recordToAttributes, unknownToAttributeValue } from "./internal/attributes.ts"
36
37 // =============================================================================
38 // Service Definitions
39 // =============================================================================
40
41 /**
42 * Context service containing the OpenTelemetry `Tracer` used to create spans for Effect tracing.
43 *
44 * @stability unstable
45 * @category services
46 * @since 4.0.0
47 */
48 export class OtelTracer extends Context.Service<
49 OtelTracer,
50 Otel.Tracer
51 >()("@effect/opentelemetry/Tracer") {}
52
53 /**
54 * Context service containing the OpenTelemetry `TracerProvider` used to obtain tracers.
55 *
56 * @stability unstable
57 * @category services
58 * @since 4.0.0
59 */
60 export class OtelTracerProvider extends Context.Service<
61 OtelTracerProvider,
62 Otel.TracerProvider
63 >()("@effect/opentelemetry/Tracer/OtelTracerProvider") {}
64
65 /**
66 * Context service containing OpenTelemetry trace flags used when constructing external span contexts.
67 *
68 * @stability unstable
69 * @category services
70 * @since 4.0.0
71 */
72 export class OtelTraceFlags extends Context.Service<
73 OtelTraceFlags,
74 Otel.TraceFlags
75 >()("@effect/opentelemetry/Tracer/OtelTraceFlags") {}
76
77 /**
78 * Context service containing OpenTelemetry trace state used when constructing external span contexts.
79 *
80 * @stability unstable
81 * @category services
82 * @since 4.0.0
83 */
84 export class OtelTraceState extends Context.Service<
85 OtelTraceState,
86 Otel.TraceState
87 >()("@effect/opentelemetry/Tracer/OtelTraceState") {}
88
89 // =============================================================================
90 // Constructors
91 // =============================================================================
92
93 /**
94 * Creates an Effect `Tracer` implementation backed by the configured OpenTelemetry tracer.
95 *
96 * @stability unstable
97 * @category constructors
98 * @since 4.0.0
99 */
100 export const make: Effect.Effect<Tracer.Tracer, never, OtelTracer> = Effect.map(
101 Effect.service(OtelTracer),
102 (tracer) =>
103 Tracer.make({
104 span(options) {
105 return new OtelSpan(
106 Otel.context,
107 Otel.trace,
108 tracer,
109 options
110 )
111 },
112 context(primitive, fiber) {
113 const currentSpan = getPropagatedSpan(fiber.cache.span)
114
115 if (currentSpan === undefined) {
116 return primitive["~effect/Effect/evaluate"](fiber)
117 }
118
119 const context = populateContext(Otel.context.active(), currentSpan)
120 return Otel.context.with(
121 context.setValue(EffectSpanKey, Otel.trace.getSpan(context)),
122 () => primitive["~effect/Effect/evaluate"](fiber)
123 )
124 }
125 })
126 )
127
128 /**
129 * Creates an Effect external span from an OpenTelemetry span context, preserving trace flags and trace state when provided.
130 *
131 * @stability unstable
132 * @category constructors
133 * @since 4.0.0
134 */
135 export const makeExternalSpan = (options: {
136 readonly traceId: string
137 readonly spanId: string
138 readonly traceFlags?: number | undefined
139 readonly traceState?: string | Otel.TraceState | undefined
140 }): Tracer.ExternalSpan => {
141 let annotations = Context.empty()
142 if (options.traceFlags !== undefined) {
143 annotations = Context.add(annotations, OtelTraceFlags, options.traceFlags)
144 }
145
146 if (typeof options.traceState === "string") {
147 try {
148 annotations = Context.add(annotations, OtelTraceState, Otel.createTraceState(options.traceState))
149 } catch {
150 //
151 }
152 } else if (options.traceState) {
153 annotations = Context.add(annotations, OtelTraceState, options.traceState)
154 }
155
156 return {
157 _tag: "ExternalSpan",
158 traceId: options.traceId,
159 spanId: options.spanId,
160 sampled: Predicate.isNotUndefined(options.traceFlags) ? isSampled(options.traceFlags) : true,
161 annotations
162 }
163 }
164
165 // =============================================================================
166 // Layers
167 // =============================================================================
168
169 /**
170 * Layer that provides the current global OpenTelemetry tracer provider.
171 *
172 * @stability unstable
173 * @category layers
174 * @since 4.0.0
175 */
176 export const layerGlobalProvider: Layer.Layer<OtelTracerProvider> = Layer.sync(
177 OtelTracerProvider,
178 () => Otel.trace.getTracerProvider()
179 )
180
181 /**
182 * Layer that creates an OpenTelemetry tracer from the provided tracer provider,
183 * using `effect` and the current Effect version as the instrumentation scope.
184 *
185 * @stability unstable
186 * @category layers
187 * @since 4.0.0
188 */
189 export const layerTracer: Layer.Layer<OtelTracer, never, OtelTracerProvider> = Layer.effect(
190 OtelTracer,
191 Effect.gen(function*() {
192 const provider = yield* OtelTracerProvider
193 return provider.getTracer("effect", Version.getCurrentVersion())
194 })
195 )
196
197 /**
198 * Layer that creates an OpenTelemetry tracer from the global tracer provider.
199 *
200 * @stability unstable
201 * @category layers
202 * @since 4.0.0
203 */
204 export const layerGlobalTracer: Layer.Layer<OtelTracer> = layerTracer.pipe(
205 Layer.provide(layerGlobalProvider)
206 )
207
208 /**
209 * Layer that installs an Effect tracer backed by the global OpenTelemetry tracer provider.
210 *
211 * @stability unstable
212 * @category layers
213 * @since 4.0.0
214 */
215 export const layerGlobal: Layer.Layer<OtelTracer> = Layer.effect(Tracer.Tracer, make).pipe(
216 Layer.provideMerge(layerGlobalTracer)
217 )
218
219 /**
220 * Layer that installs the Effect tracer using an `OtelTracer` already provided in the environment.
221 *
222 * @stability unstable
223 * @category layers
224 * @since 4.0.0
225 */
226 export const layerWithoutOtelTracer: Layer.Layer<never, never, OtelTracer> = Layer.effect(Tracer.Tracer, make)
227
228 /**
229 * Layer that creates an OpenTelemetry tracer from a provider, then installs it as the Effect tracer.
230 *
231 * **When to use**
232 *
233 * Use when you already provide an `OtelTracerProvider` and want Effect spans
234 * backed by a tracer derived from it.
235 *
236 * @see {@link layerTracer} for creating only the OpenTelemetry tracer service
237 * @see {@link layerGlobal} for installing the Effect tracer from the global provider
238 * @see {@link layerWithoutOtelTracer} for installing an already-provided `OtelTracer`
239 *
240 * @stability unstable
241 * @category layers
242 * @since 4.0.0
243 */
244 export const layer: Layer.Layer<OtelTracer, never, OtelTracerProvider> = layerWithoutOtelTracer.pipe(
245 Layer.provideMerge(layerTracer)
246 )
247
248 // =============================================================================
249 // Utilities / Combinators
250 // =============================================================================
251
252 const bigint1e6 = BigInt(1_000_000)
253 const bigint1e9 = BigInt(1_000_000_000)
254
255 /**
256 * Gets the current OpenTelemetry span.
257 *
258 * **Details**
259 *
260 * This accessor works with both the official OpenTelemetry API, such as
261 * `Tracer.layer` and `NodeSdk.layer`, and the lightweight OTLP module, such as
262 * `OtlpTracer.layer`. When using OTLP, the returned span is a wrapper that
263 * conforms to the OpenTelemetry `Span` interface.
264 *
265 * @stability unstable
266 * @category accessors
267 * @since 4.0.0
268 */
269 export const currentOtelSpan: Effect.Effect<Otel.Span, Cause.NoSuchElementError> = Effect.clockWith((clock) =>
270 Effect.map(Effect.currentSpan, (span) =>
271 OtelSpanTypeId in span
272 ? (span as OtelSpan).span
273 : makeOtelSpan(span, clock))
274 )
275
276 const makeOtelSpan = (span: Tracer.Span, clock: Clock.Clock): Otel.Span => {
277 const spanContext: Otel.SpanContext = {
278 traceId: span.traceId,
279 spanId: span.spanId,
280 traceFlags: span.sampled ? Otel.TraceFlags.SAMPLED : Otel.TraceFlags.NONE,
281 isRemote: false
282 }
283
284 let exit = Exit.void
285
286 const self: Otel.Span = {
287 spanContext: () => spanContext,
288 setAttribute(key, value) {
289 span.attribute(key, value)
290 return self
291 },
292 setAttributes(attributes) {
293 for (const [key, value] of Object.entries(attributes)) {
294 span.attribute(key, value)
295 }
296 return self
297 },
298 addEvent(name) {
299 let attributes: Otel.Attributes | undefined = undefined
300 let startTime: Otel.TimeInput | undefined = undefined
301 if (arguments.length === 3) {
302 attributes = arguments[1]
303 startTime = arguments[2]
304 } else {
305 startTime = arguments[1]
306 }
307 span.event(name, convertOtelTimeInput(startTime, clock), attributes)
308 return self
309 },
310 addLink(link) {
311 span.addLinks([{
312 span: makeExternalSpan(link.context),
313 attributes: link.attributes ?? {}
314 }])
315 return self
316 },
317 addLinks(links) {
318 span.addLinks(links.map((link) => ({
319 span: makeExternalSpan(link.context),
320 attributes: link.attributes ?? {}
321 })))
322 return self
323 },
324 setStatus(status) {
325 exit = status.code === Otel.SpanStatusCode.ERROR
326 ? Exit.die(status.message ?? "Unknown error")
327 : Exit.void
328 return self
329 },
330 updateName: () => self,
331 end(endTime) {
332 const time = convertOtelTimeInput(endTime, clock)
333 span.end(time, exit)
334 return self
335 },
336 isRecording: constTrue,
337 recordException(exception, timeInput) {
338 const time = convertOtelTimeInput(timeInput, clock)
339 const cause = Cause.fail(exception)
340 const error = Cause.prettyErrors(cause, {
341 includeCauseInStack: true
342 })[0]
343 span.event(error.message, time, {
344 "exception.type": error.name,
345 "exception.message": error.message,
346 "exception.stacktrace": error.stack ?? ""
347 })
348 }
349 }
350 return self
351 }
352
353 const convertOtelTimeInput = (input: Otel.TimeInput | undefined, clock: Clock.Clock): bigint => {
354 if (input === undefined) {
355 return clock.currentTimeNanosUnsafe()
356 } else if (typeof input === "number") {
357 return BigInt(Math.round(input * 1_000_000))
358 } else if (input instanceof Date) {
359 return BigInt(input.getTime()) * bigint1e6
360 }
361 const [seconds, nanos] = input
362 return BigInt(seconds) * bigint1e9 + BigInt(nanos)
363 }
364
365 /**
366 * Sets an effect's parent span from the given OpenTelemetry `SpanContext`.
367 *
368 * **When to use**
369 *
370 * Use when you need an effect to continue a trace from a parent span context
371 * produced by OpenTelemetry instrumentation outside Effect.
372 *
373 * @stability unstable
374 * @category propagation
375 * @since 4.0.0
376 */
377 export const withSpanContext: {
378 (
379 spanContext: Otel.SpanContext
380 ): <A, E, R>(
381 self: Effect.Effect<A, E, R>
382 ) => Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>
383 <A, E, R>(
384 self: Effect.Effect<A, E, R>,
385 spanContext: Otel.SpanContext
386 ): Effect.Effect<A, E, Exclude<R, Tracer.ParentSpan>>
387 } = dual(2, <A, E, R>(
388 self: Effect.Effect<A, E, R>,
389 spanContext: Otel.SpanContext
390 ) => Effect.withParentSpan(self, makeExternalSpan(spanContext)))
391
392 // =============================================================================
393 // Internals
394 // =============================================================================
395
396 const OtelSpanTypeId = "~@effect/opentelemetry/OtelTracer/OtelSpan"
397
398 const kindMap = {
399 "internal": Otel.SpanKind.INTERNAL,
400 "client": Otel.SpanKind.CLIENT,
401 "server": Otel.SpanKind.SERVER,
402 "producer": Otel.SpanKind.PRODUCER,
403 "consumer": Otel.SpanKind.CONSUMER
404 }
405
406 /** @internal */
407 export class OtelSpan implements Tracer.Span {
408 readonly [OtelSpanTypeId]: typeof OtelSpanTypeId
409 readonly _tag = "Span"
410
411 readonly name: string
412 readonly kind: Tracer.SpanKind
413 readonly annotations: Context.Context<never>
414 readonly links: Array<Tracer.SpanLink>
415 readonly span: Otel.Span
416 readonly spanId: string
417 readonly traceId: string
418 readonly attributes = new Map<string, unknown>()
419 readonly sampled: boolean
420 readonly parent: Option.Option<Tracer.AnySpan>
421 status: Tracer.SpanStatus
422
423 constructor(
424 contextApi: Otel.ContextAPI,
425 traceApi: Otel.TraceAPI,
426 tracer: Otel.Tracer,
427 options: Parameters<Tracer.Tracer["span"]>[0]
428 ) {
429 this[OtelSpanTypeId] = OtelSpanTypeId
430 this.name = options.name
431 this.annotations = options.annotations
432 this.links = options.links
433 this.kind = options.kind
434 const active = contextApi.active()
435 const fromActive = options.root !== true && Option.isNone(options.parent)
436 this.parent = fromActive ? getOtelParent(traceApi, active, options.annotations) : options.parent
437 this.span = tracer.startSpan(
438 options.name,
439 {
440 startTime: nanosToHrTime(options.startTime),
441 links: options.links.length > 0
442 ? options.links.map((link) => ({
443 context: makeSpanContext(link.span),
444 attributes: recordToAttributes(link.attributes)
445 }))
446 : undefined as any,
447 kind: kindMap[this.kind]
448 },
449 Option.isNone(this.parent) ?
450 Otel.trace.deleteSpan(active) :
451 // Keep the active span object: some SDKs, such as Sentry, record children on it.
452 fromActive && !overridesTraceContext(options.annotations) ?
453 active :
454 populateContext(active, this.parent.value, options.annotations)
455 )
456 const spanContext = this.span.spanContext()
457 this.spanId = spanContext.spanId
458 this.traceId = spanContext.traceId
459 this.status = {
460 _tag: "Started",
461 startTime: options.startTime
462 }
463 this.sampled = isSampled(spanContext.traceFlags)
464 }
465
466 attribute(key: string, value: unknown) {
467 if (this.status._tag === "Ended") return
468 this.span.setAttribute(key, unknownToAttributeValue(value))
469 this.attributes.set(key, value)
470 }
471
472 addLinks(links: ReadonlyArray<Tracer.SpanLink>): void {
473 if (this.status._tag === "Ended") return
474 // oxlint-disable-next-line no-restricted-syntax
475 this.links.push(...links)
476 this.span.addLinks(links.map((link) => ({
477 context: makeSpanContext(link.span),
478 attributes: recordToAttributes(link.attributes)
479 })))
480 }
481
482 end(endTime: bigint, exit: Exit.Exit<unknown, unknown>) {
483 if (this.status._tag === "Ended") return
484 const hrTime = nanosToHrTime(endTime)
485 this.status = {
486 _tag: "Ended",
487 endTime,
488 exit,
489 startTime: this.status.startTime
490 }
491
492 if (exit._tag === "Success") {
493 this.span.setStatus({ code: Otel.SpanStatusCode.OK })
494 } else {
495 if (Cause.hasInterruptsOnly(exit.cause)) {
496 this.span.setAttribute("effect.fiber.interrupted", true)
497 } else {
498 const errors = Cause.prettyErrors(exit.cause, {
499 includeCauseInStack: true
500 })
501 if (errors.length > 0) {
502 for (const error of errors) {
503 this.span.recordException(error, hrTime)
504 }
505 this.span.setStatus({
506 code: Otel.SpanStatusCode.ERROR,
507 message: errors[0].message
508 })
509 } else {
510 this.span.setStatus({ code: Otel.SpanStatusCode.OK })
511 }
512 }
513 }
514 this.span.end(hrTime)
515 }
516
517 event(name: string, startTime: bigint, attributes?: Record<string, unknown>) {
518 if (this.status._tag === "Ended") return
519 this.span.addEvent(
520 name,
521 attributes ? recordToAttributes(attributes) : undefined,
522 nanosToHrTime(startTime)
523 )
524 }
525 }
526
527 const isSampled = (traceFlags: Otel.TraceFlags): boolean =>
528 (traceFlags & Otel.TraceFlags.SAMPLED) === Otel.TraceFlags.SAMPLED
529
530 class OtelParentSpanContext extends Context.Service<
531 OtelParentSpanContext,
532 Otel.SpanContext
533 >()("@effect/opentelemetry/Tracer/OtelParentSpanContext") {}
534
535 // Prevents re-entry from inheriting Effect-installed spans.
536 const EffectSpanKey = Otel.createContextKey("@effect/opentelemetry/OtelTracer/EffectSpan")
537
538 const getOtelParent = (
539 tracer: Otel.TraceAPI,
540 context: Otel.Context,
541 annotations: Context.Context<never>
542 ): Option.Option<Tracer.AnySpan> => {
543 const otelSpan = tracer.getSpan(context)
544 if (otelSpan === undefined || otelSpan === context.getValue(EffectSpanKey)) return Option.none()
545 const otelParent = otelSpan.spanContext()
546 if (!tracer.isSpanContextValid(otelParent)) return Option.none()
547 return Option.some(Tracer.externalSpan({
548 spanId: otelParent.spanId,
549 traceId: otelParent.traceId,
550 sampled: isSampled(otelParent.traceFlags),
551 annotations: Context.add(annotations, OtelParentSpanContext, otelParent)
552 }))
553 }
554
555 const overridesTraceContext = (annotations: Context.Context<never>): boolean =>
556 Context.getOrUndefined(annotations, OtelTraceFlags) !== undefined ||
557 Context.getOrUndefined(annotations, OtelTraceState) !== undefined
558
559 const makeSpanContext = (
560 span: Tracer.AnySpan,
561 annotations?: Context.Context<never>
562 ): Otel.SpanContext => {
563 const otelParent = Context.getOrUndefined(span.annotations, OtelParentSpanContext)
564 if (otelParent !== undefined) {
565 if (annotations === undefined) return otelParent
566 const traceFlags = extractTraceService(span, annotations, OtelTraceFlags)
567 const traceState = extractTraceService(span, annotations, OtelTraceState)
568 // Read fields explicitly because object spread skips prototype getters.
569 return {
570 traceId: otelParent.traceId,
571 spanId: otelParent.spanId,
572 isRemote: otelParent.isRemote!,
573 traceFlags: traceFlags ?? otelParent.traceFlags,
574 traceState: traceState ?? otelParent.traceState!
575 }
576 }
577 const traceFlags = makeTraceFlags(span, annotations)
578 const traceState = makeTraceState(span, annotations)!
579 return ({
580 spanId: span.spanId,
581 traceId: span.traceId,
582 isRemote: span._tag === "ExternalSpan",
583 traceFlags,
584 traceState
585 })
586 }
587
588 const makeTraceFlags = (
589 span: Tracer.AnySpan,
590 annotations: Context.Context<never> | undefined
591 ): Otel.TraceFlags => {
592 let traceFlags: Otel.TraceFlags | undefined
593 if (Predicate.isNotUndefined(annotations)) {
594 traceFlags = extractTraceService(span, annotations, OtelTraceFlags)
595 if (Predicate.isUndefined(traceFlags)) {
596 traceFlags = Context.getOrUndefined(span.annotations, OtelTraceFlags)
597 }
598 }
599 return traceFlags ?? (span.sampled ? Otel.TraceFlags.SAMPLED : Otel.TraceFlags.NONE)
600 }
601
602 const makeTraceState = (
603 span: Tracer.AnySpan,
604 annotations: Context.Context<never> | undefined
605 ): Otel.TraceState | undefined => {
606 let traceState: Otel.TraceState | undefined
607 if (Predicate.isNotUndefined(annotations)) {
608 traceState = extractTraceService(span, annotations, OtelTraceState)
609 if (Predicate.isUndefined(traceState)) {
610 traceState = Context.getOrUndefined(span.annotations, OtelTraceState)
611 }
612 }
613 return traceState
614 }
615
616 const extractTraceService = <I, S>(
617 parent: Tracer.AnySpan,
618 annotations: Context.Context<never>,
619 service: Context.Service<I, S>
620 ) => {
621 const instance = Context.getOrUndefined(annotations, service)
622 if (Predicate.isNotUndefined(instance)) {
623 return instance
624 }
625 return Context.getOrUndefined(parent.annotations, service)
626 }
627
628 const getPropagatedSpan = (span: Tracer.AnySpan | undefined): Tracer.AnySpan | undefined => {
629 while (span !== undefined && Context.get(span.annotations, Tracer.DisablePropagation)) {
630 span = span._tag === "Span" ? Option.getOrUndefined(span.parent) : undefined
631 }
632 return span
633 }
634
635 /** @internal */
636 export const populateContext = (
637 context: Otel.Context,
638 span: Tracer.AnySpan,
639 annotations?: Context.Context<never> | undefined
640 ): Otel.Context =>
641 span instanceof OtelSpan ?
642 Otel.trace.setSpan(context, span.span) :
643 Otel.trace.setSpanContext(context, makeSpanContext(span, annotations))