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
Expand Up @@ -28,14 +28,21 @@ export default Sentry.withSentry(
rpcTracePropagationBindings: ['MY_DURABLE_OBJECT'],
}),
{
async fetch(request, env) {
async fetch(request, env, ctx) {
const url = new URL(request.url);

if (url.pathname === '/queue/send') {
await env.MY_QUEUE.send({ action: 'test' });
return new Response('Queued');
}

if (url.pathname === '/ctx-exports') {
const namespace = (ctx as unknown as { exports: { MyDurableObject: DurableObjectNamespace } }).exports
.MyDurableObject;
const response = await namespace.getByName('test').fetch(new Request('http://fake-host/hello'));
return new Response(await response.text());
}

const id = env.MY_DURABLE_OBJECT.idFromName('test');
const stub = env.MY_DURABLE_OBJECT.get(id);
const response = await stub.fetch(new Request('http://fake-host/hello'));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,38 @@ it('propagates trace from worker to durable object', async ({ signal }) => {
expect(doSpan?.parent_span_id).toBe(workerSpan?.span_id);
});

it('propagates trace from worker to a durable object reached through ctx.exports', async ({ signal }) => {
let workerSpan: SerializedStreamedSpan | undefined;
let doSpan: SerializedStreamedSpan | undefined;

const runner = createRunner(__dirname)
.expect(envelope => {
const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment);

expect(getSpanOp(segmentSpan!)).toBe('http.server');
expect(segmentSpan?.attributes['url.path']).toEqual({ type: 'string', value: '/hello' });
doSpan = segmentSpan;
})
.expect(envelope => {
const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment);

expect(getSpanOp(segmentSpan!)).toBe('http.server');
expect(segmentSpan?.attributes['url.path']).toEqual({ type: 'string', value: '/ctx-exports' });
workerSpan = segmentSpan;
})
.unordered()
.start(signal);

const response = await runner.makeRequest<string>('get', '/ctx-exports');
expect(response).toBe('DO is fine');

await runner.completed();

expect(workerSpan?.trace_id).toBeDefined();
expect(doSpan?.trace_id).toBe(workerSpan?.trace_id);
expect(doSpan?.parent_span_id).toBe(workerSpan?.span_id);
});

it('propagates trace from queue handler to durable object', async ({ signal }) => {
let queueSpan: SerializedStreamedSpan | undefined;
let doSpan: SerializedStreamedSpan | undefined;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"name": "cloudflare-durable-objects",
"main": "index.ts",
"compatibility_date": "2025-06-17",
"compatibility_flags": ["nodejs_compat"],
"compatibility_flags": ["nodejs_compat", "enable_ctx_exports"],
"migrations": [
{
"new_sqlite_classes": ["MyDurableObject"],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,17 @@ export const LoopbackEntrypoint = Sentry.withSentry(
LoopbackEntrypointBase,
);

class LoopbackFetchEntrypointBase extends WorkerEntrypoint<Env, { greeting: string }> {
fetch(): Response {
return new Response(`${this.ctx.props.greeting} from the loopback entrypoint`);
}
}

export const LoopbackFetchEntrypoint = Sentry.withSentry(
(env: Env) => ({ dsn: env.SENTRY_DSN, tracesSampleRate: 1.0 }),
LoopbackFetchEntrypointBase,
);

export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
Expand Down Expand Up @@ -75,6 +86,16 @@ export default Sentry.withSentry(
return Response.json(result);
}

if (url.pathname === '/call-loopback-fetch') {
const loopback = (
ctx as unknown as {
exports: { LoopbackFetchEntrypoint(options: { props: { greeting: string } }): Fetcher };
}
).exports.LoopbackFetchEntrypoint({ props: { greeting: 'Hello' } });
const response = await loopback.fetch(new Request('http://fake-host/loopback'));
return new Response(await response.text());
}

if (url.pathname === '/call-loopback-rpc-error') {
try {
await (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,35 @@ it('does not inject RPC trace metadata into receiver calls when rpcTracePropagat
await runner.completed();
});

it('propagates trace from Worker to a WorkerEntrypoint called with props through ctx.exports', async ({ signal }) => {
let workerSpan: SerializedStreamedSpan | undefined;
let entrypointSpan: SerializedStreamedSpan | undefined;

const runner = createRunner(__dirname)
.expect(envelope => {
const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment);
expect(segmentSpan?.attributes['url.path']).toEqual({ type: 'string', value: '/call-loopback-fetch' });
workerSpan = segmentSpan;
})
.expect(envelope => {
const segmentSpan = getSpansFromEnvelope(envelope).find(span => span.is_segment);
expect(getSpanOp(segmentSpan!)).toBe('http.server');
expect(segmentSpan?.attributes['url.path']).toEqual({ type: 'string', value: '/loopback' });
entrypointSpan = segmentSpan;
})
.unordered()
.start(signal);

const response = await runner.makeRequest<string>('get', '/call-loopback-fetch');
expect(response).toBe('Hello from the loopback entrypoint');

await runner.completed();

expect(workerSpan?.trace_id).toBeDefined();
expect(entrypointSpan?.trace_id).toBe(workerSpan?.trace_id);
expect(entrypointSpan?.parent_span_id).toBe(workerSpan?.span_id);
});

it('captures errors from loopback WorkerEntrypoint RPC without trace propagation', async ({ signal }) => {
const runner = createRunner(__dirname)
.expect(envelope => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,22 @@
"@types/node": "^26.1.2",
"@types/react": "^19.3.0",
"@types/react-dom": "^19.3.0",
"@vinext/cloudflare": "^1.4.0",
"@vitejs/plugin-react": "^6.1.1",
"@vitejs/plugin-rsc": "^0.5.35",
"react-server-dom-webpack": "^19.3.0",
"typescript": "~6.0.3",
"vinext": "^1.0.1",
"vite": "^8.3.0",
"wrangler": "^4.135.0"
},
"sentryTest": {
"optionalVariants": [
{
"build-command": "E2E_VINEXT_WORKERS_CACHE=1 pnpm test:build",
"assert-command": "pnpm test tests/page-errors.test.ts",
"label": "vinext-cf-workers (workers cache)"
}
]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { connection } from 'next/server';

export default async function PageError() {
await connection();
throw new Error('Page render error from vinext');
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import { expect, test } from '@playwright/test';
import { collectStreamedSpans, waitForError } from '@sentry-internal/test-utils';

test('Captures an error thrown while a page renders', async ({ request }) => {
const errorPromise = waitForError('vinext-cf-workers', event => {
return event.exception?.values?.[0]?.value === 'Page render error from vinext';
});
// vinext's Workers Cache adapter renders the page in a second invocation, whose request URL has a
// `__vinext_cache_key` query parameter. The error must be in the trace of the incoming request.
const requestSpansPromise = collectStreamedSpans('vinext-cf-workers', spans =>
spans.some(span => span.is_segment && span.name === 'GET /page-error' && !span.attributes['url.query']),
);

const response = await request.get('/page-error');
expect(response.status()).toBe(500);

const errorEvent = await errorPromise;
const requestSpans = await requestSpansPromise;

expect(errorEvent.sdk?.name).toBe('sentry.javascript.nextjs');
expect(errorEvent.environment).toBe('qa');
expect(errorEvent.transaction).toBe('GET /page-error');
expect(errorEvent.exception?.values?.[0]?.mechanism).toEqual({
handled: false,
type: 'auto.function.nextjs.on_request_error',
});
expect(errorEvent.contexts?.trace?.trace_id).toBe(requestSpans[0]?.trace_id);
});
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { cloudflare } from '@cloudflare/vite-plugin';
import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';
import { workersCacheCdnAdapter } from '@vinext/cloudflare/cache/workers-cache-cdn-adapter';
import vinext from 'vinext';
import { defineConfig } from 'vite';

// `worker/index.ts` contains no Sentry calls: in a vinext build the plugin wraps it with `withSentry` from
// `@sentry/nextjs/cloudflare`.
export default defineConfig({
plugins: [
vinext(),
// The `vinext-cf-workers (workers cache)` variant renders cacheable pages in the `VinextCachedResponse`
// entrypoint, which the default export calls through `ctx.exports`.
vinext(process.env.E2E_VINEXT_WORKERS_CACHE ? { cache: { cdn: workersCacheCdnAdapter() } } : {}),
cloudflare({ viteEnvironment: { name: 'rsc', childEnvironments: ['ssr'] } }),
sentryCloudflareVitePlugin(),
],
Expand Down
55 changes: 30 additions & 25 deletions packages/cloudflare/src/instrumentations/worker/instrumentEnv.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,8 @@ const instrumentedBindings = new WeakMap<object, unknown>();
* - R2 Buckets (via `head` + `put` + `createMultipartUpload` duck-typing)
* - Workers AI (via `run` + `gateway` + `toMarkdown` duck-typing)
*
* `ctx.exports` is wrapped the same way, as its entries are bindings to this Worker's own exports.
*
* @param env - The Cloudflare env object to instrument
* @param options - Optional CloudflareOptions to control RPC and Queue trace propagation
*/
Expand Down Expand Up @@ -104,31 +106,7 @@ export function instrumentEnv<Env extends Record<string, unknown>>(env: Env, opt
}

if (isJSRPC(item)) {
const instrumented = new Proxy(item, {
get(target, p) {
const value = Reflect.get(target, p);

if (p === 'fetch' && typeof value === 'function') {
return instrumentFetcher((...args) => Reflect.apply(value, target, args));
}

if (p === 'connect' && typeof value === 'function') {
return (...args: unknown[]) => Reflect.apply(value, target, args);
}

if (
propagateRpcTrace &&
typeof value === 'function' &&
typeof p === 'string' &&
!STUB_NON_RPC_METHODS.has(p)
) {
return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args));
}

return value;
},
});

const instrumented = instrumentServiceStub(item, propagateRpcTrace);
instrumentedBindings.set(item, instrumented);
return instrumented;
}
Expand All @@ -137,3 +115,30 @@ export function instrumentEnv<Env extends Record<string, unknown>>(env: Env, opt
},
});
}

function instrumentServiceStub<T extends object>(stub: T, propagateRpcTrace: boolean): T {
return new Proxy(stub, {
get(target, p) {
const value = Reflect.get(target, p);

if (p === 'fetch' && typeof value === 'function') {
return instrumentFetcher((...args) => Reflect.apply(value, target, args));
}

if (p === 'connect' && typeof value === 'function') {
return (...args: unknown[]) => Reflect.apply(value, target, args);
}

if (propagateRpcTrace && typeof value === 'function' && typeof p === 'string' && !STUB_NON_RPC_METHODS.has(p)) {
return (...args: unknown[]) => Reflect.apply(value, target, appendRpcMeta(args));
}

return value;
},
// An entrypoint in `ctx.exports` is callable: `ctx.exports.Name({ props })` returns a stub with these props.
apply(target, thisArg, args) {
const result: unknown = Reflect.apply(target as (...args: unknown[]) => unknown, thisArg, args);
return isProxyable(result) ? instrumentServiceStub(result, propagateRpcTrace) : result;
},
});
}
12 changes: 12 additions & 0 deletions packages/cloudflare/src/utils/instrumentContext.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { type DurableObjectState, type DurableObjectStorage, type ExecutionContext } from '@cloudflare/workers-types';
import { instrumentDurableObjectStorage } from '../instrumentations/instrumentDurableObjectStorage';
import { instrumentEnv } from '../instrumentations/worker/instrumentEnv';

type ContextType = ExecutionContext | DurableObjectState;
type OverridesStore<T extends ContextType> = Map<keyof T, (...args: unknown[]) => unknown>;
Expand All @@ -11,6 +12,8 @@ type OverridesStore<T extends ContextType> = Map<keyof T, (...args: unknown[]) =
* - Allows overriding of methods (e.g., waitUntil)
* - For DurableObjectState: instruments storage operations (get, put, delete, list, etc.)
* to create Sentry spans automatically
* - Instruments `exports` like `env`, so `fetch` calls to this Worker's own entrypoints carry
* the trace headers
*
* @param ctx - The execution context or DurableObjectState to instrument
* @returns An instrumented copy of the context
Expand Down Expand Up @@ -59,6 +62,15 @@ export function instrumentContext<T extends ContextType>(ctx: T): T {
};
}

if ('exports' in ctx) {
let instrumentedExports: unknown;
descriptors.exports = {
configurable: true,
enumerable: true,
get: () => (instrumentedExports ??= instrumentEnv(ctx.exports as Record<string, unknown>)),
};
}

return Object.create(ctx, descriptors);
}

Expand Down
Loading
Loading