@sentry/cloudflare 11.0.0-beta.2 → 11.0.0-rc.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/dev/index.js +4 -0
- package/build/cjs/dev/index.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js +19 -17
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentEmail.js +4 -3
- package/build/cjs/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js +10 -5
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/dev/orchestrion-deferred-channels.js +39 -0
- package/build/cjs/dev/orchestrion-deferred-channels.js.map +1 -0
- package/build/cjs/dev/orchestrion-diagnostics-channel.js +83 -0
- package/build/cjs/dev/orchestrion-diagnostics-channel.js.map +1 -0
- package/build/cjs/dev/vite/index.js +6 -1
- package/build/cjs/dev/vite/index.js.map +1 -1
- package/build/cjs/dev/vite/mastraObservability.js +39 -0
- package/build/cjs/dev/vite/mastraObservability.js.map +1 -0
- package/build/cjs/dev/wrapMethodWithSentry.js +8 -4
- package/build/cjs/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/dev/wrapRequestHandlerWithInit.js +2 -0
- package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/cjs/prod/index.js +4 -0
- package/build/cjs/prod/index.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js +19 -17
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentEmail.js +4 -3
- package/build/cjs/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js +10 -5
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/prod/orchestrion-deferred-channels.js +39 -0
- package/build/cjs/prod/orchestrion-deferred-channels.js.map +1 -0
- package/build/cjs/prod/orchestrion-diagnostics-channel.js +83 -0
- package/build/cjs/prod/orchestrion-diagnostics-channel.js.map +1 -0
- package/build/cjs/prod/vite/index.js +6 -1
- package/build/cjs/prod/vite/index.js.map +1 -1
- package/build/cjs/prod/vite/mastraObservability.js +39 -0
- package/build/cjs/prod/vite/mastraObservability.js.map +1 -0
- package/build/cjs/prod/wrapMethodWithSentry.js +8 -4
- package/build/cjs/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/prod/wrapRequestHandlerWithInit.js +2 -0
- package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/dev/index.js +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentD1.js +20 -18
- package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentEmail.js +6 -5
- package/build/esm/dev/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js +12 -7
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/dev/orchestrion-deferred-channels.js +35 -0
- package/build/esm/dev/orchestrion-deferred-channels.js.map +1 -0
- package/build/esm/dev/orchestrion-diagnostics-channel.js +77 -0
- package/build/esm/dev/orchestrion-diagnostics-channel.js.map +1 -0
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/vite/index.js +6 -1
- package/build/esm/dev/vite/index.js.map +1 -1
- package/build/esm/dev/vite/mastraObservability.js +36 -0
- package/build/esm/dev/vite/mastraObservability.js.map +1 -0
- package/build/esm/dev/wrapMethodWithSentry.js +7 -3
- package/build/esm/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/dev/wrapRequestHandlerWithInit.js +2 -0
- package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/prod/index.js +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentD1.js +20 -18
- package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentEmail.js +6 -5
- package/build/esm/prod/instrumentations/worker/instrumentEmail.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js +12 -7
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/prod/orchestrion-deferred-channels.js +35 -0
- package/build/esm/prod/orchestrion-deferred-channels.js.map +1 -0
- package/build/esm/prod/orchestrion-diagnostics-channel.js +77 -0
- package/build/esm/prod/orchestrion-diagnostics-channel.js.map +1 -0
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/vite/index.js +6 -1
- package/build/esm/prod/vite/index.js.map +1 -1
- package/build/esm/prod/vite/mastraObservability.js +36 -0
- package/build/esm/prod/vite/mastraObservability.js.map +1 -0
- package/build/esm/prod/wrapMethodWithSentry.js +7 -3
- package/build/esm/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/prod/wrapRequestHandlerWithInit.js +2 -0
- package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/types/index.d.ts +2 -2
- package/build/types/index.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentEmail.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
- package/build/types/orchestrion-deferred-channels.d.ts +26 -0
- package/build/types/orchestrion-deferred-channels.d.ts.map +1 -0
- package/build/types/orchestrion-diagnostics-channel.d.ts +44 -0
- package/build/types/orchestrion-diagnostics-channel.d.ts.map +1 -0
- package/build/types/vite/index.d.ts.map +1 -1
- package/build/types/vite/mastraObservability.d.ts +27 -0
- package/build/types/vite/mastraObservability.d.ts.map +1 -0
- package/build/types/wrapMethodWithSentry.d.ts.map +1 -1
- package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
- package/package.json +10 -5
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: 'Module' } });
|
|
2
|
+
|
|
3
|
+
const realDc = require('node:diagnostics_channel');
|
|
4
|
+
const orchestrionDeferredChannels = require('./orchestrion-deferred-channels.js');
|
|
5
|
+
|
|
6
|
+
const cache = /* @__PURE__ */ new Map();
|
|
7
|
+
function channelHasSubscribers(ch) {
|
|
8
|
+
const value = ch.hasSubscribers;
|
|
9
|
+
return typeof value === "function" ? Boolean(value.call(ch)) : Boolean(value);
|
|
10
|
+
}
|
|
11
|
+
function wrapSubChannel(tracing, real) {
|
|
12
|
+
return {
|
|
13
|
+
name: real.name,
|
|
14
|
+
// A method (not a getter) so it reads truthy as a property in the emit guard *and* is callable,
|
|
15
|
+
// matching workerd's native shape. Forced `true`: on Cloudflare a channel is only injected for a
|
|
16
|
+
// bundled integration, so the wrapper's no-subscriber short-circuit buys nothing — and disabling
|
|
17
|
+
// it is what lets the wrapper run (and reach us) at module scope before `init()` has subscribed.
|
|
18
|
+
hasSubscribers() {
|
|
19
|
+
return true;
|
|
20
|
+
},
|
|
21
|
+
publish(ctx) {
|
|
22
|
+
const hadSubscribers = channelHasSubscribers(real);
|
|
23
|
+
try {
|
|
24
|
+
real.publish(ctx);
|
|
25
|
+
} catch (error) {
|
|
26
|
+
if (!orchestrionDeferredChannels.isGlobalScopeError(error)) {
|
|
27
|
+
throw error;
|
|
28
|
+
}
|
|
29
|
+
if (!hadSubscribers) {
|
|
30
|
+
orchestrionDeferredChannels.deferChannelEvent(tracing, ctx);
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
runStores(ctx, fn, ...rest) {
|
|
35
|
+
try {
|
|
36
|
+
return real.runStores(ctx, fn, ...rest);
|
|
37
|
+
} catch (error) {
|
|
38
|
+
if (!orchestrionDeferredChannels.isGlobalScopeError(error)) {
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
return fn();
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
subscribe: real.subscribe.bind(real),
|
|
45
|
+
unsubscribe: real.unsubscribe.bind(real),
|
|
46
|
+
bindStore: real.bindStore.bind(real),
|
|
47
|
+
unbindStore: real.unbindStore.bind(real)
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
function tracingChannel(name) {
|
|
51
|
+
const cached = cache.get(name);
|
|
52
|
+
if (cached) {
|
|
53
|
+
return cached;
|
|
54
|
+
}
|
|
55
|
+
const real = realDc.tracingChannel(name);
|
|
56
|
+
const facade = {
|
|
57
|
+
start: wrapSubChannel(real, real.start),
|
|
58
|
+
end: wrapSubChannel(real, real.end),
|
|
59
|
+
asyncStart: wrapSubChannel(real, real.asyncStart),
|
|
60
|
+
asyncEnd: wrapSubChannel(real, real.asyncEnd),
|
|
61
|
+
error: wrapSubChannel(real, real.error),
|
|
62
|
+
// Iterator (`:next`) channels call these on the tracingChannel itself; delegate to the real
|
|
63
|
+
// implementation (they only run in-request, where publish/runStores are allowed).
|
|
64
|
+
traceSync: real.traceSync.bind(real),
|
|
65
|
+
tracePromise: real.tracePromise.bind(real),
|
|
66
|
+
traceCallback: real.traceCallback.bind(real),
|
|
67
|
+
subscribe: real.subscribe.bind(real),
|
|
68
|
+
unsubscribe: real.unsubscribe.bind(real)
|
|
69
|
+
};
|
|
70
|
+
cache.set(name, facade);
|
|
71
|
+
return facade;
|
|
72
|
+
}
|
|
73
|
+
const channel = realDc.channel;
|
|
74
|
+
const subscribe = realDc.subscribe;
|
|
75
|
+
const unsubscribe = realDc.unsubscribe;
|
|
76
|
+
const orchestrionDiagnosticsChannel = { tracingChannel, channel, subscribe, unsubscribe };
|
|
77
|
+
|
|
78
|
+
exports.channel = channel;
|
|
79
|
+
exports.default = orchestrionDiagnosticsChannel;
|
|
80
|
+
exports.subscribe = subscribe;
|
|
81
|
+
exports.tracingChannel = tracingChannel;
|
|
82
|
+
exports.unsubscribe = unsubscribe;
|
|
83
|
+
//# sourceMappingURL=orchestrion-diagnostics-channel.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"orchestrion-diagnostics-channel.js","sources":["../../../src/orchestrion-diagnostics-channel.ts"],"sourcesContent":["/**\n * A workerd-safe `diagnostics_channel` façade for the orchestrion EMIT side, and the\n * `dcModule` target for the Cloudflare orchestrion build (see `vite/index.ts`): orchestrion's\n * transformed code imports `tracingChannel` from here (its default export) instead of\n * `node:diagnostics_channel`.\n *\n * On workerd, `channel.publish()` and `channel.runStores()` throw at module/global scope\n * (\"Disallowed operation called within global scope …\"); only inside a request handler do they\n * work. `subscribe` and channel creation are fine anywhere. Orchestrion's transformed code emits\n * `start.runStores(...)` / `end.publish(...)` at each wrapped call site, so a library\n * instantiated at module scope (`const app = new Hono()`) throws the moment it is wrapped — or,\n * if no subscriber exists yet, is skipped by the wrapper's `if (!hasSubscribers) return\n * __apm$traced()` short-circuit and never instrumented.\n *\n * This façade delegates to the real `node:diagnostics_channel` singletons — so subscribers, which\n * keep subscribing through `node:diagnostics_channel`, are reached unchanged — and changes two\n * things:\n *\n * 1. `hasSubscribers` always reports `true`, so the wrapper never short-circuits. On Cloudflare a\n * channel is only injected for an integration that is actually bundled, so the short-circuit\n * buys nothing — and disabling it is what lets the wrapper run (and reach us) at module scope,\n * before the per-request cached `init()` has subscribed.\n * 2. When a delegated `publish`/`runStores` throws the global-scope error, the event is queued via\n * {@link deferChannelEvent} instead. {@link flushDeferredChannelEvents}, called at the top of\n * the request handler after `init()`, emits it via the real channel — now inside a request,\n * where publish works.\n *\n * In a request handler nothing throws, so every call is a transparent pass-through to the real\n * channel: lifecycle channels (spans, context binding) behave exactly as on Node.\n */\nimport * as realDc from 'node:diagnostics_channel';\nimport { deferChannelEvent, isGlobalScopeError } from './orchestrion-deferred-channels';\n\ntype Ctx = Record<string, unknown>;\n\n// One façade per channel name (node's `tracingChannel` is itself a per-name singleton), built\n// once when the transformed module declares `const CH = tracingChannel(name)`.\nconst cache = new Map<string, realDc.TracingChannel>();\n\n// `Channel.hasSubscribers` is a getter on Node but a method on workerd — normalize both to a\n// boolean. (This shape difference is also why the emit wrapper never short-circuits on workerd:\n// its `if (!ch.start.hasSubscribers)` guard reads a truthy method reference.)\nfunction channelHasSubscribers(ch: realDc.Channel): boolean {\n const value = (ch as { hasSubscribers: unknown }).hasSubscribers;\n return typeof value === 'function' ? Boolean((value as () => unknown).call(ch)) : Boolean(value);\n}\n\nfunction wrapSubChannel(tracing: realDc.TracingChannel, real: realDc.Channel): realDc.Channel {\n return {\n name: real.name,\n // A method (not a getter) so it reads truthy as a property in the emit guard *and* is callable,\n // matching workerd's native shape. Forced `true`: on Cloudflare a channel is only injected for a\n // bundled integration, so the wrapper's no-subscriber short-circuit buys nothing — and disabling\n // it is what lets the wrapper run (and reach us) at module scope before `init()` has subscribed.\n hasSubscribers(): boolean {\n return true;\n },\n publish(ctx: Ctx): void {\n // Snapshot subscriber presence before publishing — it decides whether to defer if the\n // global-scope error fires below.\n const hadSubscribers = channelHasSubscribers(real);\n try {\n real.publish(ctx);\n } catch (error) {\n if (!isGlobalScopeError(error)) {\n throw error;\n }\n // We're at module scope (workerd throws here even with no subscribers). If someone was\n // already subscribed — top-level `Sentry.init()` — workerd delivered to them before\n // throwing, so they got it exactly once; don't defer. Otherwise — the common per-request\n // cached-init case — nobody received it, so defer for a subscriber that registers later\n // (at `init()`), which then gets it exactly once. In a request `publish` doesn't throw,\n // so this path never defers a normal in-request event.\n if (!hadSubscribers) {\n deferChannelEvent(tracing, ctx);\n }\n }\n },\n runStores(ctx: Ctx, fn: (...args: unknown[]) => unknown, ...rest: unknown[]): unknown {\n try {\n return real.runStores(ctx, fn, ...rest);\n } catch (error) {\n if (!isGlobalScopeError(error)) {\n throw error;\n }\n // publish() is gated too, so the store can't be established — just run the wrapped call\n // so its return value (e.g. the constructed instance) is produced now. Its own\n // `end.publish` runs back through this façade and is deferred.\n return fn();\n }\n },\n subscribe: real.subscribe.bind(real),\n unsubscribe: real.unsubscribe.bind(real),\n bindStore: real.bindStore.bind(real),\n unbindStore: real.unbindStore.bind(real),\n } as unknown as realDc.Channel;\n}\n\nexport function tracingChannel<T = Ctx>(name: string): realDc.TracingChannel<T> {\n const cached = cache.get(name);\n if (cached) {\n return cached;\n }\n\n const real = realDc.tracingChannel(name);\n const facade = {\n start: wrapSubChannel(real, real.start),\n end: wrapSubChannel(real, real.end),\n asyncStart: wrapSubChannel(real, real.asyncStart),\n asyncEnd: wrapSubChannel(real, real.asyncEnd),\n error: wrapSubChannel(real, real.error),\n // Iterator (`:next`) channels call these on the tracingChannel itself; delegate to the real\n // implementation (they only run in-request, where publish/runStores are allowed).\n traceSync: real.traceSync.bind(real),\n tracePromise: real.tracePromise.bind(real),\n traceCallback: real.traceCallback.bind(real),\n subscribe: real.subscribe.bind(real),\n unsubscribe: real.unsubscribe.bind(real),\n } as unknown as realDc.TracingChannel<T>;\n\n cache.set(name, facade);\n return facade;\n}\n\nexport const channel = realDc.channel;\nexport const subscribe = realDc.subscribe;\nexport const unsubscribe = realDc.unsubscribe;\n\n// Orchestrion's emit imports the default and destructures `tracingChannel`.\nexport default { tracingChannel, channel, subscribe, unsubscribe };\n"],"names":["isGlobalScopeError","deferChannelEvent"],"mappings":";;;;;AAqCA,MAAM,KAAA,uBAAY,GAAA,EAAmC;AAKrD,SAAS,sBAAsB,EAAA,EAA6B;AAC1D,EAAA,MAAM,QAAS,EAAA,CAAmC,cAAA;AAClD,EAAA,OAAO,OAAO,KAAA,KAAU,UAAA,GAAa,OAAA,CAAS,KAAA,CAAwB,KAAK,EAAE,CAAC,CAAA,GAAI,OAAA,CAAQ,KAAK,CAAA;AACjG;AAEA,SAAS,cAAA,CAAe,SAAgC,IAAA,EAAsC;AAC5F,EAAA,OAAO;AAAA,IACL,MAAM,IAAA,CAAK,IAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKX,cAAA,GAA0B;AACxB,MAAA,OAAO,IAAA;AAAA,IACT,CA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AO,MAAA,CAAO,cAAA,CAAe,IAAI,CAAA;AACvC,EAAA,MAAM,MAAA,GAAS;AAAA,IACb,KAAA,EAAO,cAAA,CAAe,IAAA,EAAM,IAAA,CAAK,KAAK,CAAA;AAAA,IACtC,GAAA,EAAK,cAAA,CAAe,IAAA,EAAM,IAAA,CAAK,GAAG,CAAA;AAAA,IAClC,UAAA,EAAY,cAAA,CAAe,IAAA,EAAM,IAAA,CAAK,UAAU,CAAA;AAAA,IAChD,QAAA,EAAU,cAAA,CAAe,IAAA,EAAM,IAAA,CAAK,QAAQ,CAAA;AAAA,IAC5C,KAAA,EAAO,cAAA,CAAe,IAAA,EAAM,IAAA,CAAK,KAAK,CAAA;AAAA;AAAA;AAAA,IAGtC,SAAA,EAAW,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA;AAAA,IACnC,YAAA,EAAc,IAAA,CAAK,YAAA,CAAa,IAAA,CAAK,IAAI,CAAA;AAAA,IACzC,aAAA,EAAe,IAAA,CAAK,aAAA,CAAc,IAAA,CAAK,IAAI,CAAA;AAAA,IAC3C,SAAA,EAAW,IAAA,CAAK,SAAA,CAAU,IAAA,CAAK,IAAI,CAAA;AAAA,IACnC,WAAA,EAAa,IAAA,CAAK,WAAA,CAAY,IAAA,CAAK,IAAI;AAAA,GACzC;AAEA,EAAA,KAAA,CAAM,GAAA,CAAI,MAAM,MAAM,CAAA;AACtB,EAAA,OAAO,MAAA;AACT;AAEO,MAAM,UAAU,MAAA,CAAO;AACvB,MAAM,YAAY,MAAA,CAAO;AACzB,MAAM,cAAc,MAAA,CAAO;AAGlC,sCAAe,EAAE,cAAA,EAAgB,OAAA,EAAS,SAAA,EAAW,WAAA,EAAY;;;;;;;;"}
|
|
@@ -2,12 +2,17 @@ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
|
2
2
|
|
|
3
3
|
const vite = require('@sentry/server-utils/orchestrion/vite');
|
|
4
4
|
const autoInstrument = require('./autoInstrument.js');
|
|
5
|
+
const mastraObservability = require('./mastraObservability.js');
|
|
5
6
|
|
|
6
7
|
function sentryCloudflareVitePlugin(options = {}) {
|
|
7
8
|
return [
|
|
8
9
|
vite.sentryOrchestrionPlugin({
|
|
9
|
-
buildTimeInstrumentation: options.buildTimeInstrumentation
|
|
10
|
+
buildTimeInstrumentation: options.buildTimeInstrumentation,
|
|
11
|
+
// Route the injected `tracingChannel` imports through the workerd-safe façade so a
|
|
12
|
+
// dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.
|
|
13
|
+
dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel"
|
|
10
14
|
}),
|
|
15
|
+
mastraObservability.sentryMastraObservabilityProviderPlugin(),
|
|
11
16
|
...options.autoInstrumentation !== false ? [autoInstrument.sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })] : []
|
|
12
17
|
];
|
|
13
18
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n }),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":["sentryOrchestrionPlugin","sentryCloudflareAutoInstrumentPlugin"],"mappings":"
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n }),\n sentryMastraObservabilityProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":["sentryOrchestrionPlugin","sentryMastraObservabilityProviderPlugin","sentryCloudflareAutoInstrumentPlugin"],"mappings":";;;;;;AAoFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACLA,4BAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU;AAAA,KACX,CAAA;AAAA,IACDC,2DAAA,EAAwC;AAAA,IACxC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAACC,mDAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
|
|
3
|
+
const node_module = require('node:module');
|
|
4
|
+
const node_path = require('node:path');
|
|
5
|
+
const MagicString = require('magic-string');
|
|
6
|
+
|
|
7
|
+
const PROVIDER_IDENTIFIER = "__SENTRY_MASTRA_OBSERVABILITY__";
|
|
8
|
+
const MASTRA_INTEGRATION_ID = /@sentry\/server-utils\/build\/esm\/integrations\/mastra\.js$/;
|
|
9
|
+
function isMastraIntegrationModuleId(id) {
|
|
10
|
+
const normalizedId = id.replace(/\\/g, "/").replace(/[?#].*$/, "");
|
|
11
|
+
return MASTRA_INTEGRATION_ID.test(normalizedId);
|
|
12
|
+
}
|
|
13
|
+
function sentryMastraObservabilityProviderPlugin() {
|
|
14
|
+
let providerSnippet;
|
|
15
|
+
return {
|
|
16
|
+
name: "sentry-cloudflare-mastra-observability-provider",
|
|
17
|
+
configResolved(config) {
|
|
18
|
+
try {
|
|
19
|
+
node_module.createRequire(node_path.resolve(config.root, "noop.js")).resolve("@mastra/observability");
|
|
20
|
+
} catch {
|
|
21
|
+
return;
|
|
22
|
+
}
|
|
23
|
+
providerSnippet = `import * as ${PROVIDER_IDENTIFIER} from '@mastra/observability';
|
|
24
|
+
(globalThis.__SENTRY_ORCHESTRION__ = globalThis.__SENTRY_ORCHESTRION__ || {});
|
|
25
|
+
(globalThis.__SENTRY_ORCHESTRION__.providedModules = globalThis.__SENTRY_ORCHESTRION__.providedModules || {})['@mastra/observability'] = ${PROVIDER_IDENTIFIER};
|
|
26
|
+
`;
|
|
27
|
+
},
|
|
28
|
+
transform(code, id) {
|
|
29
|
+
if (!providerSnippet || !isMastraIntegrationModuleId(id)) return void 0;
|
|
30
|
+
const ms = new MagicString.default(code);
|
|
31
|
+
ms.prepend(providerSnippet);
|
|
32
|
+
return { code: ms.toString(), map: ms.generateMap({ hires: true }) };
|
|
33
|
+
}
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
exports.isMastraIntegrationModuleId = isMastraIntegrationModuleId;
|
|
38
|
+
exports.sentryMastraObservabilityProviderPlugin = sentryMastraObservabilityProviderPlugin;
|
|
39
|
+
//# sourceMappingURL=mastraObservability.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"mastraObservability.js","sources":["../../../../src/vite/mastraObservability.ts"],"sourcesContent":["import { createRequire } from 'node:module';\nimport { resolve } from 'node:path';\nimport MagicString from 'magic-string';\n\n// Namespace binding the injected provider import uses; read back by the integration\n// off the global marker.\nconst PROVIDER_IDENTIFIER = '__SENTRY_MASTRA_OBSERVABILITY__';\n\n// The bundled `@sentry/server-utils` Mastra integration module (ESM build — the only\n// one a worker loads). Its `loadMastraObservability` reads `@mastra/observability` off\n// the global marker this provider populates, instead of `createRequire`, which cannot\n// resolve a package inside a bundled worker.\nconst MASTRA_INTEGRATION_ID = /@sentry\\/server-utils\\/build\\/esm\\/integrations\\/mastra\\.js$/;\n\n/** Whether `id` is the Sentry Mastra integration module the provider injects into. */\nexport function isMastraIntegrationModuleId(id: string): boolean {\n const normalizedId = id.replace(/\\\\/g, '/').replace(/[?#].*$/, '');\n return MASTRA_INTEGRATION_ID.test(normalizedId);\n}\n\n/**\n * Splices a static `import * as … from '@mastra/observability'` into Sentry's own\n * Mastra integration module and stashes the namespace on the global orchestrion\n * marker.\n *\n * On Cloudflare the integration cannot `createRequire('@mastra/observability')` to\n * bootstrap Mastra's observability pipeline — there is no on-disk `node_modules` in\n * workerd — so without this the user has to construct and wire up an `Observability`\n * themselves. The import is static (statically analyzable, no lazy `import()`), lands\n * in Sentry's module rather than the user's code, and is only emitted when the package\n * actually resolves; if it is absent, the integration keeps its Node `createRequire`\n * fallback and the marker stays empty.\n */\nexport function sentryMastraObservabilityProviderPlugin(): {\n name: string;\n configResolved(config: { root: string }): void;\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined;\n} {\n let providerSnippet: string | undefined;\n\n return {\n name: 'sentry-cloudflare-mastra-observability-provider',\n\n configResolved(config: { root: string }): void {\n // Resolved at build time (Node), so this `createRequire` never ships to the worker.\n try {\n createRequire(resolve(config.root, 'noop.js')).resolve('@mastra/observability');\n } catch {\n return;\n }\n providerSnippet =\n `import * as ${PROVIDER_IDENTIFIER} from '@mastra/observability';\\n` +\n '(globalThis.__SENTRY_ORCHESTRION__ = globalThis.__SENTRY_ORCHESTRION__ || {});\\n' +\n '(globalThis.__SENTRY_ORCHESTRION__.providedModules = globalThis.__SENTRY_ORCHESTRION__.providedModules || {})' +\n `['@mastra/observability'] = ${PROVIDER_IDENTIFIER};\\n`;\n },\n\n transform(code: string, id: string): { code: string; map: ReturnType<MagicString['generateMap']> } | undefined {\n if (!providerSnippet || !isMastraIntegrationModuleId(id)) return undefined;\n\n const ms = new MagicString(code);\n ms.prepend(providerSnippet);\n return { code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Property(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
2
|
|
|
3
|
+
const attributes = require('@sentry/conventions/attributes');
|
|
4
|
+
const op = require('@sentry/conventions/op');
|
|
3
5
|
const core = require('@sentry/core');
|
|
4
6
|
const flush = require('./flush.js');
|
|
5
7
|
const instrument = require('./instrument.js');
|
|
@@ -92,12 +94,14 @@ function wrapMethodWithSentry(wrapperOptions, handler, callback, noMark) {
|
|
|
92
94
|
return onRejected(e);
|
|
93
95
|
}
|
|
94
96
|
}
|
|
95
|
-
const attributes = wrapperOptions.spanOp ? {
|
|
96
|
-
[
|
|
97
|
-
[
|
|
97
|
+
const attributes$1 = wrapperOptions.spanOp ? {
|
|
98
|
+
[attributes.SENTRY_OP]: wrapperOptions.spanOp,
|
|
99
|
+
[attributes.SENTRY_ORIGIN]: origin,
|
|
100
|
+
// `function` spans are already named like their function name, so we just set `code.function.name` here.
|
|
101
|
+
...wrapperOptions.spanOp === op.FUNCTION && { [attributes.CODE_FUNCTION_NAME]: methodName }
|
|
98
102
|
} : {};
|
|
99
103
|
const executeSpan = () => {
|
|
100
|
-
return core.startSpan({ name: methodName, attributes }, (span) => {
|
|
104
|
+
return core.startSpan({ name: methodName, attributes: attributes$1 }, (span) => {
|
|
101
105
|
if (startNewTrace && storage) {
|
|
102
106
|
const storedContext = traceLinks.getStoredSpanContext(storage, methodName);
|
|
103
107
|
if (storedContext) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wrapMethodWithSentry.js","sources":["../../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n isThenable,\n type Scope,\n SEMANTIC_ATTRIBUTE_SENTRY_OP,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n startNewTrace as startNewTraceCore,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\nexport interface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n /**\n * The span name, or a resolver called with the RPC metadata of the current call.\n * Returning `undefined` skips the span and only captures errors.\n */\n spanName?: string | ((rpcMeta: SerializedTraceData | undefined) => string | undefined);\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n const spanName =\n typeof wrapperOptions.spanName === 'function' ? wrapperOptions.spanName(rpcMeta) : wrapperOptions.spanName;\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n // Resolved once per invocation and cached on its state: reading `ctx.waitUntil`\n // on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Re-init when the scope has no usable client (a previous handler disposed it, e.g.\n // DO alarm handlers) or for `startNewTrace`, so the client points at this\n // invocation's context. With `cacheClient: true` `init()` returns the isolate's\n // cached client and only creates (and caches) a fresh one when nothing is cached yet;\n // `cacheClient: false` creates one per invocation.\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const captureAndRethrow = (e: unknown): never => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n throw e;\n };\n\n const onRejected = (e: unknown) => {\n try {\n return captureAndRethrow(e);\n } finally {\n waitUntil?.(teardown());\n }\n };\n\n if (!spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SEMANTIC_ATTRIBUTE_SENTRY_OP]: wrapperOptions.spanOp,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: origin,\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO: Remove this once EAP can store span links. We currently only set this attribute so that we\n // can obtain the previous trace information from the EAP store. Long-term, EAP will handle\n // span links and then we should remove this again. Also throwing in a TODO(v11), to remind us\n // to check this at v11 time :)\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(undefined, captureAndRethrow);\n }\n return result;\n } catch (e) {\n return captureAndRethrow(e);\n }\n });\n };\n\n // The boundary flush (teardown) must run after the method span has ended, so the\n // span is in the buffer when that flush drains it. Running it inside the span\n // callback (before `startSpan` ends the span) would leave the span for the eager\n // path and cost a second flush per invocation.\n const runWithTeardown = (run: () => unknown): unknown => {\n let out: unknown;\n try {\n out = run();\n } catch (e) {\n // Synchronous throw: `startSpan` already ended the span and rethrew.\n waitUntil?.(teardown());\n throw e;\n }\n if (isThenable(out)) {\n return out.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n waitUntil?.(teardown());\n throw e;\n },\n );\n }\n waitUntil?.(teardown());\n return out;\n };\n\n if (rpcMeta) {\n return runWithTeardown(() =>\n continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n ),\n );\n }\n\n if (startNewTrace) {\n return runWithTeardown(() => startNewTraceCore(() => executeSpan()));\n }\n\n return runWithTeardown(executeSpan);\n };\n\n return withInvocationIsolationScope(\n wrappedFunction,\n wrapperOptions.context as ExecutionContextCompat | undefined,\n );\n },\n }),\n noMark,\n );\n}\n"],"names":["isObjectLike","ensureInstrumented","rpcMeta","extractRpcMeta","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","init","storeSpanContext","flushAndDispose","captureException","isThenable","SEMANTIC_ATTRIBUTE_SENTRY_OP","SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN","startSpan","getStoredSpanContext","buildSpanLinks","continueTrace","startNewTraceCore","withInvocationIsolationScope"],"mappings":";;;;;;;;;;;AAiCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAIA,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CAAQ,OAAA,IAAW,EAAA,EAAG;AAAA,gBAC7E;AAAA;AACF,aACF;AAAA,UACF;AAEA,UAAA,IAAI,aAAA,EAAe;AACjB,YAAA,OAAO,gBAAgB,MAAMgB,kBAAA,CAAkB,MAAM,WAAA,EAAa,CAAC,CAAA;AAAA,UACrE;AAEA,UAAA,OAAO,gBAAgB,WAAW,CAAA;AAAA,QACpC,CAAA;AAEA,QAAA,OAAOC,4CAAA;AAAA,UACL,eAAA;AAAA,UACA,cAAA,CAAe;AAAA,SACjB;AAAA,MACF;AAAA,KACD,CAAA;AAAA,IACH;AAAA,GACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"wrapMethodWithSentry.js","sources":["../../../src/wrapMethodWithSentry.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport type { SerializedTraceData } from '@sentry/core';\nimport { CODE_FUNCTION_NAME, SENTRY_OP, SENTRY_ORIGIN } from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport {\n isObjectLike,\n captureException,\n continueTrace,\n isThenable,\n type Scope,\n startNewTrace as startNewTraceCore,\n startSpan,\n} from '@sentry/core';\nimport type { CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { ensureInstrumented } from './instrument';\nimport { init } from './sdk';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { extractRpcMeta } from './utils/rpcMeta';\nimport { buildSpanLinks, getStoredSpanContext, storeSpanContext } from './utils/traceLinks';\n\n/** Extended DurableObjectState with originalStorage exposed by instrumentContext */\nexport interface InstrumentedDurableObjectState extends DurableObjectState {\n originalStorage?: DurableObjectStorage;\n}\n\n/**\n * Resolves uninstrumented DO storage for the current invocation.\n * Prefer `thisArg.ctx` (the live Durable Object instance) over the context captured at\n * construction time to avoid cross-DO I/O errors in the same isolate.\n */\nfunction resolveOriginalStorage(\n context: ExecutionContext | InstrumentedDurableObjectState | undefined,\n thisArg: unknown,\n): DurableObjectStorage | undefined {\n if (isObjectLike(thisArg) && 'ctx' in thisArg) {\n const doCtx = (thisArg as { ctx: InstrumentedDurableObjectState }).ctx;\n if (doCtx?.originalStorage) {\n return doCtx.originalStorage;\n }\n }\n\n if (context && 'originalStorage' in context && context.originalStorage) {\n return context.originalStorage;\n }\n\n return undefined;\n}\n\ntype MethodWrapperOptions = {\n /**\n * The span name, or a resolver called with the RPC metadata of the current call.\n * Returning `undefined` skips the span and only captures errors.\n */\n spanName?: string | ((rpcMeta: SerializedTraceData | undefined) => string | undefined);\n spanOp?: string;\n options: CloudflareOptions;\n context: ExecutionContext | InstrumentedDurableObjectState;\n /**\n * If true, starts a fresh trace instead of inheriting from a parent trace.\n * Useful for scheduled/independent invocations like alarms.\n *\n * If true, it also stores the current span context and links to the previous invocation's span.\n * Uses Durable Object storage to persist the link. The link is set asynchronously via `span.addLinks()`\n * in a `waitUntil` to avoid blocking.\n *\n * @default false\n */\n startNewTrace?: boolean;\n /**\n * The trace origin identifying which instrumentation created the span, e.g. `auto.faas.cloudflare.durable_object`.\n * Used both as the span's `sentry.origin` attribute and as the `mechanism.type` for captured exceptions.\n */\n origin: string;\n};\n\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type UncheckedMethod = (...args: any[]) => any;\ntype OriginalMethod = UncheckedMethod;\n\n/**\n * Wraps a method with Sentry error tracking and optional tracing.\n * Supports starting new traces and linking to previous invocations via Durable Object storage.\n *\n * @param wrapperOptions - The options for the wrapper.\n * @param handler - The method to wrap.\n * @param callback - The callback to call.\n * @param noMark - Whether to mark the method as instrumented.\n * @returns The wrapped method.\n */\nexport function wrapMethodWithSentry<T extends OriginalMethod>(\n wrapperOptions: MethodWrapperOptions,\n handler: T,\n callback?: (...args: Parameters<T>) => void,\n noMark?: true,\n): T {\n return ensureInstrumented(\n handler,\n original =>\n new Proxy(original, {\n apply(target, thisArg, rawArgs: Parameters<T>) {\n const { startNewTrace, origin } = wrapperOptions;\n\n // For RPC methods, extract Sentry trace context from the trailing argument.\n // The caller side (instrumentDurableObjectStub / JSRPC proxy) appends it;\n // we strip it here so the user's method never sees it.\n let args = rawArgs;\n let rpcMeta: SerializedTraceData | undefined;\n\n if (wrapperOptions.spanOp === 'rpc') {\n const extracted = extractRpcMeta(rawArgs);\n args = extracted.args;\n rpcMeta = extracted.rpcMeta;\n }\n\n const spanName =\n typeof wrapperOptions.spanName === 'function' ? wrapperOptions.spanName(rpcMeta) : wrapperOptions.spanName;\n\n const wrappedFunction = (scope: Scope): unknown | Promise<unknown> => {\n // In certain situations, the passed context can become undefined.\n // For example, for Astro while prerendering pages at build time.\n // see: https://github.com/getsentry/sentry-javascript/issues/13217\n const context: typeof wrapperOptions.context | undefined = wrapperOptions.context;\n\n // see: https://github.com/getsentry/sentry-javascript/issues/22328\n // Resolved once per invocation and cached on its state: reading `ctx.waitUntil`\n // on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context as ExecutionContextCompat)?.bind(context)\n : undefined;\n const storage = resolveOriginalStorage(context, thisArg);\n\n let scopeClient = scope.getClient();\n // Re-init when the scope has no usable client (a previous handler disposed it, e.g.\n // DO alarm handlers) or for `startNewTrace`, so the client points at this\n // invocation's context. With `cacheClient: true` `init()` returns the isolate's\n // cached client and only creates (and caches) a fresh one when nothing is cached yet;\n // `cacheClient: false` creates one per invocation.\n if (startNewTrace || !scopeClient?.getTransport()) {\n const client = init({\n ...wrapperOptions.options,\n ctx: context as unknown as ExecutionContext | undefined,\n });\n scope.setClient(client);\n scopeClient = client;\n }\n\n const clientToDispose = scopeClient;\n const methodName = spanName || 'unknown';\n\n const teardown = async (): Promise<void> => {\n if (startNewTrace && storage) {\n storeSpanContext(storage, methodName);\n }\n await flushAndDispose(clientToDispose);\n };\n\n const onFulfilled = (res: unknown) => {\n waitUntil?.(teardown());\n return res;\n };\n\n const captureAndRethrow = (e: unknown): never => {\n captureException(e, {\n mechanism: {\n type: origin,\n handled: false,\n },\n });\n throw e;\n };\n\n const onRejected = (e: unknown) => {\n try {\n return captureAndRethrow(e);\n } finally {\n waitUntil?.(teardown());\n }\n };\n\n if (!spanName) {\n try {\n if (callback) {\n callback(...args);\n }\n\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(onFulfilled, onRejected);\n } else {\n return onFulfilled(result);\n }\n } catch (e) {\n return onRejected(e);\n }\n }\n\n const attributes = wrapperOptions.spanOp\n ? {\n [SENTRY_OP]: wrapperOptions.spanOp,\n [SENTRY_ORIGIN]: origin,\n // `function` spans are already named like their function name, so we just set `code.function.name` here.\n ...(wrapperOptions.spanOp === FUNCTION && { [CODE_FUNCTION_NAME]: methodName }),\n }\n : {};\n\n const executeSpan = (): unknown => {\n return startSpan({ name: methodName, attributes }, span => {\n if (startNewTrace && storage) {\n const storedContext = getStoredSpanContext(storage, methodName);\n\n if (storedContext) {\n span.addLinks(buildSpanLinks(storedContext));\n // TODO(v12): Remove this once the Sentry trace view finds linked traces via span links.\n // EAP stores span links, but the trace view still reads this attribute to navigate to the\n // previous/next trace.\n const sampledFlag = storedContext.sampled ? '1' : '0';\n span.setAttribute(\n 'sentry.previous_trace',\n `${storedContext.traceId}-${storedContext.spanId}-${sampledFlag}`,\n );\n }\n }\n\n try {\n const result = Reflect.apply(target, thisArg, args);\n\n if (isThenable(result)) {\n return result.then(undefined, captureAndRethrow);\n }\n return result;\n } catch (e) {\n return captureAndRethrow(e);\n }\n });\n };\n\n // The boundary flush (teardown) must run after the method span has ended, so the\n // span is in the buffer when that flush drains it. Running it inside the span\n // callback (before `startSpan` ends the span) would leave the span for the eager\n // path and cost a second flush per invocation.\n const runWithTeardown = (run: () => unknown): unknown => {\n let out: unknown;\n try {\n out = run();\n } catch (e) {\n // Synchronous throw: `startSpan` already ended the span and rethrew.\n waitUntil?.(teardown());\n throw e;\n }\n if (isThenable(out)) {\n return out.then(\n res => {\n waitUntil?.(teardown());\n return res;\n },\n e => {\n waitUntil?.(teardown());\n throw e;\n },\n );\n }\n waitUntil?.(teardown());\n return out;\n };\n\n if (rpcMeta) {\n return runWithTeardown(() =>\n continueTrace(\n { sentryTrace: rpcMeta['sentry-trace'] || '', baggage: rpcMeta.baggage || '' },\n executeSpan,\n ),\n );\n }\n\n if (startNewTrace) {\n return runWithTeardown(() => startNewTraceCore(() => executeSpan()));\n }\n\n return runWithTeardown(executeSpan);\n };\n\n return withInvocationIsolationScope(\n wrappedFunction,\n wrapperOptions.context as ExecutionContextCompat | undefined,\n );\n },\n }),\n noMark,\n );\n}\n"],"names":["isObjectLike","ensureInstrumented","rpcMeta","extractRpcMeta","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","init","storeSpanContext","flushAndDispose","captureException","isThenable","attributes","SENTRY_OP","SENTRY_ORIGIN","FUNCTION","CODE_FUNCTION_NAME","startSpan","getStoredSpanContext","buildSpanLinks","continueTrace","startNewTraceCore","withInvocationIsolationScope"],"mappings":";;;;;;;;;;;;;AAiCA,SAAS,sBAAA,CACP,SACA,OAAA,EACkC;AAClC,EAAA,IAAIA,iBAAA,CAAa,OAAO,CAAA,IAAK,KAAA,IAAS,OAAA,EAAS;AAC7C,IAAA,MAAM,QAAS,OAAA,CAAoD,GAAA;AACnE,IAAA,IAAI,OAAO,eAAA,EAAiB;AAC1B,MAAA,OAAO,KAAA,CAAM,eAAA;AAAA,IACf;AAAA,EACF;AAEA,EAAA,IAAI,OAAA,IAAW,iBAAA,IAAqB,OAAA,IAAW,OAAA,CAAQ,eAAA,EAAiB;AACtE,IAAA,OAAO,OAAA,CAAQ,eAAA;AAAA,EACjB;AAEA,EAAA,OAAO,MAAA;AACT;AA2CO,SAAS,oBAAA,CACd,cAAA,EACA,OAAA,EACA,QAAA,EACA,MAAA,EACG;AACH,EAAA,OAAOC,6BAAA;AAAA,IACL,OAAA;AAAA,IACA,C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;;"}
|
|
@@ -4,6 +4,7 @@ const attributes = require('@sentry/conventions/attributes');
|
|
|
4
4
|
const op = require('@sentry/conventions/op');
|
|
5
5
|
const core = require('@sentry/core');
|
|
6
6
|
const httpServer = require('./integrations/httpServer.js');
|
|
7
|
+
const orchestrionDeferredChannels = require('./orchestrion-deferred-channels.js');
|
|
7
8
|
const flush = require('./flush.js');
|
|
8
9
|
const scopeUtils = require('./scope-utils.js');
|
|
9
10
|
const invocationContext = require('./utils/invocationContext.js');
|
|
@@ -22,6 +23,7 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
|
|
|
22
23
|
const errorMechanismType = getRequestErrorMechanismType(context);
|
|
23
24
|
const client = initSdk({ ...options, ctx: context });
|
|
24
25
|
isolationScope.setClient(client);
|
|
26
|
+
orchestrionDeferredChannels.flushDeferredChannelEvents();
|
|
25
27
|
const urlObject = core.parseStringToURLObject(request.url);
|
|
26
28
|
const [rawName, attributes$1] = core.getHttpSpanDetailsFromUrlObject(
|
|
27
29
|
urlObject,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"wrapRequestHandlerWithInit.js","sources":["../../../src/wrapRequestHandlerWithInit.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport {\n captureException,\n continueTrace,\n getHttpSpanDetailsFromUrlObject,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n} from '@sentry/core';\nimport { captureIncomingRequestBody } from './integrations/httpServer';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { classifyResponseStreaming } from './utils/streaming';\n\nfunction getRequestErrorMechanismType(context: ExecutionContextCompat | undefined): string {\n // Durable Object fetch handlers use DO state as context (see instrumentDurableObjectWithSentry)\n return context && 'storage' in context ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';\n}\n\nexport interface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContextCompat | undefined;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\ntype InitSdk = (options: CloudflareOptions) => CloudflareClient | undefined;\n\n/**\n * Same as {@link wrapRequestHandler}, but with the SDK initialization injected.\n *\n * Wrappers that are only reachable from the main entry point — where `nodejs_compat` is a\n * requirement anyway — pass `init` from `sdk.ts` to get the full default integrations.\n *\n * @internal\n */\nexport function wrapRequestHandlerWithInit(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n initSdk: InitSdk,\n): Promise<Response> {\n return withInvocationIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // The un-instrumented waitUntil, so flushAndDispose cannot deadlock on the flush\n // lock's own wrapper. Resolved once per invocation and cached on its state; reading\n // `ctx.waitUntil` on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context).bind(context)\n : undefined;\n const errorMechanismType = getRequestErrorMechanismType(context);\n\n const client = initSdk({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n const urlObject = parseStringToURLObject(request.url);\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n 'auto.http.cloudflare',\n request,\n undefined,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !client || !hasSpanStreamingEnabled(client)\n ? rawName\n : request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n if (client) {\n Object.assign(\n attributes,\n httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers), client.getDataCollectionOptions()),\n );\n }\n\n attributes[SENTRY_OP] = HTTP_SERVER;\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split('/');\n attributes[NETWORK_PROTOCOL_NAME] = protocolName;\n attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;\n }\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n throw e;\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n if (client) {\n await captureIncomingRequestBody(client, request);\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n waitUntil?.(flushAndDispose(client));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n try {\n let ended = false;\n\n const endSpanOnce = (): void => {\n if (ended) return;\n\n ended = true;\n span.end();\n waitUntil?.(flushAndDispose(client));\n };\n\n const transform = new TransformStream({\n flush() {\n // Source stream completed normally.\n endSpanOnce();\n },\n cancel() {\n // Client disconnected (or downstream cancelled). The `cancel`\n // is being called while the response is still considered\n // active, so this is a safe place to end the span.\n endSpanOnce();\n },\n });\n\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch {\n span.end();\n waitUntil?.(flushAndDispose(client));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n\n // Don't dispose for protocol upgrades (101 Switching Protocols) - the connection stays alive.\n // This includes WebSocket upgrades where webSocketMessage/webSocketClose handlers\n // will still be called and may need the client to capture errors.\n if (res.status === 101) {\n waitUntil?.(client?.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n return res;\n });\n },\n );\n }, wrapperOptions.context);\n}\n"],"names":["withInvocationIsolationScope","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","parseStringToURLObject","attributes","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","httpHeadersToSpanAttributes","winterCGHeadersToDict","SENTRY_OP","HTTP_SERVER","addCloudResourceContext","addRequest","addCultureContext","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","captureException","flushAndDispose","captureIncomingRequestBody","continueTrace","startSpanManual","setHttpStatus","classifyResponseStreaming"],"mappings":";;;;;;;;;;;;AA6BA,SAAS,6BAA6B,OAAA,EAAqD;AAEzF,EAAA,OAAO,OAAA,IAAW,SAAA,IAAa,OAAA,GAAU,qCAAA,GAAwC,sBAAA;AACnF;AA6BO,SAAS,0BAAA,CACd,cAAA,EACA,OAAA,EACA,OAAA,EACmB;AACnB,EAAA,OAAOA,4CAAA,CAA6B,OAAM,cAAA,KAAkB;AAC1D,IAAA,MAAM,EAAE,OAAA,EAAS,OAAA,EAAS,aAAA,GAAgB,MAAK,GAAI,cAAA;AACnD,IAAA,MAAM,UAAU,cAAA,CAAe,OAAA;AAK/B,IAAA,MAAM,kBAAkBC,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,GACdC,wCAAA,CAAuB,eAAe,CAAA,GACtC,OAAA,GACEC,0BAAA,CAAqB,OAAO,CAAA,CAAE,IAAA,CAAK,OAAO,CAAA,GAC1C,MAAA;AACN,IAAA,MAAM,kBAAA,GAAqB,6BAA6B,OAAO,CAAA;AAE/D,IAAA,MAAM,SAAS,OAAA,CAAQ,EAAE,GAAG,OAAA,EAAS,GAAA,EAAK,SAAS,CAAA;AACnD,IAAA,cAAA,CAAe,UAAU,MAAM,CAAA;AAE/B,IAAA,MAAM,SAAA,GAAYC,2BAAA,CAAuB,OAAA,CAAQ,GAAG,CAAA;AACpD,IAAA,MAAM,CAAC,OAAA,EAASC,YAAU,CAAA,GAAIC,oCAAA;AAAA,MAC5B,SAAA;AAAA,MACA,QAAA;AAAA,MACA,sBAAA;AAAA,MACA,OAAA;AAAA,MACA,MAAA;AAAA,MACA;AAAA,KACF;AAGA,IAAA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AA,GAAY,MAAA,EAAQ,KAAA,CAAM,GAAI,CAAC,CAAA;AAAA,UACjC,CAAA,MAAO;AACL,YAAA,SAAA,GAAYA,qBAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,UACrC;AACA,UAAA,OAAO,GAAA;AAAA,QACT,CAAC,CAAA;AAAA,MACH;AAAA,KACF;AAAA,EACF,CAAA,EAAG,eAAe,OAAO,CAAA;AAC3B;;;;"}
|
|
1
|
+
{"version":3,"file":"wrapRequestHandlerWithInit.js","sources":["../../../src/wrapRequestHandlerWithInit.ts"],"sourcesContent":["import type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport {\n NETWORK_PROTOCOL_NAME,\n NETWORK_PROTOCOL_VERSION,\n SENTRY_OP,\n SENTRY_SEGMENT_NAME_SOURCE,\n} from '@sentry/conventions/attributes';\nimport { HTTP_SERVER } from '@sentry/conventions/op';\nimport {\n captureException,\n continueTrace,\n getHttpSpanDetailsFromUrlObject,\n hasSpanStreamingEnabled,\n httpHeadersToSpanAttributes,\n HTTP_SPAN_NAME_FALLBACK,\n parseStringToURLObject,\n setHttpStatus,\n startSpanManual,\n winterCGHeadersToDict,\n} from '@sentry/core';\nimport { captureIncomingRequestBody } from './integrations/httpServer';\nimport { flushDeferredChannelEvents } from './orchestrion-deferred-channels';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport type { ExecutionContextCompat } from './executionContext';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { addCloudResourceContext, addCultureContext, addRequest } from './scope-utils';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\nimport { classifyResponseStreaming } from './utils/streaming';\n\nfunction getRequestErrorMechanismType(context: ExecutionContextCompat | undefined): string {\n // Durable Object fetch handlers use DO state as context (see instrumentDurableObjectWithSentry)\n return context && 'storage' in context ? 'auto.faas.cloudflare.durable_object' : 'auto.http.cloudflare';\n}\n\nexport interface RequestHandlerWrapperOptions {\n options: CloudflareOptions;\n request: Request<unknown, IncomingRequestCfProperties<unknown> | CfProperties<unknown>>;\n context: ExecutionContextCompat | undefined;\n /**\n * If true, errors will be captured, rethrown and sent to Sentry.\n * Otherwise, errors are rethrown but not captured.\n *\n * You most likely don't want to set this to `false`, if you use `wrapRequestHandler` directly.\n * This is primarily meant as an escape hatch for higher-level SDKs relying on additional error\n * capturing mechanisms where this wrapper captures errors too early or too generally.\n *\n * @default true\n */\n captureErrors?: boolean;\n}\n\ntype InitSdk = (options: CloudflareOptions) => CloudflareClient | undefined;\n\n/**\n * Same as {@link wrapRequestHandler}, but with the SDK initialization injected.\n *\n * Wrappers that are only reachable from the main entry point — where `nodejs_compat` is a\n * requirement anyway — pass `init` from `sdk.ts` to get the full default integrations.\n *\n * @internal\n */\nexport function wrapRequestHandlerWithInit(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n initSdk: InitSdk,\n): Promise<Response> {\n return withInvocationIsolationScope(async isolationScope => {\n const { options, request, captureErrors = true } = wrapperOptions;\n const context = wrapperOptions.context;\n\n // The un-instrumented waitUntil, so flushAndDispose cannot deadlock on the flush\n // lock's own wrapper. Resolved once per invocation and cached on its state; reading\n // `ctx.waitUntil` on a native context is a runtime getter call.\n const invocationState = getInvocationState();\n const waitUntil = invocationState\n ? getInvocationWaitUntil(invocationState)\n : context\n ? getOriginalWaitUntil(context).bind(context)\n : undefined;\n const errorMechanismType = getRequestErrorMechanismType(context);\n\n const client = initSdk({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n // Emit any orchestrion channel events deferred at module scope (e.g. a top-level\n // `const app = new Hono()` wrapped by build-time instrumentation): we're now in a\n // request, where workerd allows publish, and init() above has registered subscribers.\n flushDeferredChannelEvents();\n\n const urlObject = parseStringToURLObject(request.url);\n const [rawName, attributes] = getHttpSpanDetailsFromUrlObject(\n urlObject,\n 'server',\n 'auto.http.cloudflare',\n request,\n undefined,\n client,\n );\n // With span streaming, span names have to be low cardinality, so we can't fall back to the URL.\n // A `route` source means the name already is (e.g. the `/` path), so it is kept as-is.\n const name =\n attributes[SENTRY_SEGMENT_NAME_SOURCE] === 'route' || !client || !hasSpanStreamingEnabled(client)\n ? rawName\n : request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;\n\n const contentLength = request.headers.get('content-length');\n if (contentLength) {\n attributes['http.request.body.size'] = parseInt(contentLength, 10);\n }\n\n const userAgentHeader = request.headers.get('user-agent');\n if (userAgentHeader) {\n attributes['user_agent.original'] = userAgentHeader;\n }\n\n if (client) {\n Object.assign(\n attributes,\n httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers), client.getDataCollectionOptions()),\n );\n }\n\n attributes[SENTRY_OP] = HTTP_SERVER;\n\n addCloudResourceContext(isolationScope);\n addRequest(isolationScope, request);\n if (request.cf) {\n addCultureContext(isolationScope, request.cf);\n\n if (typeof request.cf.httpProtocol === 'string') {\n const [protocolName, protocolVersion] = request.cf.httpProtocol.toLowerCase().split('/');\n attributes[NETWORK_PROTOCOL_NAME] = protocolName;\n attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;\n }\n }\n\n // Do not capture spans for OPTIONS and HEAD requests\n if (request.method === 'OPTIONS' || request.method === 'HEAD') {\n try {\n return await handler();\n } catch (e) {\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n throw e;\n } finally {\n waitUntil?.(flushAndDispose(client));\n }\n }\n\n if (client) {\n await captureIncomingRequestBody(client, request);\n }\n\n return continueTrace(\n { sentryTrace: request.headers.get('sentry-trace') || '', baggage: request.headers.get('baggage') },\n () => {\n // Note: This span will not have a duration unless I/O happens in the handler. This is\n // because of how the cloudflare workers runtime works.\n // See: https://developers.cloudflare.com/workers/runtime-apis/performance/\n\n // Use startSpanManual to control when span ends (needed for streaming responses)\n return startSpanManual({ name, attributes }, async span => {\n let res: Response;\n\n try {\n res = await handler();\n setHttpStatus(span, res.status);\n\n // After the handler runs, the span name might have been updated by nested instrumentation\n // (e.g., Remix parameterizing routes). The span should already have the correct name\n // from that instrumentation, so we don't need to do anything here.\n } catch (e) {\n span.end();\n if (captureErrors) {\n captureException(e, { mechanism: { handled: false, type: errorMechanismType } });\n }\n waitUntil?.(flushAndDispose(client));\n throw e;\n }\n\n // Classify response to detect actual streaming\n const classification = classifyResponseStreaming(res);\n\n if (classification.isStreaming && res.body) {\n try {\n let ended = false;\n\n const endSpanOnce = (): void => {\n if (ended) return;\n\n ended = true;\n span.end();\n waitUntil?.(flushAndDispose(client));\n };\n\n const transform = new TransformStream({\n flush() {\n // Source stream completed normally.\n endSpanOnce();\n },\n cancel() {\n // Client disconnected (or downstream cancelled). The `cancel`\n // is being called while the response is still considered\n // active, so this is a safe place to end the span.\n endSpanOnce();\n },\n });\n\n return new Response(res.body.pipeThrough(transform), {\n status: res.status,\n statusText: res.statusText,\n headers: res.headers,\n });\n } catch {\n span.end();\n waitUntil?.(flushAndDispose(client));\n return res;\n }\n }\n\n // Non-streaming response - end span immediately and return original\n span.end();\n\n // Don't dispose for protocol upgrades (101 Switching Protocols) - the connection stays alive.\n // This includes WebSocket upgrades where webSocketMessage/webSocketClose handlers\n // will still be called and may need the client to capture errors.\n if (res.status === 101) {\n waitUntil?.(client?.flush(2000));\n } else {\n waitUntil?.(flushAndDispose(client));\n }\n return res;\n });\n },\n );\n }, wrapperOptions.context);\n}\n"],"names":["withInvocationIsolationScope","getInvocationState","getInvocationWaitUntil","getOriginalWaitUntil","flushDeferredChannelEvents","parseStringToURLObject","attributes","getHttpSpanDetailsFromUrlObject","SENTRY_SEGMENT_NAME_SOURCE","hasSpanStreamingEnabled","HTTP_SPAN_NAME_FALLBACK","httpHeadersToSpanAttributes","winterCGHeadersToDict","SENTRY_OP","HTTP_SERVER","addCloudResourceContext","addRequest","addCultureContext","NETWORK_PROTOCOL_NAME","NETWORK_PROTOCOL_VERSION","captureException","flushAndDispose","captureIncomingRequestBody","continueTrace","startSpanManual","setHttpStatus","classif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AAC,CAAA;AAAA,MACH;AAAA,KACF;AAAA,EACF,CAAA,EAAG,eAAe,OAAO,CAAA;AAC3B;;;;"}
|
package/build/esm/dev/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { SDK_VERSION, SEMANTIC_ATTRIBUTE_SENTRY_OP, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, SEMANTIC_ATTRIBUTE_SENTRY_SAMPLE_RATE, SENTRY_SEGMENT_NAME_SOURCE, Scope, addBreadcrumb, addEventProcessor, addIntegration, bindScopeToEmitter, captureCheckIn, captureConsoleIntegration, captureEvent, captureException, captureFeedback, captureMessage, close, consoleIntegration, consoleLoggingIntegration, continueTrace, createConsolaReporter, createTransport, dedupeIntegration, eventFiltersIntegration, extraErrorDataIntegration, featureFlagsIntegration, flush, functionToStringIntegration, getActiveSpan, getClient, getCurrentScope, getGlobalScope, getIsolationScope, getRootSpan, getSpanDescendants, getSpanStatusFromHttpCode, getTraceData, getTraceMetaTags, growthbookIntegration, 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, spanToStaticSpanJSON, spanToTraceHeader, startInactiveSpan, startNewTrace, startSpan, startSpanManual, supabaseIntegration, suppressTracing, updateSpanName, withActiveSpan, withIsolationScope, withMonitor, withScope, withStaticSpan, withStreamedSpan, zodErrorsIntegration } from '@sentry/core';
|
|
2
2
|
export { trpcMiddleware, wrapMcpServerWithSentry } from '@sentry/core/server';
|
|
3
|
-
export { createLangChainCallbackHandler, getOtlpTracesEndpoint, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentWorkersAiClient, openTelemetryIntegration, prismaIntegration, vercelAIIntegration } from '@sentry/server-utils';
|
|
3
|
+
export { createFlueInstrumentation, createLangChainCallbackHandler, eveConversationHook, getInstrumentedModuleNames, getOtlpTracesEndpoint, instrumentAnthropicAiClient, instrumentCreateReactAgent, instrumentGoogleGenAIClient, instrumentLangChainEmbeddings, instrumentMistralAiClient, instrumentOpenAiClient, instrumentPostgresJsSql, instrumentStateGraph, instrumentWorkersAiClient, openTelemetryIntegration, prismaIntegration, vercelAIIntegration } from '@sentry/server-utils';
|
|
4
4
|
export { withSentry } from './withSentry.js';
|
|
5
5
|
export { defineCloudflareOptions } from './defineCloudflareOptions.js';
|
|
6
6
|
export { instrumentAgentWithSentry, instrumentDurableObjectWithSentry } from './durableobject.js';
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { SENTRY_OP } from '@sentry/conventions/attributes';
|
|
2
2
|
import { DB_QUERY } from '@sentry/conventions/op';
|
|
3
3
|
import { startSpan, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN, getClient, hasSpanStreamingEnabled, addBreadcrumb, SPAN_STATUS_ERROR } from '@sentry/core';
|
|
4
|
-
import {
|
|
4
|
+
import { sanitizeSqlQuery, getSqlQuerySummary } from '@sentry/server-utils';
|
|
5
5
|
import { ensureInstrumented } from '../../instrument.js';
|
|
6
6
|
|
|
7
7
|
const patchedStatement = /* @__PURE__ */ new WeakSet();
|
|
@@ -9,40 +9,41 @@ function instrumentD1PreparedStatementQueries(statement, query) {
|
|
|
9
9
|
if (patchedStatement.has(statement)) {
|
|
10
10
|
return statement;
|
|
11
11
|
}
|
|
12
|
+
const queryText = query ? sanitizeSqlQuery(query) : void 0;
|
|
12
13
|
statement.first = new Proxy(statement.first, {
|
|
13
14
|
apply(target, thisArg, args) {
|
|
14
|
-
return startSpan(createStartSpanOptions(
|
|
15
|
+
return startSpan(createStartSpanOptions(queryText, "first"), async () => {
|
|
15
16
|
const res = await Reflect.apply(target, thisArg, args);
|
|
16
|
-
createD1Breadcrumb(
|
|
17
|
+
createD1Breadcrumb(queryText, "first");
|
|
17
18
|
return res;
|
|
18
19
|
});
|
|
19
20
|
}
|
|
20
21
|
});
|
|
21
22
|
statement.run = new Proxy(statement.run, {
|
|
22
23
|
apply(target, thisArg, args) {
|
|
23
|
-
return startSpan(createStartSpanOptions(
|
|
24
|
+
return startSpan(createStartSpanOptions(queryText, "run"), async (span) => {
|
|
24
25
|
const d1Response = await Reflect.apply(target, thisArg, args);
|
|
25
26
|
applyD1ReturnObjectToSpan(span, d1Response);
|
|
26
|
-
createD1Breadcrumb(
|
|
27
|
+
createD1Breadcrumb(queryText, "run", d1Response);
|
|
27
28
|
return d1Response;
|
|
28
29
|
});
|
|
29
30
|
}
|
|
30
31
|
});
|
|
31
32
|
statement.all = new Proxy(statement.all, {
|
|
32
33
|
apply(target, thisArg, args) {
|
|
33
|
-
return startSpan(createStartSpanOptions(
|
|
34
|
+
return startSpan(createStartSpanOptions(queryText, "all"), async (span) => {
|
|
34
35
|
const d1Result = await Reflect.apply(target, thisArg, args);
|
|
35
36
|
applyD1ReturnObjectToSpan(span, d1Result);
|
|
36
|
-
createD1Breadcrumb(
|
|
37
|
+
createD1Breadcrumb(queryText, "all", d1Result);
|
|
37
38
|
return d1Result;
|
|
38
39
|
});
|
|
39
40
|
}
|
|
40
41
|
});
|
|
41
42
|
statement.raw = new Proxy(statement.raw, {
|
|
42
43
|
apply(target, thisArg, args) {
|
|
43
|
-
return startSpan(createStartSpanOptions(
|
|
44
|
+
return startSpan(createStartSpanOptions(queryText, "raw"), async () => {
|
|
44
45
|
const res = await Reflect.apply(target, thisArg, args);
|
|
45
|
-
createD1Breadcrumb(
|
|
46
|
+
createD1Breadcrumb(queryText, "raw");
|
|
46
47
|
return res;
|
|
47
48
|
});
|
|
48
49
|
}
|
|
@@ -71,27 +72,27 @@ function getAttributesFromD1Response(d1Result) {
|
|
|
71
72
|
"cloudflare.d1.rows_written": d1Result.meta.rows_written
|
|
72
73
|
};
|
|
73
74
|
}
|
|
74
|
-
function createD1Breadcrumb(
|
|
75
|
+
function createD1Breadcrumb(message, type, d1Result) {
|
|
75
76
|
addBreadcrumb({
|
|
76
77
|
category: "query",
|
|
77
|
-
message
|
|
78
|
+
message,
|
|
78
79
|
data: {
|
|
79
80
|
...d1Result ? getAttributesFromD1Response(d1Result) : {},
|
|
80
81
|
"db.operation.name": type
|
|
81
82
|
}
|
|
82
83
|
});
|
|
83
84
|
}
|
|
84
|
-
function createStartSpanOptions(
|
|
85
|
-
const querySummary =
|
|
85
|
+
function createStartSpanOptions(queryText, type) {
|
|
86
|
+
const querySummary = queryText ? getSqlQuerySummary(queryText) : void 0;
|
|
86
87
|
const client = getClient();
|
|
87
|
-
const name = client && hasSpanStreamingEnabled(client) ? querySummary || "cloudflare-d1" :
|
|
88
|
+
const name = client && hasSpanStreamingEnabled(client) ? querySummary || "cloudflare-d1" : queryText ?? "cloudflare-d1";
|
|
88
89
|
return {
|
|
89
90
|
name,
|
|
90
91
|
attributes: {
|
|
91
92
|
[SENTRY_OP]: DB_QUERY,
|
|
92
93
|
"db.system.name": "cloudflare-d1",
|
|
93
94
|
"db.operation.name": type,
|
|
94
|
-
"db.query.text":
|
|
95
|
+
"db.query.text": queryText,
|
|
95
96
|
"db.query.summary": querySummary,
|
|
96
97
|
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.cloudflare.d1"
|
|
97
98
|
}
|
|
@@ -109,7 +110,7 @@ function instrumentBatch(batch) {
|
|
|
109
110
|
return new Proxy(batch, {
|
|
110
111
|
apply(target, thisArg, args) {
|
|
111
112
|
const statements = args[0];
|
|
112
|
-
const queryText = statements.map((statement) => statement.statement ?? "").filter(Boolean).join("\n");
|
|
113
|
+
const queryText = statements.map((statement) => statement.statement ?? "").filter(Boolean).map((statement) => sanitizeSqlQuery(statement)).join("\n");
|
|
113
114
|
return startSpan(
|
|
114
115
|
{
|
|
115
116
|
name: "D1 batch",
|
|
@@ -142,9 +143,10 @@ function _instrumentD1(db) {
|
|
|
142
143
|
db.exec = new Proxy(db.exec, {
|
|
143
144
|
apply(target, thisArg, args) {
|
|
144
145
|
const [query] = args;
|
|
145
|
-
|
|
146
|
+
const queryText = query ? sanitizeSqlQuery(query) : void 0;
|
|
147
|
+
return startSpan(createStartSpanOptions(queryText, "exec"), async () => {
|
|
146
148
|
const res = await Reflect.apply(target, thisArg, args);
|
|
147
|
-
createD1Breadcrumb(
|
|
149
|
+
createD1Breadcrumb(queryText, "exec");
|
|
148
150
|
return res;
|
|
149
151
|
});
|
|
150
152
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentD1.js","sources":["../../../../../src/instrumentations/worker/instrumentD1.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { D1Database, D1DatabaseSession, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/core';\nimport {\n addBreadcrumb,\n getClient,\n hasSpanStreamingEnabled,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startSpan,\n} from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport { ensureInstrumented } from '../../instrument';\n\n// Patching is based on internal Cloudflare D1 API\n// https://github.com/cloudflare/workerd/blob/cd5279e7b305003f1d9c851e73efa9d67e4b68b2/src/cloudflare/internal/d1-api.ts\n\nconst patchedStatement = new WeakSet<D1PreparedStatement>();\n\n/**\n * Patches the query methods of a Cloudflare D1 prepared statement with Sentry.\n */\nfunction instrumentD1PreparedStatementQueries(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n if (patchedStatement.has(statement)) {\n return statement;\n }\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.first = new Proxy(statement.first, {\n apply(target, thisArg, args: Parameters<typeof statement.first>) {\n return startSpan(createStartSpanOptions(query, 'first'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'first');\n return res;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.run = new Proxy(statement.run, {\n apply(target, thisArg, args: Parameters<typeof statement.run>) {\n return startSpan(createStartSpanOptions(query, 'run'), async span => {\n const d1Response = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Response);\n createD1Breadcrumb(query, 'run', d1Response);\n return d1Response;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.all = new Proxy(statement.all, {\n apply(target, thisArg, args: Parameters<typeof statement.all>) {\n return startSpan(createStartSpanOptions(query, 'all'), async span => {\n const d1Result = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Result);\n createD1Breadcrumb(query, 'all', d1Result);\n return d1Result;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.raw = new Proxy(statement.raw, {\n apply(target, thisArg, args: Parameters<typeof statement.raw>) {\n return startSpan(createStartSpanOptions(query, 'raw'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'raw');\n return res;\n });\n },\n });\n\n patchedStatement.add(statement);\n\n return statement;\n}\n\n/**\n * Instruments a Cloudflare D1 prepared statement with Sentry.\n *\n * This is meant to be used as a top-level call, under the hood it calls `instrumentD1PreparedStatementQueries`\n * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched.\n */\nfunction instrumentD1PreparedStatement(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.bind = new Proxy(statement.bind, {\n apply(target, thisArg, args: Parameters<typeof statement.bind>) {\n return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return instrumentD1PreparedStatementQueries(statement, query);\n}\n\n/**\n * Add D1Response meta information to a span.\n *\n * See: https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object\n */\nfunction applyD1ReturnObjectToSpan(span: Span, d1Result: D1Response): void {\n if (!d1Result.success) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n\n span.setAttributes(getAttributesFromD1Response(d1Result));\n}\n\nfunction getAttributesFromD1Response(d1Result: D1Response): SpanAttributes {\n return {\n 'cloudflare.d1.duration': d1Result.meta.duration,\n 'cloudflare.d1.rows_read': d1Result.meta.rows_read,\n 'cloudflare.d1.rows_written': d1Result.meta.rows_written,\n };\n}\n\ntype D1QueryType = 'first' | 'run' | 'all' | 'raw' | 'batch' | 'exec';\n\nfunction createD1Breadcrumb(query: string, type: D1QueryType, d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message: query,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'db.operation.name': type,\n },\n });\n}\n\nfunction createStartSpanOptions(query: string, type: D1QueryType): StartSpanOptions {\n const querySummary = query ? getSqlQuerySummary(sanitizeSqlQuery(query)) : undefined;\n\n const client = getClient();\n const name = client && hasSpanStreamingEnabled(client) ? querySummary || 'cloudflare-d1' : query;\n\n return {\n name,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': type,\n 'db.query.text': query,\n 'db.query.summary': querySummary,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\nfunction instrumentPrepare(\n prepare: D1Database['prepare'] | D1DatabaseSession['prepare'],\n): D1Database['prepare'] | D1DatabaseSession['prepare'] {\n return new Proxy(prepare, {\n apply(target, thisArg, args: Parameters<typeof prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n}\n\nfunction instrumentBatch(\n batch: D1Database['batch'] | D1DatabaseSession['batch'],\n): D1Database['batch'] | D1DatabaseSession['batch'] {\n return new Proxy(batch, {\n apply(target, thisArg, args: Parameters<typeof batch>) {\n const statements = args[0];\n // D1PreparedStatement exposes a `statement` property at runtime, but it's not in @cloudflare/workers-types.\n // https://github.com/cloudflare/workerd/blob/dc12d7650b4f5d4f9ba6a47aa45fad769cdf8db4/src/cloudflare/internal/d1-api.ts#L210\n const queryText = statements\n .map(statement => (statement as unknown as { statement?: string }).statement ?? '')\n .filter(Boolean)\n .join('\\n');\n\n return startSpan(\n {\n name: 'D1 batch',\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': 'batch',\n 'db.query.text': queryText || undefined,\n 'db.operation.batch.size': statements.length,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n },\n async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb('D1 batch', 'batch');\n return res;\n },\n );\n },\n });\n}\n\nfunction instrumentD1Session(session: D1DatabaseSession): D1DatabaseSession {\n session.prepare = instrumentPrepare(session.prepare);\n session.batch = instrumentBatch(session.batch);\n return session;\n}\n\nfunction _instrumentD1(db: D1Database): D1Database {\n db.prepare = instrumentPrepare(db.prepare);\n db.batch = instrumentBatch(db.batch);\n\n db.exec = new Proxy(db.exec, {\n apply(target, thisArg, args: Parameters<typeof db.exec>) {\n const [query] = args;\n return startSpan(createStartSpanOptions(query, 'exec'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(query, 'exec');\n return res;\n });\n },\n });\n\n if ('withSession' in db && typeof db.withSession === 'function') {\n db.withSession = new Proxy(db.withSession, {\n apply(target, thisArg, args: [unknown]) {\n return instrumentD1Session(Reflect.apply(target, thisArg, args) as D1DatabaseSession);\n },\n });\n }\n\n return db;\n}\n\nexport function instrumentD1(db: D1Database): D1Database {\n return ensureInstrumented(db, _instrumentD1);\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,gBA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ACtF;AAAA,KACD,CAAA;AAAA,EACH;AAEA,EAAA,OAAO,EAAA;AACT;AAEO,SAAS,aAAa,EAAA,EAA4B;AACvD,EAAA,OAAO,kBAAA,CAAmB,IAAI,aAAa,CAAA;AAC7C;;;;"}
|
|
1
|
+
{"version":3,"file":"instrumentD1.js","sources":["../../../../../src/instrumentations/worker/instrumentD1.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/unbound-method */\nimport type { D1Database, D1DatabaseSession, D1PreparedStatement, D1Response } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport type { Span, SpanAttributes, StartSpanOptions } from '@sentry/core';\nimport {\n addBreadcrumb,\n getClient,\n hasSpanStreamingEnabled,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n SPAN_STATUS_ERROR,\n startSpan,\n} from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport { ensureInstrumented } from '../../instrument';\n\n// Patching is based on internal Cloudflare D1 API\n// https://github.com/cloudflare/workerd/blob/cd5279e7b305003f1d9c851e73efa9d67e4b68b2/src/cloudflare/internal/d1-api.ts\n\nconst patchedStatement = new WeakSet<D1PreparedStatement>();\n\n/**\n * Patches the query methods of a Cloudflare D1 prepared statement with Sentry.\n */\nfunction instrumentD1PreparedStatementQueries(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n if (patchedStatement.has(statement)) {\n return statement;\n }\n\n const queryText = query ? sanitizeSqlQuery(query) : undefined;\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.first = new Proxy(statement.first, {\n apply(target, thisArg, args: Parameters<typeof statement.first>) {\n return startSpan(createStartSpanOptions(queryText, 'first'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(queryText, 'first');\n return res;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.run = new Proxy(statement.run, {\n apply(target, thisArg, args: Parameters<typeof statement.run>) {\n return startSpan(createStartSpanOptions(queryText, 'run'), async span => {\n const d1Response = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Response);\n createD1Breadcrumb(queryText, 'run', d1Response);\n return d1Response;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.all = new Proxy(statement.all, {\n apply(target, thisArg, args: Parameters<typeof statement.all>) {\n return startSpan(createStartSpanOptions(queryText, 'all'), async span => {\n const d1Result = await Reflect.apply(target, thisArg, args);\n applyD1ReturnObjectToSpan(span, d1Result);\n createD1Breadcrumb(queryText, 'all', d1Result);\n return d1Result;\n });\n },\n });\n\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.raw = new Proxy(statement.raw, {\n apply(target, thisArg, args: Parameters<typeof statement.raw>) {\n return startSpan(createStartSpanOptions(queryText, 'raw'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(queryText, 'raw');\n return res;\n });\n },\n });\n\n patchedStatement.add(statement);\n\n return statement;\n}\n\n/**\n * Instruments a Cloudflare D1 prepared statement with Sentry.\n *\n * This is meant to be used as a top-level call, under the hood it calls `instrumentD1PreparedStatementQueries`\n * to patch the query methods. The reason for this abstraction is to ensure that the `bind` method is also patched.\n */\nfunction instrumentD1PreparedStatement(statement: D1PreparedStatement, query: string): D1PreparedStatement {\n // statement.bind() returns a new instance of D1PreparedStatement, so we have to patch it as well.\n // eslint-disable-next-line @typescript-eslint/unbound-method\n statement.bind = new Proxy(statement.bind, {\n apply(target, thisArg, args: Parameters<typeof statement.bind>) {\n return instrumentD1PreparedStatementQueries(Reflect.apply(target, thisArg, args), query);\n },\n });\n\n return instrumentD1PreparedStatementQueries(statement, query);\n}\n\n/**\n * Add D1Response meta information to a span.\n *\n * See: https://developers.cloudflare.com/d1/build-with-d1/d1-client-api/#return-object\n */\nfunction applyD1ReturnObjectToSpan(span: Span, d1Result: D1Response): void {\n if (!d1Result.success) {\n span.setStatus({ code: SPAN_STATUS_ERROR });\n }\n\n span.setAttributes(getAttributesFromD1Response(d1Result));\n}\n\nfunction getAttributesFromD1Response(d1Result: D1Response): SpanAttributes {\n return {\n 'cloudflare.d1.duration': d1Result.meta.duration,\n 'cloudflare.d1.rows_read': d1Result.meta.rows_read,\n 'cloudflare.d1.rows_written': d1Result.meta.rows_written,\n };\n}\n\ntype D1QueryType = 'first' | 'run' | 'all' | 'raw' | 'batch' | 'exec';\n\n/** The message is the span's query text (already sanitized) or a static label such as `D1 batch`. */\nfunction createD1Breadcrumb(message: string | undefined, type: D1QueryType, d1Result?: D1Response): void {\n addBreadcrumb({\n category: 'query',\n message,\n data: {\n ...(d1Result ? getAttributesFromD1Response(d1Result) : {}),\n 'db.operation.name': type,\n },\n });\n}\n\nfunction createStartSpanOptions(queryText: string | undefined, type: D1QueryType): StartSpanOptions {\n const querySummary = queryText ? getSqlQuerySummary(queryText) : undefined;\n\n const client = getClient();\n const name =\n client && hasSpanStreamingEnabled(client) ? querySummary || 'cloudflare-d1' : (queryText ?? 'cloudflare-d1');\n\n return {\n name,\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': type,\n 'db.query.text': queryText,\n 'db.query.summary': querySummary,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n };\n}\n\nfunction instrumentPrepare(\n prepare: D1Database['prepare'] | D1DatabaseSession['prepare'],\n): D1Database['prepare'] | D1DatabaseSession['prepare'] {\n return new Proxy(prepare, {\n apply(target, thisArg, args: Parameters<typeof prepare>) {\n const [query] = args;\n return instrumentD1PreparedStatement(Reflect.apply(target, thisArg, args), query);\n },\n });\n}\n\nfunction instrumentBatch(\n batch: D1Database['batch'] | D1DatabaseSession['batch'],\n): D1Database['batch'] | D1DatabaseSession['batch'] {\n return new Proxy(batch, {\n apply(target, thisArg, args: Parameters<typeof batch>) {\n const statements = args[0];\n // D1PreparedStatement exposes a `statement` property at runtime, but it's not in @cloudflare/workers-types.\n // https://github.com/cloudflare/workerd/blob/dc12d7650b4f5d4f9ba6a47aa45fad769cdf8db4/src/cloudflare/internal/d1-api.ts#L210\n const queryText = statements\n .map(statement => (statement as unknown as { statement?: string }).statement ?? '')\n .filter(Boolean)\n .map(statement => sanitizeSqlQuery(statement))\n .join('\\n');\n\n return startSpan(\n {\n name: 'D1 batch',\n attributes: {\n [SENTRY_OP]: DB_QUERY,\n 'db.system.name': 'cloudflare-d1',\n 'db.operation.name': 'batch',\n 'db.query.text': queryText || undefined,\n 'db.operation.batch.size': statements.length,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.d1',\n },\n },\n async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb('D1 batch', 'batch');\n return res;\n },\n );\n },\n });\n}\n\nfunction instrumentD1Session(session: D1DatabaseSession): D1DatabaseSession {\n session.prepare = instrumentPrepare(session.prepare);\n session.batch = instrumentBatch(session.batch);\n return session;\n}\n\nfunction _instrumentD1(db: D1Database): D1Database {\n db.prepare = instrumentPrepare(db.prepare);\n db.batch = instrumentBatch(db.batch);\n\n db.exec = new Proxy(db.exec, {\n apply(target, thisArg, args: Parameters<typeof db.exec>) {\n const [query] = args;\n const queryText = query ? sanitizeSqlQuery(query) : undefined;\n return startSpan(createStartSpanOptions(queryText, 'exec'), async () => {\n const res = await Reflect.apply(target, thisArg, args);\n createD1Breadcrumb(queryText, 'exec');\n return res;\n });\n },\n });\n\n if ('withSession' in db && typeof db.withSession === 'function') {\n db.withSession = new Proxy(db.withSession, {\n apply(target, thisArg, args: [unknown]) {\n return instrumentD1Session(Reflect.apply(target, thisArg, args) as D1DatabaseSession);\n },\n });\n }\n\n return db;\n}\n\nexport function instrumentD1(db: D1Database): D1Database {\n return ensureInstrumented(db, _instrumentD1);\n}\n"],"names":[],"mappings":";;;;;;AAmBA,MAAM,gBAAA,uBAAuB,OAAA,EAA6B;AAK1D,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