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

main
ts 113 lines 4.2 KB
Raw
1 /**
2 * Effect Tracer that mirrors `Effect.withSpan` / `Effect.fn` spans into
3 * Cloudflare Workers Observability via `tracing.startActiveSpan`.
4 *
5 * Built once per event (see {@link Telemetry} + `buildEventTelemetry`).
6 * Captures the invocation's async context; do not cache the built Tracer
7 * across requests. Not exported from the Cloudflare barrel.
8 */
9 import { AsyncLocalStorage } from "node:async_hooks";
10 import * as Cause from "effect/Cause";
11 import * as Effect from "effect/Effect";
12 import * as Exit from "effect/Exit";
13 import * as Layer from "effect/Layer";
14 import * as Option from "effect/Option";
15 import * as Predicate from "effect/Predicate";
16 import * as Tracer from "effect/Tracer";
17 import cloudflare_workers from "./cloudflare_workers.ts";
18
19 type SpanOptions = Parameters<Tracer.Tracer["span"]>[0];
20 type RunInContext = ReturnType<typeof AsyncLocalStorage.snapshot>;
21 type CloudflareSpan = ReturnType<(typeof import("cloudflare:workers"))["tracing"]["startSpan"]>;
22
23 class Span extends Tracer.NativeSpan {
24 constructor(
25 options: SpanOptions,
26 readonly runInContext: RunInContext,
27 readonly cloudflareSpan?: CloudflareSpan,
28 ) {
29 // Cascade Cloudflare's decision: an untraced invocation (`isTraced`
30 // false — e.g. traces disabled; head sampling is applied later, at
31 // ingestion) or a runtime without the API marks the Effect span
32 // unsampled, so descendants skip `startActiveSpan` entirely.
33 super({
34 ...options,
35 sampled: options.sampled && (cloudflareSpan?.isTraced ?? false),
36 });
37 }
38
39 override attribute(key: string, value: unknown): void {
40 super.attribute(key, value);
41 if (Predicate.isString(value) || Predicate.isNumber(value) || Predicate.isBoolean(value)) {
42 this.cloudflareSpan?.setAttribute(key, value);
43 }
44 }
45
46 override end(endTime: bigint, exit: Exit.Exit<unknown, unknown>): void {
47 super.end(endTime, exit);
48 const outcome = Exit.isSuccess(exit)
49 ? "success"
50 : Cause.hasInterruptsOnly(exit.cause)
51 ? "interrupted"
52 : "failure";
53 this.cloudflareSpan?.setAttribute("effect.exit", outcome);
54 // Only a failure (or defect) is an error. Success and pure interruption
55 // stay `unset`: `ok` is final in Cloudflare, so the tracer never claims
56 // it, and a cancellation is not an application error.
57 if (Exit.isFailure(exit) && outcome === "failure") {
58 this.cloudflareSpan?.setStatus({
59 code: "error",
60 message: Cause.prettyErrors(exit.cause)[0]?.message,
61 });
62 }
63 this.cloudflareSpan?.end();
64 }
65 }
66
67 /**
68 * Per-event Tracer Layer. Cloudflare owns sampling and export; scalar
69 * attributes are forwarded; events, links, and non-scalars stay
70 * Effect-local. Completion is recorded as `effect.exit`, and a failure also
71 * sets the span status to `error`. Effect trace/span IDs are independent
72 * of Cloudflare's opaque IDs.
73 */
74 export const layer: Layer.Layer<never> = Layer.effect(
75 Tracer.Tracer,
76 Effect.gen(function* () {
77 // `tracing` only exists on compatibility dates >= 2026-07-28. Deploy
78 // already rejects older dates (`assertCloudflareTelemetryCompatibility`),
79 // so a missing API here (an old local workerd) just keeps spans
80 // Effect-local.
81 const { tracing } = yield* cloudflare_workers;
82 const invocationContext = AsyncLocalStorage.snapshot();
83 const contextFor = (span: Tracer.AnySpan | undefined): RunInContext => {
84 while (span?._tag === "Span") {
85 if (span instanceof Span) return span.runInContext;
86 span = Option.getOrUndefined(span.parent);
87 }
88 return invocationContext;
89 };
90
91 return Tracer.make({
92 span(options) {
93 const parentContext = options.root
94 ? invocationContext
95 : contextFor(Option.getOrUndefined(options.parent));
96
97 if (!options.sampled || tracing?.startActiveSpan === undefined) {
98 return new Span(options, parentContext);
99 }
100
101 return parentContext(() =>
102 tracing.startActiveSpan(
103 options.name,
104 (span) => new Span(options, AsyncLocalStorage.snapshot(), span),
105 ),
106 );
107 },
108 context(primitive, fiber) {
109 return contextFor(fiber.cache.span)(() => primitive["~effect/Effect/evaluate"](fiber));
110 },
111 });
112 }),
113 );