@libo11y/workers 0.8.0 → 0.9.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/README.md CHANGED
@@ -2,19 +2,19 @@
2
2
 
3
3
  The libo11y platform for Cloudflare Workers and Durable Objects (workerd).
4
4
  It binds [`@libo11y/core`](https://github.com/libo11y/libo11y/tree/main/ts/packages/core)
5
- to a Worker isolate: setup memoized per isolate, OTLP/HTTP export over
6
- `fetch` or a binding's `fetch`, the `AsyncLocalStorage` context, cumulative
7
- metrics exported on flush, flushing through `waitUntil`, and spans for
8
- `fetch`, `queue` and `scheduled` handlers.
5
+ to a Worker isolate: setup memoized per isolate, OTLP/HTTP export with bounded
6
+ retry over `fetch` or a binding's `fetch`, the `AsyncLocalStorage` context,
7
+ dirty-aware snapshot-diffing metrics exported on flush, flushing through
8
+ `waitUntil`, composable tracing helpers for Durable Objects, alarms, queues,
9
+ and cron triggers, and an authenticated RUM gateway proxy helper.
9
10
 
10
11
  ```sh
11
12
  npm install @libo11y/workers
12
13
  ```
13
14
 
14
- The package first ships in `ts/v0.8.0`. Until its first npm publish,
15
- install it from the tarball on the
16
- [`ts/v0.8.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.8.0):
17
- `npm install https://github.com/libo11y/libo11y/releases/download/ts/v0.8.0/libo11y-workers-0.8.0.tgz`.
15
+ The package first ships in `ts/v0.8.0` and is published on npm at `0.9.0`
16
+ (and attached as a tarball to the
17
+ [`ts/v0.9.0` GitHub Release](https://github.com/libo11y/libo11y/releases/tag/ts/v0.9.0)).
18
18
 
19
19
  `@opentelemetry/api` is a peer dependency. npm 7 and later and Bun install
20
20
  it automatically. If your application already depends on it, use a version
@@ -74,12 +74,17 @@ export default instrument(
74
74
  `SERVER` span named `"<METHOD> <route>"`, where the handler names the route
75
75
  with `setRoute` or `serve.route` does, that continues an inbound W3C `traceparent`, the stable
76
76
  HTTP semantic conventions, and `http.server.request.duration` with
77
- exemplars. `queue` gets a `CONSUMER` span `"process <queue>"` with the
78
- messaging attributes, and `scheduled` a `SERVER` span `"scheduled <cron>"`
79
- with `faas.trigger`, `faas.cron` and `faas.time`. A throw marks the span
80
- failed and is rethrown. Other members of the handler, such as `email`, pass
81
- through. `instrument` returns a new plain object, so pass an object literal
82
- rather than a class instance.
77
+ exemplars. Pass `serve: false` when a framework (such as Effect's `HttpRouter`)
78
+ owns its own HTTP server spans while keeping isolate setup and `waitUntil`
79
+ flushing. `queue` gets a `CONSUMER` span `"process <queue>"` with the
80
+ messaging attributes and automatic deduplicated span links extracted from
81
+ `_o11y` carriers in message bodies, and `scheduled` gets a `SERVER` span
82
+ `"scheduled <cron>"` with `faas.trigger`, `faas.cron` and `faas.time`. Both
83
+ `queue` and `scheduled` pass `{ forceMetrics: true }` on flush so changed
84
+ metrics export within the event even on mixed `fetch` + `queue`/`scheduled`
85
+ Workers. A throw marks the span failed and is rethrown. Other members of the
86
+ handler, such as `email`, pass through. `instrument` returns a new plain
87
+ object, so pass an object literal rather than a class instance.
83
88
 
84
89
  When setup fails, for example without a service name, the handler runs
85
90
  without telemetry and the failure is written once per isolate to
@@ -87,8 +92,8 @@ without telemetry and the failure is written once per isolate to
87
92
 
88
93
  ## Setup and flushing by hand
89
94
 
90
- An application that makes its own server spans, as Effect's `HttpServer`
91
- does, or a Durable Object, calls `setup` and `scheduleFlush` itself:
95
+ An application that manages its own spans or a Durable Object calls `setup`
96
+ and `scheduleFlush` directly (or uses `instrument(handler, { serve: false })`):
92
97
 
93
98
  ```ts
94
99
  import { scheduleFlush, setup, type WorkersOptions } from "@libo11y/workers";
@@ -118,16 +123,41 @@ export default {
118
123
  - `scheduleFlush(ctx, telemetry, options?)` hands `telemetry.forceFlush()` to
119
124
  `ctx.waitUntil`, so the export outlives the response. `ctx` is a Worker's
120
125
  `ExecutionContext` or a Durable Object's `DurableObjectState`; both have
121
- `waitUntil`. `telemetry` may be `setup`'s promise. It returns the flush,
122
- which never rejects.
126
+ `waitUntil`. `options.forceMetrics` bypasses `metricsFlushIntervalMillis`
127
+ for that flush, and `options.timeoutMillis` (default `5000` ms) bounds both
128
+ the flush and OTLP exporter retries. `telemetry` may be `setup`'s promise.
129
+ It returns the flush, which never rejects.
123
130
  - `createTelemetry(options)` builds a telemetry without installing it and
124
131
  without memoizing it.
125
132
 
126
- `instrumentServe`, `instrumentFetch` and `setRoute` are re-exported from
127
- `@libo11y/server/edge`, the part of `@libo11y/server` that imports no
128
- Node builtin.
129
-
130
- ## Durable Objects
133
+ `instrumentServe`, `instrumentFetch`, `setRoute`, and the byte-aware queue
134
+ carrier codec (`DEFAULT_CARRIER_FIELD`, `attachQueueCarrier`,
135
+ `extractQueueCarrier`, `batchQueueMessages`) are re-exported from
136
+ `@libo11y/core/edge`, which imports no Node builtin.
137
+
138
+ ## Durable Objects, alarms, queues, and cron helpers
139
+
140
+ Composable tracing helpers emit semconv 1.41.0 spans under scope
141
+ `"@libo11y/workers"` without requiring `ExportedHandler` wrapping:
142
+
143
+ - `enrichDurableObjectSpan(span, className)`: adds `o11y.durable_object.class`
144
+ to an existing span without opening a duplicate span.
145
+ - `traceDurableObjectMethod(className, method, fn, options?)` and
146
+ `traceDurableObjectMethods(className, methods, options?)`: wrap Durable
147
+ Object server methods in `SERVER` spans (`"<Class>/<method>"` with
148
+ `rpc.system.name = "cloudflare_durable_object"`, `rpc.method`, and
149
+ `o11y.durable_object.class`).
150
+ - `traceDurableObjectCall(className, method, fn, options?)` and
151
+ `traceDurableObjectStub(className, stub, options?)`: wrap caller-side
152
+ Durable Object calls in `CLIENT` spans (and inject W3C trace headers on
153
+ `stub.fetch(...)`).
154
+ - `traceAlarm(className, callbackName, fn, options?)`: starts a root `SERVER`
155
+ timer span linked to any supplied detached `Carrier`s.
156
+ - `traceScheduled(cronOrController, fn, options?)`: starts a root `SERVER`
157
+ timer span (`"scheduled <job|cron>"`).
158
+ - `traceQueueBatch(batchOrQueue, fn, options?)`: starts a root `CONSUMER`
159
+ span (`"process <queue>"`) and automatically links extracted `_o11y`
160
+ `Carrier`s from batch messages.
131
161
 
132
162
  A Durable Object shares its isolate, and so its telemetry, with the Worker
133
163
  that defines it. Set up in the handler and flush through the object's own
@@ -135,12 +165,13 @@ that defines it. Set up in the handler and flush through the object's own
135
165
 
136
166
  ```ts
137
167
  import { DurableObject } from "cloudflare:workers";
138
- import { instrumentServe, scheduleFlush, setup } from "@libo11y/workers";
168
+ import { instrumentServe, scheduleFlush, setup, traceDurableObjectMethod } from "@libo11y/workers";
139
169
 
140
170
  export class Room extends DurableObject<Env> {
141
171
  async fetch(request: Request): Promise<Response> {
142
172
  const telemetry = await setup(options(this.env));
143
- const serve = instrumentServe(() => this.handle(request), { telemetry, route: () => "/room" });
173
+ const handle = traceDurableObjectMethod("Room", "handle", () => this.handle(request), { telemetry });
174
+ const serve = instrumentServe(handle, { telemetry, route: () => "/room" });
144
175
  try {
145
176
  return await serve(request);
146
177
  } finally {
@@ -150,16 +181,34 @@ export class Room extends DurableObject<Env> {
150
181
  }
151
182
  ```
152
183
 
153
- A Worker that calls the object through `instrumentFetch` propagates its
154
- trace context, so the object's server span is a child of the Worker's
155
- client span:
184
+ ## RUM gateway proxy
185
+
186
+ `createRumProxy` and `proxyRum` forward same-origin `/_o11y/...` RUM ingest,
187
+ replay, remote config, and source map/dSYM upload requests to
188
+ `o11yrum-gateway` (typically over a Workers VPC Service binding):
156
189
 
157
190
  ```ts
158
- const stub = env.ROOM.get(env.ROOM.idFromName("lobby"));
159
- const call = instrumentFetch((input, init) => stub.fetch(new Request(input, init)), { telemetry });
160
- const res = await call("https://room.internal/");
191
+ import { createRumProxy, isRumProxyPath } from "@libo11y/workers";
192
+
193
+ const rumProxy = createRumProxy({
194
+ gatewayOrigin: "http://o11yrum-gateway.o11y-rum.svc.cluster.local:8081",
195
+ fetch: env.RUM_GATEWAY ? (req) => env.RUM_GATEWAY.fetch(req) : undefined,
196
+ trustedEdge: { secret: env.RUM_EDGE_SECRET },
197
+ });
198
+
199
+ if (isRumProxyPath(new URL(request.url).pathname)) {
200
+ return rumProxy(request);
201
+ }
161
202
  ```
162
203
 
204
+ The proxy strips `cookie`, forwarding headers, all inbound `cf-*` headers
205
+ (including spoofed `cf-ipcountry`), any inbound hop-credential header, and
206
+ `authorization` (except on `POST` to `/_o11y/v1/sourcemaps` and
207
+ `/_o11y/v1/dsyms`). It rebuilds `x-forwarded-for` strictly from
208
+ `cf-connecting-ip`, and when `trustedEdge` is configured it populates
209
+ `cf-ipcountry` strictly from Cloudflare's `request.cf.country` and injects
210
+ the configured hop-credential header (default `x-o11y-edge-secret`).
211
+
163
212
  ## Configuration
164
213
 
165
214
  A Worker has no process environment. Configuration comes from the options,
@@ -172,11 +221,11 @@ read, and a signal with nothing injected exports nothing, as in core.
172
221
 
173
222
  `WorkersOptions` is core's `TelemetryOptions` with three more fields:
174
223
 
175
- | Option | Default | What it does |
176
- | ---------------------------- | --------------------------- | ------------------------------------------------------------------------------------ |
177
- | `env` | none | the Worker's env bindings, for their `OTEL_*` variables |
178
- | `exporter` | from `OTEL_EXPORTER_OTLP_*` | where and how to export, as below |
179
- | `metricsFlushIntervalMillis` | `15000` | the least time between two metric exports of one isolate; `0` exports on every flush |
224
+ | Option | Default | What it does |
225
+ | ---------------------------- | -------------------------------------------- | --------------------------------------------------------------------------------------------------------- |
226
+ | `env` | none | the Worker's env bindings, for their `OTEL_*` variables |
227
+ | `exporter` | from `OTEL_EXPORTER_OTLP_*` | where and how to export, as below |
228
+ | `metricsFlushIntervalMillis` | `0` (`15000` in `instrument()` with `serve`) | minimum time between metric collections in one isolate; `0` collects on every flush and exports on change |
180
229
 
181
230
  `exporter` takes:
182
231
 
@@ -193,21 +242,35 @@ read, and a signal with nothing injected exports nothing, as in core.
193
242
  `http/json`. To export through a binding, write the function so the binding
194
243
  stays its `this`: `fetch: (req) => env.OTLP.fetch(req)`.
195
244
 
196
- An export never throws into the application. A status outside 2xx, a
197
- network error or a deadline fails the export, and the flush report names
198
- the failed signals. There are no retries: an invocation is too short to wait
199
- for one.
245
+ An export never throws into the application. Transient responses (`429`,
246
+ `502`, `503`, `504`) and network errors retry up to 2 times (3 total
247
+ attempts, 200 ms to 1000 ms equal jitter, honoring strict RFC 9110
248
+ `Retry-After`), strictly capped within `Math.min(timeoutMillis,
249
+ remainingFlushDeadlineMillis)` and failing fast whenever the next wait would
250
+ exceed the remaining deadline. On `2xx` responses, a bounded response body is
251
+ inspected for OTLP `partialSuccess` rejections without failing the export.
200
252
 
201
253
  ## Metrics
202
254
 
203
255
  Metrics are CUMULATIVE, which Prometheus' OTLP receiver requires, unless
204
256
  `OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE` says `delta` or
205
257
  `lowmemory`. A periodic reader cannot work in a Worker, since a timer runs
206
- only while an invocation is alive, so the metric reader has no timer: it
207
- exports when the telemetry flushes, at most once per
208
- `metricsFlushIntervalMillis`, and always at shutdown. A skipped flush loses
209
- nothing, because the next export carries every measurement since the
210
- isolate started. Traces and logs export on every flush.
258
+ only while an invocation is alive, so `FlushMetricReader` collects on flush
259
+ with snapshot-diffing dirty tracking:
260
+
261
+ - Plain `setup()` defaults `metricsFlushIntervalMillis` to `0`: read-only
262
+ invocations skip unchanged CUMULATIVE snapshots (0 `/v1/metrics` POSTs),
263
+ while changed values, new pending exemplars, failed-export retries, and
264
+ `DELTA` snapshots export within the event.
265
+ - `instrument()` with `instrumentServe` enabled (`serve !== false`) defaults
266
+ `metricsFlushIntervalMillis` to `15000` ms so per-request HTTP RED metrics
267
+ are batched, while `queue` and `scheduled` flushes set `forceMetrics: true`
268
+ so mixed Workers never lose queue or cron counts to the `fetch` throttle.
269
+ - Calling plain `setup()` together with `instrumentServe` without setting an
270
+ explicit `metricsFlushIntervalMillis` exports changed HTTP metrics on every
271
+ request.
272
+
273
+ Traces and logs export on every flush.
211
274
 
212
275
  ## Resource
213
276
 
@@ -234,17 +297,18 @@ rec.assertCorrelated();
234
297
  await rec.shutdown();
235
298
  ```
236
299
 
237
- The package's own suite runs a Worker, a Durable Object and an Effect
238
- `HttpRouter` app under a real workerd (`src/workerd.test.ts`) and checks what
239
- reaches an OTLP sink.
300
+ The package's own suite runs a Worker, a Durable Object, a RUM proxy, and an
301
+ Effect `HttpRouter` app (`instrument({ serve: false })`) under a real workerd
302
+ (`src/workerd.test.ts`) and checks what reaches an OTLP sink.
240
303
 
241
304
  ## Known limitations
242
305
 
243
306
  - `Date.now()` and `performance.now()` advance only across I/O in workerd, so
244
307
  a span that does only CPU work has a duration of 0.
245
308
  - Each isolate is a separate `service.instance.id` with its own cumulative
246
- series. Prometheus sees a new series per isolate, and the measurements of
247
- an isolate that is evicted after its last metric export are lost.
309
+ series. Prometheus sees a new series per isolate, and any measurements
310
+ buffered during a throttled `fetch` window are lost if the isolate is
311
+ evicted before the next metric export.
248
312
  - A span that ends after its invocation's flush, such as the server span of
249
313
  a streamed HTML or event-stream body, is exported by a later flush in the
250
314
  same isolate.
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Composable Cloudflare Workers, Durable Object, alarm, scheduled, and Queues tracing primitives.
3
+ *
4
+ * Every span name, kind, and attribute comes from @libo11y/core/edge's single-owner convention
5
+ * builders (OpenTelemetry semconv 1.41.0). All spans emitted by these helpers use the
6
+ * "@libo11y/workers" instrumentation scope.
7
+ */
8
+ import { type Carrier, type Telemetry } from "@libo11y/core";
9
+ import { type Attributes, type Link, type Span } from "@opentelemetry/api";
10
+ /** The fields of a queue MessageBatch the span reads. */
11
+ export interface WorkerMessageBatch {
12
+ /** The queue's name: messaging.destination.name. */
13
+ readonly queue: string;
14
+ /** The messages: their count is messaging.batch.message_count. */
15
+ readonly messages: readonly unknown[];
16
+ }
17
+ /** The fields of a ScheduledController the span reads. */
18
+ export interface WorkerScheduledController {
19
+ /** The cron pattern that fired: faas.cron. */
20
+ readonly cron: string;
21
+ /** When the invocation was scheduled, in milliseconds since the epoch: faas.time. */
22
+ readonly scheduledTime: number;
23
+ }
24
+ /** Common options for composable Workers span helpers. */
25
+ export interface TraceSpanOptions {
26
+ /** Explicit telemetry handle. Defaults to the global OpenTelemetry providers. */
27
+ readonly telemetry?: Telemetry;
28
+ /** Additional span attributes merged on top of the convention attributes. */
29
+ readonly attributes?: Attributes;
30
+ /** Additional span links attached to the started span. */
31
+ readonly links?: readonly Link[];
32
+ }
33
+ /** Options for {@link traceAlarm}. */
34
+ export interface TraceAlarmOptions extends TraceSpanOptions {
35
+ /** Optional detached Carriers (e.g. from drained outbox rows) attached as deduplicated span links. */
36
+ readonly carriers?: Iterable<Carrier | null | undefined>;
37
+ }
38
+ /** Options for {@link traceScheduled}. */
39
+ export interface TraceScheduledOptions extends TraceSpanOptions {
40
+ /** Optional logical job name; defaults to the cron expression when omitted. */
41
+ readonly job?: string;
42
+ /** Optional Unix timestamp in milliseconds for faas.time. */
43
+ readonly scheduledTime?: number;
44
+ }
45
+ /** Options for {@link traceQueueBatch}. */
46
+ export interface TraceQueueBatchOptions extends TraceSpanOptions {
47
+ /** Property name carrying the serialized Carrier in message bodies. Defaults to "_o11y". */
48
+ readonly carrierField?: string;
49
+ /** Additional detached Carriers attached as deduplicated span links alongside extracted ones. */
50
+ readonly carriers?: Iterable<Carrier | null | undefined>;
51
+ /** Explicit message count when passing a queue name string instead of a WorkerMessageBatch. */
52
+ readonly messageCount?: number;
53
+ }
54
+ /**
55
+ * Enriches an existing span inside a Durable Object with `o11y.durable_object.class` without
56
+ * opening a duplicate span. Safe no-op when span is undefined.
57
+ */
58
+ export declare function enrichDurableObjectSpan(span: Span | undefined, className: string): void;
59
+ /**
60
+ * Wraps a Durable Object server-side method in a semconv 1.41.0 SERVER span named
61
+ * `"<className>/<method>"` with `rpc.system.name = "cloudflare_durable_object"`,
62
+ * `rpc.method = "<className>/<method>"`, and `o11y.durable_object.class = className`.
63
+ */
64
+ export declare function traceDurableObjectMethod<This, Args extends unknown[], R>(className: string, method: string, fn: (this: This, ...args: Args) => R, options?: TraceSpanOptions): (this: This, ...args: Args) => R;
65
+ /**
66
+ * Wraps every own enumerable function property on `methods` with {@link traceDurableObjectMethod},
67
+ * passing non-function properties through unchanged.
68
+ */
69
+ export declare function traceDurableObjectMethods<T extends object>(className: string, methods: T, options?: TraceSpanOptions): T;
70
+ /**
71
+ * Runs a caller-side Durable Object invocation inside a semconv 1.41.0 CLIENT span named
72
+ * `"<className>/<method>"` with `rpc.system.name = "cloudflare_durable_object"`,
73
+ * `rpc.method = "<className>/<method>"`, and `o11y.durable_object.class = className`.
74
+ */
75
+ export declare function traceDurableObjectCall<R>(className: string, method: string, fn: (span: Span) => R, options?: TraceSpanOptions): R;
76
+ /**
77
+ * Wraps a Cloudflare Durable Object stub in a Proxy that traces every method invocation with a
78
+ * semconv 1.41.0 CLIENT span. Calls to `stub.fetch(...)` also inject the active trace context
79
+ * into the forwarded Request headers so the Durable Object joins the caller's trace.
80
+ *
81
+ * Note: Promise-based RPC pipelining (such as `stub.getService().doWork()`) is not preserved
82
+ * through this Proxy wrapper because awaited calls are wrapped in standard Promises. For
83
+ * pipelined RPC calls, wrap the final awaited invocation with {@link traceDurableObjectCall}.
84
+ */
85
+ export declare function traceDurableObjectStub<T extends object>(className: string, stub: T, options?: TraceSpanOptions): T;
86
+ /**
87
+ * Runs a Durable Object alarm handler inside a root SERVER span (`"<className> alarm <callbackName>"`)
88
+ * with `o11y.durable_object.class`, `faas.trigger = "timer"`, and deduplicated span links from any
89
+ * supplied detached Carriers.
90
+ */
91
+ export declare function traceAlarm<R>(className: string, callbackName: string, fn: (span: Span) => R, options?: TraceAlarmOptions): R;
92
+ /**
93
+ * Runs a Cloudflare Workers scheduled/cron handler inside a root SERVER span
94
+ * (`"scheduled <job|cron>"`) with `faas.trigger = "timer"`, `faas.cron`, and `faas.time`.
95
+ */
96
+ export declare function traceScheduled<R>(cron: string | WorkerScheduledController, fn: (span: Span) => R, options?: TraceScheduledOptions): R;
97
+ /**
98
+ * Runs a Cloudflare Queues batch consumer inside a root CONSUMER span (`"process <queue>"`)
99
+ * with semconv 1.41.0 messaging attributes, automatically extracting detached `_o11y` Carriers
100
+ * from batch messages and attaching deduplicated span links back to the originating operations.
101
+ */
102
+ export declare function traceQueueBatch<R>(batch: WorkerMessageBatch | string, fn: (span: Span) => R, options?: TraceQueueBatchOptions): R;
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Composable Cloudflare Workers, Durable Object, alarm, scheduled, and Queues tracing primitives.
3
+ *
4
+ * Every span name, kind, and attribute comes from @libo11y/core/edge's single-owner convention
5
+ * builders (OpenTelemetry semconv 1.41.0). All spans emitted by these helpers use the
6
+ * "@libo11y/workers" instrumentation scope.
7
+ */
8
+ import { linksFromCarriers } from "@libo11y/core";
9
+ import { alarmSpanSpec, durableObjectEnrichAttributes, durableObjectSpanSpec, extractQueueCarrier, queueBatchSpanSpec, scheduledSpanSpec, } from "@libo11y/core/edge";
10
+ import { context, propagation, SpanKind, SpanStatusCode, trace, } from "@opentelemetry/api";
11
+ import { VERSION } from "./version.js";
12
+ /** The instrumentation scope of @libo11y/workers spans. */
13
+ const SCOPE = "@libo11y/workers";
14
+ const HEADERS_SETTER = {
15
+ set: (carrier, key, value) => {
16
+ carrier.set(key, value);
17
+ },
18
+ };
19
+ const STUB_PASSTHROUGH_KEYS = new Set([
20
+ "then",
21
+ "catch",
22
+ "finally",
23
+ "toJSON",
24
+ "toString",
25
+ "valueOf",
26
+ "hasOwnProperty",
27
+ "isPrototypeOf",
28
+ "propertyIsEnumerable",
29
+ "toLocaleString",
30
+ "constructor",
31
+ "__proto__",
32
+ ]);
33
+ function errorType(err) {
34
+ if (err instanceof Error && err.name !== "")
35
+ return err.name;
36
+ return "_OTHER";
37
+ }
38
+ function failSpan(span, err) {
39
+ try {
40
+ if (err instanceof Error)
41
+ span.recordException(err);
42
+ else
43
+ span.recordException(String(err));
44
+ span.setAttribute("error.type", errorType(err));
45
+ span.setStatus({ code: SpanStatusCode.ERROR });
46
+ }
47
+ catch {
48
+ // A span that cannot record changes nothing the caller sees.
49
+ }
50
+ }
51
+ function safeEnd(span) {
52
+ try {
53
+ span.end();
54
+ }
55
+ catch {
56
+ // Telemetry never fails the caller.
57
+ }
58
+ }
59
+ function isThenable(value) {
60
+ return ((typeof value === "object" || typeof value === "function") &&
61
+ value !== null &&
62
+ typeof value.then === "function");
63
+ }
64
+ function mergeLinks(carriers, extraLinks) {
65
+ const links = carriers === undefined ? [] : linksFromCarriers(carriers);
66
+ if (extraLinks !== undefined && extraLinks.length > 0) {
67
+ const seen = new Set(links.map((l) => `${l.context.traceId}:${l.context.spanId}`));
68
+ for (const link of extraLinks) {
69
+ const key = `${link.context.traceId}:${link.context.spanId}`;
70
+ if (seen.has(key))
71
+ continue;
72
+ seen.add(key);
73
+ links.push(link);
74
+ }
75
+ }
76
+ return links.length > 0 ? links : undefined;
77
+ }
78
+ function runWithSpec(spec, fn, options, extra = {}) {
79
+ let start;
80
+ try {
81
+ const tp = options?.telemetry?.tracerProvider ?? trace.getTracerProvider();
82
+ const tracer = tp.getTracer(SCOPE, VERSION);
83
+ const attributes = options?.attributes === undefined ? spec.attributes : { ...spec.attributes, ...options.attributes };
84
+ const spanOptions = {
85
+ kind: spec.kind,
86
+ attributes,
87
+ ...(extra.root === true ? { root: true } : {}),
88
+ ...(extra.links !== undefined && extra.links.length > 0 ? { links: [...extra.links] } : {}),
89
+ };
90
+ start = (run) => tracer.startActiveSpan(spec.name, spanOptions, run);
91
+ }
92
+ catch {
93
+ start = undefined;
94
+ }
95
+ if (start === undefined) {
96
+ return fn(trace.wrapSpanContext({
97
+ traceId: "00000000000000000000000000000000",
98
+ spanId: "0000000000000000",
99
+ traceFlags: 0,
100
+ }));
101
+ }
102
+ return start((span) => {
103
+ let result;
104
+ try {
105
+ result = fn(span);
106
+ }
107
+ catch (err) {
108
+ failSpan(span, err);
109
+ safeEnd(span);
110
+ throw err;
111
+ }
112
+ if (isThenable(result)) {
113
+ return Promise.resolve(result).then((value) => {
114
+ safeEnd(span);
115
+ return value;
116
+ }, (err) => {
117
+ failSpan(span, err);
118
+ safeEnd(span);
119
+ throw err;
120
+ });
121
+ }
122
+ safeEnd(span);
123
+ return result;
124
+ });
125
+ }
126
+ function carrierFromQueueMessage(message, field) {
127
+ if (typeof message !== "object" || message === null)
128
+ return undefined;
129
+ const opts = field === undefined ? undefined : { field };
130
+ const body = message.body;
131
+ if (body !== undefined) {
132
+ const fromBody = extractQueueCarrier(body, opts);
133
+ if (fromBody !== undefined)
134
+ return fromBody;
135
+ }
136
+ return extractQueueCarrier(message, opts);
137
+ }
138
+ /**
139
+ * Enriches an existing span inside a Durable Object with `o11y.durable_object.class` without
140
+ * opening a duplicate span. Safe no-op when span is undefined.
141
+ */
142
+ export function enrichDurableObjectSpan(span, className) {
143
+ if (span === undefined)
144
+ return;
145
+ try {
146
+ span.setAttributes(durableObjectEnrichAttributes(className));
147
+ }
148
+ catch {
149
+ // Telemetry never fails the caller.
150
+ }
151
+ }
152
+ /**
153
+ * Wraps a Durable Object server-side method in a semconv 1.41.0 SERVER span named
154
+ * `"<className>/<method>"` with `rpc.system.name = "cloudflare_durable_object"`,
155
+ * `rpc.method = "<className>/<method>"`, and `o11y.durable_object.class = className`.
156
+ */
157
+ export function traceDurableObjectMethod(className, method, fn, options) {
158
+ const spec = durableObjectSpanSpec(className, method, SpanKind.SERVER);
159
+ const links = mergeLinks(undefined, options?.links);
160
+ return function (...args) {
161
+ return runWithSpec(spec, () => fn.apply(this, args), options, { links });
162
+ };
163
+ }
164
+ /**
165
+ * Wraps every own enumerable function property on `methods` with {@link traceDurableObjectMethod},
166
+ * passing non-function properties through unchanged.
167
+ */
168
+ export function traceDurableObjectMethods(className, methods, options) {
169
+ const wrapped = {};
170
+ for (const [key, value] of Object.entries(methods)) {
171
+ wrapped[key] =
172
+ typeof value === "function"
173
+ ? traceDurableObjectMethod(className, key, value, options)
174
+ : value;
175
+ }
176
+ return wrapped;
177
+ }
178
+ /**
179
+ * Runs a caller-side Durable Object invocation inside a semconv 1.41.0 CLIENT span named
180
+ * `"<className>/<method>"` with `rpc.system.name = "cloudflare_durable_object"`,
181
+ * `rpc.method = "<className>/<method>"`, and `o11y.durable_object.class = className`.
182
+ */
183
+ export function traceDurableObjectCall(className, method, fn, options) {
184
+ const spec = durableObjectSpanSpec(className, method, SpanKind.CLIENT);
185
+ const links = mergeLinks(undefined, options?.links);
186
+ return runWithSpec(spec, fn, options, { links });
187
+ }
188
+ /**
189
+ * Wraps a Cloudflare Durable Object stub in a Proxy that traces every method invocation with a
190
+ * semconv 1.41.0 CLIENT span. Calls to `stub.fetch(...)` also inject the active trace context
191
+ * into the forwarded Request headers so the Durable Object joins the caller's trace.
192
+ *
193
+ * Note: Promise-based RPC pipelining (such as `stub.getService().doWork()`) is not preserved
194
+ * through this Proxy wrapper because awaited calls are wrapped in standard Promises. For
195
+ * pipelined RPC calls, wrap the final awaited invocation with {@link traceDurableObjectCall}.
196
+ */
197
+ export function traceDurableObjectStub(className, stub, options) {
198
+ const cache = new Map();
199
+ return new Proxy(stub, {
200
+ get(target, prop) {
201
+ const value = Reflect.get(target, prop, target);
202
+ if (typeof prop !== "string" || STUB_PASSTHROUGH_KEYS.has(prop) || typeof value !== "function") {
203
+ return value;
204
+ }
205
+ const raw = value;
206
+ const cached = cache.get(prop);
207
+ if (cached !== undefined && cached.raw === raw)
208
+ return cached.wrapped;
209
+ const wrapped = prop === "fetch"
210
+ ? (...args) => traceDurableObjectCall(className, "fetch", () => {
211
+ const first = args[0];
212
+ if (first instanceof Request || typeof first === "string" || first instanceof URL) {
213
+ const req = first instanceof Request
214
+ ? new Request(first, args[1])
215
+ : new Request(String(first), args[1]);
216
+ try {
217
+ const propImpl = options?.telemetry?.propagator ?? propagation;
218
+ propImpl.inject(context.active(), req.headers, HEADERS_SETTER);
219
+ }
220
+ catch {
221
+ // Propagation failure never breaks the DO fetch call.
222
+ }
223
+ return raw.call(target, req);
224
+ }
225
+ return raw.apply(target, args);
226
+ }, options)
227
+ : (...args) => traceDurableObjectCall(className, prop, () => raw.apply(target, args), options);
228
+ cache.set(prop, { raw, wrapped });
229
+ return wrapped;
230
+ },
231
+ });
232
+ }
233
+ /**
234
+ * Runs a Durable Object alarm handler inside a root SERVER span (`"<className> alarm <callbackName>"`)
235
+ * with `o11y.durable_object.class`, `faas.trigger = "timer"`, and deduplicated span links from any
236
+ * supplied detached Carriers.
237
+ */
238
+ export function traceAlarm(className, callbackName, fn, options) {
239
+ const spec = alarmSpanSpec(className, callbackName);
240
+ const links = mergeLinks(options?.carriers, options?.links);
241
+ return runWithSpec(spec, fn, options, { root: true, links });
242
+ }
243
+ /**
244
+ * Runs a Cloudflare Workers scheduled/cron handler inside a root SERVER span
245
+ * (`"scheduled <job|cron>"`) with `faas.trigger = "timer"`, `faas.cron`, and `faas.time`.
246
+ */
247
+ export function traceScheduled(cron, fn, options) {
248
+ const cronExpr = typeof cron === "string" ? cron : cron.cron;
249
+ const scheduledTime = options?.scheduledTime ?? (typeof cron === "string" ? undefined : cron.scheduledTime);
250
+ const spec = scheduledSpanSpec(cronExpr, {
251
+ ...(options?.job === undefined ? {} : { job: options.job }),
252
+ ...(scheduledTime === undefined ? {} : { scheduledTime }),
253
+ });
254
+ const links = mergeLinks(undefined, options?.links);
255
+ return runWithSpec(spec, fn, options, { root: true, links });
256
+ }
257
+ /**
258
+ * Runs a Cloudflare Queues batch consumer inside a root CONSUMER span (`"process <queue>"`)
259
+ * with semconv 1.41.0 messaging attributes, automatically extracting detached `_o11y` Carriers
260
+ * from batch messages and attaching deduplicated span links back to the originating operations.
261
+ */
262
+ export function traceQueueBatch(batch, fn, options) {
263
+ const queue = typeof batch === "string" ? batch : batch.queue;
264
+ const messageCount = options?.messageCount ?? (typeof batch === "string" ? undefined : batch.messages.length);
265
+ const extracted = [];
266
+ if (typeof batch !== "string") {
267
+ for (const msg of batch.messages) {
268
+ const c = carrierFromQueueMessage(msg, options?.carrierField);
269
+ if (c !== undefined)
270
+ extracted.push(c);
271
+ }
272
+ }
273
+ if (options?.carriers !== undefined) {
274
+ for (const c of options.carriers) {
275
+ if (c !== undefined && c !== null)
276
+ extracted.push(c);
277
+ }
278
+ }
279
+ const spec = queueBatchSpanSpec(queue, messageCount);
280
+ const links = mergeLinks(extracted, options?.links);
281
+ return runWithSpec(spec, fn, options, { root: true, links });
282
+ }
package/dist/env.d.ts CHANGED
@@ -1,9 +1,3 @@
1
- /**
2
- * The OTEL_* variables of a Worker. A Worker has no process environment: its variables and secrets
3
- * arrive as the env bindings object each handler receives, beside bindings that are not strings
4
- * (KV namespaces, service bindings, Durable Object namespaces). The string-valued OTEL_* keys of
5
- * that object are the standard variables; nothing else is read.
6
- */
7
1
  /** The OTEL_* variables, as core's Platform.env returns them. */
8
2
  export type OtelEnv = Readonly<Record<string, string | undefined>>;
9
3
  /** Picks the string-valued OTEL_* keys of a Worker's env bindings. Any other key is ignored. */