@sentry/cloudflare 11.2.0 → 11.4.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/durableobject.js +4 -1
- package/build/cjs/dev/durableobject.js.map +1 -1
- package/build/cjs/dev/instrumentations/instrumentSqlStorage.js +20 -6
- package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/dev/utils/internalSqlQuery.js +5 -0
- package/build/cjs/dev/utils/internalSqlQuery.js.map +1 -1
- package/build/cjs/dev/utils/invocationScope.js +12 -1
- package/build/cjs/dev/utils/invocationScope.js.map +1 -1
- package/build/cjs/dev/utils/traceLinks.js +2 -1
- package/build/cjs/dev/utils/traceLinks.js.map +1 -1
- package/build/cjs/prod/durableobject.js +4 -1
- package/build/cjs/prod/durableobject.js.map +1 -1
- package/build/cjs/prod/instrumentations/instrumentSqlStorage.js +20 -6
- package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/prod/utils/internalSqlQuery.js +5 -0
- package/build/cjs/prod/utils/internalSqlQuery.js.map +1 -1
- package/build/cjs/prod/utils/invocationScope.js +12 -1
- package/build/cjs/prod/utils/invocationScope.js.map +1 -1
- package/build/cjs/prod/utils/traceLinks.js +2 -1
- package/build/cjs/prod/utils/traceLinks.js.map +1 -1
- package/build/esm/dev/durableobject.js +4 -1
- package/build/esm/dev/durableobject.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentSqlStorage.js +22 -8
- package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/utils/internalSqlQuery.js +5 -1
- package/build/esm/dev/utils/internalSqlQuery.js.map +1 -1
- package/build/esm/dev/utils/invocationScope.js +12 -2
- package/build/esm/dev/utils/invocationScope.js.map +1 -1
- package/build/esm/dev/utils/traceLinks.js +3 -2
- package/build/esm/dev/utils/traceLinks.js.map +1 -1
- package/build/esm/prod/durableobject.js +4 -1
- package/build/esm/prod/durableobject.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentSqlStorage.js +22 -8
- package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/utils/internalSqlQuery.js +5 -1
- package/build/esm/prod/utils/internalSqlQuery.js.map +1 -1
- package/build/esm/prod/utils/invocationScope.js +12 -2
- package/build/esm/prod/utils/invocationScope.js.map +1 -1
- package/build/esm/prod/utils/traceLinks.js +3 -2
- package/build/esm/prod/utils/traceLinks.js.map +1 -1
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/instrumentations/instrumentSqlStorage.d.ts.map +1 -1
- package/build/types/utils/internalSqlQuery.d.ts +5 -0
- package/build/types/utils/internalSqlQuery.d.ts.map +1 -1
- package/build/types/utils/invocationScope.d.ts +13 -3
- package/build/types/utils/invocationScope.d.ts.map +1 -1
- package/build/types/utils/traceLinks.d.ts.map +1 -1
- package/package.json +5 -5
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durableobject.js","sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategy();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods ? undefined : resolvePrototypeMethods(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = Reflect.construct(target, [context, instrumentedEnv], newTarget) as T;\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made while an\n // invocation is already in flight comes from the instance itself (`this.helper()` inside\n // `fetch`, `alarm` or another RPC method). Check that before touching per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;AA0CO,SAAS,kCAAA,CACd,MAAA,EACA,GAAA,EACA,GAAA,EACA,WACA,eAAA,EAMA;AACA,EAAA,wCAAA,EAAyC;AACzC,EAAA,MAAM,OAAA,G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CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;AAyCO,SAAS,yBAAA,CAOd,iBAA0E,UAAA,EAAkB;AAC5F,EAAA,MAAM,iBAAA,GAAoB,IAAI,KAAA,CAAM,UAAA,EAAY;AAAA,IAC9C,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAS,yBAAwB,GAAI,kCAAA;AAAA,QACzD,MAAA;AAAA,QACA,GAAA;AAAA,QACA,GAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,yBAAA,CAA0B,GAAG,CAAA;AAM7B,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAA,EAAS,uBAAuB,CAAA;AAAA,IACtF;AAAA,GACD,CAAA;AACD,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"durableobject.js","sources":["../../../src/durableobject.ts"],"sourcesContent":["/* eslint-disable max-lines */\n/* eslint-disable @typescript-eslint/unbound-method */\nimport { RPC } from '@sentry/conventions/op';\nimport { getDefaultIsolationScope, getIsolationScope, isObjectLike, startNewTrace } from '@sentry/core';\nimport type { DurableObject } from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategy } from '@sentry/server-utils/no-diagnostic-channels';\nimport type { CloudflareOptions } from './client';\nimport { getInstrumented, markAsInstrumented } from './instrument';\nimport { instrumentDurableObjectHandlers } from './instrumentations/instrumentDurableObjectHandlers';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { getFinalOptions } from './options';\nimport { instrumentContext } from './utils/instrumentContext';\nimport { withConstructionIsolationScope } from './utils/invocationScope';\nimport { hasRpcMeta } from './utils/rpcMeta';\nimport { instrumentCloudflareAgent } from './instrumentations/agents';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { type UncheckedMethod, wrapMethodWithSentry } from './wrapMethodWithSentry';\n\n/**\n * The instrumented context passed between the shared construction helpers.\n *\n * This is intentionally `any` rather than `ReturnType<typeof instrumentContext<DurableObjectState>>`.\n * A concrete `DurableObjectState` here forces `tsc` to structurally relate its `storage: SqlStorage`\n * graph against the `ExecutionContext | InstrumentedDurableObjectState` parameter of\n * `wrapMethodWithSentry`, while the RPC-branded `DurableObject` from `cloudflare:workers` is also in\n * scope. That union comparison explodes (1296×1296) and hangs the type build. The original inline\n * implementation avoided this only incidentally, because `ctx` reached it as `any` through the Proxy\n * `construct` trap. Keeping the shared context `any` preserves that behavior.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\ntype InstrumentedDurableObjectContext = any;\n\n/**\n * Constructs a Durable Object instance and instruments its built-in handler methods\n * (`fetch`, `alarm`, `webSocketMessage`, `webSocketClose`, `webSocketError`).\n *\n * This is the shared construction path used by both {@link instrumentDurableObjectWithSentry}\n * and {@link instrumentAgentWithSentry}. It intentionally does NOT apply the RPC prototype-method\n * instrumentation — callers apply that last via {@link finalizeWithRpcInstrumentation}, after any\n * additional per-instance instrumentation has been layered onto the returned object.\n *\n * @internal\n */\nexport function constructInstrumentedDurableObject<E, T extends DurableObject<E>>(\n target: new (state: DurableObjectState, env: E) => T,\n ctx: DurableObjectState,\n env: E,\n newTarget: NewableFunction,\n optionsCallback: (env: E) => CloudflareOptions,\n): {\n obj: T;\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n frameworkManagedMethods: ReadonlySet<string>;\n} {\n setAsyncLocalStorageAsyncContextStrategy();\n const options = getFinalOptions(optionsCallback(env), env);\n // See InstrumentedDurableObjectContext — `ctx` is widened to `any` so the concrete\n // `DurableObjectState` type never enters the checker's relation graph in this module.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const context = instrumentContext(ctx as any);\n const instrumentedEnv = instrumentEnv(env as Record<string, unknown>, options);\n\n const prototype = (newTarget as unknown as { prototype?: object }).prototype ?? target.prototype;\n const cachedFrameworkManagedMethods = frameworkManagedMethodsCache.get(prototype);\n const methodsBeforeConstruction = cachedFrameworkManagedMethods ? undefined : resolvePrototypeMethods(prototype);\n\n // Pass `newTarget` so that subclasses of the instrumented class (e.g. the wrapper classes\n // created by wrangler's local dev tooling or `@cloudflare/vitest-pool-workers`) keep their\n // own prototype — otherwise subclass methods disappear and `instanceof` checks break.\n const obj = withConstructionIsolationScope(\n () => Reflect.construct(target, [context, instrumentedEnv], newTarget) as T,\n );\n\n const frameworkManagedMethods = resolveFrameworkManagedMethods(\n prototype,\n obj,\n methodsBeforeConstruction,\n cachedFrameworkManagedMethods,\n );\n\n instrumentDurableObjectHandlers(obj, options, context);\n\n return { obj, options, context, frameworkManagedMethods };\n}\n\nconst frameworkManagedMethodsCache = new WeakMap<object, ReadonlySet<string>>();\n\n/**\n * Collects the methods visible from a prototype, using normal property lookup precedence.\n * Methods inherited from `Object.prototype` are excluded because they cannot be Durable Object RPC methods.\n */\nfunction resolvePrototypeMethods(prototype: object | null): Map<string, unknown> {\n const methods = new Map<string, unknown>();\n\n for (let current = prototype; current && current !== Object.prototype; current = Object.getPrototypeOf(current)) {\n for (const name of Object.getOwnPropertyNames(current)) {\n // The first occurrence wins, mirroring what a property lookup on the instance would find\n if (name === 'constructor' || methods.has(name)) {\n continue;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(current, name);\n\n if (descriptor && typeof descriptor.value === 'function') {\n methods.set(name, descriptor.value);\n }\n }\n }\n\n return methods;\n}\n\n/**\n * Finds methods that a framework replaced while constructing the first instance.\n *\n * Some frameworks register methods by function identity, so replacing one of their wrappers would\n * break dispatch. The result is cached because frameworks commonly install their wrappers only\n * once; later constructions would no longer reveal which methods they manage.\n */\nfunction resolveFrameworkManagedMethods(\n prototype: object,\n obj: object,\n methodsBeforeConstruction: Map<string, unknown> | undefined,\n cached: ReadonlySet<string> | undefined,\n): ReadonlySet<string> {\n if (cached) {\n return cached;\n }\n\n const methodsAfterConstruction = resolvePrototypeMethods(Object.getPrototypeOf(obj) as object);\n const managed = new Set<string>();\n\n for (const [name, method] of methodsAfterConstruction) {\n const before = methodsBeforeConstruction?.get(name);\n\n if (before && before !== method) {\n managed.add(name);\n }\n }\n\n frameworkManagedMethodsCache.set(prototype, managed);\n\n return managed;\n}\n\ntype RpcInstanceState = {\n options: CloudflareOptions;\n context: InstrumentedDurableObjectContext;\n /** Per-instance cache of the instrumented method wrappers, keyed by method name. Created on first use. */\n instrumentedMethods?: Map<string, UncheckedMethod>;\n};\n\n/**\n * Method names the runtime never dispatches over RPC, so wrapping them buys no tracing.\n *\n * Mirrors `isReservedName` in workerd (`src/workerd/api/worker-rpc.c++`): the runtime rejects these\n * before any property lookup happens. `fetch`, `alarm` and the `webSocket*` handlers are also\n * instrumented per-instance as own properties, and `constructor` is on every prototype.\n */\nconst RESERVED_RPC_METHOD_NAMES: ReadonlySet<string> = new Set([\n 'constructor',\n 'fetch',\n 'connect',\n 'alarm',\n 'webSocketMessage',\n 'webSocketClose',\n 'webSocketError',\n 'dup',\n]);\n\n// Prototype wrappers are shared by all instances, while SDK options and traced method caches are not.\nconst rpcInstanceStates = new WeakMap<object, RpcInstanceState>();\n\n/**\n * Instruments a constructed Durable Object's RPC methods.\n *\n * RPC methods are wrapped on the prototype because Cloudflare dispatches them with the Durable\n * Object instance as the receiver. This preserves native private-field access and keeps the methods\n * visible to Cloudflare's RPC dispatcher. Built-in handlers, Agent handlers, and methods managed by\n * another framework are left untouched.\n *\n * Call this after all per-instance instrumentation has been applied.\n *\n * @param obj The constructed Durable Object instance.\n * @param options The resolved SDK options for this instance.\n * @param context The instrumented execution context for this instance.\n * @param excludedMethods Method names owned by another framework and therefore not safe to wrap.\n * @returns The same Durable Object instance, with eligible prototype methods instrumented.\n * @internal\n */\nexport function finalizeWithRpcInstrumentation<T extends object>(\n obj: T,\n options: CloudflareOptions,\n context: InstrumentedDurableObjectContext,\n excludedMethods?: ReadonlySet<string>,\n): T {\n rpcInstanceStates.set(obj, { options, context });\n\n instrumentPrototypeRpcMethods(obj, excludedMethods);\n\n return obj;\n}\n\n/**\n * Returns a prototype method when it is eligible for RPC instrumentation.\n */\nfunction getRpcMethodDescriptor(\n obj: object,\n prototype: object,\n methodName: string,\n excludedMethods?: ReadonlySet<string>,\n): PropertyDescriptor | undefined {\n if (\n RESERVED_RPC_METHOD_NAMES.has(methodName) ||\n Object.prototype.hasOwnProperty.call(obj, methodName) ||\n excludedMethods?.has(methodName)\n ) {\n return undefined;\n }\n\n const descriptor = Object.getOwnPropertyDescriptor(prototype, methodName);\n\n if (!descriptor || typeof descriptor.value !== 'function' || getInstrumented(descriptor.value)) {\n return undefined;\n }\n\n return descriptor;\n}\n\n/**\n * Wraps eligible methods on the instance's prototype chain once per class.\n */\nfunction instrumentPrototypeRpcMethods(obj: object, excludedMethods?: ReadonlySet<string>): void {\n let prototype: object | null = Object.getPrototypeOf(obj);\n\n while (prototype && prototype !== Object.prototype) {\n for (const methodName of Object.getOwnPropertyNames(prototype)) {\n const descriptor = getRpcMethodDescriptor(obj, prototype, methodName, excludedMethods);\n\n if (!descriptor) {\n continue;\n }\n\n const wrapped = createRpcPrototypeWrapper(methodName, descriptor.value as UncheckedMethod);\n\n try {\n Object.defineProperty(prototype, methodName, { ...descriptor, value: wrapped });\n } catch {}\n\n // Only the wrapper is marked, not the original method: `wrapMethodWithSentry` resolves\n // through the same global map and must not resolve the original to this wrapper,\n // which would recurse.\n markAsInstrumented(wrapped);\n }\n\n prototype = Object.getPrototypeOf(prototype);\n }\n}\n\n/**\n * Returns the instance's instrumented wrapper for an RPC method, creating it on first use.\n */\nfunction getInstrumentedRpcMethod(\n state: RpcInstanceState,\n methodName: string,\n originalMethod: UncheckedMethod,\n): UncheckedMethod {\n const instrumentedMethods = (state.instrumentedMethods ??= new Map());\n let instrumented = instrumentedMethods.get(methodName);\n\n if (!instrumented) {\n instrumented = wrapMethodWithSentry(\n {\n options: state.options,\n context: state.context,\n spanName: rpcMeta => (rpcMeta ? methodName : undefined),\n spanOp: RPC,\n origin: 'auto.faas.cloudflare.durable_object',\n },\n originalMethod,\n undefined,\n true,\n );\n instrumentedMethods.set(methodName, instrumented);\n }\n\n return instrumented;\n}\n\n/**\n * Creates a prototype wrapper that instruments external RPC calls.\n *\n * The wrapper looks up SDK state from its receiver, allowing one prototype function to serve every\n * instance. A call carrying Sentry metadata continues that trace in an `rpc` span. A call without it\n * still gets a client, so its errors, logs and metrics are captured, but no span. Calls the instance\n * makes to its own methods run the original method directly. The original function name and arity\n * are preserved because frameworks may inspect them for dispatch.\n */\nfunction createRpcPrototypeWrapper(methodName: string, originalMethod: UncheckedMethod): UncheckedMethod {\n const wrapper = function (this: unknown, ...args: unknown[]): unknown {\n const traced = hasRpcMeta(args);\n\n // workerd dispatches an incoming RPC call outside any async context, so a call made on any other\n // isolation scope comes from the instance itself (`this.helper()` inside `fetch`, `alarm`,\n // another RPC method or async work the constructor started). Check that before touching\n // per-instance state.\n if (!traced && getIsolationScope() !== getDefaultIsolationScope()) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const state = isObjectLike(this) ? rpcInstanceStates.get(this) : undefined;\n\n if (!state) {\n return Reflect.apply(originalMethod, this, args);\n }\n\n const instrumented = getInstrumentedRpcMethod(state, methodName, originalMethod);\n\n if (traced) {\n return Reflect.apply(instrumented, this, args);\n }\n\n // Unlike a WorkerEntrypoint, a Durable Object instance is long-lived and serves overlapping\n // calls. Without a new trace, every untraced call would share the trace of the default scope.\n return startNewTrace(() => Reflect.apply(instrumented, this, args));\n };\n\n Object.defineProperties(wrapper, {\n name: { value: originalMethod.name, configurable: true },\n length: { value: originalMethod.length, configurable: true },\n });\n\n return wrapper as UncheckedMethod;\n}\n\n/**\n * Instruments a Durable Object class to capture errors and performance data.\n *\n * Instruments the following methods by default:\n * - fetch\n * - alarm\n * - webSocketMessage\n * - webSocketClose\n * - webSocketError\n *\n * RPC methods (prototype methods) are instrumented too: an incoming trace continues into them, and\n * errors, logs and metrics are captured whether or not the caller propagates a trace.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param DurableObjectClass The Durable Object class to instrument.\n * @returns The instrumented Durable Object class.\n *\n * @example\n * ```ts\n * class MyDurableObjectBase extends DurableObject {\n * constructor(ctx: DurableObjectState, env: Env) {\n * super(ctx, env);\n * }\n * }\n *\n * export const MyDurableObject = instrumentDurableObjectWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyDurableObjectBase,\n * );\n * ```\n */\nexport function instrumentDurableObjectWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, DurableObjectClass: C): C {\n const InstrumentedClass = new Proxy(DurableObjectClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n\n/**\n * Instruments a Cloudflare [`agents`](https://www.npmjs.com/package/agents) Agent class with Sentry.\n *\n * An `Agent` is a Durable Object under the hood, so this applies the same instrumentation as\n * {@link instrumentDurableObjectWithSentry} (request transactions, `alarm`, WebSocket handlers, RPC\n * trace propagation, SQL spans) and additionally captures Agent-specific telemetry via\n * `instrumentCloudflareAgent`:\n *\n * - **Callable RPC spans** — a span (op `rpc`) for each `@callable()` method invoked over WebSocket.\n * - **Breadcrumbs** — for every Agent observability event (`rpc`, `state:update`, `connect`,\n * `disconnect`, `schedule:*`, `queue:*`, `workflow:*`, `email:*`, `mcp:*`, ...).\n *\n * Cloudflare Workers cannot auto-instrument, so the Agent class must be wrapped manually.\n *\n * @param optionsCallback Function that returns the options for the SDK initialization.\n * @param AgentClass The Agent class to instrument.\n * @returns The instrumented Agent class.\n *\n * @example\n * ```ts\n * import { Agent, callable, routeAgentRequest } from 'agents';\n * import * as Sentry from '@sentry/cloudflare';\n *\n * class MyAgentBase extends Agent<Env> {\n * @callable()\n * async greet(name: string): Promise<string> {\n * return `Hello, ${name}!`;\n * }\n * }\n *\n * export const MyAgent = Sentry.instrumentAgentWithSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * tracesSampleRate: 1.0,\n * }),\n * MyAgentBase,\n * );\n * ```\n */\nexport function instrumentAgentWithSentry<\n Env = DefaultEnv,\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends DurableObject<any> = DurableObject<Env>,\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (state: DurableObjectState, env: any) => T = new (state: DurableObjectState, env: any) => T,\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, Env>) => StrictCloudflareOptions<O>, AgentClass: C): C {\n const InstrumentedClass = new Proxy(AgentClass, {\n construct(target, [ctx, env], newTarget) {\n const { obj, options, context, frameworkManagedMethods } = constructInstrumentedDurableObject(\n target,\n ctx,\n env,\n newTarget,\n optionsCallback,\n );\n\n instrumentCloudflareAgent(obj);\n\n // Apply RPC prototype-method instrumentation last, so the Agent-specific own-property\n // handlers we just installed are excluded from RPC method tracing. Methods the Agent\n // framework installed itself are excluded too — `instrumentCloudflareAgent` traces those by\n // wrapping the dispatch instead of the method.\n return finalizeWithRpcInstrumentation(obj, options, context, frameworkManagedMethods);\n },\n });\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AA2CO,SAAS,kCAAA,CACd,MAAA,EACA,GAAA,EACA,GAAA,EACA,WACA,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EAAK,OAAA,EAAS,OAAA,EAAS,uBAAuB,CAAA;AAAA,IACtF;AAAA,GACD,CAAA;AAED,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;AAyCO,SAAS,yBAAA,CAOd,iBAA0E,UAAA,EAAkB;AAC5F,EAAA,MAAM,iBAAA,GAAoB,IAAI,KAAA,CAAM,UAAA,EAAY;AAAA,IAC9C,UAAU,MAAA,EAAQ,CAAC,GAAA,EAAK,GAAG,GAAG,SAAA,EAAW;AACvC,MAAA,MAAM,EAAE,GAAA,EAAK,OAAA,EAAS,OAAA,EAAS,yBAAwB,GAAI,kCAAA;AAAA,QACzD,MAAA;AAAA,QACA,GAAA;AAAA,QACA,GAAA;AAAA,QACA,SAAA;AAAA,QACA;AAAA,OACF;AAEA,MAAA,yBAAA,CAA0B,GAAG,CAAA;AAM7B,MAAA,OAAO,8BAAA,CAA+B,GAAA,EAAK,OAAA,EAAS,OAAA,EAAS,uBAAuB,CAAA;AAAA,IACtF;AAAA,GACD,CAAA;AACD,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
|
|
@@ -1,9 +1,15 @@
|
|
|
1
1
|
import { SENTRY_OP } from '@sentry/conventions/attributes';
|
|
2
2
|
import { DB_QUERY } from '@sentry/conventions/op';
|
|
3
|
-
import { getClient,
|
|
3
|
+
import { startSpan, getClient, hasSpansEnabled, getActiveSpan, spanIsSampled, SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN } from '@sentry/core';
|
|
4
4
|
import { sanitizeSqlQuery, getSqlQuerySummary } from '@sentry/server-utils';
|
|
5
|
-
import { targetsCloudflareInternalTable } from '../utils/internalSqlQuery.js';
|
|
5
|
+
import { mayTargetCloudflareInternalTable, targetsCloudflareInternalTable } from '../utils/internalSqlQuery.js';
|
|
6
6
|
|
|
7
|
+
const SPAN_ATTRIBUTES = {
|
|
8
|
+
[SENTRY_OP]: DB_QUERY,
|
|
9
|
+
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.cloudflare.durable_object.sql",
|
|
10
|
+
"db.system.name": "cloudflare-durable-object-sql",
|
|
11
|
+
"db.operation.name": "exec"
|
|
12
|
+
};
|
|
7
13
|
function instrumentSqlStorage(sql) {
|
|
8
14
|
return new Proxy(sql, {
|
|
9
15
|
get(target, prop, _receiver) {
|
|
@@ -12,32 +18,40 @@ function instrumentSqlStorage(sql) {
|
|
|
12
18
|
return original;
|
|
13
19
|
}
|
|
14
20
|
return function(...args) {
|
|
21
|
+
const callOriginal = () => original.apply(target, args);
|
|
15
22
|
const [query, ...bindings] = args;
|
|
23
|
+
if (childSpanWillNotBeRecorded() && !mayTargetCloudflareInternalTable(query)) {
|
|
24
|
+
return startSpan({ name: "exec", attributes: SPAN_ATTRIBUTES }, callOriginal);
|
|
25
|
+
}
|
|
16
26
|
const sanitizedQuery = sanitizeSqlQuery(query);
|
|
17
27
|
const querySummary = getSqlQuerySummary(sanitizedQuery);
|
|
18
28
|
const allowlist = getClient()?.getOptions()?.durableObjectSqlSpanAllowlist;
|
|
19
29
|
if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {
|
|
20
|
-
return
|
|
30
|
+
return callOriginal();
|
|
21
31
|
}
|
|
22
32
|
return startSpan(
|
|
23
33
|
{
|
|
24
34
|
name: querySummary || sanitizedQuery,
|
|
25
35
|
attributes: {
|
|
26
|
-
|
|
27
|
-
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: "auto.db.cloudflare.durable_object.sql",
|
|
28
|
-
"db.system.name": "cloudflare-durable-object-sql",
|
|
29
|
-
"db.operation.name": "exec",
|
|
36
|
+
...SPAN_ATTRIBUTES,
|
|
30
37
|
"db.query.text": sanitizedQuery,
|
|
31
38
|
"db.query.summary": querySummary,
|
|
32
39
|
"cloudflare.durable_object.query.bindings": bindings.length
|
|
33
40
|
}
|
|
34
41
|
},
|
|
35
|
-
|
|
42
|
+
callOriginal
|
|
36
43
|
);
|
|
37
44
|
};
|
|
38
45
|
}
|
|
39
46
|
});
|
|
40
47
|
}
|
|
48
|
+
function childSpanWillNotBeRecorded() {
|
|
49
|
+
if (!hasSpansEnabled()) {
|
|
50
|
+
return true;
|
|
51
|
+
}
|
|
52
|
+
const activeSpan = getActiveSpan();
|
|
53
|
+
return !!activeSpan && !spanIsSampled(activeSpan);
|
|
54
|
+
}
|
|
41
55
|
|
|
42
56
|
export { instrumentSqlStorage };
|
|
43
57
|
//# sourceMappingURL=instrumentSqlStorage.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport {
|
|
1
|
+
{"version":3,"file":"instrumentSqlStorage.js","sources":["../../../../src/instrumentations/instrumentSqlStorage.ts"],"sourcesContent":["import type { SqlStorage } from '@cloudflare/workers-types';\nimport { SENTRY_OP } from '@sentry/conventions/attributes';\nimport { DB_QUERY } from '@sentry/conventions/op';\nimport {\n getActiveSpan,\n getClient,\n hasSpansEnabled,\n SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,\n spanIsSampled,\n startSpan,\n} from '@sentry/core';\nimport { getSqlQuerySummary, sanitizeSqlQuery } from '@sentry/server-utils';\nimport type { CloudflareClientOptions } from '../client';\nimport { mayTargetCloudflareInternalTable, targetsCloudflareInternalTable } from '../utils/internalSqlQuery';\n\nconst SPAN_ATTRIBUTES = {\n [SENTRY_OP]: DB_QUERY,\n [SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.db.cloudflare.durable_object.sql',\n 'db.system.name': 'cloudflare-durable-object-sql',\n 'db.operation.name': 'exec',\n};\n\n/**\n * Instruments the Durable Object SqlStorage `exec` method with Sentry spans.\n *\n * @param sql - The SqlStorage instance to instrument\n * @returns An instrumented SqlStorage instance\n */\nexport function instrumentSqlStorage(sql: SqlStorage): SqlStorage {\n return new Proxy(sql, {\n get(target, prop, _receiver) {\n const original = Reflect.get(target, prop, target);\n\n if (prop !== 'exec' || typeof original !== 'function') {\n return original;\n }\n\n return function (this: unknown, ...args: unknown[]) {\n const callOriginal = (): ReturnType<SqlStorage['exec']> =>\n (original as (...a: unknown[]) => ReturnType<SqlStorage['exec']>).apply(target, args);\n\n const [query, ...bindings] = args as [string, ...unknown[]];\n\n if (childSpanWillNotBeRecorded() && !mayTargetCloudflareInternalTable(query)) {\n // This span is never sent, so skip the costly sanitize and summary\n // steps. We still start the span so it records its dropped span\n // outcome. A query that may target a `cf_` table takes the full path,\n // because an internal query must start no span.\n return startSpan({ name: 'exec', attributes: SPAN_ATTRIBUTES }, callOriginal);\n }\n\n const sanitizedQuery = sanitizeSqlQuery(query);\n const querySummary = getSqlQuerySummary(sanitizedQuery);\n\n // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- rule false positive: the cast reaches the Cloudflare-only `durableObjectSqlSpanAllowlist`; tsc errors without it\n const allowlist = (getClient()?.getOptions() as CloudflareClientOptions | undefined)\n ?.durableObjectSqlSpanAllowlist;\n\n if (targetsCloudflareInternalTable(querySummary, allowlist, sanitizedQuery)) {\n return callOriginal();\n }\n\n return startSpan(\n {\n name: querySummary || sanitizedQuery,\n attributes: {\n ...SPAN_ATTRIBUTES,\n 'db.query.text': sanitizedQuery,\n 'db.query.summary': querySummary,\n 'cloudflare.durable_object.query.bindings': bindings.length,\n },\n },\n callOriginal,\n );\n };\n },\n });\n}\n\n/**\n * Returns `true` when `startSpan` creates a non-recording span: spans are disabled, or the active span\n * is not sampled. Must agree with `createChildOrRootSpan` and `_startChildSpan` in `@sentry/core`.\n */\nfunction childSpanWillNotBeRecorded(): boolean {\n if (!hasSpansEnabled()) {\n return true;\n }\n\n const activeSpan = getActiveSpan();\n return !!activeSpan && !spanIsSampled(activeSpan);\n}\n"],"names":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AAM,YAAA,IAAgB,cAAA;AAAA,YACtB,UAAA,EAAY;AAAA,cACV,GAAG,eAAA;AAAA,cACH,eAAA,EAAiB,cAAA;AAAA,cACjB,kBAAA,EAAoB,YAAA;AAAA,cACpB,4CAA4C,QAAA,CAAS;AAAA;AACvD,WACF;AAAA,UACA;AAAA,SACF;AAAA,MACF,CAAA;AAAA,IACF;AAAA,GACD,CAAA;AACH;AAMA,SAAS,0BAAA,GAAsC;AAC7C,EAAA,IAAI,CAAC,iBAAgB,EAAG;AACtB,IAAA,OAAO,IAAA;AAAA,EACT;AAEA,EAAA,MAAM,aAAa,aAAA,EAAc;AACjC,EAAA,OAAO,CAAC,CAAC,UAAA,IAAc,CAAC,cAAc,UAAU,CAAA;AAClD;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"11.
|
|
1
|
+
{"type":"module","version":"11.4.0","sideEffects":false}
|
|
@@ -11,6 +11,10 @@ function targetsCloudflareInternalTable(querySummary, allowlist, queryText) {
|
|
|
11
11
|
const [, ...tables] = querySummary.split(" ");
|
|
12
12
|
return tables.some((table) => isCloudflareInternalTable(table, allowlist));
|
|
13
13
|
}
|
|
14
|
+
function mayTargetCloudflareInternalTable(query) {
|
|
15
|
+
return CF_PREFIX_RE.test(query);
|
|
16
|
+
}
|
|
17
|
+
const CF_PREFIX_RE = /\bcf_/i;
|
|
14
18
|
const CREATE_INDEX_TABLE_RE = /^\s*CREATE\s+(?:UNIQUE\s+)?INDEX(?:\s+IF\s+(?:NOT\s+)?EXISTS)?\s+[^\s(,;)]+\s+ON\s+(?<table>[^\s(,;)]+)/i;
|
|
15
19
|
function isCloudflareInternalTable(table, allowlist) {
|
|
16
20
|
if (!table.toLowerCase().startsWith("cf_")) {
|
|
@@ -19,5 +23,5 @@ function isCloudflareInternalTable(table, allowlist) {
|
|
|
19
23
|
return !allowlist?.length || !stringMatchesSomePattern(table, allowlist, true);
|
|
20
24
|
}
|
|
21
25
|
|
|
22
|
-
export { targetsCloudflareInternalTable };
|
|
26
|
+
export { mayTargetCloudflareInternalTable, targetsCloudflareInternalTable };
|
|
23
27
|
//# sourceMappingURL=internalSqlQuery.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internalSqlQuery.js","sources":["../../../../src/utils/internalSqlQuery.ts"],"sourcesContent":["import { stringMatchesSomePattern } from '@sentry/core';\n\n/**\n * Cloudflare frameworks that build on Durable Objects (`agents`, `partyserver`, ...) manage their\n * own internal SQLite tables, all namespaced with a `cf_` prefix — e.g. `cf_agents_schedules`,\n * `cf_agent_state`, `cf_ai_chat_stream_chunks`. Queries against them (schedule polling, chat-stream\n * persistence, state bookkeeping) are framework implementation details that otherwise flood traces\n * with dozens of zero-signal `db.query` spans per request. The exact set of tables even varies\n * between framework versions, so we match the reserved prefix rather than an enumerated list.\n *\n * The `cf_` prefix is a reserved convention for framework-managed tables, so user tables should not\n * use it. In case a user table does collide with the prefix, the `durableObjectSqlSpanAllowlist`\n * option lets them opt those tables back into instrumentation.\n *\n * The check operates on the query summary produced by `getSqlQuerySummary` (`{operation} {table} ...`,\n * the same value used as the span name), so table targets are already isolated from the rest of the\n * query. The one exception is `CREATE INDEX`: its summary carries the index name, not the indexed\n * table (upstream OTel convention), so the `cf_` target only appears in the ON clause of the full\n * statement, which `queryText` is needed for.\n */\nexport function targetsCloudflareInternalTable(\n querySummary: string | undefined,\n allowlist?: Array<string | RegExp>,\n queryText?: string,\n): boolean {\n if (!querySummary) {\n return false;\n }\n\n const indexedTable = queryText ? CREATE_INDEX_TABLE_RE.exec(queryText)?.groups?.['table'] : undefined;\n if (indexedTable) {\n return isCloudflareInternalTable(indexedTable, allowlist);\n }\n\n const [, ...tables] = querySummary.split(' ');\n\n return tables.some(table => isCloudflareInternalTable(table, allowlist));\n}\n\n// `CREATE [UNIQUE] INDEX [IF NOT EXISTS] <name> ON <table>` — the IF EXISTS shape mirrors DDL_RE\n// in @sentry/core.\nconst CREATE_INDEX_TABLE_RE =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+[^\\s(,;)]+\\s+ON\\s+(?<table>[^\\s(,;)]+)/i;\n\nfunction isCloudflareInternalTable(table: string, allowlist?: Array<string | RegExp>): boolean {\n if (!table.toLowerCase().startsWith('cf_')) {\n return false;\n }\n\n // A table on the allowlist is treated as a user table and stays instrumented, even though it\n // matches the reserved prefix.\n return !allowlist?.length || !stringMatchesSomePattern(table, allowlist, true);\n}\n"],"names":[],"mappings":";;AAoBO,SAAS,8BAAA,CACd,YAAA,EACA,SAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,YAAY,qBAAA,CAAsB,IAAA,CAAK,SAAS,CAAA,EAAG,MAAA,GAAS,OAAO,CAAA,GAAI,MAAA;AAC5F,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,OAAO,yBAAA,CAA0B,cAAc,SAAS,CAAA;AAAA,EAC1D;AAEA,EAAA,MAAM,GAAG,GAAG,MAAM,CAAA,GAAI,YAAA,CAAa,MAAM,GAAG,CAAA;AAE5C,EAAA,OAAO,OAAO,IAAA,CAAK,CAAA,KAAA,KAAS,yBAAA,CAA0B,KAAA,EAAO,SAAS,CAAC,CAAA;AACzE;
|
|
1
|
+
{"version":3,"file":"internalSqlQuery.js","sources":["../../../../src/utils/internalSqlQuery.ts"],"sourcesContent":["import { stringMatchesSomePattern } from '@sentry/core';\n\n/**\n * Cloudflare frameworks that build on Durable Objects (`agents`, `partyserver`, ...) manage their\n * own internal SQLite tables, all namespaced with a `cf_` prefix — e.g. `cf_agents_schedules`,\n * `cf_agent_state`, `cf_ai_chat_stream_chunks`. Queries against them (schedule polling, chat-stream\n * persistence, state bookkeeping) are framework implementation details that otherwise flood traces\n * with dozens of zero-signal `db.query` spans per request. The exact set of tables even varies\n * between framework versions, so we match the reserved prefix rather than an enumerated list.\n *\n * The `cf_` prefix is a reserved convention for framework-managed tables, so user tables should not\n * use it. In case a user table does collide with the prefix, the `durableObjectSqlSpanAllowlist`\n * option lets them opt those tables back into instrumentation.\n *\n * The check operates on the query summary produced by `getSqlQuerySummary` (`{operation} {table} ...`,\n * the same value used as the span name), so table targets are already isolated from the rest of the\n * query. The one exception is `CREATE INDEX`: its summary carries the index name, not the indexed\n * table (upstream OTel convention), so the `cf_` target only appears in the ON clause of the full\n * statement, which `queryText` is needed for.\n */\nexport function targetsCloudflareInternalTable(\n querySummary: string | undefined,\n allowlist?: Array<string | RegExp>,\n queryText?: string,\n): boolean {\n if (!querySummary) {\n return false;\n }\n\n const indexedTable = queryText ? CREATE_INDEX_TABLE_RE.exec(queryText)?.groups?.['table'] : undefined;\n if (indexedTable) {\n return isCloudflareInternalTable(indexedTable, allowlist);\n }\n\n const [, ...tables] = querySummary.split(' ');\n\n return tables.some(table => isCloudflareInternalTable(table, allowlist));\n}\n\n/**\n * Returns `false` when the raw `query` has no word that starts with `cf_`, so it cannot target a\n * Cloudflare internal table. Needs no sanitizing, which makes it cheap enough to run on every query.\n */\nexport function mayTargetCloudflareInternalTable(query: string): boolean {\n return CF_PREFIX_RE.test(query);\n}\n\nconst CF_PREFIX_RE = /\\bcf_/i;\n\n// `CREATE [UNIQUE] INDEX [IF NOT EXISTS] <name> ON <table>` — the IF EXISTS shape mirrors DDL_RE\n// in @sentry/core.\nconst CREATE_INDEX_TABLE_RE =\n /^\\s*CREATE\\s+(?:UNIQUE\\s+)?INDEX(?:\\s+IF\\s+(?:NOT\\s+)?EXISTS)?\\s+[^\\s(,;)]+\\s+ON\\s+(?<table>[^\\s(,;)]+)/i;\n\nfunction isCloudflareInternalTable(table: string, allowlist?: Array<string | RegExp>): boolean {\n if (!table.toLowerCase().startsWith('cf_')) {\n return false;\n }\n\n // A table on the allowlist is treated as a user table and stays instrumented, even though it\n // matches the reserved prefix.\n return !allowlist?.length || !stringMatchesSomePattern(table, allowlist, true);\n}\n"],"names":[],"mappings":";;AAoBO,SAAS,8BAAA,CACd,YAAA,EACA,SAAA,EACA,SAAA,EACS;AACT,EAAA,IAAI,CAAC,YAAA,EAAc;AACjB,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,YAAA,GAAe,YAAY,qBAAA,CAAsB,IAAA,CAAK,SAAS,CAAA,EAAG,MAAA,GAAS,OAAO,CAAA,GAAI,MAAA;AAC5F,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,OAAO,yBAAA,CAA0B,cAAc,SAAS,CAAA;AAAA,EAC1D;AAEA,EAAA,MAAM,GAAG,GAAG,MAAM,CAAA,GAAI,YAAA,CAAa,MAAM,GAAG,CAAA;AAE5C,EAAA,OAAO,OAAO,IAAA,CAAK,CAAA,KAAA,KAAS,yBAAA,CAA0B,KAAA,EAAO,SAAS,CAAC,CAAA;AACzE;AAMO,SAAS,iCAAiC,KAAA,EAAwB;AACvE,EAAA,OAAO,YAAA,CAAa,KAAK,KAAK,CAAA;AAChC;AAEA,MAAM,YAAA,GAAe,QAAA;AAIrB,MAAM,qBAAA,GACJ,0GAAA;AAEF,SAAS,yBAAA,CAA0B,OAAe,SAAA,EAA6C;AAC7F,EAAA,IAAI,CAAC,KAAA,CAAM,WAAA,EAAY,CAAE,UAAA,CAAW,KAAK,CAAA,EAAG;AAC1C,IAAA,OAAO,KAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,SAAA,EAAW,MAAA,IAAU,CAAC,wBAAA,CAAyB,KAAA,EAAO,WAAW,IAAI,CAAA;AAC/E;;;;"}
|
|
@@ -1,9 +1,19 @@
|
|
|
1
1
|
import { getIsolationScope, getDefaultIsolationScope, withIsolationScope } from '@sentry/core';
|
|
2
2
|
import { setInvocationState } from './invocationContext.js';
|
|
3
3
|
|
|
4
|
+
const constructionScopes = /* @__PURE__ */ new WeakSet();
|
|
5
|
+
function withConstructionIsolationScope(callback) {
|
|
6
|
+
if (getIsolationScope() !== getDefaultIsolationScope()) {
|
|
7
|
+
return callback();
|
|
8
|
+
}
|
|
9
|
+
return withIsolationScope((scope) => {
|
|
10
|
+
constructionScopes.add(scope);
|
|
11
|
+
return callback();
|
|
12
|
+
});
|
|
13
|
+
}
|
|
4
14
|
function withInvocationIsolationScope(callback, context) {
|
|
5
15
|
const isolationScope = getIsolationScope();
|
|
6
|
-
const isEntryPoint = isolationScope === getDefaultIsolationScope();
|
|
16
|
+
const isEntryPoint = isolationScope === getDefaultIsolationScope() || constructionScopes.has(isolationScope);
|
|
7
17
|
const newIsolationScope = isEntryPoint ? isolationScope.clone() : isolationScope;
|
|
8
18
|
if (isEntryPoint) {
|
|
9
19
|
setInvocationState(newIsolationScope, { ctx: context });
|
|
@@ -11,5 +21,5 @@ function withInvocationIsolationScope(callback, context) {
|
|
|
11
21
|
return withIsolationScope(newIsolationScope, () => callback(newIsolationScope));
|
|
12
22
|
}
|
|
13
23
|
|
|
14
|
-
export { withInvocationIsolationScope };
|
|
24
|
+
export { withConstructionIsolationScope, withInvocationIsolationScope };
|
|
15
25
|
//# sourceMappingURL=invocationScope.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invocationScope.js","sources":["../../../../src/utils/invocationScope.ts"],"sourcesContent":["import { getDefaultIsolationScope, getIsolationScope, type Scope, withIsolationScope } from '@sentry/core';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { setInvocationState } from './invocationContext';\n\n/**\n * Runs `callback` on the isolation scope for the current invocation.\n *\n * An instrumented handler is either the entry point of an invocation or reentrant — reached from\n * another instrumented handler already serving the same invocation (a Durable Object method calling\n * its own `fetch`, an RPC method reaching a sibling method). Only the entry point may fork:\n *\n * - Forking at the entry point is mandatory. `setUser`/`setTag` write to the isolation scope, and a\n * Durable Object's isolation scope outlives the invocation that touched it, so without a fork one\n * invocation's user and tags reappear on the next invocation's events in the same isolate.\n * Forking clones, so request data set by an enclosing wrapper is still inherited.\n * - Forking again when reentrant would be wrong. Everything below the entry point is one logical\n * unit of work: a nested call must see what the caller set and be able to add to it, the way it\n * would if the SDK were not wrapping it at all.\n *\n * The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in\n * flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default\n * is therefore enough to tell the two cases apart. The stack fallback does not fork, so it reports the
|
|
1
|
+
{"version":3,"file":"invocationScope.js","sources":["../../../../src/utils/invocationScope.ts"],"sourcesContent":["import { getDefaultIsolationScope, getIsolationScope, type Scope, withIsolationScope } from '@sentry/core';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { setInvocationState } from './invocationContext';\n\nconst constructionScopes = new WeakSet<Scope>();\n\n/**\n * Runs a Durable Object constructor on a forked isolation scope.\n *\n * Async work the constructor starts, such as a `blockConcurrencyWhile` callback, runs after the RPC\n * wrappers are installed and inherits this scope, so the calls it makes to the instance's own methods\n * are not treated as incoming RPC calls. The scope is not an invocation: it has no invocation state,\n * and an instrumented handler that this work calls still forks a scope of its own.\n */\nexport function withConstructionIsolationScope<T>(callback: () => T): T {\n if (getIsolationScope() !== getDefaultIsolationScope()) {\n return callback();\n }\n\n return withIsolationScope(scope => {\n constructionScopes.add(scope);\n return callback();\n });\n}\n\n/**\n * Runs `callback` on the isolation scope for the current invocation.\n *\n * An instrumented handler is either the entry point of an invocation or reentrant — reached from\n * another instrumented handler already serving the same invocation (a Durable Object method calling\n * its own `fetch`, an RPC method reaching a sibling method). Only the entry point may fork:\n *\n * - Forking at the entry point is mandatory. `setUser`/`setTag` write to the isolation scope, and a\n * Durable Object's isolation scope outlives the invocation that touched it, so without a fork one\n * invocation's user and tags reappear on the next invocation's events in the same isolate.\n * Forking clones, so request data set by an enclosing wrapper is still inherited.\n * - Forking again when reentrant would be wrong. Everything below the entry point is one logical\n * unit of work: a nested call must see what the caller set and be able to add to it, the way it\n * would if the SDK were not wrapping it at all.\n *\n * The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in\n * flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default\n * and the construction scopes (see {@link withConstructionIsolationScope}) is therefore enough to tell\n * the two cases apart. The stack fallback does not fork, so it reports the default scope even inside an\n * invocation; there the fork degrades to a no-op, which the stack strategy tolerates. This matches the\n * approach used by `patchEventHandler` in Nuxt.\n */\nexport function withInvocationIsolationScope<T>(callback: (scope: Scope) => T, context?: ExecutionContextCompat): T {\n const isolationScope = getIsolationScope();\n\n const isEntryPoint = isolationScope === getDefaultIsolationScope() || constructionScopes.has(isolationScope);\n const newIsolationScope = isEntryPoint ? isolationScope.clone() : isolationScope;\n\n if (isEntryPoint) {\n setInvocationState(newIsolationScope, { ctx: context });\n }\n\n return withIsolationScope(newIsolationScope, () => callback(newIsolationScope));\n}\n"],"names":[],"mappings":";;;AAIA,MAAM,kBAAA,uBAAyB,OAAA,EAAe;AAUvC,SAAS,+BAAkC,QAAA,EAAsB;AACtE,EAAA,IAAI,iBAAA,EAAkB,KAAM,wBAAA,EAAyB,EAAG;AACtD,IAAA,OAAO,QAAA,EAAS;AAAA,EAClB;AAEA,EAAA,OAAO,mBAAmB,CAAA,KAAA,KAAS;AACjC,IAAA,kBAAA,CAAmB,IAAI,KAAK,CAAA;AAC5B,IAAA,OAAO,QAAA,EAAS;AAAA,EAClB,CAAC,CAAA;AACH;AAwBO,SAAS,4BAAA,CAAgC,UAA+B,OAAA,EAAqC;AAClH,EAAA,MAAM,iBAAiB,iBAAA,EAAkB;AAEzC,EAAA,MAAM,eAAe,cAAA,KAAmB,wBAAA,EAAyB,IAAK,kBAAA,CAAmB,IAAI,cAAc,CAAA;AAC3G,EAAA,MAAM,iBAAA,GAAoB,YAAA,GAAe,cAAA,CAAe,KAAA,EAAM,GAAI,cAAA;AAElE,EAAA,IAAI,YAAA,EAAc;AAChB,IAAA,kBAAA,CAAmB,iBAAA,EAAmB,EAAE,GAAA,EAAK,OAAA,EAAS,CAAA;AAAA,EACxD;AAEA,EAAA,OAAO,kBAAA,CAAmB,iBAAA,EAAmB,MAAM,QAAA,CAAS,iBAAiB,CAAC,CAAA;AAChF;;;;"}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
|
+
import { SENTRY_LINK_TYPE } from '@sentry/conventions/attributes';
|
|
1
2
|
import { TraceFlags } from '@opentelemetry/api';
|
|
2
|
-
import { getActiveSpan, spanIsSampled, debug
|
|
3
|
+
import { getActiveSpan, spanIsSampled, debug } from '@sentry/core';
|
|
3
4
|
import { DEBUG_BUILD } from '../debug-build.js';
|
|
4
5
|
|
|
5
6
|
const SENTRY_TRACE_LINK_KEY_PREFIX = "__SENTRY_TRACE_LINK__";
|
|
@@ -39,7 +40,7 @@ function buildSpanLinks(storedContext) {
|
|
|
39
40
|
traceFlags: storedContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE
|
|
40
41
|
},
|
|
41
42
|
attributes: {
|
|
42
|
-
[
|
|
43
|
+
[SENTRY_LINK_TYPE]: "previous_trace"
|
|
43
44
|
}
|
|
44
45
|
}
|
|
45
46
|
];
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"traceLinks.js","sources":["../../../../src/utils/traceLinks.ts"],"sourcesContent":["import type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport { TraceFlags } from '@opentelemetry/api';\nimport type { SpanLink } from '@sentry/core';\nimport { debug, getActiveSpan,
|
|
1
|
+
{"version":3,"file":"traceLinks.js","sources":["../../../../src/utils/traceLinks.ts"],"sourcesContent":["import { SENTRY_LINK_TYPE } from '@sentry/conventions/attributes';\nimport type { DurableObjectStorage } from '@cloudflare/workers-types';\nimport { TraceFlags } from '@opentelemetry/api';\nimport type { SpanLink } from '@sentry/core';\nimport { debug, getActiveSpan, spanIsSampled } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\n/** Storage key prefix for the span context that links consecutive method invocations */\nconst SENTRY_TRACE_LINK_KEY_PREFIX = '__SENTRY_TRACE_LINK__';\n\n/** Stored span context for creating span links */\nexport interface StoredSpanContext {\n traceId: string;\n spanId: string;\n sampled: boolean;\n}\n\n/**\n * Gets the storage key for a specific method's trace link.\n */\nexport function getTraceLinkKey(methodName: string): string {\n return `${SENTRY_TRACE_LINK_KEY_PREFIX}${methodName}`;\n}\n\n/**\n * Stores the current span context in Durable Object storage for trace linking.\n * Uses the original uninstrumented storage to avoid creating spans for internal operations.\n * Errors are silently ignored to prevent internal storage failures from propagating to user code.\n */\nexport function storeSpanContext(originalStorage: DurableObjectStorage, methodName: string): void {\n try {\n const activeSpan = getActiveSpan();\n if (activeSpan) {\n const spanContext = activeSpan.spanContext();\n const storedContext: StoredSpanContext = {\n traceId: spanContext.traceId,\n spanId: spanContext.spanId,\n sampled: spanIsSampled(activeSpan),\n };\n\n originalStorage.kv.put(getTraceLinkKey(methodName), storedContext);\n }\n } catch (error) {\n // Silently ignore storage errors to prevent internal failures from affecting user code\n DEBUG_BUILD && debug.log(`[CloudflareClient] Error storing span context for method ${methodName}`, error);\n }\n}\n\n/**\n * Retrieves a stored span context from Durable Object storage.\n * Errors are silently ignored to prevent internal storage failures from propagating to user code.\n */\nexport function getStoredSpanContext(\n originalStorage: DurableObjectStorage,\n methodName: string,\n): StoredSpanContext | undefined {\n try {\n return originalStorage.kv.get<StoredSpanContext>(getTraceLinkKey(methodName));\n } catch (error) {\n // Silently ignore storage errors to prevent internal failures from affecting user code\n DEBUG_BUILD && debug.log(`[CloudflareClient] Error retrieving span context for method ${methodName}`, error);\n return undefined;\n }\n}\n\n/**\n * Builds span links from a stored span context.\n */\nexport function buildSpanLinks(storedContext: StoredSpanContext): SpanLink[] {\n return [\n {\n context: {\n traceId: storedContext.traceId,\n spanId: storedContext.spanId,\n traceFlags: storedContext.sampled ? TraceFlags.SAMPLED : TraceFlags.NONE,\n },\n attributes: {\n [SENTRY_LINK_TYPE]: 'previous_trace',\n },\n },\n ];\n}\n"],"names":[],"mappings":";;;;;AAQA,MAAM,4BAAA,GAA+B,uBAAA;AAY9B,SAAS,gBAAgB,UAAA,EAA4B;AAC1D,EAAA,OAAO,CAAA,EAAG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AAA;AACtB;AACF,GACF;AACF;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"durableobject.d.ts","sourceRoot":"","sources":["../../src/durableobject.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;
|
|
1
|
+
{"version":3,"file":"durableobject.d.ts","sourceRoot":"","sources":["../../src/durableobject.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAExD,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,UAAU,CAAC;AASlD,OAAO,KAAK,EAAE,UAAU,EAAE,UAAU,EAAE,uBAAuB,EAAE,MAAM,SAAS,CAAC;AAG/E;;;;;;;;;;GAUG;AAEH,KAAK,gCAAgC,GAAG,GAAG,CAAC;AAE5C;;;;;;;;;;GAUG;AACH,wBAAgB,kCAAkC,CAAC,CAAC,EAAE,CAAC,SAAS,aAAa,CAAC,CAAC,CAAC,EAC9E,MAAM,EAAE,KAAK,KAAK,EAAE,kBAAkB,EAAE,GAAG,EAAE,CAAC,KAAK,CAAC,EACpD,GAAG,EAAE,kBAAkB,EACvB,GAAG,EAAE,CAAC,EACN,SAAS,EAAE,eAAe,EAC1B,eAAe,EAAE,CAAC,GAAG,EAAE,CAAC,KAAK,iBAAiB,GAC7C;IACD,GAAG,EAAE,CAAC,CAAC;IACP,OAAO,EAAE,iBAAiB,CAAC;IAC3B,OAAO,EAAE,gCAAgC,CAAC;IAC1C,uBAAuB,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;CAC9C,CA8BA;AA0FD;;;;;;;;;;;;;;;;GAgBG;AACH,wBAAgB,8BAA8B,CAAC,CAAC,SAAS,MAAM,EAC7D,GAAG,EAAE,CAAC,EACN,OAAO,EAAE,iBAAiB,EAC1B,OAAO,EAAE,gCAAgC,EACzC,eAA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AC;
|
|
1
|
+
{"version":3,"file":"instrumentSqlStorage.d.ts","sourceRoot":"","sources":["../../../src/instrumentations/instrumentSqlStorage.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,2BAA2B,CAAC;AAsB5D;;;;;GAKG;AACH,wBAAgB,oBAAoB,CAAC,GAAG,EAAE,UAAU,GAAG,UAAU,CAiDhE"}
|
|
@@ -17,4 +17,9 @@
|
|
|
17
17
|
* statement, which `queryText` is needed for.
|
|
18
18
|
*/
|
|
19
19
|
export declare function targetsCloudflareInternalTable(querySummary: string | undefined, allowlist?: Array<string | RegExp>, queryText?: string): boolean;
|
|
20
|
+
/**
|
|
21
|
+
* Returns `false` when the raw `query` has no word that starts with `cf_`, so it cannot target a
|
|
22
|
+
* Cloudflare internal table. Needs no sanitizing, which makes it cheap enough to run on every query.
|
|
23
|
+
*/
|
|
24
|
+
export declare function mayTargetCloudflareInternalTable(query: string): boolean;
|
|
20
25
|
//# sourceMappingURL=internalSqlQuery.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"internalSqlQuery.d.ts","sourceRoot":"","sources":["../../../src/utils/internalSqlQuery.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,8BAA8B,CAC5C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,SAAS,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,EAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAaT"}
|
|
1
|
+
{"version":3,"file":"internalSqlQuery.d.ts","sourceRoot":"","sources":["../../../src/utils/internalSqlQuery.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,8BAA8B,CAC5C,YAAY,EAAE,MAAM,GAAG,SAAS,EAChC,SAAS,CAAC,EAAE,KAAK,CAAC,MAAM,GAAG,MAAM,CAAC,EAClC,SAAS,CAAC,EAAE,MAAM,GACjB,OAAO,CAaT;AAED;;;GAGG;AACH,wBAAgB,gCAAgC,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAEvE"}
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { type Scope } from '@sentry/core';
|
|
2
2
|
import type { ExecutionContextCompat } from '../executionContext';
|
|
3
|
+
/**
|
|
4
|
+
* Runs a Durable Object constructor on a forked isolation scope.
|
|
5
|
+
*
|
|
6
|
+
* Async work the constructor starts, such as a `blockConcurrencyWhile` callback, runs after the RPC
|
|
7
|
+
* wrappers are installed and inherits this scope, so the calls it makes to the instance's own methods
|
|
8
|
+
* are not treated as incoming RPC calls. The scope is not an invocation: it has no invocation state,
|
|
9
|
+
* and an instrumented handler that this work calls still forks a scope of its own.
|
|
10
|
+
*/
|
|
11
|
+
export declare function withConstructionIsolationScope<T>(callback: () => T): T;
|
|
3
12
|
/**
|
|
4
13
|
* Runs `callback` on the isolation scope for the current invocation.
|
|
5
14
|
*
|
|
@@ -17,9 +26,10 @@ import type { ExecutionContextCompat } from '../executionContext';
|
|
|
17
26
|
*
|
|
18
27
|
* The AsyncLocalStorage strategy hands the default isolation scope back whenever no invocation is in
|
|
19
28
|
* flight, and a forked one while inside `withIsolationScope`. Reference-comparing against the default
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
29
|
+
* and the construction scopes (see {@link withConstructionIsolationScope}) is therefore enough to tell
|
|
30
|
+
* the two cases apart. The stack fallback does not fork, so it reports the default scope even inside an
|
|
31
|
+
* invocation; there the fork degrades to a no-op, which the stack strategy tolerates. This matches the
|
|
32
|
+
* approach used by `patchEventHandler` in Nuxt.
|
|
23
33
|
*/
|
|
24
34
|
export declare function withInvocationIsolationScope<T>(callback: (scope: Scope) => T, context?: ExecutionContextCompat): T;
|
|
25
35
|
//# sourceMappingURL=invocationScope.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invocationScope.d.ts","sourceRoot":"","sources":["../../../src/utils/invocationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,KAAK,KAAK,EAAsB,MAAM,cAAc,CAAC;AAC3G,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;
|
|
1
|
+
{"version":3,"file":"invocationScope.d.ts","sourceRoot":"","sources":["../../../src/utils/invocationScope.ts"],"names":[],"mappings":"AAAA,OAAO,EAA+C,KAAK,KAAK,EAAsB,MAAM,cAAc,CAAC;AAC3G,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,qBAAqB,CAAC;AAKlE;;;;;;;GAOG;AACH,wBAAgB,8BAA8B,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,CAAC,GAAG,CAAC,CAStE;AAED;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,4BAA4B,CAAC,CAAC,EAAE,QAAQ,EAAE,CAAC,KAAK,EAAE,KAAK,KAAK,CAAC,EAAE,OAAO,CAAC,EAAE,sBAAsB,GAAG,CAAC,CAWlH"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"traceLinks.d.ts","sourceRoot":"","sources":["../../../src/utils/traceLinks.ts"],"names":[],"mappings":"
|
|
1
|
+
{"version":3,"file":"traceLinks.d.ts","sourceRoot":"","sources":["../../../src/utils/traceLinks.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AAEtE,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,cAAc,CAAC;AAO7C,kDAAkD;AAClD,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,OAAO,CAAC;CAClB;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,UAAU,EAAE,MAAM,GAAG,MAAM,CAE1D;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,eAAe,EAAE,oBAAoB,EAAE,UAAU,EAAE,MAAM,GAAG,IAAI,CAiBhG;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,eAAe,EAAE,oBAAoB,EACrC,UAAU,EAAE,MAAM,GACjB,iBAAiB,GAAG,SAAS,CAQ/B;AAED;;GAEG;AACH,wBAAgB,cAAc,CAAC,aAAa,EAAE,iBAAiB,GAAG,QAAQ,EAAE,CAa3E"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sentry/cloudflare",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.4.0",
|
|
4
4
|
"description": "Official Sentry SDK for Cloudflare Workers and Pages",
|
|
5
5
|
"repository": "git://github.com/getsentry/sentry-javascript.git",
|
|
6
6
|
"homepage": "https://github.com/getsentry/sentry-javascript/tree/master/packages/cloudflare",
|
|
@@ -53,10 +53,10 @@
|
|
|
53
53
|
},
|
|
54
54
|
"dependencies": {
|
|
55
55
|
"@opentelemetry/api": "^1.9.1",
|
|
56
|
-
"@sentry/conventions": "^0.
|
|
57
|
-
"@sentry/core": "11.
|
|
58
|
-
"@sentry/opentelemetry": "11.
|
|
59
|
-
"@sentry/server-utils": "11.
|
|
56
|
+
"@sentry/conventions": "^0.25.0",
|
|
57
|
+
"@sentry/core": "11.4.0",
|
|
58
|
+
"@sentry/opentelemetry": "11.4.0",
|
|
59
|
+
"@sentry/server-utils": "11.4.0",
|
|
60
60
|
"magic-string": "~0.30.21"
|
|
61
61
|
},
|
|
62
62
|
"peerDependencies": {
|