-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathdurableobject.ts
More file actions
252 lines (223 loc) · 8.55 KB
/
durableobject.ts
File metadata and controls
252 lines (223 loc) · 8.55 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
/* eslint-disable @typescript-eslint/unbound-method */
import { captureException } from '@sentry/core';
import type { DurableObject } from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { ensureInstrumented, getInstrumented, markAsInstrumented } from './instrument';
import { instrumentEnv } from './instrumentations/worker/instrumentEnv';
import { getFinalOptions } from './options';
import { wrapRequestHandler } from './request';
import { instrumentContext } from './utils/instrumentContext';
import type { UncheckedMethod } from './wrapMethodWithSentry';
import { wrapMethodWithSentry } from './wrapMethodWithSentry';
/**
* Instruments a Durable Object class to capture errors and performance data.
*
* Instruments the following methods:
* - fetch
* - alarm
* - webSocketMessage
* - webSocketClose
* - webSocketError
*
* as well as any other public RPC methods on the Durable Object instance.
*
* @param optionsCallback Function that returns the options for the SDK initialization.
* @param DurableObjectClass The Durable Object class to instrument.
* @returns The instrumented Durable Object class.
*
* @example
* ```ts
* class MyDurableObjectBase extends DurableObject {
* constructor(ctx: DurableObjectState, env: Env) {
* super(ctx, env);
* }
* }
*
* export const MyDurableObject = instrumentDurableObjectWithSentry(
* env => ({
* dsn: env.SENTRY_DSN,
* tracesSampleRate: 1.0,
* }),
* MyDurableObjectBase,
* );
* ```
*/
export function instrumentDurableObjectWithSentry<
E,
T extends DurableObject<E>,
C extends new (state: DurableObjectState, env: E) => T,
>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {
return new Proxy(DurableObjectClass, {
construct(target, [ctx, env]) {
setAsyncLocalStorageAsyncContextStrategy();
const context = instrumentContext(ctx);
const options = getFinalOptions(optionsCallback(env), env);
const instrumentedEnv = instrumentEnv(env);
const obj = new target(context, instrumentedEnv);
// These are the methods that are available on a Durable Object
// ref: https://developers.cloudflare.com/durable-objects/api/base/
// obj.alarm
// obj.fetch
// obj.webSocketError
// obj.webSocketClose
// obj.webSocketMessage
// Any other public methods on the Durable Object instance are RPC calls.
if (obj.fetch && typeof obj.fetch === 'function') {
obj.fetch = ensureInstrumented(
obj.fetch,
original =>
new Proxy(original, {
apply(target, thisArg, args) {
return wrapRequestHandler({ options, request: args[0], context }, () => {
return Reflect.apply(target, thisArg, args);
});
},
}),
);
}
if (obj.alarm && typeof obj.alarm === 'function') {
// Alarms are independent invocations, so we start a new trace and link to the previous alarm
obj.alarm = wrapMethodWithSentry(
{ options, context, spanName: 'alarm', spanOp: 'function', startNewTrace: true },
obj.alarm,
);
}
if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {
obj.webSocketMessage = wrapMethodWithSentry(
{ options, context, spanName: 'webSocketMessage' },
obj.webSocketMessage,
);
}
if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {
obj.webSocketClose = wrapMethodWithSentry({ options, context, spanName: 'webSocketClose' }, obj.webSocketClose);
}
if (obj.webSocketError && typeof obj.webSocketError === 'function') {
obj.webSocketError = wrapMethodWithSentry(
{ options, context, spanName: 'webSocketError' },
obj.webSocketError,
(_, error) =>
captureException(error, {
mechanism: {
type: 'auto.faas.cloudflare.durable_object_websocket',
handled: false,
},
}),
);
}
for (const method of Object.getOwnPropertyNames(obj)) {
if (
method === 'fetch' ||
method === 'alarm' ||
method === 'webSocketError' ||
method === 'webSocketClose' ||
method === 'webSocketMessage'
) {
continue;
}
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
const value = (obj as any)[method] as unknown;
if (typeof value === 'function') {
// eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any
(obj as any)[method] = wrapMethodWithSentry(
{ options, context, spanName: method, spanOp: 'rpc' },
value as UncheckedMethod,
);
}
}
// Store context and options on the instance for prototype methods to access
Object.defineProperty(obj, '__SENTRY_CONTEXT__', {
value: context,
enumerable: false,
writable: false,
configurable: false,
});
Object.defineProperty(obj, '__SENTRY_OPTIONS__', {
value: options,
enumerable: false,
writable: false,
configurable: false,
});
if (options?.instrumentPrototypeMethods) {
instrumentPrototype(target, options.instrumentPrototypeMethods);
}
return obj;
},
});
}
function instrumentPrototype<T extends NewableFunction>(target: T, methodsToInstrument: boolean | string[]): void {
const proto = target.prototype;
// Get all methods from the prototype chain
const methodNames = new Set<string>();
let current = proto;
while (current && current !== Object.prototype) {
Object.getOwnPropertyNames(current).forEach(name => {
if (name !== 'constructor' && typeof (current as Record<string, unknown>)[name] === 'function') {
methodNames.add(name);
}
});
current = Object.getPrototypeOf(current);
}
// Create a set for efficient lookups when methodsToInstrument is an array
const methodsToInstrumentSet = Array.isArray(methodsToInstrument) ? new Set(methodsToInstrument) : null;
// Instrument each method on the prototype
methodNames.forEach(methodName => {
const originalMethod = (proto as Record<string, unknown>)[methodName];
if (!originalMethod) {
return;
}
const existingInstrumented = getInstrumented(originalMethod);
if (existingInstrumented) {
Object.defineProperty(proto, methodName, {
value: existingInstrumented,
enumerable: false,
writable: true,
configurable: true,
});
return;
}
// If methodsToInstrument is an array, only instrument methods in that set
if (methodsToInstrumentSet && !methodsToInstrumentSet.has(methodName)) {
return;
}
// Create a wrapper that gets context/options from the instance at runtime
const wrappedMethod = function (this: unknown, ...args: unknown[]): unknown {
const thisWithSentry = this as {
__SENTRY_CONTEXT__: DurableObjectState;
__SENTRY_OPTIONS__: CloudflareOptions;
};
const instanceContext = thisWithSentry.__SENTRY_CONTEXT__;
const instanceOptions = thisWithSentry.__SENTRY_OPTIONS__;
if (!instanceOptions) {
// Fallback to original method if no Sentry data found
return (originalMethod as UncheckedMethod).apply(this, args);
}
// Use the existing wrapper but with instance-specific context/options
const wrapper = wrapMethodWithSentry(
{
options: instanceOptions,
context: instanceContext,
spanName: methodName,
spanOp: 'rpc',
},
originalMethod as UncheckedMethod,
undefined,
true, // noMark = true since we'll mark the prototype method
);
return wrapper.apply(this, args);
};
// Only mark wrappedMethod as instrumented (not originalMethod → wrappedMethod).
// originalMethod must stay unmapped because wrappedMethod calls
// wrapMethodWithSentry(options, originalMethod) on each invocation to create
// a per-instance proxy. If originalMethod mapped to wrappedMethod, that call
// would return wrappedMethod itself, causing infinite recursion.
markAsInstrumented(wrappedMethod);
// Replace the prototype method
Object.defineProperty(proto, methodName, {
value: wrappedMethod,
enumerable: false,
writable: true,
configurable: true,
});
});
}