@sentry/cloudflare 11.8.0 → 11.9.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/client.js +17 -0
- package/build/cjs/dev/client.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js +0 -3
- package/build/cjs/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/dev/integrations/cronTriggers.js.map +1 -1
- package/build/cjs/dev/transport.js +8 -6
- package/build/cjs/dev/transport.js.map +1 -1
- package/build/cjs/dev/utils/invocationContext.js +2 -2
- package/build/cjs/dev/utils/invocationContext.js.map +1 -1
- package/build/cjs/dev/vite/transform.js +40 -4
- package/build/cjs/dev/vite/transform.js.map +1 -1
- package/build/cjs/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/dev/wrapRequestHandlerWithInit.js +15 -10
- package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/cjs/prod/client.js +17 -0
- package/build/cjs/prod/client.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js +0 -3
- package/build/cjs/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/cjs/prod/integrations/cronTriggers.js.map +1 -1
- package/build/cjs/prod/transport.js +8 -6
- package/build/cjs/prod/transport.js.map +1 -1
- package/build/cjs/prod/utils/invocationContext.js +2 -2
- package/build/cjs/prod/utils/invocationContext.js.map +1 -1
- package/build/cjs/prod/vite/transform.js +40 -4
- package/build/cjs/prod/vite/transform.js.map +1 -1
- package/build/cjs/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/cjs/prod/wrapRequestHandlerWithInit.js +15 -10
- package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/dev/client.js +18 -1
- package/build/esm/dev/client.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js +0 -3
- package/build/esm/dev/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/dev/integrations/cronTriggers.js.map +1 -1
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/transport.js +8 -6
- package/build/esm/dev/transport.js.map +1 -1
- package/build/esm/dev/utils/invocationContext.js +2 -2
- package/build/esm/dev/utils/invocationContext.js.map +1 -1
- package/build/esm/dev/vite/transform.js +40 -4
- package/build/esm/dev/vite/transform.js.map +1 -1
- package/build/esm/dev/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/dev/wrapRequestHandlerWithInit.js +16 -11
- package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/prod/client.js +18 -1
- package/build/esm/prod/client.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js +0 -3
- package/build/esm/prod/instrumentations/worker/instrumentScheduled.js.map +1 -1
- package/build/esm/prod/integrations/cronTriggers.js.map +1 -1
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/transport.js +8 -6
- package/build/esm/prod/transport.js.map +1 -1
- package/build/esm/prod/utils/invocationContext.js +2 -2
- package/build/esm/prod/utils/invocationContext.js.map +1 -1
- package/build/esm/prod/vite/transform.js +40 -4
- package/build/esm/prod/vite/transform.js.map +1 -1
- package/build/esm/prod/wrapMethodWithSentry.js.map +1 -1
- package/build/esm/prod/wrapRequestHandlerWithInit.js +16 -11
- package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/types/client.d.ts +35 -1
- package/build/types/client.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentScheduled.d.ts.map +1 -1
- package/build/types/integrations/cronTriggers.d.ts.map +1 -1
- package/build/types/transport.d.ts.map +1 -1
- package/build/types/utils/invocationContext.d.ts +3 -2
- package/build/types/utils/invocationContext.d.ts.map +1 -1
- package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
- package/package.json +8 -8
package/build/cjs/dev/client.js
CHANGED
|
@@ -5,6 +5,7 @@ const server = require('@sentry/core/server');
|
|
|
5
5
|
const debugBuild = require('./debug-build.js');
|
|
6
6
|
const invocationContext = require('./utils/invocationContext.js');
|
|
7
7
|
|
|
8
|
+
const SPAN_STREAMING_INTEGRATION_NAME = "SpanStreaming";
|
|
8
9
|
class CloudflareClient extends server.ServerRuntimeClient {
|
|
9
10
|
/**
|
|
10
11
|
* Creates a new Cloudflare SDK instance.
|
|
@@ -22,6 +23,9 @@ class CloudflareClient extends server.ServerRuntimeClient {
|
|
|
22
23
|
// TODO: Add server name
|
|
23
24
|
_flushInterval: 0
|
|
24
25
|
};
|
|
26
|
+
if ((typeof __SENTRY_TRACING__ === "undefined" || __SENTRY_TRACING__) && clientOptions.traceLifecycle !== "static" && !clientOptions.integrations.some((i) => i.name === SPAN_STREAMING_INTEGRATION_NAME)) {
|
|
27
|
+
clientOptions.integrations.push(core.spanStreamingIntegration({ flushOnSegmentEnd: false }));
|
|
28
|
+
}
|
|
25
29
|
super(clientOptions);
|
|
26
30
|
this._pendingSpans = /* @__PURE__ */ new Set();
|
|
27
31
|
this._spanCompletionPromise = null;
|
|
@@ -100,6 +104,19 @@ class CloudflareClient extends server.ServerRuntimeClient {
|
|
|
100
104
|
this._inBoundaryFlush = false;
|
|
101
105
|
}
|
|
102
106
|
}
|
|
107
|
+
/**
|
|
108
|
+
* Sends the check-in at once instead of holding it for the flush at the end of the invocation.
|
|
109
|
+
* An `in_progress` check-in of a run that is longer than the check-in margin would otherwise
|
|
110
|
+
* reach Sentry too late, and Sentry would mark the run as missed.
|
|
111
|
+
*/
|
|
112
|
+
captureCheckIn(checkIn, monitorConfig, scope) {
|
|
113
|
+
const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);
|
|
114
|
+
const transport = this.getTransport();
|
|
115
|
+
if (transport) {
|
|
116
|
+
this._registerWithInvocationWaitUntil(transport.flush(2e3));
|
|
117
|
+
}
|
|
118
|
+
return checkInId;
|
|
119
|
+
}
|
|
103
120
|
/**
|
|
104
121
|
* Disposes of the client and releases all resources.
|
|
105
122
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { ClientOptions, Options, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAuBO,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,EAAC;AAC1C,IAAA,MAAM,EAAE,SAAA,EAAW,GAAG,aAAA,EAAc,GAAI,OAAA;AAExC,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,aAAA;AAAA,MACH,QAAA,EAAU,YAAA;AAAA;AAAA,MAEV,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA;AAAA,MAE9B,cAAA,EAAgB;AAAA,KAClB;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AApCrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;AAC7C,I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G,sBAAsB,MAAM,IAAA,CAAK,YAAY,MAAMC,iCAAA,CAA6B,IAAI,CAAC,CAAC,CAAA;AAAA,EAChG;AAAA;AAAA;AAAA;AAAA;AAAA,EAMQ,YAAY,KAAA,EAAyB;AAC3C,IAAA,MAAM,kBAAkBF,oCAAA,EAAmB;AAE3C,IAAA,IAAI,eAAA,IAAmB,CAAC,eAAA,CAAgB,iBAAA,EAAmB;AACzD,MAAA;AAAA,IACF;AAEA,IAAA,KAAA,EAAM;AAAA,EACR;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,EAQQ,iCAAiC,OAAA,EAAqC;AAC5E,IAAA,MAAM,kBAAkBA,oCAAA,EAAmB;AAC3C,IAAA,MAAM,SAAA,GAAY,eAAA,IAAmBG,wCAAA,CAAuB,eAAe,CAAA;AAC3E,IAAA,IAAI,CAAC,SAAA,EAAW;AACd,MAAA;AAAA,IACF;AAEA,IAAA,IAAI;AACF,MAAA,SAAA;AAAA,QACE,OAAA,CAAQ,OAAA,CAAQ,OAAO,CAAA,CAAE,IAAA;AAAA,UACvB,MAAM,KAAA,CAAA;AAAA,UACN,MAAM,KAAA;AAAA;AACR,OACF;AAAA,IACF,CAAA,CAAA,MAAQ;AAAA,IAER;AAAA,EACF;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"client.js","sources":["../../../src/client.ts"],"sourcesContent":["import type { CheckIn, ClientOptions, MonitorConfig, Options, Scope, TracePropagationTargets } from '@sentry/core';\nimport {\n _INTERNAL_clearAiProviderSkips,\n _INTERNAL_flushLogsBuffer,\n _INTERNAL_flushMetricsBuffer,\n applySdkMetadata,\n debug,\n spanIsSampled,\n spanStreamingIntegration,\n} from '@sentry/core';\nimport type { ServerRuntimeClientOptions } from '@sentry/core/server';\nimport { ServerRuntimeClient } from '@sentry/core/server';\nimport { DEBUG_BUILD } from './debug-build';\nimport type { ExecutionContextCompat } from './executionContext';\nimport type { makeFlushLock } from './flush';\nimport type { CloudflareTransportOptions } from './transport';\nimport { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext';\n\ndeclare const __SENTRY_TRACING__: boolean;\n\nconst SPAN_STREAMING_INTEGRATION_NAME = 'SpanStreaming';\n\n/**\n * The Sentry Cloudflare SDK Client.\n *\n * @see CloudflareClientOptions for documentation on configuration options.\n * @see ServerRuntimeClient for usage documentation.\n */\nexport class CloudflareClient extends ServerRuntimeClient {\n private readonly _flushLock: ReturnType<typeof makeFlushLock> | void;\n private _pendingSpans: Set<string> = new Set();\n private _spanCompletionPromise: Promise<void> | null = null;\n private _resolveSpanCompletion: (() => void) | null = null;\n\n private _unsubscribeSpanStart: (() => void) | null = null;\n private _unsubscribeSpanEnd: (() => void) | null = null;\n\n // True while a boundary `flush()` is draining; envelopes created by that drain ride it\n // and must not each start their own eager transport flush.\n private _inBoundaryFlush = false;\n\n /**\n * Whether this client is a cached, cross-invocation client (`cacheClient`).\n * Cached clients are never disposed at an invocation boundary, so their spans/events\n * are delivered eagerly instead of waiting for a per-invocation flush.\n */\n public readonly isCachedClient: boolean;\n\n /**\n * Creates a new Cloudflare SDK instance.\n * @param options Configuration options for this SDK.\n */\n public constructor(options: CloudflareClientOptions) {\n applySdkMetadata(options, 'cloudflare');\n options._metadata = options._metadata || {};\n const { flushLock, ...serverOptions } = options;\n\n const clientOptions: ServerRuntimeClientOptions = {\n ...serverOptions,\n platform: 'javascript',\n // TODO: Grab version information\n runtime: { name: 'cloudflare' },\n // TODO: Add server name\n _flushInterval: 0,\n };\n\n // workerd can't unref timers, so the default 500ms segment-end flush timer holds every\n // Durable Object invocation open (and billed) until it fires, sampled or not. The boundary\n // flush and the eager drain already deliver streamed spans here.\n if (\n (typeof __SENTRY_TRACING__ === 'undefined' || __SENTRY_TRACING__) &&\n clientOptions.traceLifecycle !== 'static' &&\n !clientOptions.integrations.some(i => i.name === SPAN_STREAMING_INTEGRATION_NAME)\n ) {\n clientOptions.integrations.push(spanStreamingIntegration({ flushOnSegmentEnd: false }));\n }\n\n super(clientOptions);\n this._flushLock = flushLock;\n this.isCachedClient = options.cacheClient === true;\n\n // Track span lifecycle to know when to flush. Skipped for cached clients\n // (`cacheClient`): they are never disposed, so spans that end after\n // a flush are still delivered. Per-invocation clients are disposed right after\n // the boundary flush, so the flush must wait for open spans to end otherwise\n // their transaction never gets emitted.\n if (!this.isCachedClient) {\n this._unsubscribeSpanStart = this.on('spanStart', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span started:', spanId);\n\n // Negatively sampled spans never emit spanEnd,\n // so tracking them would cause _pendingSpans to grow unboundedly.\n // We should fix the inconsistent behavior for NonRecordingSpans in the future but\n // for now, we just ignore them.\n if (!spanIsSampled(span)) {\n return;\n }\n\n this._pendingSpans.add(spanId);\n\n if (!this._spanCompletionPromise) {\n this._spanCompletionPromise = new Promise(resolve => {\n this._resolveSpanCompletion = resolve;\n });\n }\n });\n\n this._unsubscribeSpanEnd = this.on('spanEnd', span => {\n const spanId = span.spanContext().spanId;\n DEBUG_BUILD && debug.log('[CloudflareClient] Span ended:', spanId);\n this._pendingSpans.delete(spanId);\n\n // If no more pending spans, resolve the completion promise\n if (this._pendingSpans.size === 0 && this._resolveSpanCompletion) {\n DEBUG_BUILD && debug.log('[CloudflareClient] All spans completed, preparing to flush');\n this._resolveSpanCompletion();\n this._resetSpanCompletionPromise();\n }\n });\n }\n }\n\n /**\n * Flushes pending operations and ensures all data is processed.\n *\n * Each phase waits at most `timeout`: the flush lock of a per-invocation client, pending spans, event\n * processing and the transport drain. So a flush can take a small multiple of `timeout`, which stays well\n * below Cloudflare's 30 second `waitUntil` limit for the timeouts the SDK uses. Sends still pending when\n * the drain times out are aborted.\n *\n * @param {number} [timeout] - Maximum time in milliseconds for each phase of the flush.\n * @return {Promise<boolean>} A promise that resolves to a boolean indicating whether the flush operation was successful.\n */\n public async flush(timeout?: number): Promise<boolean> {\n // Wait for user waitUntil-registered work to settle before draining, so events\n // captured in that work are still in the buffer. Without this the final flush\n // can drain (and the client be disposed) before background captures land.\n //\n // Only per-invocation clients (`cacheClient: false`) have a flush lock; remove this with them in v12.\n // The wait is bounded by `timeout` because a user `waitUntil` task that outlives the invocation\n // would otherwise keep the flush from draining until the runtime cancels it.\n if (this._flushLock) {\n let timer: ReturnType<typeof setTimeout> | undefined;\n await Promise.race([\n this._flushLock.finalize(),\n ...(timeout ? [new Promise<void>(resolve => (timer = setTimeout(resolve, timeout)))] : []),\n ]);\n clearTimeout(timer);\n }\n\n if (this._pendingSpans.size > 0 && this._spanCompletionPromise) {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Waiting for', this._pendingSpans.size, 'pending spans to complete...');\n\n const timeoutMs = timeout ?? 5000;\n const spanCompletionRace = Promise.race([\n this._spanCompletionPromise,\n new Promise(resolve =>\n setTimeout(() => {\n DEBUG_BUILD &&\n debug.log('[CloudflareClient] Span completion timeout after', timeoutMs, 'ms, flushing anyway');\n resolve(undefined);\n }, timeoutMs),\n ),\n ]);\n\n await spanCompletionRace;\n }\n\n // Envelopes created while this flush drains (log/metric/span buffers turning into\n // envelopes on the `flush` emit) ride its own transport drain; without the flag each\n // of them would also start an eager drain and a `waitUntil` registration.\n this._inBoundaryFlush = true;\n try {\n return await super.flush(timeout);\n } finally {\n this._inBoundaryFlush = false;\n }\n }\n\n /**\n * Sends the check-in at once instead of holding it for the flush at the end of the invocation.\n * An `in_progress` check-in of a run that is longer than the check-in margin would otherwise\n * reach Sentry too late, and Sentry would mark the run as missed.\n */\n public override captureCheckIn(checkIn: CheckIn, monitorConfig?: MonitorConfig, scope?: Scope): string {\n const checkInId = super.captureCheckIn(checkIn, monitorConfig, scope);\n const transport = this.getTransport();\n if (transport) {\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n }\n return checkInId;\n }\n\n /**\n * Disposes of the client and releases all resources.\n *\n * This method clears all Cloudflare-specific state in addition to the base client cleanup.\n * It unsubscribes from span lifecycle events and clears pending span tracking.\n *\n * Call this method after flushing to allow the client to be garbage collected.\n * After calling dispose(), the client should not be used anymore.\n */\n public override dispose(): void {\n DEBUG_BUILD && debug.log('[CloudflareClient] Disposing client...');\n\n super.dispose();\n\n if (this._unsubscribeSpanStart) {\n this._unsubscribeSpanStart();\n this._unsubscribeSpanStart = null;\n }\n if (this._unsubscribeSpanEnd) {\n this._unsubscribeSpanEnd();\n this._unsubscribeSpanEnd = null;\n }\n\n this._resetSpanCompletionPromise();\n (this as unknown as { _flushLock: ReturnType<typeof makeFlushLock> | void })._flushLock = undefined;\n }\n\n /** @inheritDoc */\n protected override _setupIntegrations(): void {\n // Clear AI provider skip registrations before setting up integrations.\n // The registry is module-global and Cloudflare calls `init()` per request, so without this a\n // single `ai` SDK call would suppress direct `env.AI.run` spans for the rest of the isolate's\n // life. Mirrors the same reset in the Node client.\n _INTERNAL_clearAiProviderSkips();\n super._setupIntegrations();\n\n // Registered after the integrations on purpose: the flush-point marker must run\n // after core and the span buffer have turned their buffers into envelopes on the\n // same `flush` emit (so those envelopes ride the boundary drain instead of starting\n // eager ones), and the eager span handler relies on `spanStreamingIntegration`\n // having already buffered the span that triggers it.\n if (this.isCachedClient) {\n // Marks the invocation's natural flush point: anything captured from now on\n // (post-response `waitUntil` work, detached continuations) has no later flush\n // to ride and is delivered eagerly by the hooks below.\n this.on('flush', () => {\n const invocationState = getInvocationState();\n if (invocationState) {\n invocationState.flushPointReached = true;\n }\n });\n this._setupEagerEnvelopeDelivery();\n this._setupEagerBufferDelivery();\n }\n }\n\n /**\n * Resets the span completion promise and resolve function.\n */\n private _resetSpanCompletionPromise(): void {\n this._pendingSpans.clear();\n this._spanCompletionPromise = null;\n this._resolveSpanCompletion = null;\n }\n\n /**\n * Drains the transport after an envelope has been accepted past the invocation's\n * flush point. The transport queues request producers until `flush()`; before the\n * flush point the boundary `flush()` drains everything, but envelopes created after\n * it (post-response `waitUntil` work, detached continuations) have no later flush to\n * ride. The drain is registered with the invocation's `waitUntil` to keep the fetch\n * alive; outside any instrumented invocation it always runs.\n */\n private _setupEagerEnvelopeDelivery(): void {\n this.on('afterEnvelope', () => {\n const transport = this.getTransport();\n const invocationState = getInvocationState();\n\n if (!transport || this._inBoundaryFlush || (invocationState && !invocationState.flushPointReached)) {\n return;\n }\n\n this._registerWithInvocationWaitUntil(transport.flush(2000));\n });\n }\n\n /**\n * Turns spans, logs and metrics captured past the invocation's flush point into\n * envelopes. Before the flush point the boundary `flush()` drains their buffers; after\n * it (or outside any instrumented invocation) nothing else would: the log/metric idle\n * timer is disabled for this runtime (`_flushInterval: 0`) and the span buffer's own 5s\n * timer fires outside any invocation, where the runtime suspends the send. Each capture\n * drains only its own bucket (the ended span's trace, the log buffer, the metric\n * buffer), so a fan-out of concurrent traces stays one envelope per trace. RPC method\n * spans never reach this path: `wrapMethodWithSentry` runs the boundary flush after the\n * method span has ended, so only work past that (e.g. detached continuations) lands here.\n */\n private _setupEagerBufferDelivery(): void {\n this.on('afterSpanEnd', span => {\n // The trace id must come from the span, not the current scope: `continueTrace`\n // writes the propagation context to the *current* scope, so the forked\n // isolation scope's propagation context carries a different trace id and\n // flushing by it silently no-ops.\n const traceId = span.spanContext().traceId;\n this._eagerDrain(() => this.emit('flushTraceSpans', traceId));\n });\n this.on('afterCaptureLog', () => this._eagerDrain(() => _INTERNAL_flushLogsBuffer(this)));\n this.on('afterCaptureMetric', () => this._eagerDrain(() => _INTERNAL_flushMetricsBuffer(this)));\n }\n\n /**\n * Runs `drain` unless the owning invocation has not reached its flush point yet\n * (before it the boundary `flush()` delivers the buffers).\n */\n private _eagerDrain(drain: () => void): void {\n const invocationState = getInvocationState();\n\n if (invocationState && !invocationState.flushPointReached) {\n return;\n }\n\n drain();\n }\n\n /**\n * Attaches a promise to the `waitUntil` of the invocation that owns the current\n * async context, so the runtime keeps the send alive after the response is returned.\n * Outside any instrumented invocation (or where the context has no `waitUntil`,\n * e.g. Astro prerendering) the send is fire-and-forget.\n */\n private _registerWithInvocationWaitUntil(promise: PromiseLike<unknown>): void {\n const invocationState = getInvocationState();\n const waitUntil = invocationState && getInvocationWaitUntil(invocationState);\n if (!waitUntil) {\n return;\n }\n\n try {\n waitUntil(\n Promise.resolve(promise).then(\n () => undefined,\n () => undefined,\n ),\n );\n } catch {\n // The owning invocation already ended; the send races isolate teardown either way.\n }\n }\n}\n\ninterface BaseCloudflareOptions {\n /**\n * @ignore Used internally to disable the deDupeIntegration for workflows.\n * @hidden Used internally to disable the deDupeIntegration for workflows.\n * @default true\n */\n enableDedupe?: boolean;\n\n /**\n * The Cloudflare SDK is not OpenTelemetry native. By default (`false`) it does not set up a tracer\n * provider; spans are emitted via the SDK's own instrumentation and scopes are isolated with\n * AsyncLocalStorage.\n *\n * Set this to `true` to opt into the OpenTelemetry compatibility tracer, which captures spans\n * emitted via `@opentelemetry/api`. Big caveat: it does not handle custom context, always working\n * off the current scope. This is good enough for many, but not all, integrations.\n *\n * @default false\n */\n enableOpenTelemetrySetup?: boolean;\n\n /**\n * The bindings on `env` that outgoing RPC calls propagate trace context to.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. An empty array\n * (the default) propagates to nothing.\n *\n * RPC has no headers to carry trace context, so the SDK appends it as a trailing argument to\n * every RPC method call on a matching binding. Only a Sentry-instrumented receiver strips that\n * argument again. Anywhere else it arrives as a real argument and changes what the method was\n * called with, so list only the bindings whose receiver you know runs Sentry.\n *\n * Propagation over `stub.fetch()` and service binding `fetch()` uses HTTP headers and is not\n * affected by this option.\n *\n * Strings match a binding name exactly, regular expressions match by pattern. Both match\n * case-insensitively.\n *\n * When you build with the Sentry Cloudflare Vite plugin, bindings that resolve to *this* worker\n * (its own Durable Objects, its self service bindings) are added for you, because the plugin\n * instruments those receivers itself. Whatever you list here is added on top of them.\n *\n * @default []\n * @example\n * ```ts\n * // Propagate to `env.ORDERS` and every `env.SVC_*` binding\n * export default Sentry.withSentry(\n * env => ({\n * dsn: env.SENTRY_DSN,\n * rpcTracePropagationBindings: ['ORDERS', /^SVC_/],\n * }),\n * handler,\n * );\n * ```\n */\n rpcTracePropagationBindings?: TracePropagationTargets;\n\n /**\n * Table names that should stay instrumented even though they match a reserved prefix used by\n * Durable Object frameworks for their internal SQLite tables: `cf_` (`agents`, `partyserver`, ...)\n * and `pi_` (pi-durable in the `PiHarness` of `agents`).\n *\n * By default, `exec` queries against tables with these prefixes are treated as framework noise and\n * no `db.query` span is created for them. If one of your own tables happens to use such a prefix,\n * add it here to opt it back into instrumentation, or add `/^pi_/` to see the statements of\n * pi-durable. Entries are matched against each table name in the\n * query summary — strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectSqlSpanAllowlist: ['cf_my_table', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectSqlSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * KV keys that should stay instrumented even though they match a reserved prefix used by Durable\n * Object frameworks (`agents`, `partyserver`, ...) for their internal storage entries.\n *\n * By default, KV reads/writes (`get`, `put`, `delete`, `list`) of `cf_`- or `__ps_`-prefixed keys\n * are treated as framework noise and no `durable_object_storage_*` span is created for them,\n * mirroring how `cf_`-prefixed SQL tables are handled (see {@link durableObjectSqlSpanAllowlist}).\n * If one of your own keys happens to use such a prefix, add it here to opt it back into\n * instrumentation. Strings must match exactly, while regular expressions give you prefix/pattern\n * matching.\n *\n * @default []\n * @example\n * ```ts\n * export default Sentry.withSentry(\n * (env) => ({\n * dsn: env.SENTRY_DSN,\n * durableObjectStorageSpanAllowlist: ['cf_my_key', /^cf_reports_/],\n * }),\n * handler,\n * );\n * ```\n */\n durableObjectStorageSpanAllowlist?: Array<string | RegExp>;\n\n /**\n * Sets an optional server name (device name).\n *\n * This is useful for identifying which server or instance is sending events.\n */\n serverName?: string;\n\n /**\n * If you use Spotlight by Sentry during development, use\n * this option to forward captured Sentry events to Spotlight.\n *\n * Either set it to true, or provide a specific Spotlight Sidecar URL.\n *\n * More details: https://spotlightjs.com/\n *\n * IMPORTANT: Only set this option to `true` while developing, not in production!\n */\n spotlight?: boolean | string;\n\n /**\n * Cache the client and reuse it across invocations within the same isolate.\n *\n * The SDK creates one client per isolate and reuses it for all requests/DO\n * handlers in that isolate. This avoids the per-invocation cost of\n * constructing a new client.\n *\n * Since a cached client outlives any single invocation, data captured after an\n * invocation's flush point (post-response `waitUntil` work, detached background\n * work) is delivered eagerly instead of waiting for a flush that never comes.\n *\n * The first `init()` in an isolate decides the cached client's options; later\n * `init()` calls with different options (e.g. another DSN) reuse the cached client\n * unchanged (a debug warning is logged for a DSN change). Use `cacheClient: false`\n * when options must differ per invocation.\n *\n * When disabled, a new client is created per invocation and disposed after the\n * handler completes.\n *\n * @default true\n */\n cacheClient?: boolean;\n\n /**\n * A function that receives the response of a `fetch` handler and the request it answers, and\n * returns whether the response body is still being produced after the handler returns.\n *\n * For `true`, the SDK keeps the `http.server` span open until the body has been sent, so spans\n * created while the body streams stay inside the request. It does this by passing the body through\n * a `TransformStream`. For `false`, the SDK ends the span when the handler returns and sends the\n * response unchanged. For `undefined` or any other value, the SDK decides: Server-Sent Events,\n * NDJSON and `application/stream+json` responses, and `text/plain` and `text/x-component`\n * responses without a `Content-Length` header count as streamed. HTML does not, so return `true`\n * for pages that are rendered with streamed SSR.\n *\n * The function must be synchronous and must not read the response body. Use the status, the\n * headers and the request URL.\n *\n * @example\n * ```ts\n * // src/instrument.server.ts\n * import { defineCloudflareOptions } from '@sentry/cloudflare';\n *\n * export default defineCloudflareOptions(env => ({\n * dsn: env.SENTRY_DSN,\n * isStreamingResponse: response =>\n * response.headers.get('content-type')?.startsWith('text/html') ? true : undefined,\n * }));\n * ```\n */\n isStreamingResponse?: (response: Response, request: Request) => boolean | undefined;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK\n *\n * @see @sentry/core Options for more information.\n */\nexport interface CloudflareOptions extends Options<CloudflareTransportOptions>, BaseCloudflareOptions {\n ctx?: ExecutionContextCompat;\n}\n\n/**\n * Configuration options for the Sentry Cloudflare SDK Client class\n *\n * @see CloudflareClient for more information.\n */\nexport interface CloudflareClientOptions extends ClientOptions<CloudflareTransportOptions>, BaseCloudflareOptions {\n flushLock?: ReturnType<typeof makeFlushLock>;\n}\n"],"names":["ServerRuntimeClient","applySdkMetadata","spanStreamingIntegration","DEBUG_BUILD","debug","spanIsSampled","_INTERNAL_clearAiProviderSkips","getInvocationState","_INTERNAL_flushLogsBuffer","_INTERNAL_flushMetricsBuffer","getInvocationWaitUntil"],"mappings":";;;;;;;AAoBA,MAAM,+BAAA,GAAkC,eAAA;AAQjC,MAAM,yBAAyBA,0BAAA,CAAoB;AAAA;AAAA;AAAA;AAAA;AAAA,EAwBjD,YAAY,OAAA,EAAkC;AACnD,IAAAC,qBAAA,CAAiB,SAAS,YAAY,CAAA;AACtC,IAAA,OAAA,CAAQ,SAAA,GAAY,OAAA,CAAQ,SAAA,IAAa,EAAC;AAC1C,IAAA,MAAM,EAAE,SAAA,EAAW,GAAG,aAAA,EAAc,GAAI,OAAA;AAExC,IAAA,MAAM,aAAA,GAA4C;AAAA,MAChD,GAAG,aAAA;AAAA,MACH,QAAA,EAAU,YAAA;AAAA;AAAA,MAEV,OAAA,EAAS,EAAE,IAAA,EAAM,YAAA,EAAa;AAAA;AAAA,MAE9B,cAAA,EAAgB;AAAA,KAClB;AAKA,IAAA,IAAA,CACG,OAAO,kBAAA,KAAuB,WAAA,IAAe,kBAAA,KAC9C,cAAc,cAAA,KAAmB,QAAA,IACjC,CAAC,aAAA,CAAc,aAAa,IAAA,CAAK,CAAA,CAAA,KAAK,CAAA,CAAE,IAAA,KAAS,+BAA+B,CAAA,EAChF;AACA,MAAA,aAAA,CAAc,aAAa,IAAA,CAAKC,6BAAA,CAAyB,EAAE,iBAAA,EAAmB,KAAA,EAAO,CAAC,CAAA;AAAA,IACxF;AAEA,IAAA,KAAA,CAAM,aAAa,CAAA;AA/CrB,IAAA,IAAA,CAAQ,aAAA,uBAAiC,GAAA,EAAI;AAC7C,IAAA,IAA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
let finishCheckIn;
|
|
42
42
|
try {
|
|
43
43
|
finishCheckIn = client?.getIntegrationByName("CronTriggers")?.startCheckIn(controller.cron);
|
|
44
|
-
if (finishCheckIn) {
|
|
45
|
-
waitUntil(Promise.resolve(client?.getTransport()?.flush(2e3)).catch(() => void 0));
|
|
46
|
-
}
|
|
47
44
|
} catch (e) {
|
|
48
45
|
debugBuild.DEBUG_BUILD && core.debug.warn("Failed to send the in_progress cron check-in", e);
|
|
49
46
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"instrumentScheduled.js","sources":["../../../../../src/instrumentations/worker/instrumentScheduled.ts"],"sourcesContent":["import type { ScheduledController } from '@cloudflare/workers-types';\nimport type { AnyExportedHandler } from '../../types';\nimport type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers';\nimport {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n FAAS_CRON,\n FAAS_TIME,\n FAAS_TRIGGER,\n SENTRY_DESCRIPTION,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport { captureException, debug, hasSpanStreamingEnabled, startSpan, withIsolationScope } from '@sentry/core';\nimport type { CloudflareOptions } from '../../client';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { flushAndDispose } from '../../flush';\nimport { ensureInstrumented } from '../../instrument';\nimport type { CronTriggersIntegration } from '../../integrations/cronTriggers';\nimport { getFinalOptions } from '../../options';\nimport { addCloudResourceContext } from '../../scope-utils';\nimport { init } from '../../sdk';\nimport { instrumentContext } from '../../utils/instrumentContext';\nimport { setInvocationState } from '../../utils/invocationContext';\nimport { instrumentEnv } from './instrumentEnv';\n\nfunction wrapScheduledHandler(\n controller: ScheduledController,\n options: CloudflareOptions,\n context: ExecutionContext,\n fn: () => unknown,\n): unknown {\n return withIsolationScope(isolationScope => {\n const waitUntil = context.waitUntil.bind(context);\n\n setInvocationState(isolationScope, { ctx: context });\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n const description = `Scheduled Cron ${controller.cron}`;\n\n return startSpan(\n {\n name: client && hasSpanStreamingEnabled(client) ? 'scheduled' : description,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n // override description inference by Relay to preserve the original (transaction-based) description.\n // sentry-conventions can't map the special case for the \"Scheduled Cron\" prefix and the chron string.\n [SENTRY_DESCRIPTION]: description,\n [CODE_FUNCTION_NAME]: 'scheduled',\n [FAAS_CRON]: controller.cron,\n [FAAS_TIME]: new Date(controller.scheduledTime).toISOString(),\n [FAAS_TRIGGER]: 'timer',\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async () => {\n let finishCheckIn: ReturnType<CronTriggersIntegration['startCheckIn']>;\n try {\n finishCheckIn = client\n ?.getIntegrationByName<CronTriggersIntegration>('CronTriggers')\n ?.startCheckIn(controller.cron);\n
|
|
1
|
+
{"version":3,"file":"instrumentScheduled.js","sources":["../../../../../src/instrumentations/worker/instrumentScheduled.ts"],"sourcesContent":["import type { ScheduledController } from '@cloudflare/workers-types';\nimport type { AnyExportedHandler } from '../../types';\nimport type { env as cloudflareEnv, WorkerEntrypoint } from 'cloudflare:workers';\nimport {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n FAAS_CRON,\n FAAS_TIME,\n FAAS_TRIGGER,\n SENTRY_DESCRIPTION,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport { captureException, debug, hasSpanStreamingEnabled, startSpan, withIsolationScope } from '@sentry/core';\nimport type { CloudflareOptions } from '../../client';\nimport { DEBUG_BUILD } from '../../debug-build';\nimport { flushAndDispose } from '../../flush';\nimport { ensureInstrumented } from '../../instrument';\nimport type { CronTriggersIntegration } from '../../integrations/cronTriggers';\nimport { getFinalOptions } from '../../options';\nimport { addCloudResourceContext } from '../../scope-utils';\nimport { init } from '../../sdk';\nimport { instrumentContext } from '../../utils/instrumentContext';\nimport { setInvocationState } from '../../utils/invocationContext';\nimport { instrumentEnv } from './instrumentEnv';\n\nfunction wrapScheduledHandler(\n controller: ScheduledController,\n options: CloudflareOptions,\n context: ExecutionContext,\n fn: () => unknown,\n): unknown {\n return withIsolationScope(isolationScope => {\n const waitUntil = context.waitUntil.bind(context);\n\n setInvocationState(isolationScope, { ctx: context });\n\n const client = init({ ...options, ctx: context });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n const description = `Scheduled Cron ${controller.cron}`;\n\n return startSpan(\n {\n name: client && hasSpanStreamingEnabled(client) ? 'scheduled' : description,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n // override description inference by Relay to preserve the original (transaction-based) description.\n // sentry-conventions can't map the special case for the \"Scheduled Cron\" prefix and the chron string.\n [SENTRY_DESCRIPTION]: description,\n [CODE_FUNCTION_NAME]: 'scheduled',\n [FAAS_CRON]: controller.cron,\n [FAAS_TIME]: new Date(controller.scheduledTime).toISOString(),\n [FAAS_TRIGGER]: 'timer',\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.scheduled',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async () => {\n let finishCheckIn: ReturnType<CronTriggersIntegration['startCheckIn']>;\n try {\n finishCheckIn = client\n ?.getIntegrationByName<CronTriggersIntegration>('CronTriggers')\n ?.startCheckIn(controller.cron);\n } catch (e) {\n DEBUG_BUILD && debug.warn('Failed to send the in_progress cron check-in', e);\n }\n\n const finish = (status: 'ok' | 'error'): void => {\n try {\n finishCheckIn?.(status);\n } catch (e) {\n DEBUG_BUILD && debug.warn(`Failed to send the ${status} cron check-in`, e);\n }\n };\n\n try {\n const result = await fn();\n finish('ok');\n return result;\n } catch (e) {\n finish('error');\n captureException(e, { mechanism: { handled: false, type: 'auto.faas.cloudflare.scheduled' } });\n throw e;\n } finally {\n waitUntil(flushAndDispose(client));\n }\n },\n );\n });\n}\n\n/**\n * Instruments a scheduled handler for ExportedHandler (env/ctx come from args).\n */\nexport function instrumentExportedHandlerScheduled<T extends AnyExportedHandler>(\n handler: T,\n optionsCallback: (env: typeof cloudflareEnv) => CloudflareOptions | undefined,\n): void {\n if (!('scheduled' in handler) || typeof handler.scheduled !== 'function') {\n return;\n }\n\n handler.scheduled = ensureInstrumented(\n handler.scheduled,\n original =>\n new Proxy(original, {\n apply(target, thisArg, args: Parameters<NonNullable<T['scheduled']>>) {\n const [controller, env, ctx] = args;\n const context = instrumentContext(ctx);\n const options = getFinalOptions(optionsCallback(env), env);\n args[1] = instrumentEnv(env, options);\n args[2] = context;\n\n return wrapScheduledHandler(controller, options, context, () => target.apply(thisArg, args));\n },\n }),\n );\n}\n\n/**\n * Instruments a scheduled method for WorkerEntrypoint (options/context already available).\n */\nexport function instrumentWorkerEntrypointScheduled<T extends WorkerEntrypoint>(\n instance: T,\n options: CloudflareOptions,\n context: ExecutionContext,\n): void {\n if (!instance.scheduled) {\n return;\n }\n\n const original = instance.scheduled.bind(instance);\n instance.scheduled = new Proxy(original, {\n apply(target, thisArg, args: [ScheduledController]) {\n const [controller] = args;\n\n return wrapScheduledHandler(controller, options, context, () => Reflect.apply(target, thisArg, args));\n },\n });\n}\n"],"names":["withIsolationScope","setInvocationState","init","addCloudResourceContext","startSpan","hasSpanStreamingEnabled","SENTRY_OP","FUNCTION","SENTRY_DESCRIPTION","CODE_FUNCTION_NAME","FAAS_CRON","FAAS_TIME","FAAS_TRIGGER","SENTRY_ORIGIN","SENTRY_SEGMENT_NAME_SOURCE","DEBUG_BUILD","debug","captureException","flushAndDispose","ensureInstrumented","instrumentContext","options","getFinalOptions","instrumentEnv"],"mappings":";;;;;;;;;;;;;;;AA2BA,SAAS,oBAAA,CACP,UAAA,EACA,OAAA,EACA,OAAA,EACA,EAAA,EACS;AACT,EAAA,OAAOA,wBAAmB,CAAA,c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CAAgB,eAAA,CAAgB,GAAG,GAAG,GAAG,CAAA;AACzD,QAAA,IAAA,CAAK,CAAC,CAAA,GAAIC,2BAAA,CAAc,GAAA,EAAKF,SAAO,CAAA;AACpC,QAAA,IAAA,CAAK,CAAC,CAAA,GAAI,OAAA;AAEV,QAAA,OAAO,oBAAA,CAAqB,YAAYA,SAAA,EAAS,OAAA,EAAS,MAAM,MAAA,CAAO,KAAA,CAAM,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,MAC7F;AAAA,KACD;AAAA,GACL;AACF;AAKO,SAAS,mCAAA,CACd,QAAA,EACA,OAAA,EACA,OAAA,EACM;AACN,EAAA,IAAI,CAAC,SAAS,SAAA,EAAW;AACvB,IAAA;AAAA,EACF;AAEA,EAAA,MAAM,QAAA,GAAW,QAAA,CAAS,SAAA,CAAU,IAAA,CAAK,QAAQ,CAAA;AACjD,EAAA,QAAA,CAAS,SAAA,GAAY,IAAI,KAAA,CAAM,QAAA,EAAU;AAAA,IACvC,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAA,EAA6B;AAClD,MAAA,MAAM,CAAC,UAAU,CAAA,GAAI,IAAA;AAErB,MAAA,OAAO,oBAAA,CAAqB,UAAA,EAAY,OAAA,EAAS,OAAA,EAAS,MAAM,QAAQ,KAAA,CAAM,MAAA,EAAQ,OAAA,EAAS,IAAI,CAAC,CAAA;AAAA,IACtG;AAAA,GACD,CAAA;AACH;;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"cronTriggers.js","sources":["../../../../src/integrations/cronTriggers.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { captureCheckIn, debug, defineIntegration, timestampInSeconds } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'CronTriggers' as const;\n\n/**\n * The monitor slug and settings for a Cron Trigger, see `cronTriggersIntegration`.\n */\nexport type CronTriggerMonitorSettings = { monitorSlug: string } & Omit<MonitorConfig, 'schedule' | 'timezone'>;\n\nexport interface CronTriggersOptions {\n /**\n * Chooses the monitor slug for a cron expression. It can also return an object with the `monitorSlug`\n * and other monitor settings, such as `checkinMargin` or `maxRuntime`. Returning `undefined`\n * sends no check-ins for that trigger, and so does a function that throws.\n */\n monitorSlug?: (cron: string) => string | CronTriggerMonitorSettings | undefined;\n}\n\n/** @internal Used by the scheduled handler instrumentation. */\nexport interface CronTriggersIntegration {\n name: string;\n startCheckIn(cron: string): ((status: 'ok' | 'error') => void) | undefined;\n}\n\nconst SLUG_TOKENS: Record<string, string> = { ' ': '-', '*': 'x', ',': '_', '-': 'to', '/': 'by' };\n\n/**\n * Derives a monitor slug from a cron expression, e.g. `30 9 * * MON-FRI` -> `cron-30-9-x-x-montofri`.\n *\n * A hash of the expression is appended when it has any other characters or the slug would be\n * longer than 50 characters, so different expressions don't share a slug.\n */\nfunction cronToMonitorSlug(cron: string): string {\n const expression = cron.trim().toLowerCase().split(/\\s+/).join(' ');\n const slug = `cron-${expression.replace(/[ *,\\-/]/g, char => SLUG_TOKENS[char] as string)}`;\n if (/^[a-z0-9_-]{1,50}$/.test(slug)) {\n return slug;\n }\n\n // A polynomial string hash modulo 2^31 - 1, at most 6 characters in base 36.\n let hash = 0;\n for (let i = 0; i < expression.length; i++) {\n hash = (hash * 31 + expression.charCodeAt(i)) % 2147483647;\n }\n return `${slug.replace(/[^a-z0-9_-]+/g, '-').slice(0, 43)}-${hash.toString(36)}`;\n}\n\nconst WEEKDAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];\n\n// Cloudflare numbers weekdays from 1 = Sunday to 7 = Saturday. Returns -1 for anything else.\nfunction weekdayIndex(value: string): number {\n return /^[1-7]$/.test(value) ? Number(value) - 1 : WEEKDAYS.indexOf(value.toUpperCase());\n}\n\nfunction convertWeekdayItem(item: string): string | undefined {\n const match = item.match(/^(\\*|\\w+)(?:-(\\w+))?(?:\\/(\\d+))?$/);\n if (!match) {\n return undefined;\n }\n const [, from, to, step] = match;\n if (step && !(Number(step) > 0)) {\n return undefined;\n }\n\n // `*` and `*/n` give the same days in both numberings, and keep their `*` meaning for Sentry.\n if (from === '*') {\n return to ? undefined : item;\n }\n\n const start = weekdayIndex(from as string);\n // A step without an end runs to Saturday, so it is written as a range.\n const end = to ? weekdayIndex(to) : step ? 6 : start;\n if (start < 0 || end < start) {\n return undefined;\n }\n\n // A step over a single day would run on to Sunday in Sentry's cron parser, so it is left out.\n if (start === end) {\n return WEEKDAYS[start];\n }\n const days = `${WEEKDAYS[start]}-${WEEKDAYS[end]}`;\n return step ? `${days}/${step}` : days;\n}\n\n/**\n * Converts a Cloudflare cron expression into a crontab Sentry accepts, which numbers weekdays from\n * 0 = Sunday. Returns `undefined` if the day fields can't be converted.\n */\nfunction cloudflareCronToCrontab(cron: string): string | undefined {\n const fields = cron.trim().split(/\\s+/);\n const [, , dayOfMonth = '', , dayOfWeek = ''] = fields;\n // Sentry rejects `W`, `?` and `L-n` in the day of month. When both day fields are set, Cloudflare and Sentry\n // run on the days that match either field, but Sentry requires both to match when one starts with `*`.\n if (\n fields.length !== 5 ||\n /[w?]|l-/i.test(dayOfMonth) ||\n (dayOfMonth !== '*' && dayOfWeek !== '*' && (dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*')))\n ) {\n return undefined;\n }\n\n const weekdays = dayOfWeek.split(',').map(convertWeekdayItem);\n return weekdays.includes(undefined) ? undefined : [...fields.slice(0, 4), weekdays.join(',')].join(' ');\n}\n\nconst _cronTriggersIntegration = ((options: CronTriggersOptions = {}): CronTriggersIntegration => {\n return {\n name: INTEGRATION_NAME,\n startCheckIn(cron) {\n // Manual runs, e.g. through `wrangler dev --test-scheduled`, can have no cron expression.\n if (!cron) {\n return undefined;\n }\n\n let monitor: string | CronTriggerMonitorSettings | undefined;\n try {\n monitor = options.monitorSlug ? options.monitorSlug(cron) : cronToMonitorSlug(cron);\n } catch (e) {\n DEBUG_BUILD && debug.warn(`[Cron Triggers] \\`monitorSlug\\` threw for \"${cron}\", sending no check-ins:`, e);\n return undefined;\n }\n\n if (!monitor) {\n return undefined;\n }\n\n const { monitorSlug, ...monitorSettings } = typeof monitor === 'string' ? { monitorSlug: monitor } : monitor;\n if (!monitorSlug) {\n return undefined;\n }\n\n const crontab = cloudflareCronToCrontab(cron);\n if (!crontab) {\n DEBUG_BUILD &&\n debug.warn(\n `[Cron Triggers] Can't convert \"${cron}\" to a Sentry schedule, sending check-ins without a schedule or the other monitor settings.`,\n );\n }\n\n // Check-ins are captured directly rather than through `withMonitor`, which would fork the\n // isolation scope and lose the invocation state attached to it.\n const checkInId = captureCheckIn(\n { monitorSlug, status: 'in_progress' },\n crontab ? { ...monitorSettings, schedule: { type: 'crontab', value: crontab } } : undefined,\n );\n const startTime = timestampInSeconds();\n\n return status => {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - startTime });\n };\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends cron check-ins for every Cron Trigger run of the `scheduled` handler, with the trigger's\n * schedule, so Sentry creates the monitor on the first run.\n *\n * Cron Triggers have no names, so map each cron expression to a slug. Without `monitorSlug`, the slug is\n * derived from the expression (`30 9 * * MON-FRI` becomes `cron-30-9-x-x-montofri`) and changes with it.\n * Workers that send to the same project get the same slug for the same expression, so they share a monitor.\n *\n * @example\n * ```ts\n * // src/monitorSlugs.ts\n * export const monitorSlugs: Record<string, string> = {\n * '30 9 * * MON-FRI': 'daily-report',\n * };\n *\n * // src/instrument.server.ts\n * import { cronTriggersIntegration, defineCloudflareOptions } from '@sentry/cloudflare';\n * import { monitorSlugs } from './monitorSlugs';\n *\n * export default defineCloudflareOptions((env) => ({\n * dsn: env.SENTRY_DSN,\n * integrations: [cronTriggersIntegration({ monitorSlug: (cron) => monitorSlugs[cron] })],\n * }));\n *\n * // src/index.ts\n * import { monitorSlugs } from './monitorSlugs';\n *\n * export default {\n * async scheduled(controller, env) {\n * switch (monitorSlugs[controller.cron]) {\n * case 'daily-report':\n * // ...\n * break;\n * }\n * },\n * };\n * ```\n */\nexport const cronTriggersIntegration = defineIntegration(_cronTriggersIntegration);\n"],"names":["DEBUG_BUILD","debug","captureCheckIn","timestampInSeconds","defineIntegration"],"mappings":";;;;;AAIA,MAAM,gBAAA,GAAmB,cAAA;AAsBzB,MAAM,WAAA,GAAsC,EAAE,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,IAAA,EAAK;AAQjG,SAAS,kBAAkB,IAAA,EAAsB;AAC/C,EAAA,MAAM,UAAA,GAAa,IAAA,CAAK,IAAA,EAAK,CAAE,WAAA,GAAc,KAAA,CAAM,KAAK,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAClE,EAAA,MAAM,IAAA,GAAO,QAAQ,UAAA,CAAW,OAAA,CAAQ,aAAa,CAAA,IAAA,KAAQ,WAAA,CAAY,IAAI,CAAW,CAAC,CAAA,CAAA;AACzF,EAAA,IAAI,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAA,EAAG;AACnC,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,UAAA,CAAW,QAAQ,CAAA,EAAA,EAAK;AAC1C,IAAA,IAAA,GAAA,CAAQ,IAAA,GAAO,EAAA,GAAK,UAAA,CAAW,UAAA,CAAW,CAAC,CAAA,IAAK,UAAA;AAAA,EAClD;AACA,EAAA,OAAO,CAAA,EAAG,IAAA,CAAK,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAChF;AAEA,MAAM,QAAA,GAAW,CAAC,KAAA,EAAO,KAAA,EAAO,OAA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AEA,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,OAAO,MAAA;AAAA,MACT;AAEA,MAAA,MAAM,EAAE,WAAA,EAAa,GAAG,eAAA,EAAgB,GAAI,OAAO,OAAA,KAAY,QAAA,GAAW,EAAE,WAAA,EAAa,OAAA,EAAQ,GAAI,OAAA;AACrG,MAAA,IAAI,CAAC,WAAA,EAAa;AAChB,QAAA,OAAO,MAAA;AAAA,MACT;AAEA,MAAA,MAAM,OAAA,GAAU,wBAAwB,IAAI,CAAA;AAC5C,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAAD,sBAAA,IACEC,UAAA,CAAM,IAAA;AAAA,UACJ,kCAAkC,IAAI,CAAA,2FAAA;AAAA,SACxC;AAAA,MACJ;AAIA,MAAA,MAAM,SAAA,GAAYC,mBAAA;AAAA,QAChB,EAAE,WAAA,EAAa,MAAA,EAAQ,aAAA,EAAc;AAAA,QACrC,OAAA,GAAU,EAAE,GAAG,eAAA,EAAiB,QAAA,EAAU,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,OAAA,EAAQ,EAAE,GAAI;AAAA,OACpF;AACA,MAAA,MAAM,YAAYC,uBAAA,EAAmB;AAErC,MAAA,OAAO,CAAA,MAAA,KAAU;AACf,QAAAD,mBAAA,CAAe,EAAE,aAAa,MAAA,EAAQ,SAAA,EAAW,UAAUC,uBAAA,EAAmB,GAAI,WAAW,CAAA;AAAA,MAC/F,CAAA;AAAA,IACF;AAAA,GACF;AACF,CAAA,CAAA;AAwCO,MAAM,uBAAA,GAA0BC,uBAAkB,wBAAwB;;;;"}
|
|
1
|
+
{"version":3,"file":"cronTriggers.js","sources":["../../../../src/integrations/cronTriggers.ts"],"sourcesContent":["import type { IntegrationFn, MonitorConfig } from '@sentry/core';\nimport { captureCheckIn, debug, defineIntegration, timestampInSeconds } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'CronTriggers' as const;\n\n/**\n * The monitor slug and settings for a Cron Trigger, see `cronTriggersIntegration`.\n */\nexport type CronTriggerMonitorSettings = { monitorSlug: string } & Omit<MonitorConfig, 'schedule' | 'timezone'>;\n\nexport interface CronTriggersOptions {\n /**\n * Chooses the monitor slug for a cron expression. It can also return an object with the `monitorSlug`\n * and other monitor settings, such as `checkinMargin` or `maxRuntime`. Returning `undefined`\n * sends no check-ins for that trigger, and so does a function that throws.\n */\n monitorSlug?: (cron: string) => string | CronTriggerMonitorSettings | undefined;\n}\n\n/** @internal Used by the scheduled handler instrumentation. */\nexport interface CronTriggersIntegration {\n name: string;\n startCheckIn(cron: string): ((status: 'ok' | 'error') => void) | undefined;\n}\n\nconst SLUG_TOKENS: Record<string, string> = { ' ': '-', '*': 'x', ',': '_', '-': 'to', '/': 'by' };\n\n/**\n * Derives a monitor slug from a cron expression, e.g. `30 9 * * MON-FRI` -> `cron-30-9-x-x-montofri`.\n *\n * A hash of the expression is appended when it has any other characters or the slug would be\n * longer than 50 characters, so different expressions don't share a slug.\n */\nfunction cronToMonitorSlug(cron: string): string {\n const expression = cron.trim().toLowerCase().split(/\\s+/).join(' ');\n const slug = `cron-${expression.replace(/[ *,\\-/]/g, char => SLUG_TOKENS[char] as string)}`;\n if (/^[a-z0-9_-]{1,50}$/.test(slug)) {\n return slug;\n }\n\n // A polynomial string hash modulo 2^31 - 1, at most 6 characters in base 36.\n let hash = 0;\n for (let i = 0; i < expression.length; i++) {\n hash = (hash * 31 + expression.charCodeAt(i)) % 2147483647;\n }\n return `${slug.replace(/[^a-z0-9_-]+/g, '-').slice(0, 43)}-${hash.toString(36)}`;\n}\n\nconst WEEKDAYS = ['SUN', 'MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT'];\n\n// Cloudflare numbers weekdays from 1 = Sunday to 7 = Saturday. Returns -1 for anything else.\nfunction weekdayIndex(value: string): number {\n return /^[1-7]$/.test(value) ? Number(value) - 1 : WEEKDAYS.indexOf(value.toUpperCase());\n}\n\nfunction convertWeekdayItem(item: string): string | undefined {\n const match = item.match(/^(\\*|\\w+)(?:-(\\w+))?(?:\\/(\\d+))?$/);\n if (!match) {\n return undefined;\n }\n const [, from, to, step] = match;\n if (step && !(Number(step) > 0)) {\n return undefined;\n }\n\n // `*` and `*/n` give the same days in both numberings, and keep their `*` meaning for Sentry.\n if (from === '*') {\n return to ? undefined : item;\n }\n\n const start = weekdayIndex(from as string);\n // A step without an end runs to Saturday, so it is written as a range.\n const end = to ? weekdayIndex(to) : step ? 6 : start;\n if (start < 0 || end < start) {\n return undefined;\n }\n\n // A step over a single day would run on to Sunday in Sentry's cron parser, so it is left out.\n if (start === end) {\n return WEEKDAYS[start];\n }\n const days = `${WEEKDAYS[start]}-${WEEKDAYS[end]}`;\n return step ? `${days}/${step}` : days;\n}\n\n/**\n * Converts a Cloudflare cron expression into a crontab Sentry accepts, which numbers weekdays from\n * 0 = Sunday. Returns `undefined` if the day fields can't be converted.\n */\nfunction cloudflareCronToCrontab(cron: string): string | undefined {\n const fields = cron.trim().split(/\\s+/);\n const [, , dayOfMonth = '', , dayOfWeek = ''] = fields;\n // Sentry rejects `W`, `?` and `L-n` in the day of month. When both day fields are set, Cloudflare and Sentry\n // run on the days that match either field, but Sentry requires both to match when one starts with `*`.\n if (\n fields.length !== 5 ||\n /[w?]|l-/i.test(dayOfMonth) ||\n (dayOfMonth !== '*' && dayOfWeek !== '*' && (dayOfMonth.startsWith('*') || dayOfWeek.startsWith('*')))\n ) {\n return undefined;\n }\n\n const weekdays = dayOfWeek.split(',').map(convertWeekdayItem);\n return weekdays.includes(undefined) ? undefined : [...fields.slice(0, 4), weekdays.join(',')].join(' ');\n}\n\nconst _cronTriggersIntegration = ((options: CronTriggersOptions = {}): CronTriggersIntegration => {\n return {\n name: INTEGRATION_NAME,\n startCheckIn(cron) {\n // Manual runs, e.g. through `wrangler dev --test-scheduled`, can have no cron expression.\n if (!cron) {\n return undefined;\n }\n\n let monitor: string | CronTriggerMonitorSettings | undefined;\n try {\n monitor = options.monitorSlug ? options.monitorSlug(cron) : cronToMonitorSlug(cron);\n } catch (e) {\n DEBUG_BUILD && debug.warn(`[Cron Triggers] \\`monitorSlug\\` threw for \"${cron}\", sending no check-ins:`, e);\n return undefined;\n }\n\n if (!monitor) {\n return undefined;\n }\n\n const { monitorSlug, ...monitorSettings } = typeof monitor === 'string' ? { monitorSlug: monitor } : monitor;\n if (!monitorSlug) {\n return undefined;\n }\n\n const crontab = cloudflareCronToCrontab(cron);\n if (!crontab) {\n DEBUG_BUILD &&\n debug.warn(\n `[Cron Triggers] Can't convert \"${cron}\" to a Sentry schedule, sending check-ins without a schedule or the other monitor settings.`,\n );\n }\n\n const checkInId = captureCheckIn(\n { monitorSlug, status: 'in_progress' },\n crontab ? { ...monitorSettings, schedule: { type: 'crontab', value: crontab } } : undefined,\n );\n const startTime = timestampInSeconds();\n\n return status => {\n captureCheckIn({ monitorSlug, status, checkInId, duration: timestampInSeconds() - startTime });\n };\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Sends cron check-ins for every Cron Trigger run of the `scheduled` handler, with the trigger's\n * schedule, so Sentry creates the monitor on the first run.\n *\n * Cron Triggers have no names, so map each cron expression to a slug. Without `monitorSlug`, the slug is\n * derived from the expression (`30 9 * * MON-FRI` becomes `cron-30-9-x-x-montofri`) and changes with it.\n * Workers that send to the same project get the same slug for the same expression, so they share a monitor.\n *\n * @example\n * ```ts\n * // src/monitorSlugs.ts\n * export const monitorSlugs: Record<string, string> = {\n * '30 9 * * MON-FRI': 'daily-report',\n * };\n *\n * // src/instrument.server.ts\n * import { cronTriggersIntegration, defineCloudflareOptions } from '@sentry/cloudflare';\n * import { monitorSlugs } from './monitorSlugs';\n *\n * export default defineCloudflareOptions((env) => ({\n * dsn: env.SENTRY_DSN,\n * integrations: [cronTriggersIntegration({ monitorSlug: (cron) => monitorSlugs[cron] })],\n * }));\n *\n * // src/index.ts\n * import { monitorSlugs } from './monitorSlugs';\n *\n * export default {\n * async scheduled(controller, env) {\n * switch (monitorSlugs[controller.cron]) {\n * case 'daily-report':\n * // ...\n * break;\n * }\n * },\n * };\n * ```\n */\nexport const cronTriggersIntegration = defineIntegration(_cronTriggersIntegration);\n"],"names":["DEBUG_BUILD","debug","captureCheckIn","timestampInSeconds","defineIntegration"],"mappings":";;;;;AAIA,MAAM,gBAAA,GAAmB,cAAA;AAsBzB,MAAM,WAAA,GAAsC,EAAE,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,IAAA,EAAK;AAQjG,SAAS,kBAAkB,IAAA,EAAsB;AAC/C,EAAA,MAAM,UAAA,GAAa,IAAA,CAAK,IAAA,EAAK,CAAE,WAAA,GAAc,KAAA,CAAM,KAAK,CAAA,CAAE,IAAA,CAAK,GAAG,CAAA;AAClE,EAAA,MAAM,IAAA,GAAO,QAAQ,UAAA,CAAW,OAAA,CAAQ,aAAa,CAAA,IAAA,KAAQ,WAAA,CAAY,IAAI,CAAW,CAAC,CAAA,CAAA;AACzF,EAAA,IAAI,oBAAA,CAAqB,IAAA,CAAK,IAAI,CAAA,EAAG;AACnC,IAAA,OAAO,IAAA;AAAA,EACT;AAGA,EAAA,IAAI,IAAA,GAAO,CAAA;AACX,EAAA,KAAA,IAAS,CAAA,GAAI,CAAA,EAAG,CAAA,GAAI,UAAA,CAAW,QAAQ,CAAA,EAAA,EAAK;AAC1C,IAAA,IAAA,GAAA,CAAQ,IAAA,GAAO,EAAA,GAAK,UAAA,CAAW,UAAA,CAAW,CAAC,CAAA,IAAK,UAAA;AAAA,EAClD;AACA,EAAA,OAAO,CAAA,EAAG,IAAA,CAAK,OAAA,CAAQ,eAAA,EAAiB,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,EAAE,CAAC,CAAA,CAAA,EAAI,IAAA,CAAK,QAAA,CAAS,EAAE,CAAC,CAAA,CAAA;AAChF;AAEA,MAAM,QAAA,GAAW,CAAC,KAAA,EAAO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AAA;AAAA,MACT;AAEA,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAA,OAAO,MAAA;AAAA,MACT;AAEA,MAAA,MAAM,EAAE,WAAA,EAAa,GAAG,eAAA,EAAgB,GAAI,OAAO,OAAA,KAAY,QAAA,GAAW,EAAE,WAAA,EAAa,OAAA,EAAQ,GAAI,OAAA;AACrG,MAAA,IAAI,CAAC,WAAA,EAAa;AAChB,QAAA,OAAO,MAAA;AAAA,MACT;AAEA,MAAA,MAAM,OAAA,GAAU,wBAAwB,IAAI,CAAA;AAC5C,MAAA,IAAI,CAAC,OAAA,EAAS;AACZ,QAAAD,sBAAA,IACEC,UAAA,CAAM,IAAA;AAAA,UACJ,kCAAkC,IAAI,CAAA,2FAAA;AAAA,SACxC;AAAA,MACJ;AAEA,MAAA,MAAM,SAAA,GAAYC,mBAAA;AAAA,QAChB,EAAE,WAAA,EAAa,MAAA,EAAQ,aAAA,EAAc;AAAA,QACrC,OAAA,GAAU,EAAE,GAAG,eAAA,EAAiB,QAAA,EAAU,EAAE,IAAA,EAAM,SAAA,EAAW,KAAA,EAAO,OAAA,EAAQ,EAAE,GAAI;AAAA,OACpF;AACA,MAAA,MAAM,YAAYC,uBAAA,EAAmB;AAErC,MAAA,OAAO,CAAA,MAAA,KAAU;AACf,QAAAD,mBAAA,CAAe,EAAE,aAAa,MAAA,EAAQ,SAAA,EAAW,UAAUC,uBAAA,EAAmB,GAAI,WAAW,CAAA;AAAA,MAC/F,CAAA;AAAA,IACF;AAAA,GACF;AACF,CAAA,CAAA;AAwCO,MAAM,uBAAA,GAA0BC,uBAAkB,wBAAwB;;;;"}
|
|
@@ -27,12 +27,14 @@ class IsolatedPromiseBuffer {
|
|
|
27
27
|
this._taskProducers = [];
|
|
28
28
|
const drainController = new AbortController();
|
|
29
29
|
this.drainSignal = drainController.signal;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
30
|
+
const tasks = oldTaskProducers.map((taskProducer) => {
|
|
31
|
+
try {
|
|
32
|
+
return taskProducer();
|
|
33
|
+
} catch (error) {
|
|
34
|
+
return Promise.reject(error);
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
this.drainSignal = void 0;
|
|
36
38
|
return new Promise((resolve) => {
|
|
37
39
|
const timer = setTimeout(() => {
|
|
38
40
|
if (timeout && timeout > 0) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"transport.js","sources":["../../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\n/**\n * How many payloads the buffer holds before it starts rejecting new ones.\n *\n * With `cacheClient` a single client is reused across an isolate's invocations, so one buffer now has to absorb\n * the payloads of many invocations rather than one. 256 is the size that held up under load testing that scenario.\n */\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 256;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n /**\n * Abort signal of the drain that is starting its requests. It is set only while `drain()` runs the task\n * producers, so a request reads the signal of the drain that sends it.\n */\n public drainSignal: AbortSignal | undefined;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n const drainController = new AbortController();\n this.drainSignal = drainController.signal;\n
|
|
1
|
+
{"version":3,"file":"transport.js","sources":["../../../src/transport.ts"],"sourcesContent":["import type { BaseTransportOptions, Transport, TransportMakeRequestResponse, TransportRequest } from '@sentry/core';\nimport { createTransport, SENTRY_BUFFER_FULL_ERROR, suppressTracing } from '@sentry/core';\n\nexport interface CloudflareTransportOptions extends BaseTransportOptions {\n /** Custom fetch function to use. This allows usage of things like Workers VPC */\n fetch?: typeof fetch;\n /** Fetch API init parameters. */\n fetchOptions?: RequestInit;\n}\n\n/**\n * How many payloads the buffer holds before it starts rejecting new ones.\n *\n * With `cacheClient` a single client is reused across an isolate's invocations, so one buffer now has to absorb\n * the payloads of many invocations rather than one. 256 is the size that held up under load testing that scenario.\n */\nconst DEFAULT_TRANSPORT_BUFFER_SIZE = 256;\n\n/**\n * This is a modified promise buffer that collects tasks until drain is called.\n * We need this in the edge runtime because edge function invocations may not share I/O objects, like fetch requests\n * and responses, and the normal PromiseBuffer inherently buffers stuff inbetween incoming requests.\n *\n * A limitation we need to be aware of is that DEFAULT_TRANSPORT_BUFFER_SIZE is the maximum amount of payloads the\n * SDK can send for a given edge function invocation.\n */\nexport class IsolatedPromiseBuffer {\n // We just have this field because the promise buffer interface requires it.\n // If we ever remove it from the interface we should also remove it here.\n public $: Array<PromiseLike<TransportMakeRequestResponse>>;\n\n /**\n * Abort signal of the drain that is starting its requests. It is set only while `drain()` runs the task\n * producers, so a request reads the signal of the drain that sends it.\n */\n public drainSignal: AbortSignal | undefined;\n\n private _taskProducers: (() => PromiseLike<TransportMakeRequestResponse>)[];\n\n private readonly _bufferSize: number;\n\n public constructor(_bufferSize = DEFAULT_TRANSPORT_BUFFER_SIZE) {\n this.$ = [];\n this._taskProducers = [];\n this._bufferSize = _bufferSize;\n }\n\n /**\n * @inheritdoc\n */\n public add(taskProducer: () => PromiseLike<TransportMakeRequestResponse>): PromiseLike<TransportMakeRequestResponse> {\n if (this._taskProducers.length >= this._bufferSize) {\n return Promise.reject(SENTRY_BUFFER_FULL_ERROR);\n }\n\n this._taskProducers.push(taskProducer);\n return Promise.resolve({});\n }\n\n /**\n * @inheritdoc\n */\n public drain(timeout?: number): PromiseLike<boolean> {\n const oldTaskProducers = [...this._taskProducers];\n this._taskProducers = [];\n\n const drainController = new AbortController();\n this.drainSignal = drainController.signal;\n const tasks = oldTaskProducers.map(taskProducer => {\n // A request that throws synchronously, such as a custom `fetch`, must not stop the other requests\n // or throw into the caller.\n try {\n return taskProducer();\n } catch (error) {\n return Promise.reject(error);\n }\n });\n this.drainSignal = undefined;\n\n return new Promise(resolve => {\n const timer = setTimeout(() => {\n if (timeout && timeout > 0) {\n // Requests still pending when the drain times out are aborted. Otherwise Cloudflare keeps them\n // until it cancels the invocation's `waitUntil` work and logs a warning.\n drainController.abort();\n resolve(false);\n }\n }, timeout);\n\n // This cannot reject\n // eslint-disable-next-line @typescript-eslint/no-floating-promises\n Promise.all(\n tasks.map(task =>\n task.then(null, () => {\n // catch all failed requests\n }),\n ),\n ).then(() => {\n // resolve to true if all fetch requests settled\n clearTimeout(timer);\n resolve(true);\n });\n });\n }\n}\n\n/**\n * Creates a Transport that uses the native fetch API to send events to Sentry.\n */\nexport function makeCloudflareTransport(options: CloudflareTransportOptions): Transport {\n const buffer = new IsolatedPromiseBuffer(options.bufferSize);\n\n function makeRequest(request: TransportRequest): PromiseLike<TransportMakeRequestResponse> {\n const drainSignal = buffer.drainSignal;\n const callerSignal = options.fetchOptions?.signal ?? undefined;\n const signal =\n drainSignal && callerSignal ? AbortSignal.any([drainSignal, callerSignal]) : (drainSignal ?? callerSignal);\n\n const requestOptions: RequestInit = {\n body: request.body as BodyInit,\n method: 'POST',\n headers: options.headers,\n ...options.fetchOptions,\n ...(signal ? { signal } : {}),\n };\n\n return suppressTracing(() => {\n return (options.fetch ?? fetch)(options.url, requestOptions).then(async response => {\n // Consume the response body to satisfy Cloudflare Workers' fetch requirements.\n // The runtime requires all fetch response bodies to be read or explicitly canceled\n // to prevent connection stalls and potential deadlocks. We read the body as text\n // even though we don't use the content, as Sentry's response information is in the headers.\n // See: https://github.com/getsentry/sentry-javascript/issues/18534\n try {\n await response.text();\n } catch {\n // no-op\n }\n\n return {\n statusCode: response.status,\n headers: {\n 'x-sentry-rate-limits': response.headers.get('X-Sentry-Rate-Limits'),\n 'retry-after': response.headers.get('Retry-After'),\n },\n };\n });\n });\n }\n\n return createTransport(options, makeRequest, buffer);\n}\n"],"names":["SENTRY_BUFFER_FULL_ERROR","suppressTracing","createTransport"],"mappings":";;;;AAgBA,MAAM,6BAAA,GAAgC,GAAA;AAU/B,MAAM,qBAAA,CAAsB;AAAA,EAe1B,WAAA,CAAY,cAAc,6BAAA,EAA+B;AAC9D,IAAA,IAAA,CAAK,IAAI,EAAC;AACV,IAAA,IAAA,CAAK,iBAAiB,EAAC;AACvB,IAAA,IAAA,CAAK,WAAA,GAAc,WAAA;AAAA,EACrB;AAAA;AAAA;AAAA;AAAA,EAKO,IAAI,YAAA,EAA0G;AACnH,IAAA,IAAI,IAAA,CAAK,cAAA,CAAe,MAAA,IAAU,IAAA,CAAK,WAAA,EAAa;AAClD,MAAA,OAAO,OAAA,CAAQ,OAAOA,6BAAwB,CAAA;AAAA,IAChD;AAEA,IAAA,IAAA,CAAK,cAAA,CAAe,KAAK,YAAY,CAAA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@@ -25,14 +25,14 @@ function setInvocationState(scope, state) {
|
|
|
25
25
|
);
|
|
26
26
|
return;
|
|
27
27
|
}
|
|
28
|
-
scope[INVOCATION_STATE] = state;
|
|
28
|
+
scope.refs[INVOCATION_STATE] = state;
|
|
29
29
|
}
|
|
30
30
|
function getInvocationState() {
|
|
31
31
|
const isolationScope = core.getIsolationScope();
|
|
32
32
|
if (isolationScope === core.getDefaultIsolationScope()) {
|
|
33
33
|
return void 0;
|
|
34
34
|
}
|
|
35
|
-
return isolationScope[INVOCATION_STATE];
|
|
35
|
+
return isolationScope.refs[INVOCATION_STATE];
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
exports.getInvocationState = getInvocationState;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"invocationContext.js","sources":["../../../../src/utils/invocationContext.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { debug, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { getOriginalWaitUntil } from '../flush';\n\n/**\n * State owned by a single invocation (request, RPC call, cron, ...).\n *\n * A cached client (`cacheClient`) is shared by all invocations running in the same\n * isolate, so anything invocation-owned must not live on the client: two overlapping\n * requests would otherwise overwrite each other's state (e.g. the execution context\n * used to register eager flushes) and the earlier invocation's envelopes would be\n * suspended when the later invocation ends.\n *\n * The state rides on the invocation's forked isolation scope, which the async\n * context strategy (AsyncLocalStorage) hands back for exactly the async context that\n * owns the invocation — including detached continuations created inside it.
|
|
1
|
+
{"version":3,"file":"invocationContext.js","sources":["../../../../src/utils/invocationContext.ts"],"sourcesContent":["import type { ExecutionContext } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\nimport { debug, getDefaultIsolationScope, getIsolationScope } from '@sentry/core';\nimport { DEBUG_BUILD } from '../debug-build';\nimport type { ExecutionContextCompat } from '../executionContext';\nimport { getOriginalWaitUntil } from '../flush';\n\n/**\n * State owned by a single invocation (request, RPC call, cron, ...).\n *\n * A cached client (`cacheClient`) is shared by all invocations running in the same\n * isolate, so anything invocation-owned must not live on the client: two overlapping\n * requests would otherwise overwrite each other's state (e.g. the execution context\n * used to register eager flushes) and the earlier invocation's envelopes would be\n * suspended when the later invocation ends.\n *\n * The state rides on the invocation's forked isolation scope, which the async\n * context strategy (AsyncLocalStorage) hands back for exactly the async context that\n * owns the invocation — including detached continuations created inside it. It lives under\n * a symbol key in the scope's `refs`, so isolation scopes forked inside the invocation\n * (`withMonitor`, `withIsolationScope`) share it, and it stays out of serialized event data.\n */\nexport interface InvocationState {\n /**\n * The execution context of the invocation that owns this scope. Eager envelope\n * sends are registered with this context's `waitUntil`, so they are attributed to\n * the invocation that captured the data even when invocations overlap.\n */\n readonly ctx: ExecutionContextCompat | undefined;\n /**\n * Set on the client's `flush` hook, the invocation's natural flush point.\n * Captures before it are drained by that flush; captures after it (in\n * `waitUntil` work or detached continuations) have no later flush to ride and\n * are delivered eagerly.\n */\n flushPointReached?: boolean;\n /**\n * `ctx.waitUntil` resolved once for this invocation (see `getInvocationWaitUntil`).\n * `null` once resolved to \"no usable waitUntil\".\n */\n waitUntil?: ExecutionContext['waitUntil'] | null;\n}\n\nconst INVOCATION_STATE: unique symbol = Symbol('sentryInvocationState');\n\n/**\n * Returns the invocation's original (un-instrumented) `waitUntil`, bound to its context,\n * resolving it on first use and caching it on the state. Reading `ctx.waitUntil` on a\n * native `ExecutionContext`/`DurableObjectState` goes through the runtime's property\n * getter every time; one read per invocation is enough.\n */\nexport function getInvocationWaitUntil(state: InvocationState): ExecutionContext['waitUntil'] | undefined {\n if (state.waitUntil === undefined) {\n const ctx = state.ctx;\n let resolved: ExecutionContext['waitUntil'] | null = null;\n try {\n const original = ctx && getOriginalWaitUntil(ctx);\n resolved = original ? original.bind(ctx) : null;\n } catch {\n // Accessing `waitUntil` can throw on foreign or already-torn-down contexts.\n }\n state.waitUntil = resolved;\n }\n return state.waitUntil ?? undefined;\n}\n\ntype ScopeRefsWithInvocationState = Scope['refs'] & {\n [INVOCATION_STATE]?: InvocationState;\n};\n\n/**\n * Attaches invocation state to a forked isolation scope. Only meaningful on a scope\n * that outlives nothing but this invocation — never attach to the default isolation\n * scope, which is shared by every invocation in the isolate.\n */\nexport function setInvocationState(scope: Scope, state: InvocationState): void {\n if (scope === getDefaultIsolationScope()) {\n DEBUG_BUILD &&\n debug.warn(\n '[Sentry] Cannot track this invocation. Telemetry captured after the invocation ends may not be delivered.',\n );\n return;\n }\n\n (scope.refs as ScopeRefsWithInvocationState)[INVOCATION_STATE] = state;\n}\n\n/**\n * Returns the state of the invocation that owns the current async context, or\n * `undefined` outside any instrumented invocation (the default isolation scope is\n * shared, so state read from it could not be attributed to one invocation — and it\n * is never attached there in the first place).\n */\nexport function getInvocationState(): InvocationState | undefined {\n const isolationScope = getIsolationScope();\n if (isolationScope === getDefaultIsolationScope()) {\n return undefined;\n }\n return (isolationScope.refs as ScopeRefsWithInvocationState)[INVOCATION_STATE];\n}\n"],"names":["getOriginalWaitUntil","getDefaultIsolationScope","DEBUG_BUILD","debug","getIsolationScope"],"mappings":";;;;;;AA2CA,MAAM,gBAAA,0BAAyC,uBAAuB,CAAA;AAQ/D,SAAS,uBAAuB,KAAA,EAAmE;AACxG,EAAA,IAAI,KAAA,CAAM,cAAc,MAAA,EAAW;AACjC,IAAA,MAAM,MAAM,KAAA,CAAM,GAAA;AAClB,IAAA,IAAI,QAAA,GAAiD,IAAA;AACrD,IAAA,IAAI;AACF,MAAA,MAAM,QAAA,GAAW,GAAA,IAAOA,0BAAA,CAAqB,GAAG,CAAA;AAChD,MAAA,QAAA,GAAW,QAAA,GAAW,QAAA,CAAS,IAAA,CAAK,GAAG,CAAA,GAAI,IAAA;AAAA,IAC7C,CAAA,CAAA,MAAQ;AAAA,IAER;AACA,IAAA,KAAA,CAAM,SAAA,GAAY,QAAA;AAAA,EACpB;AACA,EAAA,OAAO,MAAM,SAAA,IAAa,MAAA;AAC5B;AAWO,SAAS,kBAAA,CAAmB,OAAc,KAAA,EAA8B;AAC7E,EAAA,IAAI,KAAA,KAAUC,+BAAyB,EAAG;AACxC,IAAAC,sBAAA,IACEC,UAAA,CAAM,IAAA;AAAA,MACJ;AAAA,KACF;AACF,IAAA;AAAA,EACF;AAEA,EAAC,KAAA,CAAM,IAAA,CAAsC,gBAAgB,CAAA,GAAI,KAAA;AACnE;AAQO,SAAS,kBAAA,GAAkD;AAChE,EAAA,MAAM,iBAAiBC,sBAAA,EAAkB;AACzC,EAAA,IAAI,cAAA,KAAmBH,+BAAyB,EAAG;AACjD,IAAA,OAAO,MAAA;AAAA,EACT;AACA,EAAA,OAAQ,cAAA,CAAe,KAAsC,gBAAgB,CAAA;AAC/E;;;;;;"}
|
|
@@ -136,13 +136,38 @@ function wrapDefaultExport(node, ctx, state) {
|
|
|
136
136
|
return;
|
|
137
137
|
}
|
|
138
138
|
}
|
|
139
|
-
|
|
139
|
+
const source = state.ms.original;
|
|
140
|
+
const keywordsEnd = node.start + source.slice(node.start, decl.start).lastIndexOf("default") + "default".length;
|
|
141
|
+
const declaredName = decl.type === "ClassDeclaration" || decl.type === "FunctionDeclaration" ? decl.id?.name : void 0;
|
|
142
|
+
let wrapped = "__SENTRY_DEFAULT_EXPORT__";
|
|
143
|
+
if (declaredName) {
|
|
144
|
+
state.ms.remove(node.start, decl.start);
|
|
145
|
+
state.ms.appendLeft(node.end, `
|
|
146
|
+
var __SENTRY_DEFAULT_EXPORT__ = ${declaredName};`);
|
|
147
|
+
wrapped = declaredName;
|
|
148
|
+
} else if (isAnonymousFunctionOrClass(decl)) {
|
|
149
|
+
const hasSemicolon = source[node.end - 1] === ";";
|
|
150
|
+
state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ = { default:");
|
|
151
|
+
state.ms.appendLeft(hasSemicolon ? node.end - 1 : node.end, hasSemicolon ? " }.default" : " }.default;");
|
|
152
|
+
} else {
|
|
153
|
+
state.ms.overwrite(node.start, keywordsEnd, "var __SENTRY_DEFAULT_EXPORT__ =");
|
|
154
|
+
}
|
|
155
|
+
state.ms.appendLeft(node.end, "\nexport { __SENTRY_DEFAULT_EXPORT__ as default };");
|
|
140
156
|
state.ms.append(`
|
|
141
|
-
|
|
142
|
-
`);
|
|
157
|
+
__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSentry(${state.optionsFn}, ${wrapped});`);
|
|
143
158
|
state.needsImport = true;
|
|
144
159
|
state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
|
|
145
160
|
}
|
|
161
|
+
function isAnonymousFunctionOrClass(node) {
|
|
162
|
+
if (node.type === "ArrowFunctionExpression") return true;
|
|
163
|
+
const isFunctionOrClass = [
|
|
164
|
+
"FunctionExpression",
|
|
165
|
+
"FunctionDeclaration",
|
|
166
|
+
"ClassExpression",
|
|
167
|
+
"ClassDeclaration"
|
|
168
|
+
].includes(node.type);
|
|
169
|
+
return isFunctionOrClass && !node.id;
|
|
170
|
+
}
|
|
146
171
|
function handleNamedExport(node, ctx, state) {
|
|
147
172
|
const decl = node.declaration;
|
|
148
173
|
if (decl?.type === "VariableDeclaration") {
|
|
@@ -235,13 +260,24 @@ ${declaringStatement ? "" : "var "}__SENTRY_DEFAULT_EXPORT__ = __SENTRY__.withSe
|
|
|
235
260
|
state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
|
|
236
261
|
return "__SENTRY_DEFAULT_EXPORT__ as default";
|
|
237
262
|
}
|
|
263
|
+
function wrapDefaultReexport(localName, sourceLiteral, state, prelude) {
|
|
264
|
+
const target = "__SENTRY_REEXPORT_default__";
|
|
265
|
+
prelude.push(
|
|
266
|
+
localName === DEFAULT_IMPORT ? `import ${target} from ${sourceLiteral};` : `import { ${localName} as ${target} } from ${sourceLiteral};`,
|
|
267
|
+
`const __SENTRY_DEFAULT_EXPORT__ = __SENTRY__._INTERNAL_wrapUnlessInstrumented(__SENTRY__.withSentry, ${state.optionsFn}, ${target});`
|
|
268
|
+
);
|
|
269
|
+
state.needsImport = true;
|
|
270
|
+
state.autoWrapped.add(wranglerConfig.DEFAULT_EXPORT);
|
|
271
|
+
return "__SENTRY_DEFAULT_EXPORT__ as default";
|
|
272
|
+
}
|
|
238
273
|
function wrapSpecifier(specifier, sourceLiteral, ctx, state, prelude) {
|
|
239
274
|
const exportedName = specifier.type === "ExportSpecifier" && specifier.exported?.type === "Identifier" ? specifier.exported.name : void 0;
|
|
240
275
|
const localName = specifier.local?.type === "Identifier" ? specifier.local.name : void 0;
|
|
241
276
|
const kind = exportedName ? resolveWrapperKind(exportedName, sourceLiteral ? void 0 : localName, state) : void 0;
|
|
242
277
|
if (!exportedName || !localName) return void 0;
|
|
243
278
|
if (!kind) {
|
|
244
|
-
|
|
279
|
+
if (exportedName !== DEFAULT_IMPORT) return void 0;
|
|
280
|
+
return sourceLiteral ? wrapDefaultReexport(localName, sourceLiteral, state, prelude) : wrapDefaultSpecifier(localName, state);
|
|
245
281
|
}
|
|
246
282
|
if (!sourceLiteral) {
|
|
247
283
|
const localClass = state.topLevelClasses.get(localName);
|