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
7 changes: 5 additions & 2 deletions packages/cloudflare/src/durableobject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,16 @@ export function instrumentDurableObjectWithSentry<
C extends new (state: DurableObjectState, env: E) => T,
>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {
return new Proxy(DurableObjectClass, {
construct(target, [ctx, env]) {
construct(target, [ctx, env], newTarget) {
setAsyncLocalStorageAsyncContextStrategy();
const context = instrumentContext(ctx);
const options = getFinalOptions(optionsCallback(env), env);
const instrumentedEnv = instrumentEnv(env, options);

const obj = new target(context, instrumentedEnv);
// Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes
// created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their
// own prototype — otherwise subclass methods disappear and `instanceof` checks break.
const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;

// These are the methods that are available on a Durable Object
// ref: https://developers.cloudflare.com/durable-objects/api/base/
Expand Down
29 changes: 29 additions & 0 deletions packages/cloudflare/test/durableobject.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,35 @@ describe('instrumentDurableObjectWithSentry', () => {
expect(obj.constructor).toBe(testClass);
});

it('honors newTarget so that subclasses of the instrumented class keep their prototype', () => {
const testClass = class {
fetch() {
return new Response('fetch');
}

alarm() {}
};
const instrumented = instrumentDurableObjectWithSentry(vi.fn().mockReturnValue({}), testClass as any);

// Dev tooling such as wrangler or `@cloudflare/vitest-pool-workers` subclasses the exported
// (instrumented) class, so the construct trap is invoked with the subclass as `newTarget`.
class Subclass extends instrumented {
subclassMethod() {
return 'subclass-result';
}
}

const obj = Reflect.construct(Subclass, []);

// The subclass prototype must be preserved
expect(obj).toBeInstanceOf(Subclass);
expect(obj.subclassMethod()).toBe('subclass-result');

// Built-in DO methods are still instrumented
expect(getInstrumented(obj.fetch)).toBeTruthy();
expect(getInstrumented(obj.alarm)).toBeTruthy();
});

it('Does not instrument RPC methods when instrumentPrototypeMethods is not set', () => {
const testClass = class {
rpcMethod() {
Expand Down
Loading