Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default {
async fetch() {
return new Response('ok');
},
} satisfies ExportedHandler;
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
interface Env {
PRODUCER: Fetcher;
}

// Nothing is wrapped manually, the Vite plugin wraps the default export.
export default {
async fetch(_request, env) {
return env.PRODUCER.fetch('http://fake-host/');
},
// workerd calls `tailStream()` with the producer's onset event, then calls
// the returned object for the later events of that invocation.
tailStream() {
return {
outcome() {
throw new Error('Error from the tailStream outcome handler');
},
};
},
} satisfies ExportedHandler<Env>;
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import { defineCloudflareOptions } from '@sentry/cloudflare';

export default defineCloudflareOptions((env: { SENTRY_DSN: string }) => ({
dsn: env.SENTRY_DSN,
}));
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import type { Event } from '@sentry/core';
import { join } from 'path';
import { expect, it } from 'vitest';
import { createRunner } from '../../runner';

it('captures errors thrown by the handler that tailStream returns', async ({ signal }) => {
const runner = createRunner(__dirname)
// A tail consumer in another `wrangler dev` process does not receive
// streaming tail events, so the producer runs in the same process.
.withWranglerArgs('-c', join(__dirname, 'dist/cloudflare_tail_stream_producer/wrangler.json'))
.expect(envelope => {
const event = envelope[1][0]?.[1] as Event;
expect(event.exception?.values?.[0]).toEqual(
expect.objectContaining({
type: 'Error',
value: 'Error from the tailStream outcome handler',
mechanism: { type: 'auto.faas.cloudflare.tail_stream', handled: false },
}),
);
})
.start(signal);

await runner.makeRequest('get', '/');
await runner.completed();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { cloudflare } from '@cloudflare/vite-plugin';
import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';
import { defineConfig } from 'vite';

export default defineConfig({
plugins: [
cloudflare({ auxiliaryWorkers: [{ configPath: './wrangler-producer.jsonc' }] }),
sentryCloudflareVitePlugin(),
],
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "../../node_modules/wrangler/config-schema.json",
"name": "cloudflare-tail-stream-producer",
"main": "index-producer.ts",
"compatibility_date": "2025-06-17",
"compatibility_flags": ["nodejs_compat"],
"streaming_tail_consumers": [{ "service": "cloudflare-tail-stream-consumer" }],
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "../../node_modules/wrangler/config-schema.json",
"name": "cloudflare-tail-stream-consumer",
"main": "index.ts",
"compatibility_date": "2025-06-17",
"compatibility_flags": ["nodejs_compat"],
"services": [{ "binding": "PRODUCER", "service": "cloudflare-tail-stream-producer" }],
}
146 changes: 114 additions & 32 deletions packages/cloudflare/src/instrumentations/worker/instrumentTail.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import type { TraceItem } from '@cloudflare/workers-types';
import type { AnyExportedHandler } from '../../types';
import type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers';
import { captureException, withIsolationScope } from '@sentry/core';
Expand All @@ -10,13 +9,29 @@ import { addCloudResourceContext } from '../../scope-utils';
import { init } from '../../sdk';
import { instrumentContext } from '../../utils/instrumentContext';
import { setInvocationState } from '../../utils/invocationContext';
import { type UncheckedMethod } from '../../wrapMethodWithSentry';
import { instrumentEnv } from './instrumentEnv';

type TailMethod = 'tail' | 'trace' | 'tailStream';
Comment thread
isaacs marked this conversation as resolved.
Resolved

const TAIL_METHODS: TailMethod[] = ['tail', 'trace', 'tailStream'];

const MECHANISM_TYPES: Record<TailMethod, string> = {
tail: 'auto.faas.cloudflare.tail',
trace: 'auto.faas.cloudflare.trace',
tailStream: 'auto.faas.cloudflare.tail_stream',
};

/**
* Core tail handler logic - wraps execution with Sentry instrumentation.
* Note: tail handlers don't create spans, just error capture.
*/
function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext, fn: () => unknown): unknown {
function wrapTailHandler(
options: CloudflareOptions,
context: ExecutionContext,
method: TailMethod,
fn: () => unknown,
): unknown {
return withIsolationScope(async isolationScope => {
const waitUntil = context.waitUntil.bind(context);

Expand All @@ -30,7 +45,7 @@ function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext,
try {
return await fn();
} catch (e) {
captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.tail' } });
captureException(e, { mechanism: { handled: false, type: MECHANISM_TYPES[method] } });
throw e;
} finally {
waitUntil(flushAndDispose(client));
Expand All @@ -39,49 +54,116 @@ function wrapTailHandler(options: CloudflareOptions, context: ExecutionContext,
}

/**
* Instruments a tail handler for ExportedHandler (env/ctx come from args).
* workerd calls `tailStream()` once with the onset event, then calls the
* function or object methods it returns for each later batch of events.
* Each of those calls runs as its own invocation.
*/
function wrapTailStreamEventHandler(
eventHandler: unknown,
options: CloudflareOptions,
context: ExecutionContext,
): unknown {
const wrap = (fn: UncheckedMethod, getThis: (thisArg: unknown) => unknown): UncheckedMethod =>
new Proxy(fn, {
apply(target, thisArg, args) {
return wrapTailHandler(options, context, 'tailStream', () => Reflect.apply(target, getThis(thisArg), args));
},
});

if (typeof eventHandler === 'function') {
return wrap(eventHandler as UncheckedMethod, thisArg => thisArg);
}

if (eventHandler && typeof eventHandler === 'object') {
const proxy: object = new Proxy(eventHandler, {
Comment thread
isaacs marked this conversation as resolved.
Resolved
get(target, prop) {
// Getters and methods run with the raw object as `this`, so private
// fields work. workerd calls each method with the proxy as `this`.
// Rebinding it also keeps `this.helper()` in this invocation.
const value = Reflect.get(target, prop, target);
return typeof value === 'function'
? wrap(value as UncheckedMethod, thisArg => (thisArg === proxy ? target : thisArg))
: value;
},
});
return proxy;
}

return eventHandler;
}

function runTailMethod(
method: TailMethod,
options: CloudflareOptions,
context: ExecutionContext,
invoke: () => unknown,
): unknown {
if (method !== 'tailStream') {
return wrapTailHandler(options, context, method, invoke);
}

return wrapTailHandler(options, context, method, async () =>
wrapTailStreamEventHandler(await invoke(), options, context),
);
}
Comment thread
cursor[bot] marked this conversation as resolved.
Resolved

/**
* Instruments the `tail`, `trace` and `tailStream` handlers for
* ExportedHandler (env/ctx come from args).
*/
export function instrumentExportedHandlerTail<T extends AnyExportedHandler>(
handler: T,
optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined,
): void {
if (!('tail' in handler) || typeof handler.tail !== 'function') {
return;
}
for (const method of TAIL_METHODS) {
if (!(method in handler)) {
continue;
}

handler.tail = ensureInstrumented(
handler.tail,
original =>
new Proxy(original, {
apply(target, thisArg, args: Parameters<NonNullable<T['tail']>>) {
const [, env, ctx] = args;
const context = instrumentContext(ctx);
const options = getFinalOptions(optionsCallback(env), env);
args[1] = instrumentEnv(env, options);
args[2] = context;

return wrapTailHandler(options, context, () => target.apply(thisArg, args));
},
}),
);
const original = handler[method];
if (typeof original !== 'function') {
continue;
}

handler[method] = ensureInstrumented(
original,
original =>
new Proxy(original, {
apply(target, thisArg, args: Parameters<UncheckedMethod>) {
const [, env, ctx] = args;
const context = instrumentContext(ctx);
const options = getFinalOptions(optionsCallback(env), env);
args[1] = instrumentEnv(env, options);
args[2] = context;

return runTailMethod(method, options, context, () => target.apply(thisArg, args));
},
}),
);
}
}

/**
* Instruments a tail method for WorkerEntrypoint (options/context already available).
* Instruments the `tail`, `trace` and `tailStream` methods for
* WorkerEntrypoint (options/context already available).
*/
export function instrumentWorkerEntrypointTail<T extends WorkerEntrypoint>(
instance: T,
options: CloudflareOptions,
context: ExecutionContext,
): void {
if (!instance.tail) {
return;
}
const methods = instance as Partial<Record<TailMethod, UncheckedMethod>>;

const original = instance.tail.bind(instance);
instance.tail = new Proxy(original, {
apply(target, thisArg, args: [TraceItem[]]) {
return wrapTailHandler(options, context, () => Reflect.apply(target, thisArg, args));
},
});
for (const method of TAIL_METHODS) {
const original = methods[method];
if (!original) {
continue;
}

methods[method] = new Proxy(original.bind(instance), {
apply(target, thisArg, args) {
return runTailMethod(method, options, context, () => Reflect.apply(target, thisArg, args));
},
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,49 @@ describe('instrumentWorkerEntrypoint', () => {
expect(await response.text()).toBe('ok');
});

it('captures and re-throws errors thrown by the trace method', async () => {
const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException');
const error = new Error('test');
const TestClass = class extends WorkerEntrypoint {
trace() {
throw error;
}
};
const obj = Reflect.construct(
instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor),
[createMockExecutionContext(), {}],
);

await expect(obj.trace([])).rejects.toBe(error);
expect(captureExceptionSpy).toHaveBeenCalledTimes(1);
expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, {
mechanism: { handled: false, type: 'auto.faas.cloudflare.trace' },
});
});

it('captures and re-throws errors thrown by the event handler that tailStream returns', async () => {
const captureExceptionSpy = vi.spyOn(SentryCore, 'captureException');
const error = new Error('test');
const TestClass = class extends WorkerEntrypoint {
tailStream() {
return () => {
throw error;
};
}
};
const obj = Reflect.construct(
instrumentWorkerEntrypoint(vi.fn().mockReturnValue({}), TestClass as unknown as WorkerEntrypointConstructor),
[createMockExecutionContext(), {}],
);

const eventHandler = await obj.tailStream({});
await expect(eventHandler({})).rejects.toBe(error);
expect(captureExceptionSpy).toHaveBeenCalledTimes(1);
expect(captureExceptionSpy).toHaveBeenLastCalledWith(error, {
mechanism: { handled: false, type: 'auto.faas.cloudflare.tail_stream' },
});
});

it('Does not instrument ctx and env properties', () => {
const mockContext = createMockExecutionContext();
const mockEnv = {};
Expand Down Expand Up @@ -529,7 +572,7 @@ describe('instrumentWorkerEntrypoint', () => {
await obj.alarm();
await obj.webSocketMessage();

expect(initAndBind).toHaveBeenCalledTimes(3);
expect(initAndBind).toHaveBeenCalledTimes(5);
});
});

Expand Down
Loading
Loading