Skip to content
Draft
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,73 @@
import * as Sentry from '@sentry/cloudflare';
import { DurableObject } from 'cloudflare:workers';

interface Env {
SENTRY_DSN: string;
MY_DURABLE_OBJECT: DurableObjectNamespace<MyDurableObjectBase>;
}

class MyDurableObjectBase extends DurableObject<Env> {
#name: string | undefined;

setName(name: string): string {
this.#name = name;
return this.#name;
}

bootstrap(name: string): string {
// Regression for #23040 — native Durable Object RPC (facets, the Agents SDK bootstrap
// calling PartyServer's `setName()`) resolves the method on the prototype and invokes it
// with the stored Durable Object instance as the receiver. When the instrumented
// constructor returned a Proxy of the instance, native private field access failed:
// "TypeError: Cannot read private member #name from an object whose class did not declare
// it" — a Proxy never carries the target's private-field brand.
//
// Construct a fresh instrumented instance exactly as the runtime does (the raw
// DurableObjectState sits below the instrumented context's prototype), then dispatch the
// way native RPC does: prototype method, stored instance as receiver.
const rawCtx = Object.getPrototypeOf(this.ctx) as DurableObjectState;
const instance = new MyDurableObject(rawCtx, this.env);
const prototype = Object.getPrototypeOf(instance) as MyDurableObjectBase;
return prototype.setName.call(instance, name);
}
}

export const MyDurableObject = Sentry.instrumentDurableObjectWithSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
traceLifecycle: 'static',
tracesSampleRate: 1.0,
enableRpcTracePropagation: true,
}),
MyDurableObjectBase,
);

export default Sentry.withSentry(
(env: Env) => ({
dsn: env.SENTRY_DSN,
traceLifecycle: 'static',
tracesSampleRate: 1.0,
enableRpcTracePropagation: true,
}),
{
async fetch(request, env) {
const url = new URL(request.url);

if (url.pathname === '/prototype-dispatch') {
const id = env.MY_DURABLE_OBJECT.idFromName('test');
const stub = env.MY_DURABLE_OBJECT.get(id);
const name = await stub.bootstrap('agent-1');
return new Response(name);
}

if (url.pathname === '/rpc/set-name') {
const id = env.MY_DURABLE_OBJECT.idFromName('test');
const stub = env.MY_DURABLE_OBJECT.get(id);
const name = await stub.setName('agent-2');
return new Response(name);
}

return new Response('Not found', { status: 404 });
},
} satisfies ExportedHandler<Env>,
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { expect, it } from 'vitest';
import type { Event } from '@sentry/core';
import { createRunner } from '../../../runner';

// Regression for #23040 — a Durable Object using native private fields must stay functional when
// instrumented with `enableRpcTracePropagation: true`. Native RPC dispatch (Durable Object facets,
// the Agents SDK bootstrap) invokes prototype methods with the stored instance as the receiver,
// so the instrumented instance must not be a Proxy: a Proxy does not carry the private-field
// brand and `this.#field` throws "Cannot read private member".
it('keeps native private fields working when a prototype method is invoked with the instance as receiver', async ({
signal,
}) => {
const runner = createRunner(__dirname)
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1] as Event;

expect(transactionEvent).toEqual(
expect.objectContaining({
contexts: expect.objectContaining({
trace: expect.objectContaining({
op: 'rpc',
origin: 'auto.faas.cloudflare.durable_object',
}),
}),
transaction: 'bootstrap',
}),
);
})
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1] as Event;

expect(transactionEvent).toEqual(
expect.objectContaining({
contexts: expect.objectContaining({
trace: expect.objectContaining({
op: 'http.server',
origin: 'auto.http.cloudflare',
}),
}),
transaction: 'GET /prototype-dispatch',
}),
);
})
.unordered()
.start(signal);

const response = await runner.makeRequest<string>('get', '/prototype-dispatch');
expect(response).toBe('agent-1');

await runner.completed();
});

it('propagates trace and preserves the result for a regular RPC method call', async ({ signal }) => {
const runner = createRunner(__dirname)
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1] as Event;

expect(transactionEvent).toEqual(
expect.objectContaining({
contexts: expect.objectContaining({
trace: expect.objectContaining({
op: 'rpc',
data: expect.objectContaining({
'sentry.origin': 'auto.faas.cloudflare.durable_object',
}),
origin: 'auto.faas.cloudflare.durable_object',
}),
}),
transaction: 'setName',
}),
);
})
.expect(envelope => {
const transactionEvent = envelope[1]?.[0]?.[1] as Event;

expect(transactionEvent).toEqual(
expect.objectContaining({
contexts: expect.objectContaining({
trace: expect.objectContaining({
op: 'http.server',
origin: 'auto.http.cloudflare',
}),
}),
transaction: 'GET /rpc/set-name',
}),
);
})
.unordered()
.start(signal);

const response = await runner.makeRequest<string>('get', '/rpc/set-name');
expect(response).toBe('agent-2');

await runner.completed();
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "cloudflare-do-rpc-private-fields",
"main": "index.ts",
"compatibility_date": "2025-06-17",
"compatibility_flags": ["nodejs_compat"],
"migrations": [
{
"new_sqlite_classes": ["MyDurableObject"],
"tag": "v1",
},
],
"durable_objects": {
"bindings": [
{
"class_name": "MyDurableObject",
"name": "MY_DURABLE_OBJECT",
},
],
},
}
147 changes: 105 additions & 42 deletions packages/cloudflare/src/durableobject.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
/* eslint-disable @typescript-eslint/unbound-method */
import { captureException } from '@sentry/core';
import { captureException, isObjectLike } from '@sentry/core';
import type { DurableObject } from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';
import type { CloudflareOptions } from './client';
import { ensureInstrumented } from './instrument';
import { ensureInstrumented, getInstrumented, markAsInstrumented } from './instrument';
import { instrumentEnv } from './instrumentations/worker/instrumentEnv';
import { getFinalOptions } from './options';
import { wrapRequestHandlerWithInit } from './request';
Expand Down Expand Up @@ -33,8 +33,8 @@ type InstrumentedDurableObjectContext = any;
*
* This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}
* and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method
* proxy — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any additional
* per-instance instrumentation has been layered onto the returned object.
* instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any
* additional per-instance instrumentation has been layered onto the returned object.
*
* @internal
*/
Expand Down Expand Up @@ -145,10 +145,29 @@ function instrumentDurableObjectHandlers<E, T extends DurableObject<E>>(
}
}

type RpcInstanceState = {
options: CloudflareOptions;
context: InstrumentedDurableObjectContext;
/** Per-instance cache of the traced method wrappers, keyed by method name. */
tracedMethods: Map<string, UncheckedMethod>;
};

/**
* Per-instance state for the shared prototype-method wrappers, keyed on the Durable Object
* instance. The wrappers live on the class prototype, so they resolve the calling instance's
* state through this map at call time.
*/
const rpcInstanceStates = new WeakMap<object, RpcInstanceState>();

/**
* Wraps a constructed (and already handler-instrumented) Durable Object instance with the RPC
* prototype-method proxy, when RPC trace propagation is enabled. Returns the object unchanged when
* RPC instrumentation is disabled.
* Instruments the RPC prototype methods of a constructed (and already handler-instrumented)
* Durable Object instance, when RPC trace propagation is enabled. Returns the object unchanged
* when RPC instrumentation is disabled.
*
* The wrappers are installed on the class prototype rather than wrapping the instance in a
* Proxy: native Durable Object RPC resolves methods on the prototype and invokes them with the
* stored instance as the receiver, and a Proxy does not carry the instance's private-field
* brand, which breaks native private fields.
*
* This must be applied last, so that any per-instance instrumentation (own properties such as
* `fetch`, `alarm`, or Agent-specific handlers) is excluded from RPC method tracing.
Expand All @@ -165,56 +184,100 @@ export function finalizeWithRpcInstrumentation<T extends object>(
return obj;
}

// Return a Proxy that binds all methods to the original object and creates spans
// for RPC calls that have Sentry trace context propagated.
// Binding is required because frameworks may use private fields (babel WeakMap pattern),
// which fail if `this` is the Proxy instead of the original object.
const methodCache = new Map<string, UncheckedMethod>();
rpcInstanceStates.set(obj, { options, context, tracedMethods: new Map() });

return new Proxy(obj, {
get(proxyTarget, prop, receiver) {
const value = Reflect.get(proxyTarget, prop, receiver);
instrumentPrototypeRpcMethods(obj);

if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {
return value;
}
return obj;
}

const cached = methodCache.get(prop);
/**
* Wraps the function-valued methods on the instance's prototype chain, stopping at
* `Object.prototype`. Runs on every construction; methods already wrapped by a previous
* construction of the class are skipped.
*/
function instrumentPrototypeRpcMethods(obj: object): void {
let prototype: object | null = Object.getPrototypeOf(obj);

if (cached) {
return cached;
while (prototype && prototype !== Object.prototype) {
for (const methodName of Object.getOwnPropertyNames(prototype)) {
if (methodName === 'constructor') {
continue;
}

const boundMethod = (value as UncheckedMethod).bind(proxyTarget);
const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);

// Only plain methods are RPC-invocable — accessors are skipped
if (!descriptor || typeof descriptor.value !== 'function') {
continue;
}

if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop)) {
methodCache.set(prop, boundMethod);
// Methods instrumented per-instance (built-in handlers such as `fetch` and `alarm`, or
// Agent-specific handlers) live as own properties that shadow the prototype
if (Object.prototype.hasOwnProperty.call(obj, methodName)) {
continue;
}

return boundMethod;
if (getInstrumented(descriptor.value)) {
// Already wrapped by a previous construction of this class
continue;
}

// Pre-create the traced version
const tracedMethod = wrapMethodWithSentry(
{ options, context, spanName: prop, spanOp: 'rpc', origin: 'auto.faas.cloudflare.durable_object' },
boundMethod,
const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);
Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });
// Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves
// through the same global map and must not resolve the original to this wrapper,
// which would recurse.
markAsInstrumented(wrapped);
}

prototype = Object.getPrototypeOf(prototype);
}
}

/**
* Creates the shared prototype-level wrapper for a single RPC method. Per-instance state is
* resolved at call time through the receiver, so one wrapper serves every instance of the
* class — instances constructed without instrumentation (or with RPC instrumentation disabled)
* fall through to the original method.
*/
function createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {
const wrapper = function (this: unknown, ...args: unknown[]): unknown {
// Check the call-scoped metadata first: untraced calls (the common case) then skip the
// per-instance state lookup entirely. Only create a span when the caller propagated
// Sentry RPC trace metadata.
if (!extractRpcMeta(args).rpcMeta) {
return Reflect.apply(originalMethod, this, args);
}

const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;

if (!state) {
return Reflect.apply(originalMethod, this, args);
}

let traced = state.tracedMethods.get(methodName);

if (!traced) {
traced = wrapMethodWithSentry(
{
options: state.options,
context: state.context,
spanName: methodName,
spanOp: 'rpc',
origin: 'auto.faas.cloudflare.durable_object',
},
originalMethod,
undefined,
true,
);
state.tracedMethods.set(methodName, traced);
}

// Wrapper that checks for Sentry RPC metadata at call time
const wrappedMethod = ((...args: unknown[]) => {
const { rpcMeta } = extractRpcMeta(args);

// If Sentry RPC metadata is present, use the traced version (creates span)
// Otherwise, call the bound method directly (no span)
return rpcMeta ? tracedMethod(...args) : boundMethod(...args);
}) as UncheckedMethod;
return Reflect.apply(traced, this, args);
};

methodCache.set(prop, wrappedMethod);

return wrappedMethod;
},
});
return wrapper as UncheckedMethod;
}

/**
Expand Down
Loading
Loading