The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as Effect from "effect/Effect"; |
| 2 | import * as Headers from "effect/http/Headers"; |
| 3 | import * as HttpTraceContext from "effect/http/HttpTraceContext"; |
| 4 | import * as Option from "effect/Option"; |
| 5 | import * as Tracer from "effect/Tracer"; |
| 6 | |
| 7 | /** |
| 8 | * Key of the trailing argument a Durable Object RPC stub appends to carry the |
| 9 | * caller's W3C `traceparent`. Native RPC has no headers, so the trace context |
| 10 | * rides in the arguments the same way the HTTP path carries it in a header. |
| 11 | */ |
| 12 | const TRACEPARENT_KEY = "~alchemy/traceparent"; |
| 13 | |
| 14 | interface TraceContextArg { |
| 15 | readonly [TRACEPARENT_KEY]: string; |
| 16 | } |
| 17 | |
| 18 | // Checked on every call's last argument, which is often a large payload: test |
| 19 | // the key before counting keys, since `Object.keys` of a multi-megabyte |
| 20 | // `Uint8Array` allocates a string per byte and exhausts the isolate's memory. |
| 21 | const isTraceContextArg = (value: unknown): value is TraceContextArg => |
| 22 | typeof value === "object" && |
| 23 | value !== null && |
| 24 | Object.getPrototypeOf(value) === Object.prototype && |
| 25 | typeof (value as Record<string, unknown>)[TRACEPARENT_KEY] === "string" && |
| 26 | Object.keys(value).length === 1; |
| 27 | |
| 28 | /** |
| 29 | * Append the caller's active span to an RPC call's arguments. Without an |
| 30 | * active span, or with propagation disabled, the arguments are unchanged. |
| 31 | */ |
| 32 | export const withRpcTraceContext = Effect.fn(function* (args: ReadonlyArray<unknown>) { |
| 33 | if (yield* Tracer.DisablePropagation) return args; |
| 34 | const span = yield* Effect.currentParentSpan.pipe(Effect.option); |
| 35 | if (Option.isNone(span)) return args; |
| 36 | const { traceId, spanId, sampled } = span.value; |
| 37 | const traceparent = `00-${traceId.padStart(32, "0")}-${spanId}-${sampled ? "01" : "00"}`; |
| 38 | return [...args, { [TRACEPARENT_KEY]: traceparent } satisfies TraceContextArg]; |
| 39 | }); |
| 40 | |
| 41 | /** |
| 42 | * Split the trace context a caller appended (see {@link withRpcTraceContext}) |
| 43 | * off an RPC call's arguments. Calls from stubs that predate it carry none, so |
| 44 | * their arguments pass through untouched. |
| 45 | */ |
| 46 | export const takeRpcTraceContext = ( |
| 47 | args: ReadonlyArray<unknown>, |
| 48 | ): readonly [args: ReadonlyArray<unknown>, parent: Option.Option<Tracer.ExternalSpan>] => { |
| 49 | const last = args.at(-1); |
| 50 | if (!isTraceContextArg(last)) return [args, Option.none()]; |
| 51 | return [ |
| 52 | args.slice(0, -1), |
| 53 | HttpTraceContext.w3c(Headers.fromRecordUnsafe({ traceparent: last[TRACEPARENT_KEY] })), |
| 54 | ]; |
| 55 | }; |