-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathdurableobject.ts
More file actions
225 lines (203 loc) · 7.19 KB
/
durableobject.ts
File metadata and controls
225 lines (203 loc) · 7.19 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
/* eslint-disable @typescript-eslint/unbound-method */
import {
captureException,
flush,
getClient,
SEMANTIC_ATTRIBUTE_SENTRY_OP,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
startSpan,
withIsolationScope,
withScope,
} from '@sentry/core';
import type { DurableObject } from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { isInstrumented, markAsInstrumented } from './instrument';
import { getFinalOptions } from './options';
import { wrapRequestHandler } from './request';
import { init } from './sdk';
type MethodWrapperOptions = {
spanName?: string;
spanOp?: string;
options: CloudflareOptions;
context: ExecutionContext | DurableObjectState;
};
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function wrapMethodWithSentry<T extends (...args: any[]) => any>(
wrapperOptions: MethodWrapperOptions,
handler: T,
callback?: (...args: Parameters<T>) => void,
): T {
if (isInstrumented(handler)) {
return handler;
}
markAsInstrumented(handler);
return new Proxy(handler, {
apply(target, thisArg, args: Parameters<T>) {
const currentClient = getClient();
// if a client is already set, use withScope, otherwise use withIsolationScope
const sentryWithScope = currentClient ? withScope : withIsolationScope;
return sentryWithScope(async scope => {
// In certain situations, the passed context can become undefined.
// For example, for Astro while prerendering pages at build time.
// see: https://github.com/getsentry/sentry-javascript/issues/13217
const context = wrapperOptions.context as ExecutionContext | undefined;
const currentClient = scope.getClient();
if (!currentClient) {
const client = init(wrapperOptions.options);
scope.setClient(client);
}
if (!wrapperOptions.spanName) {
try {
if (callback) {
callback(...args);
}
return await Reflect.apply(target, thisArg, args);
} catch (e) {
captureException(e, {
mechanism: {
type: 'cloudflare_durableobject',
handled: false,
},
});
throw e;
} finally {
context?.waitUntil(flush(2000));
}
}
const attributes = wrapperOptions.spanOp
? {
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare_durableobjects',
}
: {};
// Only create these spans if they have a parent span.
return startSpan({ name: wrapperOptions.spanName, attributes, onlyIfParent: true }, async () => {
try {
return await Reflect.apply(target, thisArg, args);
} catch (e) {
captureException(e, {
mechanism: {
type: 'cloudflare_durableobject',
handled: false,
},
});
throw e;
} finally {
context?.waitUntil(flush(2000));
}
});
});
},
});
}
/**
* 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>>(
optionsCallback: (env: E) => CloudflareOptions,
DurableObjectClass: new (state: DurableObjectState, env: E) => T,
): new (state: DurableObjectState, env: E) => T {
return new Proxy(DurableObjectClass, {
construct(target, [context, env]) {
setAsyncLocalStorageAsyncContextStrategy();
const options = getFinalOptions(optionsCallback(env), env);
const obj = new target(context, env);
// 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' && !isInstrumented(obj.fetch)) {
obj.fetch = new Proxy(obj.fetch, {
apply(target, thisArg, args) {
return wrapRequestHandler({ options, request: args[0], context }, () =>
Reflect.apply(target, thisArg, args),
);
},
});
markAsInstrumented(obj.fetch);
}
if (obj.alarm && typeof obj.alarm === 'function') {
obj.alarm = wrapMethodWithSentry({ options, context, spanName: 'alarm' }, 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: 'cloudflare_durableobject_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' },
// eslint-disable-next-line @typescript-eslint/no-explicit-any
value as (...args: any[]) => any,
);
}
}
return obj;
},
});
}