@sentry/cloudflare 10.67.0 → 10.69.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cjs/client.js +5 -0
- package/build/cjs/client.js.map +1 -1
- package/build/cjs/defineCloudflareOptions.js +11 -0
- package/build/cjs/defineCloudflareOptions.js.map +1 -0
- package/build/cjs/durableobject.js +131 -96
- package/build/cjs/durableobject.js.map +1 -1
- package/build/cjs/index.js +6 -0
- package/build/cjs/index.js.map +1 -1
- package/build/cjs/instrumentations/agents/index.js +14 -0
- package/build/cjs/instrumentations/agents/index.js.map +1 -0
- package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js +52 -0
- package/build/cjs/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
- package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js +31 -0
- package/build/cjs/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
- package/build/cjs/instrumentations/agents/types.js +32 -0
- package/build/cjs/instrumentations/agents/types.js.map +1 -0
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js +6 -0
- package/build/cjs/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/cjs/instrumentations/instrumentSqlStorage.js +1 -1
- package/build/cjs/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/integrations/spotlight.js +64 -0
- package/build/cjs/integrations/spotlight.js.map +1 -0
- package/build/cjs/integrations/tracing/vercelai.js.map +1 -1
- package/build/cjs/nodejs_compat/index.js +10 -4
- package/build/cjs/nodejs_compat/index.js.map +1 -1
- package/build/cjs/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
- package/build/cjs/options.js +14 -1
- package/build/cjs/options.js.map +1 -1
- package/build/cjs/sdk.js +20 -1
- package/build/cjs/sdk.js.map +1 -1
- package/build/cjs/utils/internalSqlQuery.js +13 -7
- package/build/cjs/utils/internalSqlQuery.js.map +1 -1
- package/build/cjs/utils/internalStorageKey.js +44 -0
- package/build/cjs/utils/internalStorageKey.js.map +1 -0
- package/build/cjs/vite/agentClass.js +114 -0
- package/build/cjs/vite/agentClass.js.map +1 -0
- package/build/cjs/vite/autoInstrument.js +94 -0
- package/build/cjs/vite/autoInstrument.js.map +1 -0
- package/build/cjs/vite/index.js +14 -0
- package/build/cjs/vite/index.js.map +1 -0
- package/build/cjs/vite/instrumentFile.js +31 -0
- package/build/cjs/vite/instrumentFile.js.map +1 -0
- package/build/cjs/vite/moduleShape.js +231 -0
- package/build/cjs/vite/moduleShape.js.map +1 -0
- package/build/cjs/vite/transform.js +149 -0
- package/build/cjs/vite/transform.js.map +1 -0
- package/build/cjs/vite/workerEntrypoint.js +66 -0
- package/build/cjs/vite/workerEntrypoint.js.map +1 -0
- package/build/cjs/vite/wranglerConfig.js +54 -0
- package/build/cjs/vite/wranglerConfig.js.map +1 -0
- package/build/esm/client.js +6 -1
- package/build/esm/client.js.map +1 -1
- package/build/esm/defineCloudflareOptions.js +9 -0
- package/build/esm/defineCloudflareOptions.js.map +1 -0
- package/build/esm/durableobject.js +129 -97
- package/build/esm/durableobject.js.map +1 -1
- package/build/esm/index.js +4 -2
- package/build/esm/index.js.map +1 -1
- package/build/esm/instrumentations/agents/index.js +12 -0
- package/build/esm/instrumentations/agents/index.js.map +1 -0
- package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js +50 -0
- package/build/esm/instrumentations/agents/instrumentAgentCallableRpc.js.map +1 -0
- package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js +29 -0
- package/build/esm/instrumentations/agents/instrumentChatAgentConversation.js.map +1 -0
- package/build/esm/instrumentations/agents/types.js +26 -0
- package/build/esm/instrumentations/agents/types.js.map +1 -0
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js +7 -1
- package/build/esm/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/esm/instrumentations/instrumentSqlStorage.js +1 -1
- package/build/esm/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/integrations/spotlight.js +61 -0
- package/build/esm/integrations/spotlight.js.map +1 -0
- package/build/esm/integrations/tracing/vercelai.js.map +1 -1
- package/build/esm/nodejs_compat/index.js +5 -3
- package/build/esm/nodejs_compat/index.js.map +1 -1
- package/build/esm/nodejs_compat/integrations/tracing/vercelai.js.map +1 -1
- package/build/esm/options.js +14 -1
- package/build/esm/options.js.map +1 -1
- package/build/esm/package.json +1 -1
- package/build/esm/sdk.js +21 -2
- package/build/esm/sdk.js.map +1 -1
- package/build/esm/utils/internalSqlQuery.js +13 -7
- package/build/esm/utils/internalSqlQuery.js.map +1 -1
- package/build/esm/utils/internalStorageKey.js +41 -0
- package/build/esm/utils/internalStorageKey.js.map +1 -0
- package/build/esm/utils/traceLinks.js +1 -1
- package/build/esm/vite/agentClass.js +111 -0
- package/build/esm/vite/agentClass.js.map +1 -0
- package/build/esm/vite/autoInstrument.js +92 -0
- package/build/esm/vite/autoInstrument.js.map +1 -0
- package/build/esm/vite/index.js +12 -0
- package/build/esm/vite/index.js.map +1 -0
- package/build/esm/vite/instrumentFile.js +27 -0
- package/build/esm/vite/instrumentFile.js.map +1 -0
- package/build/esm/vite/moduleShape.js +227 -0
- package/build/esm/vite/moduleShape.js.map +1 -0
- package/build/esm/vite/transform.js +147 -0
- package/build/esm/vite/transform.js.map +1 -0
- package/build/esm/vite/workerEntrypoint.js +64 -0
- package/build/esm/vite/workerEntrypoint.js.map +1 -0
- package/build/esm/vite/wranglerConfig.js +52 -0
- package/build/esm/vite/wranglerConfig.js.map +1 -0
- package/build/types/client.d.ts +37 -0
- package/build/types/client.d.ts.map +1 -1
- package/build/types/defineCloudflareOptions.d.ts +38 -0
- package/build/types/defineCloudflareOptions.d.ts.map +1 -0
- package/build/types/durableobject.d.ts +81 -0
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/index.d.ts +4 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/instrumentations/agents/index.d.ts +24 -0
- package/build/types/instrumentations/agents/index.d.ts.map +1 -0
- package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
- package/build/types/instrumentations/agents/instrumentAgentCallableRpc.d.ts.map +1 -0
- package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
- package/build/types/instrumentations/agents/instrumentChatAgentConversation.d.ts.map +1 -0
- package/build/types/instrumentations/agents/types.d.ts +49 -0
- package/build/types/instrumentations/agents/types.d.ts.map +1 -0
- package/build/types/instrumentations/instrumentDurableObjectStorage.d.ts.map +1 -1
- package/build/types/integrations/spotlight.d.ts +22 -0
- package/build/types/integrations/spotlight.d.ts.map +1 -0
- package/build/types/integrations/tracing/vercelai.d.ts.map +1 -1
- package/build/types/nodejs_compat/index.d.ts +1 -1
- package/build/types/nodejs_compat/index.d.ts.map +1 -1
- package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts +1 -8
- package/build/types/nodejs_compat/integrations/tracing/vercelai.d.ts.map +1 -1
- package/build/types/options.d.ts.map +1 -1
- package/build/types/sdk.d.ts.map +1 -1
- package/build/types/utils/internalSqlQuery.d.ts +4 -2
- package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
- package/build/types/utils/internalStorageKey.d.ts +22 -0
- package/build/types/utils/internalStorageKey.d.ts.map +1 -0
- package/build/types/vite/agentClass.d.ts +41 -0
- package/build/types/vite/agentClass.d.ts.map +1 -0
- package/build/types/vite/autoInstrument.d.ts +22 -0
- package/build/types/vite/autoInstrument.d.ts.map +1 -0
- package/build/types/vite/index.d.ts +98 -0
- package/build/types/vite/index.d.ts.map +1 -0
- package/build/types/vite/instrumentFile.d.ts +22 -0
- package/build/types/vite/instrumentFile.d.ts.map +1 -0
- package/build/types/vite/moduleShape.d.ts +52 -0
- package/build/types/vite/moduleShape.d.ts.map +1 -0
- package/build/types/vite/transform.d.ts +65 -0
- package/build/types/vite/transform.d.ts.map +1 -0
- package/build/types/vite/workerEntrypoint.d.ts +12 -0
- package/build/types/vite/workerEntrypoint.d.ts.map +1 -0
- package/build/types/vite/wranglerConfig.d.ts +43 -0
- package/build/types/vite/wranglerConfig.d.ts.map +1 -0
- package/build/types-ts3.8/client.d.ts +37 -0
- package/build/types-ts3.8/defineCloudflareOptions.d.ts +38 -0
- package/build/types-ts3.8/durableobject.d.ts +81 -0
- package/build/types-ts3.8/index.d.ts +4 -2
- package/build/types-ts3.8/instrumentations/agents/index.d.ts +24 -0
- package/build/types-ts3.8/instrumentations/agents/instrumentAgentCallableRpc.d.ts +11 -0
- package/build/types-ts3.8/instrumentations/agents/instrumentChatAgentConversation.d.ts +22 -0
- package/build/types-ts3.8/instrumentations/agents/types.d.ts +49 -0
- package/build/types-ts3.8/integrations/spotlight.d.ts +22 -0
- package/build/types-ts3.8/nodejs_compat/index.d.ts +1 -1
- package/build/types-ts3.8/nodejs_compat/integrations/tracing/vercelai.d.ts +7 -14
- package/build/types-ts3.8/utils/internalSqlQuery.d.ts +4 -2
- package/build/types-ts3.8/utils/internalStorageKey.d.ts +22 -0
- package/build/types-ts3.8/vite/agentClass.d.ts +41 -0
- package/build/types-ts3.8/vite/autoInstrument.d.ts +22 -0
- package/build/types-ts3.8/vite/index.d.ts +98 -0
- package/build/types-ts3.8/vite/instrumentFile.d.ts +22 -0
- package/build/types-ts3.8/vite/moduleShape.d.ts +52 -0
- package/build/types-ts3.8/vite/transform.d.ts +65 -0
- package/build/types-ts3.8/vite/workerEntrypoint.d.ts +12 -0
- package/build/types-ts3.8/vite/wranglerConfig.d.ts +43 -0
- package/package.json +19 -5
|
@@ -7,112 +7,144 @@ import { wrapRequestHandler } from './request.js';
|
|
|
7
7
|
import { instrumentContext } from './utils/instrumentContext.js';
|
|
8
8
|
import { extractRpcMeta } from './utils/rpcMeta.js';
|
|
9
9
|
import { getEffectiveRpcPropagation } from './utils/rpcOptions.js';
|
|
10
|
+
import { instrumentCloudflareAgent } from './instrumentations/agents/index.js';
|
|
10
11
|
import { wrapMethodWithSentry } from './wrapMethodWithSentry.js';
|
|
11
12
|
|
|
12
|
-
function
|
|
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
|
-
|
|
13
|
+
function constructInstrumentedDurableObject(target, ctx, env, newTarget, optionsCallback) {
|
|
14
|
+
setAsyncLocalStorageAsyncContextStrategy();
|
|
15
|
+
const options = getFinalOptions(optionsCallback(env), env);
|
|
16
|
+
const context = instrumentContext(ctx);
|
|
17
|
+
const instrumentedEnv = instrumentEnv(env, options);
|
|
18
|
+
const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget);
|
|
19
|
+
instrumentDurableObjectHandlers(obj, options, context);
|
|
20
|
+
return { obj, options, context };
|
|
21
|
+
}
|
|
22
|
+
function instrumentDurableObjectHandlers(obj, options, context) {
|
|
23
|
+
if (obj.fetch && typeof obj.fetch === "function") {
|
|
24
|
+
obj.fetch = ensureInstrumented(
|
|
25
|
+
obj.fetch.bind(obj),
|
|
26
|
+
(original) => new Proxy(original, {
|
|
27
|
+
apply(target, thisArg, args) {
|
|
28
|
+
return wrapRequestHandler({ options, request: args[0], context }, () => {
|
|
29
|
+
return Reflect.apply(target, thisArg, args);
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
})
|
|
33
|
+
);
|
|
34
|
+
}
|
|
35
|
+
if (obj.alarm && typeof obj.alarm === "function") {
|
|
36
|
+
obj.alarm = wrapMethodWithSentry(
|
|
37
|
+
{
|
|
38
|
+
options,
|
|
39
|
+
context,
|
|
40
|
+
spanName: "alarm",
|
|
41
|
+
spanOp: "function",
|
|
42
|
+
startNewTrace: true,
|
|
43
|
+
origin: "auto.faas.cloudflare.durable_object"
|
|
44
|
+
},
|
|
45
|
+
obj.alarm.bind(obj)
|
|
46
|
+
);
|
|
47
|
+
}
|
|
48
|
+
if (obj.webSocketMessage && typeof obj.webSocketMessage === "function") {
|
|
49
|
+
obj.webSocketMessage = wrapMethodWithSentry(
|
|
50
|
+
{ options, context, spanName: "webSocketMessage", origin: "auto.faas.cloudflare.durable_object" },
|
|
51
|
+
obj.webSocketMessage.bind(obj)
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
if (obj.webSocketClose && typeof obj.webSocketClose === "function") {
|
|
55
|
+
obj.webSocketClose = wrapMethodWithSentry(
|
|
56
|
+
{ options, context, spanName: "webSocketClose", origin: "auto.faas.cloudflare.durable_object" },
|
|
57
|
+
obj.webSocketClose.bind(obj)
|
|
58
|
+
);
|
|
59
|
+
}
|
|
60
|
+
if (obj.webSocketError && typeof obj.webSocketError === "function") {
|
|
61
|
+
obj.webSocketError = wrapMethodWithSentry(
|
|
62
|
+
{ options, context, spanName: "webSocketError", origin: "auto.faas.cloudflare.durable_object" },
|
|
63
|
+
obj.webSocketError.bind(obj),
|
|
64
|
+
(_, error) => captureException(error, {
|
|
65
|
+
mechanism: {
|
|
66
|
+
type: "auto.faas.cloudflare.durable_object_websocket",
|
|
67
|
+
handled: false
|
|
68
|
+
}
|
|
69
|
+
})
|
|
70
|
+
);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
function finalizeWithRpcInstrumentation(obj, options, context) {
|
|
74
|
+
const rpcPropagation = getEffectiveRpcPropagation(options);
|
|
75
|
+
if (!rpcPropagation) {
|
|
76
|
+
return obj;
|
|
77
|
+
}
|
|
78
|
+
const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods) ? (
|
|
79
|
+
// eslint-disable-next-line typescript/no-deprecated
|
|
80
|
+
options.instrumentPrototypeMethods
|
|
81
|
+
) : void 0;
|
|
82
|
+
const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;
|
|
83
|
+
const alwaysTrace = options.enableRpcTracePropagation === void 0;
|
|
84
|
+
const methodCache = /* @__PURE__ */ new Map();
|
|
85
|
+
return new Proxy(obj, {
|
|
86
|
+
get(proxyTarget, prop, receiver) {
|
|
87
|
+
const value = Reflect.get(proxyTarget, prop, receiver);
|
|
88
|
+
if (typeof prop !== "string" || typeof value !== "function" || prop === "constructor") {
|
|
89
|
+
return value;
|
|
50
90
|
}
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
obj.webSocketClose.bind(obj)
|
|
55
|
-
);
|
|
91
|
+
const cached = methodCache.get(prop);
|
|
92
|
+
if (cached) {
|
|
93
|
+
return cached;
|
|
56
94
|
}
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
(_, error) => captureException(error, {
|
|
62
|
-
mechanism: {
|
|
63
|
-
type: "auto.faas.cloudflare.durable_object_websocket",
|
|
64
|
-
handled: false
|
|
65
|
-
}
|
|
66
|
-
})
|
|
67
|
-
);
|
|
95
|
+
const boundMethod = value.bind(proxyTarget);
|
|
96
|
+
if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop) || allowSet && !allowSet.has(prop)) {
|
|
97
|
+
methodCache.set(prop, boundMethod);
|
|
98
|
+
return boundMethod;
|
|
68
99
|
}
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
100
|
+
const tracedMethod = wrapMethodWithSentry(
|
|
101
|
+
{ options, context, spanName: prop, spanOp: "rpc", origin: "auto.faas.cloudflare.durable_object" },
|
|
102
|
+
boundMethod,
|
|
103
|
+
void 0,
|
|
104
|
+
true
|
|
105
|
+
);
|
|
106
|
+
if (alwaysTrace) {
|
|
107
|
+
methodCache.set(prop, tracedMethod);
|
|
108
|
+
return tracedMethod;
|
|
72
109
|
}
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
) : void 0;
|
|
77
|
-
const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;
|
|
78
|
-
const alwaysTrace = options.enableRpcTracePropagation === void 0;
|
|
79
|
-
const methodCache = /* @__PURE__ */ new Map();
|
|
80
|
-
return new Proxy(obj, {
|
|
81
|
-
get(proxyTarget, prop, receiver) {
|
|
82
|
-
const value = Reflect.get(proxyTarget, prop, receiver);
|
|
83
|
-
if (typeof prop !== "string" || typeof value !== "function" || prop === "constructor") {
|
|
84
|
-
return value;
|
|
85
|
-
}
|
|
86
|
-
const cached = methodCache.get(prop);
|
|
87
|
-
if (cached) {
|
|
88
|
-
return cached;
|
|
89
|
-
}
|
|
90
|
-
const boundMethod = value.bind(proxyTarget);
|
|
91
|
-
if (prop in Object.prototype || Object.prototype.hasOwnProperty.call(proxyTarget, prop) || allowSet && !allowSet.has(prop)) {
|
|
92
|
-
methodCache.set(prop, boundMethod);
|
|
93
|
-
return boundMethod;
|
|
94
|
-
}
|
|
95
|
-
const tracedMethod = wrapMethodWithSentry(
|
|
96
|
-
{ options, context, spanName: prop, spanOp: "rpc", origin: "auto.faas.cloudflare.durable_object" },
|
|
97
|
-
boundMethod,
|
|
98
|
-
void 0,
|
|
99
|
-
true
|
|
100
|
-
);
|
|
101
|
-
if (alwaysTrace) {
|
|
102
|
-
methodCache.set(prop, tracedMethod);
|
|
103
|
-
return tracedMethod;
|
|
104
|
-
}
|
|
105
|
-
const wrappedMethod = ((...args) => {
|
|
106
|
-
const { rpcMeta } = extractRpcMeta(args);
|
|
107
|
-
return rpcMeta ? tracedMethod(...args) : boundMethod(...args);
|
|
108
|
-
});
|
|
109
|
-
methodCache.set(prop, wrappedMethod);
|
|
110
|
-
return wrappedMethod;
|
|
111
|
-
}
|
|
110
|
+
const wrappedMethod = ((...args) => {
|
|
111
|
+
const { rpcMeta } = extractRpcMeta(args);
|
|
112
|
+
return rpcMeta ? tracedMethod(...args) : boundMethod(...args);
|
|
112
113
|
});
|
|
114
|
+
methodCache.set(prop, wrappedMethod);
|
|
115
|
+
return wrappedMethod;
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
function instrumentDurableObjectWithSentry(optionsCallback, DurableObjectClass) {
|
|
120
|
+
return new Proxy(DurableObjectClass, {
|
|
121
|
+
construct(target, [ctx, env], newTarget) {
|
|
122
|
+
const { obj, options, context } = constructInstrumentedDurableObject(
|
|
123
|
+
target,
|
|
124
|
+
ctx,
|
|
125
|
+
env,
|
|
126
|
+
newTarget,
|
|
127
|
+
optionsCallback
|
|
128
|
+
);
|
|
129
|
+
return finalizeWithRpcInstrumentation(obj, options, context);
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
function instrumentAgentWithSentry(optionsCallback, AgentClass) {
|
|
134
|
+
return new Proxy(AgentClass, {
|
|
135
|
+
construct(target, [ctx, env], newTarget) {
|
|
136
|
+
const { obj, options, context } = constructInstrumentedDurableObject(
|
|
137
|
+
target,
|
|
138
|
+
ctx,
|
|
139
|
+
env,
|
|
140
|
+
newTarget,
|
|
141
|
+
optionsCallback
|
|
142
|
+
);
|
|
143
|
+
instrumentCloudflareAgent(obj);
|
|
144
|
+
return finalizeWithRpcInstrumentation(obj, options, context);
|
|
113
145
|
}
|
|
114
146
|
});
|
|
115
147
|
}
|
|
116
148
|
|
|
117
|
-
export { instrumentDurableObjectWithSentry };
|
|
149
|
+
export { constructInstrumentedDurableObject, finalizeWithRpcInstrumentation, instrumentAgentWithSentry, instrumentDurableObjectWithSentry };
|
|
118
150
|
//# sourceMappingURL=durableobject.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n setAsyncLocalStorageAsyncContextStrategy();\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n const instrumentedEnv = instrumentEnv(env, options);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n // These are the methods that are available on a Durable Object\n // ref: https://developers.cloudflare.com/durable-objects/api/base/\n // obj.alarm\n // obj.fetch\n // obj.webSocketError\n // obj.webSocketClose\n // obj.webSocketMessage\n\n // Any other public methods on the Durable Object instance are RPC calls.\n\n // Bind each built-in handler to this instance before wrapping.\n // See https://github.com/getsentry/sentry-javascript/issues/22328\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch.bind(obj),\n original =>\n new Proxy(original, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () => {\n return Reflect.apply(target, thisArg, args);\n });\n },\n }),\n );\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n // Alarms are independent invocations, so we start a new trace and link to the previous alarm\n obj.alarm = wrapMethodWithSentry(\n {\n options,\n context,\n spanName: 'alarm',\n spanOp: 'function',\n startNewTrace: true,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n obj.alarm.bind(obj),\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketMessage.bind(obj),\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketClose', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketClose.bind(obj),\n );\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketError.bind(obj),\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc', origin: 'auto.faas.cloudflare.durable_object' },\n boundMethod,\n undefined,\n true,\n );\n\n // For deprecated `instrumentPrototypeMethods`, always trace.\n // For new `enableRpcTracePropagation`, only trace when RPC metadata is present.\n if (alwaysTrace) {\n methodCache.set(prop, tracedMethod);\n\n return tracedMethod;\n }\n\n // Wrapper that checks for Sentry RPC metadata at call time\n const wrappedMethod = ((...args: unknown[]) => {\n const { rpcMeta } = extractRpcMeta(args);\n\n // If Sentry RPC metadata is present, use the traced version (creates span)\n // Otherwise, call the bound method directly (no span)\n return rpcMeta ? tracedMethod(...args) : boundMethod(...args);\n }) as UncheckedMethod;\n\n methodCache.set(prop, wrappedMethod);\n\n return wrappedMethod;\n },\n });\n },\n });\n}\n"],"names":["target"],"mappings":";;;;;;;;;;;AA+CO,SAAS,iCAAA,CAId,iBAAgD,kBAAA,EAA0B;AAC1E,EAAA,OAAO,IAAI,MAAM,kBAAA,EAAoB;AAAA,IACnC,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,wCAAA,EAAyC;AACzC,MAAA,MAAM,OAAA,GAAU,kBAAkB,GAAG,CAAA;AACrC,MAAA,MAAM,OAAA,GAAU,eAAA,CAAgB,eAAA,CAAgB,GAAG,GAAG,GAAG,CAAA;AACzD,MAAA,MAAM,eAAA,GAAkB,aAAA,CAAc,GAAA,EAAK,OAAO,CAAA;AAKlD,MAAA,MAAM,GAAA,GAAM,QAAQ,SAAA,CAAU,MAAA,EAAQ,CAAC,OAAA,EAAS,eAAe,GAAG,SAAS,CAAA;AAc3E,MAAA,IAAI,GAAA,CAAI,KAAA,IAAS,OAAO,GAAA,CAAI,UAAU,UAAA,EAAY;AAChD,QAAA,GAAA,CAAI,KAAA,GAAQ,kBAAA;AAAA,UACV,GAAA,CAAI,KAAA,CAAM,IAAA,CAAK,GAAG,CAAA;AAAA,UAClB,CAAA,QAAA,KACE,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,YAClB,KAAA,CAAMA,OAAAA,EAAQ,OAAA,EAAS,IAAA,EAAM;AAC3B,cAAA,OAAO,kBAAA,CAAmB,EAAE,OAAA,EAAS,OAAA,EAAS,KAAK,CAAC,CAAA,EAAG,OAAA,EAAQ,EAAG,MAAM;AACtE,gBAAA,OAAO,OAAA,CAAQ,KAAA,CAAMA,OAAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,cAC5C,CAAC,CAAA;AAAA,YACH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,MAAA,CAAO,SAAA,IACf,MAAA,CAAO,UAAU,cAAA,CAAe,IAAA,CAAK,WAAA,EAAa,IAAI,KACrD,QAAA,IAAY,CAAC,QAAA,CAAS,GAAA,CAAI,IAAI,CAAA,EAC/B;AACA,YAAA,WAAA,CAAY,GAAA,CAAI,MAAM,WAAW,CAAA;AAEjC,YAAA,OAAO,WAAA;AAAA,UACT;AAGA,UAAA,MAAM,YAAA,GAAe,oBAAA;AAAA,YACnB,EAAE,SAAS,OAAA,EAAS,QAAA,EAAU,MAAM,MAAA,EAAQ,KAAA,EAAO,QAAQ,qCAAA,EAAsC;AAAA,YACjG,WAAA;AAAA,YACA,KAAA,CAAA;AAAA,YACA;AAAA,WACF;AAIA,UAAA,IAAI,WAAA,EAAa;AACf,YAAA,WAAA,CAAY,GAAA,CAAI,MAAM,YAAY,CAAA;AAElC,YAAA,OAAO,YAAA;AAAA,UACT;AAGA,UAAA,MAAM,aAAA,IAAiB,IAAI,IAAA,KAAoB;AAC7C,YAAA,MAAM,EAAE,OAAA,EAAQ,GAAI,cAAA,CAAe,IAAI,CAAA;AAIvC,YAAA,OAAO,UAAU,YAAA,CAAa,GAAG,IAAI,CAAA,GAAI,WAAA,CAAY,GAAG,IAAI,CAAA;AAAA,UAC9D,CAAA,CAAA;AAEA,UAAA,WAAA,CAAY,GAAA,CAAI,MAAM,aAAa,CAAA;AAEnC,UAAA,OAAO,aAAA;AAAA,QACT;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AACH;;;;"}
|
|
1
|
+
{"version":3,"file":"durableobject.js","sources":["../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport { captureException } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from './async';\nimport type { CloudflareOptions } from './client';\nimport { ensureInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { wrapRequestHandler } from './request';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { getEffectiveRpcPropagation } from './utils/rpcOptions';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * proxy — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any additional\n * per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): { obj: T; options: CloudflareOptions; context: InstrumentedDurableObjectContext } {\n setAsyncLocalStorageAsyncContextStrategy();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context };\n}\n\n/**\n * Instruments the built-in Durable Object handler methods on a constructed instance.\n *\n * These are the methods that are available on a Durable Object\n * ref: https://developers.cloudflare.com/durable-objects/api/base/\n * - obj.alarm\n * - obj.fetch\n * - obj.webSocketError\n * - obj.webSocketClose\n * - obj.webSocketMessage\n *\n * Any other public methods on the Durable Object instance are RPC calls.\n */\nfunction instrumentDurableObjectHandlers<E, T extends DurableObject<E>>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n): void {\n // Bind each built-in handler to this instance before wrapping.\n // See https://github.com/getsentry/sentry-javascript/issues/22328\n if (obj.fetch && typeof obj.fetch === 'function') {\n obj.fetch = ensureInstrumented(\n obj.fetch.bind(obj),\n original =>\n new Proxy(original, {\n apply(target, thisArg, args) {\n return wrapRequestHandler({ options, request: args[0], context }, () => {\n return Reflect.apply(target, thisArg, args);\n });\n },\n }),\n );\n }\n\n if (obj.alarm && typeof obj.alarm === 'function') {\n // Alarms are independent invocations, so we start a new trace and link to the previous alarm\n obj.alarm = wrapMethodWithSentry(\n {\n options,\n context,\n spanName: 'alarm',\n spanOp: 'function',\n startNewTrace: true,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n obj.alarm.bind(obj),\n );\n }\n\n if (obj.webSocketMessage && typeof obj.webSocketMessage === 'function') {\n obj.webSocketMessage = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketMessage', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketMessage.bind(obj),\n );\n }\n\n if (obj.webSocketClose && typeof obj.webSocketClose === 'function') {\n obj.webSocketClose = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketClose', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketClose.bind(obj),\n );\n }\n\n if (obj.webSocketError && typeof obj.webSocketError === 'function') {\n obj.webSocketError = wrapMethodWithSentry(\n { options, context, spanName: 'webSocketError', origin: 'auto.faas.cloudflare.durable_object' },\n obj.webSocketError.bind(obj),\n (_, error) =>\n captureException(error, {\n mechanism: {\n type: 'auto.faas.cloudflare.durable_object_websocket',\n handled: false,\n },\n }),\n );\n }\n}\n\n/**\n * Wraps a constructed (and already handler-instrumented) Durable Object instance with the RPC\n * prototype-method proxy, when RPC trace propagation is enabled. Returns the object unchanged when\n * RPC instrumentation is disabled.\n *\n * This must be applied last, so that any per-instance instrumentation (own properties such as\n * `fetch`, `alarm`, or Agent-specific handlers) is excluded from RPC method tracing.\n *\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n): T {\n // Get effective RPC propagation setting (handles deprecation of instrumentPrototypeMethods)\n const rpcPropagation = getEffectiveRpcPropagation(options);\n\n // Skip RPC instrumentation if not enabled\n if (!rpcPropagation) {\n return obj;\n }\n\n // If `instrumentPrototypeMethods` was passed as an array (deprecated),\n // only the listed method names should be instrumented.\n // eslint-disable-next-line typescript/no-deprecated\n const instrumentPrototypeMethods = Array.isArray(options.instrumentPrototypeMethods)\n ? // eslint-disable-next-line typescript/no-deprecated\n options.instrumentPrototypeMethods\n : undefined;\n const allowSet = instrumentPrototypeMethods ? new Set(instrumentPrototypeMethods) : null;\n\n // When using the deprecated `instrumentPrototypeMethods` option, always create spans.\n // When using the new `enableRpcTracePropagation`, only create spans when RPC metadata is present.\n const alwaysTrace = options.enableRpcTracePropagation === undefined;\n\n // Return a Proxy that binds all methods to the original object and creates spans\n // for RPC calls that have Sentry trace context propagated.\n // Binding is required because frameworks may use private fields (babel WeakMap pattern),\n // which fail if `this` is the Proxy instead of the original object.\n const methodCache = new Map<string, UncheckedMethod>();\n\n return new Proxy(obj, {\n get(proxyTarget, prop, receiver) {\n const value = Reflect.get(proxyTarget, prop, receiver);\n\n if (typeof prop !== 'string' || typeof value !== 'function' || prop === 'constructor') {\n return value;\n }\n\n const cached = methodCache.get(prop);\n\n if (cached) {\n return cached;\n }\n\n const boundMethod = (value as UncheckedMethod).bind(proxyTarget);\n\n if (\n prop in Object.prototype ||\n Object.prototype.hasOwnProperty.call(proxyTarget, prop) ||\n (allowSet && !allowSet.has(prop))\n ) {\n methodCache.set(prop, boundMethod);\n\n return boundMethod;\n }\n\n // Pre-create the traced version\n const tracedMethod = wrapMethodWithSentry(\n { options, context, spanName: prop, spanOp: 'rpc', origin: 'auto.faas.cloudflare.durable_object' },\n boundMethod,\n undefined,\n true,\n );\n\n // For deprecated `instrumentPrototypeMethods`, always trace.\n // For new `enableRpcTracePropagation`, only trace when RPC metadata is present.\n if (alwaysTrace) {\n methodCache.set(prop, tracedMethod);\n\n return tracedMethod;\n }\n\n // Wrapper that checks for Sentry RPC metadata at call time\n const wrappedMethod = ((...args: unknown[]) => {\n const { rpcMeta } = extractRpcMeta(args);\n\n // If Sentry RPC metadata is present, use the traced version (creates span)\n // Otherwise, call the bound method directly (no span)\n return rpcMeta ? tracedMethod(...args) : boundMethod(...args);\n }) as UncheckedMethod;\n\n methodCache.set(prop, wrappedMethod);\n\n return wrappedMethod;\n },\n });\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * To instrument RPC methods (prototype methods), enable the `enableRpcTracePropagation` option.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, DurableObjectClass: C): C {\n return new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context);\n },\n });\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * enableRpcTracePropagation: true,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n E,\n T extends DurableObject<E>,\n C extends new (state: DurableObjectState, env: E) => T,\n>(optionsCallback: (env: E) => CloudflareOptions, AgentClass: C): C {\n return new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing.\n return finalizeWithRpcInstrumentation(obj, options, context);\n },\n });\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AAwCO,SAAS,kCAAA,CACd,MAAA,EACA,GAAA,EACA,GAAA,EACA,WACA,eAAA,EACmF;AACnF,EAAA,wCAAA,EAAyC;AACzC,EAAA,MAAM,OAAA,GAAU,eAAA,CAAgB,eAAA,CAAgB,GAAG,GAAG,GAAG,CAAA;AAIzD,EAAA,MAAM,OAAA,GAAU,kBAAkB,GAAU,CAAA;AAC5C,EAAA,MAAM,eAAA,GAAkB,aAAA,CAAc,GAAA,EAAgC,OAAO,CAAA;AAK7E,EAAA,MAAM,GAAA,GAAM,QAAQ,SAAA,CAAU,MAAA,EAAQ,CAAC,OAAA,EAAS,eAAe,GAAG,SAAS,CAAA;AAE3E,EAAA,+BAAA,CAAgC,GAAA,EAAK,SAAS,OAAO,CAAA;AAErD,EAAA,OAAO,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAQ;AACjC;AAeA,SAAS,+BAAA,CACP,GAAA,EACA,OAAA,EACA,OAAA,EACM;AAGN,EAAA,IAAI,GAAA,CAAI,KAAA,IAAS,OAAO,GAAA,CAAI,UAAU,UAAA,EAAY;AAChD,IAAA,GAAA,CAAI,KAAA,GAAQ,kBAAA;AAAA,MACV,GAAA,CAAI,KAAA,CAAM,IAAA,CAAK,GAAG,CAAA;AAAA,MAClB,CAAA,QAAA,KACE,IAAI,KAA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A,OAAO,aAAA;AAAA,IACT;AAAA,GACD,CAAA;AACH;AAmCO,SAAS,iCAAA,CAId,iBAAgD,kBAAA,EAA0B;AAC1E,EAAA,OAAO,IAAI,MAAM,kBAAA,EAAoB;AAAA,IACnC,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAQ,GAAI,kCAAA;AAAA,QAChC,MAAA;AAAA,QACA,GAAA;AAAA,QACA,GAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7D;AAAA,GACD,CAAA;AACH;AA0CO,SAAS,yBAAA,CAId,iBAAgD,UAAA,EAAkB;AAClE,EAAA,OAAO,IAAI,MAAM,UAAA,EAAY;AAAA,IAC3B,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAQ,GAAI,kCAAA;AAAA,QAChC,MAAA;AAAA,QACA,GAAA;AAAA,QACA,GAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,yBAAA,CAA0B,GAAG,CAAA;AAI7B,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7D;AAAA,GACD,CAAA;AACH;;;;"}
|
package/build/esm/index.js
CHANGED
|
@@ -1,12 +1,14 @@
|
|
|
1
|
-
export { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, bindScopeToEmitter, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, close, consoleIntegration, consoleLoggingIntegration, continueTrace, createConsolaReporter, createLangChainCallbackHandler, createTransport, dedupeIntegration, eventFiltersIntegration, extraErrorDataIntegration, featureFlagsIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, getTraceData, getTraceMetaTags, growthbookIntegration, inboundFiltersIntegration, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentLangGraph, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentSupabaseClient, isEnabled, isInitialized, lastEventId, linkedErrorsIntegration, logger, metrics, moduleMetadataIntegration, requestDataIntegration, rewriteFramesIntegration, setAttribute, setAttributes, setContext, setConversationId, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanStreamingIntegration, spanToBaggageHeader, spanToJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSpan, startSpanManual, supabaseIntegration, suppressTracing, trpcMiddleware, updateSpanName, withActiveSpan, withIsolationScope, withMonitor, withScope, withStreamedSpan, wrapMcpServerWithSentry, zodErrorsIntegration } from '@sentry/core';
|
|
1
|
+
export { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SEMANTIC_ATTRIBUTE_SENTRY_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, bindScopeToEmitter, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, close, consoleIntegration, consoleLoggingIntegration, continueTrace, createConsolaReporter, createLangChainCallbackHandler, createTransport, dedupeIntegration, eventFiltersIntegration, extraErrorDataIntegration, featureFlagsIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, getTraceData, getTraceMetaTags, growthbookIntegration, inboundFiltersIntegration, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentLangGraph, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentSupabaseClient, isEnabled, isInitialized, lastEventId, linkedErrorsIntegration, logger, metrics, moduleMetadataIntegration, requestDataIntegration, rewriteFramesIntegration, setAttribute, setAttributes, setContext, setConversationId, setCurrentClient, setExtra, setExtras, setHttpStatus, setMeasurement, setTag, setTags, setUser, spanStreamingIntegration, spanToBaggageHeader, spanToJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSpan, startSpanManual, supabaseIntegration, suppressTracing, trpcMiddleware, updateSpanName, withActiveSpan, withIsolationScope, withMonitor, withScope, withStreamedSpan, wrapMcpServerWithSentry, zodErrorsIntegration } from '@sentry/core';
|
|
2
2
|
export { withSentry } from './withSentry.js';
|
|
3
|
-
export {
|
|
3
|
+
export { defineCloudflareOptions } from './defineCloudflareOptions.js';
|
|
4
|
+
export { instrumentAgentWithSentry, instrumentDurableObjectWithSentry } from './durableobject.js';
|
|
4
5
|
export { sentryPagesPlugin } from './pages-plugin.js';
|
|
5
6
|
export { wrapRequestHandler } from './request.js';
|
|
6
7
|
export { CloudflareClient } from './client.js';
|
|
7
8
|
export { getDefaultIntegrations } from './sdk.js';
|
|
8
9
|
export { httpServerIntegration } from './integrations/httpServer.js';
|
|
9
10
|
export { fetchIntegration } from './integrations/fetch.js';
|
|
11
|
+
export { spotlightIntegration } from './integrations/spotlight.js';
|
|
10
12
|
export { vercelAIIntegration } from './integrations/tracing/vercelai.js';
|
|
11
13
|
export { honoIntegration } from './integrations/hono.js';
|
|
12
14
|
export { instrumentD1WithSentry } from './instrumentations/worker/instrumentD1.js';
|
package/build/esm/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":[],"sourcesContent":[],"names":[],"mappings":";;;;;;;;;;;;;;;"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { instrumentAgentCallableRpc } from './instrumentAgentCallableRpc.js';
|
|
2
|
+
import { instrumentChatAgentConversation } from './instrumentChatAgentConversation.js';
|
|
3
|
+
|
|
4
|
+
function instrumentCloudflareAgent(agent) {
|
|
5
|
+
const internals = agent;
|
|
6
|
+
instrumentAgentCallableRpc(internals);
|
|
7
|
+
instrumentChatAgentConversation(internals);
|
|
8
|
+
return agent;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export { instrumentCloudflareAgent };
|
|
12
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/instrumentations/agents/index.ts"],"sourcesContent":["import { instrumentAgentCallableRpc } from './instrumentAgentCallableRpc';\nimport { instrumentChatAgentConversation } from './instrumentChatAgentConversation';\nimport type { AgentInternals } from './types';\n\n/**\n * Instruments an instance of a Cloudflare [`agents`](https://www.npmjs.com/package/agents) `Agent`\n * with Sentry, adding telemetry that is specific to the Agent's runtime behavior:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Conversation correlation** — sets the conversation id on the scope for each unit of agent\n * work — chat turn or callable RPC call — so `gen_ai` spans created within it are correlated, for\n * chat and plain agents alike. Defaults to the instance `name` and is rotated when the chat is\n * cleared (the `message:clear` observability event).\n *\n * It only hooks the `agents` package internals and uses Sentry's tracing primitives. On Cloudflare\n * Workers, prefer `instrumentAgentWithSentry`, which additionally instruments the Durable Object\n * handlers and initializes the SDK; that function calls this one internally.\n *\n * The hooks replace own-properties on the instance and defer to the original implementation, so\n * they compose with any other instrumentation applied to the same instance.\n *\n * @param agent The `agents` `Agent` instance to instrument.\n * @returns The same instance, instrumented.\n *\n * @internal Use `instrumentAgentWithSentry` instead — this is called internally by it.\n */\nexport function instrumentCloudflareAgent<T extends object>(agent: T): T {\n const internals = agent as T & AgentInternals;\n\n instrumentAgentCallableRpc(internals);\n instrumentChatAgentConversation(internals);\n\n return agent;\n}\n"],"names":[],"mappings":";;;AA0BO,SAAS,0BAA4C,KAAA,EAAa;AACvE,EAAA,MAAM,SAAA,GAAY,KAAA;AAElB,EAAA,0BAAA,CAA2B,SAAS,CAAA;AACpC,EAAA,+BAAA,CAAgC,SAAS,CAAA;AAEzC,EAAA,OAAO,KAAA;AACT;;;;"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { debug, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_OP } from '@sentry/core';
|
|
2
|
+
import { DEBUG_BUILD } from '../../debug-build.js';
|
|
3
|
+
import { AGENT_SPAN_ORIGIN, getAgentAttributes, setAgentConversationId } from './types.js';
|
|
4
|
+
|
|
5
|
+
function instrumentAgentCallableRpc(obj) {
|
|
6
|
+
const original = obj.onMessage;
|
|
7
|
+
if (typeof original !== "function") {
|
|
8
|
+
DEBUG_BUILD && debug.log("[Sentry] Agent `onMessage` not found \u2014 callable RPC span instrumentation skipped.");
|
|
9
|
+
return;
|
|
10
|
+
}
|
|
11
|
+
obj.onMessage = new Proxy(original, {
|
|
12
|
+
apply(target, thisArg, args) {
|
|
13
|
+
const method = extractCallableMethod(args[1]);
|
|
14
|
+
if (!method) {
|
|
15
|
+
return Reflect.apply(target, thisArg, args);
|
|
16
|
+
}
|
|
17
|
+
return startSpan(
|
|
18
|
+
{
|
|
19
|
+
name: method,
|
|
20
|
+
attributes: {
|
|
21
|
+
[SEMANTIC_ATTRIBUTE_SENTRY_OP]: "rpc",
|
|
22
|
+
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: AGENT_SPAN_ORIGIN,
|
|
23
|
+
...getAgentAttributes(thisArg)
|
|
24
|
+
}
|
|
25
|
+
},
|
|
26
|
+
() => {
|
|
27
|
+
setAgentConversationId(thisArg);
|
|
28
|
+
return Reflect.apply(target, thisArg, args);
|
|
29
|
+
}
|
|
30
|
+
);
|
|
31
|
+
}
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
function extractCallableMethod(message) {
|
|
35
|
+
const text = typeof message === "string" ? message : message instanceof ArrayBuffer ? new TextDecoder().decode(message) : void 0;
|
|
36
|
+
if (!text) {
|
|
37
|
+
return void 0;
|
|
38
|
+
}
|
|
39
|
+
try {
|
|
40
|
+
const parsed = JSON.parse(text);
|
|
41
|
+
if (parsed.type === "rpc" && typeof parsed.method === "string" && Array.isArray(parsed.args)) {
|
|
42
|
+
return parsed.method;
|
|
43
|
+
}
|
|
44
|
+
} catch {
|
|
45
|
+
}
|
|
46
|
+
return void 0;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export { instrumentAgentCallableRpc };
|
|
50
|
+
//# sourceMappingURL=instrumentAgentCallableRpc.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instrumentAgentCallableRpc.js","sources":["../../../../src/instrumentations/agents/instrumentAgentCallableRpc.ts"],"sourcesContent":["import { debug, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { AGENT_SPAN_ORIGIN, type AgentInternals, getAgentAttributes, setAgentConversationId } from './types';\n\n/**\n * Wraps the Agent's `onMessage` handler to create a span for each `@callable()` RPC invocation.\n * RPC requests arrive as WebSocket messages, so this span nests under the active transaction for\n * the WebSocket message (on Cloudflare, the instrumented Durable Object `webSocketMessage` hook).\n *\n * Also sets the conversation id on the scope for the duration of the call: callable methods are the\n * unit of work for plain (non-chat) agents, which run LLM calls just like chat turns do.\n */\nexport function instrumentAgentCallableRpc(obj: AgentInternals): void {\n const original = obj.onMessage;\n if (typeof original !== 'function') {\n DEBUG_BUILD && debug.log('[Sentry] Agent `onMessage` not found — callable RPC span instrumentation skipped.');\n return;\n }\n\n obj.onMessage = new Proxy(original, {\n apply(target, thisArg: AgentInternals, args: unknown[]): unknown {\n const method = extractCallableMethod(args[1]);\n\n if (!method) {\n return Reflect.apply(target, thisArg, args);\n }\n\n return startSpan(\n {\n name: method,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: 'rpc',\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: AGENT_SPAN_ORIGIN,\n ...getAgentAttributes(thisArg),\n },\n },\n () => {\n setAgentConversationId(thisArg);\n return Reflect.apply(target, thisArg, args);\n },\n );\n },\n });\n}\n\n/** Extracts the RPC method name from a WebSocket message, mirroring the SDK's `isRPCRequest`. */\nfunction extractCallableMethod(message: unknown): string | undefined {\n const text =\n typeof message === 'string'\n ? message\n : message instanceof ArrayBuffer\n ? new TextDecoder().decode(message)\n : undefined;\n\n if (!text) {\n return undefined;\n }\n\n try {\n const parsed = JSON.parse(text) as { type?: unknown; method?: unknown; args?: unknown };\n if (parsed.type === 'rpc' && typeof parsed.method === 'string' && Array.isArray(parsed.args)) {\n return parsed.method;\n }\n } catch {\n // Not JSON, or not an RPC request — no span.\n }\n\n return undefined;\n}\n"],"names":[],"mappings":";;;;AAYO,SAAS,2BAA2B,GAAA,EAA2B;AACpE,EAAA,MAAM,WAAW,GAAA,CAAI,SAAA;AACrB,EAAA,IAAI,OAAO,aAAa,UAAA,EAAY;AAClC,IAAA,WAAA,IAAe,KAAA,CAAM,IAAI,wFAAmF,CAAA;AAC5G,IAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,SAAA,GAAY,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,IAClC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAyB,IAAA,EAA0B;AAC/D,MAAA,MAAM,MAAA,GAAS,qBAAA,CAAsB,IAAA,CAAK,CAAC,CAAC,CAAA;AAE5C,MAAA,IAAI,CAA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|
3
|
+
|
|
4
|
+
function instrumentChatAgentConversation(obj) {
|
|
5
|
+
const originalEmit = obj._emit;
|
|
6
|
+
if (typeof originalEmit === "function") {
|
|
7
|
+
obj._emit = new Proxy(originalEmit, {
|
|
8
|
+
apply(target, thisArg, args) {
|
|
9
|
+
if (args[0] === "message:clear") {
|
|
10
|
+
thisArg.__sentryConversationId = uuid4();
|
|
11
|
+
}
|
|
12
|
+
return Reflect.apply(target, thisArg, args);
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
const original = obj.onChatMessage;
|
|
17
|
+
if (typeof original !== "function") {
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
obj.onChatMessage = new Proxy(original, {
|
|
21
|
+
apply(target, thisArg, args) {
|
|
22
|
+
setAgentConversationId(thisArg);
|
|
23
|
+
return Reflect.apply(target, thisArg, args);
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export { instrumentChatAgentConversation };
|
|
29
|
+
//# sourceMappingURL=instrumentChatAgentConversation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"instrumentChatAgentConversation.js","sources":["../../../../src/instrumentations/agents/instrumentChatAgentConversation.ts"],"sourcesContent":["import { uuid4 } from '@sentry/core';\nimport { type AgentInternals, setAgentConversationId } from './types';\n\n/**\n * For chat agents (`AIChatAgent` from `@cloudflare/ai-chat`), correlates each chat turn's AI spans\n * with a conversation id on the active scope.\n *\n * In the Agents model one agent instance is one long-lived conversation, so the instance `name` is\n * the base conversation id. When the user clears the chat, they expect a fresh conversation — but\n * recreating the Durable Object for that would also drop the MCP/OAuth state stored per instance\n * (GitHub/Sentry sign-in). To get a fresh conversation id *without* losing that state, we rotate an\n * in-memory id on the instance when the SDK reports a cleared chat, and stamp that (falling back to\n * the instance `name` before the first clear).\n *\n * The id itself is not attached to spans here — the SDK's `conversationIdIntegration` reads it off\n * the scope at `spanStart` and stamps `gen_ai.conversation.id` onto the AI spans created inside the\n * turn (e.g. by the Workers AI instrumentation), which correlates a turn's model and tool calls.\n *\n * Plain (non-chat) `Agent`s do not define `onChatMessage`, so they are skipped here — their unit\n * of work is the callable RPC method, where `instrumentAgentCallableRpc` sets the conversation id\n * instead.\n */\nexport function instrumentChatAgentConversation(obj: AgentInternals): void {\n // Rotate the conversation id when the chat is cleared. `_emit` is the central choke-point through\n // which all `agents:*` observability events are published, and it already exists on the base\n // `Agent` class — so this hook composes with the RPC instrumentation, which keys off the same\n // surface. We shadow it with an own property so the original stays reachable on the prototype.\n const originalEmit = obj._emit;\n\n if (typeof originalEmit === 'function') {\n obj._emit = new Proxy(originalEmit, {\n apply(target, thisArg: AgentInternals, args: [string, Record<string, unknown>?]) {\n if (args[0] === 'message:clear') {\n thisArg.__sentryConversationId = uuid4();\n }\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n }\n\n const original = obj.onChatMessage;\n\n if (typeof original !== 'function') {\n return;\n }\n\n obj.onChatMessage = new Proxy(original, {\n apply(target, thisArg: AgentInternals, args: unknown[]): unknown {\n setAgentConversationId(thisArg);\n\n return Reflect.apply(target, thisArg, args);\n },\n });\n}\n"],"names":[],"mappings":";;;AAsBO,SAAS,gCAAgC,GAAA,EAA2B;AAKzE,EAAA,MAAM,eAAe,GAAA,CAAI,KAAA;AAEzB,EAAA,IAAI,OAAO,iBAAiB,UAAA,EAAY;AACtC,IAAA,GAAA,CAAI,KAAA,GAAQ,IAAI,KAAA,CAAM,YAAA,EAAc;AAAA,MAClC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAyB,IAAA,EAA0C;AAC/E,QAAA,IAAI,IAAA,CAAK,CAAC,CAAA,KAAM,eAAA,EAAiB;AAC/B,UAAA,OAAA,CAAQ,yBAAyB,KAAA,EAAM;AAAA,QACzC;AAEA,QAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,MAC5C;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,MAAM,WAAW,GAAA,CAAI,aAAA;AAErB,EAAA,IAAI,OAAO,aAAa,UAAA,EAAY;AAClC,IAAA;AAAA,EACF;AAEA,EAAA,GAAA,CAAI,aAAA,GAAgB,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,IACtC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAyB,IAAA,EAA0B;AAC/D,MAAA,sBAAA,CAAuB,OAAO,CAAA;AAE9B,MAAA,OAAO,OAAA,CAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAA;AAAA,IAC5C;AAAA,GACD,CAAA;AACH;;;;"}
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { getCurrentScope } from '@sentry/core';
|
|
2
|
+
|
|
3
|
+
const AGENT_SPAN_ORIGIN = "auto.faas.cloudflare.agents";
|
|
4
|
+
const AGENT_CLASS_ATTRIBUTE = "cloudflare.agent.class";
|
|
5
|
+
const AGENT_NAME_ATTRIBUTE = "cloudflare.agent.name";
|
|
6
|
+
function getAgentAttributes(instance) {
|
|
7
|
+
const attributes = {};
|
|
8
|
+
const agentClass = instance._ParentClass?.name;
|
|
9
|
+
if (typeof agentClass === "string" && agentClass) {
|
|
10
|
+
attributes[AGENT_CLASS_ATTRIBUTE] = agentClass;
|
|
11
|
+
}
|
|
12
|
+
const agentName = instance.name;
|
|
13
|
+
if (typeof agentName === "string" && agentName) {
|
|
14
|
+
attributes[AGENT_NAME_ATTRIBUTE] = agentName;
|
|
15
|
+
}
|
|
16
|
+
return attributes;
|
|
17
|
+
}
|
|
18
|
+
function setAgentConversationId(instance) {
|
|
19
|
+
const conversationId = instance.__sentryConversationId ?? instance.name;
|
|
20
|
+
if (typeof conversationId === "string" && conversationId) {
|
|
21
|
+
getCurrentScope().setConversationId(conversationId);
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export { AGENT_CLASS_ATTRIBUTE, AGENT_NAME_ATTRIBUTE, AGENT_SPAN_ORIGIN, getAgentAttributes, setAgentConversationId };
|
|
26
|
+
//# sourceMappingURL=types.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.js","sources":["../../../../src/instrumentations/agents/types.ts"],"sourcesContent":["import { getCurrentScope } from '@sentry/core';\n\nexport const AGENT_SPAN_ORIGIN = 'auto.faas.cloudflare.agents';\nexport const AGENT_CLASS_ATTRIBUTE = 'cloudflare.agent.class';\nexport const AGENT_NAME_ATTRIBUTE = 'cloudflare.agent.name';\n\n/**\n * The subset of the `agents` `Agent` instance internals that we instrument. These are runtime\n * implementation details of the `agents` package (v0.13.x) rather than part of its public type\n * surface, so every access is guarded and wrapping degrades gracefully if a name changes upstream.\n */\nexport interface AgentInternals {\n /** Central choke-point through which all `agents:*` observability events are published. */\n _emit?: (type: string, payload?: Record<string, unknown>) => void;\n /** WebSocket message handler; dispatches `@callable()` RPC requests. */\n onMessage?: (...args: unknown[]) => unknown;\n /**\n * Chat-turn handler. Only `AIChatAgent` (from `@cloudflare/ai-chat`) defines this; a plain `Agent`\n * does not, so its presence discriminates a chat agent.\n */\n onChatMessage?: (...args: unknown[]) => unknown;\n /** The user's Agent class (used by the SDK for the observability event `agent` field). */\n _ParentClass?: { name?: string };\n /** The Agent instance name, which in the Agents model identifies the conversation/thread. */\n name?: string;\n /**\n * Internal: the active conversation id, rotated when the chat is cleared (the `message:clear`\n * observability event) so a reset chat groups as a fresh conversation while the instance (and its\n * MCP/OAuth state) stays put. Set by `instrumentChatAgentConversation`; falls back to `name`\n * before the first clear.\n */\n __sentryConversationId?: string;\n}\n\n/** Reads best-effort agent identity attributes from the instance, tolerating missing internals. */\nexport function getAgentAttributes(instance: AgentInternals): Record<string, string> {\n const attributes: Record<string, string> = {};\n\n const agentClass = instance._ParentClass?.name;\n if (typeof agentClass === 'string' && agentClass) {\n attributes[AGENT_CLASS_ATTRIBUTE] = agentClass;\n }\n\n const agentName = instance.name;\n if (typeof agentName === 'string' && agentName) {\n attributes[AGENT_NAME_ATTRIBUTE] = agentName;\n }\n\n return attributes;\n}\n\n/**\n * Sets the agent instance's conversation id on the current scope for the duration of the\n * surrounding unit of work (chat turn, callable RPC call). In the Agents model one instance is one\n * conversation, so the instance `name` is the natural conversation id — for chat and plain agents\n * alike, since plain agents run LLM calls too (e.g. inside `@callable()` methods). Once the chat\n * has been cleared, the rotated `__sentryConversationId` takes precedence so LLM calls from any\n * unit of work group under the fresh conversation.\n *\n * `conversationIdIntegration` reads the id off the scope at `spanStart` and stamps\n * `gen_ai.conversation.id` onto AI spans created within the unit of work, correlating its model\n * and tool calls. Callers run inside a per-event forked scope (`wrapMethodWithSentry`), so the id\n * does not leak into unrelated events.\n */\nexport function setAgentConversationId(instance: AgentInternals): void {\n const conversationId = instance.__sentryConversationId ?? instance.name;\n\n if (typeof conversationId === 'string' && conversationId) {\n getCurrentScope().setConversationId(conversationId);\n }\n}\n"],"names":[],"mappings":";;AAEO,MAAM,iBAAA,GAAoB;AAC1B,MAAM,qBAAA,GAAwB;AAC9B,MAAM,oBAAA,GAAuB;AA+B7B,SAAS,mBAAmB,QAAA,EAAkD;AACnF,EAAA,MAAM,aAAqC,EAAC;AAE5C,EAAA,MAAM,UAAA,GAAa,SAAS,YAAA,EAAc,IAAA;AAC1C,EAAA,IAAI,OAAO,UAAA,KAAe,QAAA,IAAY,UAAA,EAAY;AAChD,IAAA,UAAA,CAAW,qBAAqB,CAAA,GAAI,UAAA;AAAA,EACtC;AAEA,EAAA,MAAM,YAAY,QAAA,CAAS,IAAA;AAC3B,EAAA,IAAI,OAAO,SAAA,KAAc,QAAA,IAAY,SAAA,EAAW;AAC9C,IAAA,UAAA,CAAW,oBAAoB,CAAA,GAAI,SAAA;AAAA,EACrC;AAEA,EAAA,OAAO,UAAA;AACT;AAeO,SAAS,uBAAuB,QAAA,EAAgC;AACrE,EAAA,MAAM,cAAA,GAAiB,QAAA,CAAS,sBAAA,IAA0B,QAAA,CAAS,IAAA;AAEnE,EAAA,IAAI,OAAO,cAAA,KAAmB,QAAA,IAAY,cAAA,EAAgB;AACxD,IAAA,eAAA,EAAgB,CAAE,kBAAkB,cAAc,CAAA;AAAA,EACpD;AACF;;;;"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import { startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, isThenable } from '@sentry/core';
|
|
1
|
+
import { getClient, startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, isThenable } from '@sentry/core';
|
|
2
|
+
import { getStorageKeys, targetsCloudflareInternalKey } from '../utils/internalStorageKey.js';
|
|
2
3
|
import { storeSpanContext } from '../utils/traceLinks.js';
|
|
3
4
|
import { instrumentDurableObjectSyncKvStorage } from './instrumentDurableObjectSyncKvStorage.js';
|
|
4
5
|
import { instrumentSqlStorage } from './instrumentSqlStorage.js';
|
|
@@ -22,6 +23,11 @@ function instrumentDurableObjectStorage(storage, waitUntil) {
|
|
|
22
23
|
return original.bind(target);
|
|
23
24
|
}
|
|
24
25
|
return function(...args) {
|
|
26
|
+
const allowlist = getClient()?.getOptions()?.durableObjectStorageSpanAllowlist;
|
|
27
|
+
const keys = getStorageKeys(methodName, args);
|
|
28
|
+
if (keys && keys.length > 0 && keys.every((key) => targetsCloudflareInternalKey(key, allowlist))) {
|
|
29
|
+
return original.apply(target, args);
|
|
30
|
+
}
|
|
25
31
|
return startSpan(
|
|
26
32
|
{
|
|
27
33
|
// Use underscore naming to match Cloudflare's native instrumentation (e.g., "durable_object_storage_get")
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentDurableObjectStorage.js","sources":["../../../src/instrumentations/instrumentDurableObjectStorage.ts"],"sourcesContent":["import type { DurableObjectStorage, SyncKvStorage, SqlStorage } from '@cloudflare/workers-types';\nimport { isThenable, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport { storeSpanContext } from '../utils/traceLinks';\nimport { instrumentDurableObjectSyncKvStorage } from './instrumentDurableObjectSyncKvStorage';\nimport { instrumentSqlStorage } from './instrumentSqlStorage';\n\nconst STORAGE_METHODS_TO_INSTRUMENT = ['get', 'put', 'delete', 'list', 'setAlarm', 'getAlarm', 'deleteAlarm'] as const;\n\ntype StorageMethod = (typeof STORAGE_METHODS_TO_INSTRUMENT)[number];\n\ntype WaitUntil = (promise: Promise<unknown>) => void;\n\n/**\n * Instruments DurableObjectStorage methods with Sentry spans.\n *\n * Wraps the following async methods:\n * - get, put, delete, list (KV API)\n * - setAlarm, getAlarm, deleteAlarm (Alarm API)\n *\n * When setAlarm is called, it also stores the current span context so that when\n * the alarm fires later, it can link back to the trace that called setAlarm.\n *\n * @param storage - The DurableObjectStorage instance to instrument\n * @param waitUntil - Optional waitUntil function to defer span context storage\n * @returns An instrumented DurableObjectStorage instance\n */\nexport function instrumentDurableObjectStorage(\n storage: DurableObjectStorage,\n waitUntil?: WaitUntil,\n): DurableObjectStorage {\n return new Proxy(storage, {\n get(target, prop, _receiver) {\n // Use `target` as the receiver instead of the proxy (`_receiver`).\n // Native workerd getters (e.g., `storage.sql`) validate `this` via\n // internal slots. Passing the proxy as receiver breaks that check,\n // causing \"Illegal invocation: function called with incorrect `this`\n // reference\" errors.\n const original = Reflect.get(target, prop, target);\n\n if (prop === 'kv' && original != null && 'get' in original && 'put' in original) {\n return instrumentDurableObjectSyncKvStorage(original as SyncKvStorage);\n }\n\n if (prop === 'sql' && original != null && 'databaseSize' in original && 'exec' in original) {\n return instrumentSqlStorage(original as SqlStorage);\n }\n\n if (typeof original !== 'function') {\n return original;\n }\n\n const methodName = prop as string;\n if (!STORAGE_METHODS_TO_INSTRUMENT.includes(methodName as StorageMethod)) {\n return (original as (...args: unknown[]) => unknown).bind(target);\n }\n\n return function (this: unknown, ...args: unknown[]) {\n return startSpan(\n {\n // Use underscore naming to match Cloudflare's native instrumentation (e.g., \"durable_object_storage_get\")\n name: `durable_object_storage_${methodName}`,\n op: 'db',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object',\n 'db.system.name': 'cloudflare.durable_object.storage',\n 'db.operation.name': methodName,\n },\n },\n () => {\n const teardown = async (): Promise<void> => {\n // When setAlarm is called, store the current span context so that when the alarm\n // fires later, it can link back to the trace that called setAlarm.\n // We use the original (uninstrumented) storage (target) to avoid creating a span\n // for this internal operation. The storage is deferred via waitUntil to not block.\n if (methodName === 'setAlarm') {\n storeSpanContext(target, 'alarm');\n }\n };\n\n const result = (original as (...args: unknown[]) => unknown).apply(target, args);\n\n if (!isThenable(result)) {\n waitUntil?.(teardown());\n\n return result;\n }\n\n return result.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n throw e;\n },\n );\n },\n );\n };\n },\n });\n}\n"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"instrumentDurableObjectStorage.js","sources":["../../../src/instrumentations/instrumentDurableObjectStorage.ts"],"sourcesContent":["import type { DurableObjectStorage, SyncKvStorage, SqlStorage } from '@cloudflare/workers-types';\nimport { getClient, isThenable, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, startSpan } from '@sentry/core';\nimport type { CloudflareClientOptions } from '../client';\nimport { getStorageKeys, targetsCloudflareInternalKey } from '../utils/internalStorageKey';\nimport { storeSpanContext } from '../utils/traceLinks';\nimport { instrumentDurableObjectSyncKvStorage } from './instrumentDurableObjectSyncKvStorage';\nimport { instrumentSqlStorage } from './instrumentSqlStorage';\n\nconst STORAGE_METHODS_TO_INSTRUMENT = ['get', 'put', 'delete', 'list', 'setAlarm', 'getAlarm', 'deleteAlarm'] as const;\n\ntype StorageMethod = (typeof STORAGE_METHODS_TO_INSTRUMENT)[number];\n\ntype WaitUntil = (promise: Promise<unknown>) => void;\n\n/**\n * Instruments DurableObjectStorage methods with Sentry spans.\n *\n * Wraps the following async methods:\n * - get, put, delete, list (KV API)\n * - setAlarm, getAlarm, deleteAlarm (Alarm API)\n *\n * When setAlarm is called, it also stores the current span context so that when\n * the alarm fires later, it can link back to the trace that called setAlarm.\n *\n * @param storage - The DurableObjectStorage instance to instrument\n * @param waitUntil - Optional waitUntil function to defer span context storage\n * @returns An instrumented DurableObjectStorage instance\n */\nexport function instrumentDurableObjectStorage(\n storage: DurableObjectStorage,\n waitUntil?: WaitUntil,\n): DurableObjectStorage {\n return new Proxy(storage, {\n get(target, prop, _receiver) {\n // Use `target` as the receiver instead of the proxy (`_receiver`).\n // Native workerd getters (e.g., `storage.sql`) validate `this` via\n // internal slots. Passing the proxy as receiver breaks that check,\n // causing \"Illegal invocation: function called with incorrect `this`\n // reference\" errors.\n const original = Reflect.get(target, prop, target);\n\n if (prop === 'kv' && original != null && 'get' in original && 'put' in original) {\n return instrumentDurableObjectSyncKvStorage(original as SyncKvStorage);\n }\n\n if (prop === 'sql' && original != null && 'databaseSize' in original && 'exec' in original) {\n return instrumentSqlStorage(original as SqlStorage);\n }\n\n if (typeof original !== 'function') {\n return original;\n }\n\n const methodName = prop as string;\n if (!STORAGE_METHODS_TO_INSTRUMENT.includes(methodName as StorageMethod)) {\n return (original as (...args: unknown[]) => unknown).bind(target);\n }\n\n return function (this: unknown, ...args: unknown[]) {\n // KV entries managed by the DO framework itself (agents/partyserver state) are bookkeeping\n // rather than user work — skip the span, mirroring how `cf_` SQL tables are treated.\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectStorageSpanAllowlist;\n const keys = getStorageKeys(methodName, args);\n if (keys && keys.length > 0 && keys.every(key => targetsCloudflareInternalKey(key, allowlist))) {\n return (original as (...a: unknown[]) => unknown).apply(target, args);\n }\n\n return startSpan(\n {\n // Use underscore naming to match Cloudflare's native instrumentation (e.g., \"durable_object_storage_get\")\n name: `durable_object_storage_${methodName}`,\n op: 'db',\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object',\n 'db.system.name': 'cloudflare.durable_object.storage',\n 'db.operation.name': methodName,\n },\n },\n () => {\n const teardown = async (): Promise<void> => {\n // When setAlarm is called, store the current span context so that when the alarm\n // fires later, it can link back to the trace that called setAlarm.\n // We use the original (uninstrumented) storage (target) to avoid creating a span\n // for this internal operation. The storage is deferred via waitUntil to not block.\n if (methodName === 'setAlarm') {\n storeSpanContext(target, 'alarm');\n }\n };\n\n const result = (original as (...args: unknown[]) => unknown).apply(target, args);\n\n if (!isThenable(result)) {\n waitUntil?.(teardown());\n\n return result;\n }\n\n return result.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n throw e;\n },\n );\n },\n );\n };\n },\n });\n}\n"],"names":[],"mappings":";;;;;;AAQA,MAAM,6BAAA,GAAgC,CAAC,KAAA,EAAO,KAAA,EAAO,UAAU,MAAA,EAAQ,UAAA,EAAY,YAAY,aAAa,CAAA;AAoBrG,SAAS,8BAAA,CACd,SACA,SAAA,EACsB;AACtB,EAAA,OAAO,IAAI,MAAM,OAAA,EAAS;AAAA,IACxB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAM3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,SAAS,IAAA,IAAQ,QAAA,IAAY,QAAQ,KAAA,IAAS,QAAA,IAAY,SAAS,QAAA,EAAU;AAC/E,QAAA,OAAO,qCAAqC,QAAyB,CAAA;AAAA,MACvE;AAEA,MAAA,IAAI,SAAS,KAAA,IAAS,QAAA,IAAY,QAAQ,cAAA,IAAkB,QAAA,IAAY,UAAU,QAAA,EAAU;AAC1F,QAAA,OAAO,qBAAqB,QAAsB,CAAA;AAAA,MACpD;AAEA,MAAA,IAAI,OAAO,aAAa,UAAA,EAAY;AAClC,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,MAAM,UAAA,GAAa,IAAA;AACnB,MAAA,IAAI,CAAC,6BAAA,CAA8B,QAAA,CAAS,UAA2B,CAAA,EAAG;AACxE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AO,GAAA;AAAA,cACT,CAAA;AAAA,cACA,CAAA,CAAA,KAAK;AACH,gBAAA,MAAM,CAAA;AAAA,cACR;AAAA,aACF;AAAA,UACF;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;;;;"}
|
|
@@ -13,7 +13,7 @@ function instrumentSqlStorage(sql) {
|
|
|
13
13
|
const sanitizedQuery = _INTERNAL_sanitizeSqlQuery(query);
|
|
14
14
|
const querySummary = _INTERNAL_getSqlQuerySummary(sanitizedQuery);
|
|
15
15
|
const allowlist = getClient()?.getOptions()?.durableObjectSqlSpanAllowlist;
|
|
16
|
-
if (targetsCloudflareInternalTable(querySummary, allowlist)) {
|
|
16
|
+
if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {
|
|
17
17
|
return original.apply(target, args);
|
|
18
18
|
}
|
|
19
19
|
return startSpan(
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentSqlStorage.js","sources":["../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport {\n _INTERNAL_getSqlQuerySummary,\n _INTERNAL_sanitizeSqlQuery,\n getClient,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareClientOptions } from '../client';\nimport { targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n const sanitizedQuery = _INTERNAL_sanitizeSqlQuery(query);\n const querySummary = _INTERNAL_getSqlQuerySummary(sanitizedQuery);\n\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist)) {\n return (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n }\n\n return startSpan(\n {\n op: 'db.query',\n name: querySummary || sanitizedQuery,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n () => (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args),\n );\n };\n },\n });\n}\n"],"names":[],"mappings":";;;AAiBO,SAAS,qBAAqB,GAAA,EAA6B;AAChE,EAAA,OAAO,IAAI,MAAM,GAAA,EAAK;AAAA,IACpB,GAAA,CAAI,MAAA,EAAQ,IAAA,EAAM,SAAA,EAAW;AAC3B,MAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,GAAA,CAAI,MAAA,EAAQ,MAAM,MAAM,CAAA;AAEjD,MAAA,IAAI,IAAA,KAAS,MAAA,IAAU,OAAO,QAAA,KAAa,UAAA,EAAY;AACrD,QAAA,OAAO,QAAA;AAAA,MACT;AAEA,MAAA,OAAO,YAA4B,IAAA,EAAiB;AAClD,QAAA,MAAM,CAAC,KAAA,EAAO,GAAG,QAAQ,CAAA,GAAI,IAAA;AAE7B,QAAA,MAAM,cAAA,GAAiB,2BAA2B,KAAK,CAAA;AACvD,QAAA,MAAM,YAAA,GAAe,6BAA6B,cAAc,CAAA;AAEhE,QAAA,MAAM,SAAA,GAAa,SAAA,EAAU,EAAG,UAAA,EAAW,EACvC,6BAAA;AAEJ,QAAA,IAAI,8BAAA,CAA+B,YAAA,EAAc,
|
|
1
|
+
{"version":3,"file":"instrumentSqlStorage.js","sources":["../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport {\n _INTERNAL_getSqlQuerySummary,\n _INTERNAL_sanitizeSqlQuery,\n getClient,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareClientOptions } from '../client';\nimport { targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n const sanitizedQuery = _INTERNAL_sanitizeSqlQuery(query);\n const querySummary = _INTERNAL_getSqlQuerySummary(sanitizedQuery);\n\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n }\n\n return startSpan(\n {\n op: 'db.query',\n name: querySummary || sanitizedQuery,\n attributes: {\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n () => (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args),\n );\n };\n },\n });\n}\n"],"names":[],"mappings":";;;AAiBO,SAAS,qBAAqB,GAAA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