@sentry/cloudflare 11.10.0 → 11.12.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/baseSdk.js +4 -8
- package/build/cjs/dev/baseSdk.js.map +1 -1
- package/build/cjs/dev/client.js.map +1 -1
- package/build/cjs/dev/durableobject.js +20 -4
- package/build/cjs/dev/durableobject.js.map +1 -1
- package/build/cjs/dev/index.js +2 -1
- package/build/cjs/dev/index.js.map +1 -1
- package/build/cjs/dev/instrumentations/instrumentDurableObjectStorage.js +2 -2
- package/build/cjs/dev/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/cjs/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js +2 -2
- package/build/cjs/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
- package/build/cjs/dev/instrumentations/instrumentSqlStorage.js +5 -5
- package/build/cjs/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js +12 -12
- package/build/cjs/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentEnv.js +4 -3
- package/build/cjs/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentQueue.js +38 -7
- package/build/cjs/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js +44 -22
- package/build/cjs/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentR2.js +1 -1
- package/build/cjs/dev/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/cjs/dev/integrations/httpServer.js +15 -72
- package/build/cjs/dev/integrations/httpServer.js.map +1 -1
- package/build/cjs/dev/request.js.map +1 -1
- package/build/cjs/dev/scope-utils.js +2 -6
- package/build/cjs/dev/scope-utils.js.map +1 -1
- package/build/cjs/dev/sdk.js +2 -5
- package/build/cjs/dev/sdk.js.map +1 -1
- package/build/cjs/dev/utils/{rpcPropagation.js → bindingPropagation.js} +6 -3
- package/build/cjs/dev/utils/bindingPropagation.js.map +1 -0
- package/build/cjs/dev/utils/queueTraceMeta.js +44 -0
- package/build/cjs/dev/utils/queueTraceMeta.js.map +1 -0
- package/build/cjs/dev/vite/index.js +2 -1
- package/build/cjs/dev/vite/index.js.map +1 -1
- package/build/cjs/dev/workflows.js +9 -6
- package/build/cjs/dev/workflows.js.map +1 -1
- package/build/cjs/dev/wrapRequestHandlerWithInit.js +36 -110
- package/build/cjs/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/cjs/prod/baseSdk.js +4 -8
- package/build/cjs/prod/baseSdk.js.map +1 -1
- package/build/cjs/prod/client.js.map +1 -1
- package/build/cjs/prod/durableobject.js +20 -4
- package/build/cjs/prod/durableobject.js.map +1 -1
- package/build/cjs/prod/index.js +2 -1
- package/build/cjs/prod/index.js.map +1 -1
- package/build/cjs/prod/instrumentations/instrumentDurableObjectStorage.js +2 -2
- package/build/cjs/prod/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/cjs/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js +2 -2
- package/build/cjs/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
- package/build/cjs/prod/instrumentations/instrumentSqlStorage.js +5 -5
- package/build/cjs/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js +12 -12
- package/build/cjs/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentEnv.js +4 -3
- package/build/cjs/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentQueue.js +38 -7
- package/build/cjs/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js +44 -22
- package/build/cjs/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentR2.js +1 -1
- package/build/cjs/prod/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/cjs/prod/integrations/httpServer.js +15 -72
- package/build/cjs/prod/integrations/httpServer.js.map +1 -1
- package/build/cjs/prod/request.js.map +1 -1
- package/build/cjs/prod/scope-utils.js +2 -6
- package/build/cjs/prod/scope-utils.js.map +1 -1
- package/build/cjs/prod/sdk.js +2 -5
- package/build/cjs/prod/sdk.js.map +1 -1
- package/build/cjs/prod/utils/{rpcPropagation.js → bindingPropagation.js} +6 -3
- package/build/cjs/prod/utils/bindingPropagation.js.map +1 -0
- package/build/cjs/prod/utils/queueTraceMeta.js +44 -0
- package/build/cjs/prod/utils/queueTraceMeta.js.map +1 -0
- package/build/cjs/prod/vite/index.js +2 -1
- package/build/cjs/prod/vite/index.js.map +1 -1
- package/build/cjs/prod/workflows.js +9 -6
- package/build/cjs/prod/workflows.js.map +1 -1
- package/build/cjs/prod/wrapRequestHandlerWithInit.js +36 -110
- package/build/cjs/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/dev/baseSdk.js +4 -7
- package/build/esm/dev/baseSdk.js.map +1 -1
- package/build/esm/dev/client.js.map +1 -1
- package/build/esm/dev/durableobject.js +20 -4
- package/build/esm/dev/durableobject.js.map +1 -1
- package/build/esm/dev/index.js +2 -1
- package/build/esm/dev/index.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentDurableObjectStorage.js +3 -3
- package/build/esm/dev/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js +3 -3
- package/build/esm/dev/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
- package/build/esm/dev/instrumentations/instrumentSqlStorage.js +6 -6
- package/build/esm/dev/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentD1.js +13 -13
- package/build/esm/dev/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentEnv.js +3 -2
- package/build/esm/dev/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentQueue.js +39 -8
- package/build/esm/dev/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js +46 -24
- package/build/esm/dev/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentR2.js +1 -1
- package/build/esm/dev/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/esm/dev/integrations/httpServer.js +16 -71
- package/build/esm/dev/integrations/httpServer.js.map +1 -1
- package/build/esm/dev/package.json +1 -1
- package/build/esm/dev/request.js.map +1 -1
- package/build/esm/dev/scope-utils.js +3 -6
- package/build/esm/dev/scope-utils.js.map +1 -1
- package/build/esm/dev/sdk.js +4 -6
- package/build/esm/dev/sdk.js.map +1 -1
- package/build/esm/dev/utils/{rpcPropagation.js → bindingPropagation.js} +6 -4
- package/build/esm/dev/utils/bindingPropagation.js.map +1 -0
- package/build/esm/dev/utils/queueTraceMeta.js +41 -0
- package/build/esm/dev/utils/queueTraceMeta.js.map +1 -0
- package/build/esm/dev/vite/index.js +2 -1
- package/build/esm/dev/vite/index.js.map +1 -1
- package/build/esm/dev/workflows.js +11 -8
- package/build/esm/dev/workflows.js.map +1 -1
- package/build/esm/dev/wrapRequestHandlerWithInit.js +41 -115
- package/build/esm/dev/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/esm/prod/baseSdk.js +4 -7
- package/build/esm/prod/baseSdk.js.map +1 -1
- package/build/esm/prod/client.js.map +1 -1
- package/build/esm/prod/durableobject.js +20 -4
- package/build/esm/prod/durableobject.js.map +1 -1
- package/build/esm/prod/index.js +2 -1
- package/build/esm/prod/index.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentDurableObjectStorage.js +3 -3
- package/build/esm/prod/instrumentations/instrumentDurableObjectStorage.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js +3 -3
- package/build/esm/prod/instrumentations/instrumentDurableObjectSyncKvStorage.js.map +1 -1
- package/build/esm/prod/instrumentations/instrumentSqlStorage.js +6 -6
- package/build/esm/prod/instrumentations/instrumentSqlStorage.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentD1.js +13 -13
- package/build/esm/prod/instrumentations/worker/instrumentD1.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentEnv.js +3 -2
- package/build/esm/prod/instrumentations/worker/instrumentEnv.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentQueue.js +39 -8
- package/build/esm/prod/instrumentations/worker/instrumentQueue.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js +46 -24
- package/build/esm/prod/instrumentations/worker/instrumentQueueProducer.js.map +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentR2.js +1 -1
- package/build/esm/prod/instrumentations/worker/instrumentR2.js.map +1 -1
- package/build/esm/prod/integrations/httpServer.js +16 -71
- package/build/esm/prod/integrations/httpServer.js.map +1 -1
- package/build/esm/prod/package.json +1 -1
- package/build/esm/prod/request.js.map +1 -1
- package/build/esm/prod/scope-utils.js +3 -6
- package/build/esm/prod/scope-utils.js.map +1 -1
- package/build/esm/prod/sdk.js +4 -6
- package/build/esm/prod/sdk.js.map +1 -1
- package/build/esm/prod/utils/{rpcPropagation.js → bindingPropagation.js} +6 -4
- package/build/esm/prod/utils/bindingPropagation.js.map +1 -0
- package/build/esm/prod/utils/queueTraceMeta.js +41 -0
- package/build/esm/prod/utils/queueTraceMeta.js.map +1 -0
- package/build/esm/prod/vite/index.js +2 -1
- package/build/esm/prod/vite/index.js.map +1 -1
- package/build/esm/prod/workflows.js +11 -8
- package/build/esm/prod/workflows.js.map +1 -1
- package/build/esm/prod/wrapRequestHandlerWithInit.js +41 -115
- package/build/esm/prod/wrapRequestHandlerWithInit.js.map +1 -1
- package/build/types/baseSdk.d.ts +6 -18
- package/build/types/baseSdk.d.ts.map +1 -1
- package/build/types/client.d.ts +30 -0
- package/build/types/client.d.ts.map +1 -1
- package/build/types/durableobject.d.ts.map +1 -1
- package/build/types/instrumentations/instrumentSqlStorage.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentD1.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentEnv.d.ts +1 -1
- package/build/types/instrumentations/worker/instrumentEnv.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentQueue.d.ts.map +1 -1
- package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts +1 -1
- package/build/types/instrumentations/worker/instrumentQueueProducer.d.ts.map +1 -1
- package/build/types/integrations/httpServer.d.ts +9 -20
- package/build/types/integrations/httpServer.d.ts.map +1 -1
- package/build/types/request.d.ts +3 -4
- package/build/types/request.d.ts.map +1 -1
- package/build/types/scope-utils.d.ts +0 -4
- package/build/types/scope-utils.d.ts.map +1 -1
- package/build/types/sdk.d.ts +3 -8
- package/build/types/sdk.d.ts.map +1 -1
- package/build/types/utils/{rpcPropagation.d.ts → bindingPropagation.d.ts} +6 -1
- package/build/types/utils/bindingPropagation.d.ts.map +1 -0
- package/build/types/utils/queueTraceMeta.d.ts +7 -0
- package/build/types/utils/queueTraceMeta.d.ts.map +1 -0
- package/build/types/vite/index.d.ts.map +1 -1
- package/build/types/workflows.d.ts.map +1 -1
- package/build/types/wrapRequestHandlerWithInit.d.ts +1 -1
- package/build/types/wrapRequestHandlerWithInit.d.ts.map +1 -1
- package/package.json +17 -14
- package/build/cjs/dev/utils/rpcPropagation.js.map +0 -1
- package/build/cjs/prod/utils/rpcPropagation.js.map +0 -1
- package/build/esm/dev/utils/rpcPropagation.js.map +0 -1
- package/build/esm/prod/utils/rpcPropagation.js.map +0 -1
- package/build/types/utils/rpcPropagation.d.ts.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"httpServer.js","sources":["../../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, IntegrationFn, MaxRequestBodySize, Span } from '@sentry/core';\nimport {\n captureBodyFromWinterCGRequest,\n defineIntegration,\n getIsolationScope,\n hasSpansEnabled,\n parseStringToURLObject,\n safeCallback,\n} from '@sentry/core';\nimport type { AssertTrue, CheckServerRequestOptions } from '@sentry/core/server';\nimport { isStaticAssetRequest } from '@sentry/core/server';\nimport { DEBUG_BUILD } from '../debug-build';\n\nconst INTEGRATION_NAME = 'HttpServer' as const;\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n\n /**\n * Do not create spans for incoming requests whose URL path makes the given callback return `true`.\n *\n * `urlPath` is the path of the request, including the query string. `request` is the incoming\n * {@link Request}. Errors thrown by the handler are still captured.\n */\n ignoreIncomingRequests?: (urlPath: string, request: Request) => boolean;\n\n /**\n * Whether to automatically ignore common static asset requests (favicon.ico, robots.txt, etc.)\n * when creating spans.\n *\n * @default `true`\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * Whether to create spans for incoming requests.\n * Errors are still captured and request data is still attached when this is `false`.\n * Defaults to the client's tracing configuration (`hasSpansEnabled`).\n */\n spans?: boolean;\n\n /**\n * A hook that can be used to mutate the span for incoming requests.\n * This is triggered after the span is created, before the request handler runs.\n */\n onSpanCreated?: (span: Span, request: Request) => void;\n\n /**\n * A hook that can be used to mutate the span one last time before it ends.\n * For a streamed response, this runs when the stream finishes.\n * It is not called when the request handler throws.\n */\n onSpanEnd?: (span: Span, request: Request, response: Response) => void;\n}\n\n// Checks these options against the shared `ServerRequestOptions`. A new\n// shared field fails to compile here, until this integration supports\n// it or lists it as unsupported.\ntype _ServerRequestOptionsCheck = AssertTrue<\n CheckServerRequestOptions<\n HttpServerIntegrationOptions,\n Request,\n Response,\n // Not supported. A worker has no long-lived process to run the timer\n // that flushes session aggregates.\n 'sessions' | 'sessionFlushingDelayMS'\n >\n>;\n\ninterface HttpServerIntegrationInstance extends HttpServerIntegrationOptions {\n name: string;\n maxRequestBodySize: MaxRequestBodySize | undefined;\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegrationInstance => {\n return {\n name: INTEGRATION_NAME,\n maxRequestBodySize: options.maxRequestBodySize,\n ignoreRequestBody: options.ignoreRequestBody,\n ignoreIncomingRequests: options.ignoreIncomingRequests,\n ignoreStaticAssets: options.ignoreStaticAssets ?? true,\n spans: options.spans,\n onSpanCreated: options.onSpanCreated,\n onSpanEnd: options.onSpanEnd,\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n\n/**\n * Capture the request body based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport async function captureIncomingRequestBody(client: Client, request: Request): Promise<void> {\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n\n if (!integration) {\n return;\n }\n\n const configuredBodySize = integration.maxRequestBodySize;\n const effectiveBodySize: MaxRequestBodySize =\n configuredBodySize ??\n (client.getDataCollectionOptions().httpBodies.includes('incomingRequest') ? 'medium' : 'none');\n\n if (effectiveBodySize === 'none') {\n return;\n }\n\n // Skip GET and HEAD requests - they don't have bodies\n // Also skip OPTIONS, even if they may have a body, they might not give a lot of extra value\n if (request.method === 'GET' || request.method === 'HEAD' || request.method === 'OPTIONS') {\n return;\n }\n\n const ignoreRequestBody = integration.ignoreRequestBody;\n if (\n ignoreRequestBody &&\n // If the filter throws, skip the body so it cannot leak data the filter was meant to hide.\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreRequestBody`, skipping the body:' : '',\n () => ignoreRequestBody(request.url, request),\n () => true,\n )\n ) {\n return;\n }\n\n const isolationScope = getIsolationScope();\n await captureBodyFromWinterCGRequest(request, isolationScope, effectiveBodySize);\n}\n\n/**\n * Whether to create a span for the incoming request, based on the HttpServer integration config.\n * Called internally by `wrapRequestHandler`.\n */\nexport function shouldCreateIncomingRequestSpan(client: Client | undefined, request: Request): boolean {\n if (!client) {\n return false;\n }\n\n const integration = client.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n if (!(integration?.spans ?? hasSpansEnabled(client.getOptions()))) {\n return false;\n }\n\n const urlObject = parseStringToURLObject(request.url);\n const urlPath = urlObject ? `${urlObject.pathname}${urlObject.search}` : '/';\n if (integration?.ignoreStaticAssets && request.method === 'GET' && isStaticAssetRequest(urlPath)) {\n return false;\n }\n\n const ignoreIncomingRequests = integration?.ignoreIncomingRequests;\n return !(\n ignoreIncomingRequests &&\n safeCallback(\n DEBUG_BUILD ? 'Error in `ignoreIncomingRequests`, creating the span:' : '',\n () => ignoreIncomingRequests(urlPath, request),\n () => false,\n )\n );\n}\n\n/**\n * The `onSpanCreated` and `onSpanEnd` hooks of the HttpServer integration, guarded so that a hook\n * that throws does not fail the request. Called internally by `wrapRequestHandler`.\n */\nexport function getIncomingRequestSpanHooks(client: Client | undefined): {\n onSpanCreated: (span: Span, request: Request) => void;\n onSpanEnd: (span: Span, request: Request, response: Response) => void;\n} {\n const integration = client?.getIntegrationByName<HttpServerIntegrationInstance>(INTEGRATION_NAME);\n return {\n onSpanCreated: (span, request) =>\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanCreated`:' : '',\n () => integration?.onSpanCreated?.(span, request),\n () => undefined,\n ),\n onSpanEnd: (span, request, response) =>\n safeCallback(\n DEBUG_BUILD ? 'Error in `onSpanEnd`:' : '',\n () => integration?.onSpanEnd?.(span, request, response),\n () => undefined,\n ),\n };\n}\n"],"names":[],"mappings":";;;;AAaA,MAAM,gBAAA,GAAmB,YAAA;AA8FzB,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAAqC;AAC7G,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,oBAAoB,OAAA,CAAQ,kBAAA;AAAA,IAC5B,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,IAC3B,wBAAwB,OAAA,CAAQ,sBAAA;AAAA,IAChC,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,IAAA;AAAA,IAClD,OAAO,OAAA,CAAQ,KAAA;AAAA,IACf,eAAe,OAAA,CAAQ,aAAA;AAAA,IACvB,WAAW,OAAA,CAAQ;AAAA,GACrB;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwB,kBAAkB,sBAAsB;AAM7E,eAAsB,0BAAA,CAA2B,QAAgB,OAAA,EAAiC;AAChG,EAAA,MAAM,WAAA,GAAc,MAAA,CAAO,oBAAA,CAAoD,gBAAgB,CAAA;AAE/F,EAAA,IAAI,CAAC,WAAA,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AQ,CAAA,EAAG,SAAA,CAAU,MAAM,CAAA,CAAA,GAAK,GAAA;AACzE,EAAA,IAAI,aAAa,kBAAA,IAAsB,OAAA,CAAQ,WAAW,KAAA,IAAS,oBAAA,CAAqB,OAAO,CAAA,EAAG;AAChG,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,MAAM,yBAAyB,WAAA,EAAa,sBAAA;AAC5C,EAAA,OAAO,EACL,sBAAA,IACA,YAAA;AAAA,IACE,cAAc,uDAAA,GAA0D,EAAA;AAAA,IACxE,MAAM,sBAAA,CAAuB,OAAA,EAAS,OAAO,CAAA;AAAA,IAC7C,MAAM;AAAA,GACR,CAAA;AAEJ;AAMO,SAAS,4BAA4B,MAAA,EAG1C;AACA,EAAA,MAAM,WAAA,GAAc,MAAA,EAAQ,oBAAA,CAAoD,gBAAgB,CAAA;AAChG,EAAA,OAAO;AAAA,IACL,aAAA,EAAe,CAAC,IAAA,EAAM,OAAA,KACpB,YAAA;AAAA,MACE,cAAc,2BAAA,GAA8B,EAAA;AAAA,MAC5C,MAAM,WAAA,EAAa,aAAA,GAAgB,IAAA,EAAM,OAAO,CAAA;AAAA,MAChD,MAAM;AAAA,KACR;AAAA,IACF,SAAA,EAAW,CAAC,IAAA,EAAM,OAAA,EAAS,QAAA,KACzB,YAAA;AAAA,MACE,cAAc,uBAAA,GAA0B,EAAA;AAAA,MACxC,MAAM,WAAA,EAAa,SAAA,GAAY,IAAA,EAAM,SAAS,QAAQ,CAAA;AAAA,MACtD,MAAM;AAAA;AACR,GACJ;AACF;;;;"}
|
|
1
|
+
{"version":3,"file":"httpServer.js","sources":["../../../../src/integrations/httpServer.ts"],"sourcesContent":["import type { Client, Integration, IntegrationFn, MaxRequestBodySize, Span } from '@sentry/core';\nimport { defineIntegration } from '@sentry/core';\nimport type { AssertTrue, CheckServerRequestOptions, ServerRequestOptions } from '@sentry/core/server';\n\nconst INTEGRATION_NAME = 'HttpServer' as const;\n\nexport interface HttpServerIntegrationOptions {\n /**\n * Controls the maximum size of incoming request bodies attached to events.\n *\n * Only applies to requests with textual content types (text/*, application/json,\n * application/x-www-form-urlencoded, application/xml, application/graphql).\n * Binary data is not captured.\n *\n * Available options:\n * - `'none'`: No request bodies will be attached\n * - `'small'`: Request bodies up to 1,000 bytes will be attached\n * - `'medium'`: Request bodies up to 10,000 bytes will be attached (default)\n * - `'always'`: Request bodies will always be attached (up to 1MB limit)\n *\n * @default 'medium'\n */\n maxRequestBodySize?: MaxRequestBodySize;\n\n /**\n * Do not capture the request body for incoming HTTP requests to URLs where the given callback returns `true`.\n * This can be useful for long running requests where the body is not needed, health check endpoints,\n * or requests containing sensitive data that should not be captured.\n *\n * @param url The full URL of the incoming request, including query string, protocol, host, etc.\n * @param request The incoming Request object.\n * @returns `true` to skip body capture for this request, `false` to capture normally.\n *\n * @example\n * ```ts\n * Sentry.httpServerIntegration({\n * ignoreRequestBody: (url) => url.includes('/health') || url.includes('/upload'),\n * })\n * ```\n */\n ignoreRequestBody?: (url: string, request: Request) => boolean;\n\n /**\n * Do not create spans for incoming requests whose URL path makes the given callback return `true`.\n *\n * `urlPath` is the path of the request, including the query string. `request` is the incoming\n * {@link Request}. Errors thrown by the handler are still captured.\n */\n ignoreIncomingRequests?: (urlPath: string, request: Request) => boolean;\n\n /**\n * Whether to automatically ignore common static asset requests (favicon.ico, robots.txt, etc.)\n * when creating spans.\n *\n * @default `true`\n */\n ignoreStaticAssets?: boolean;\n\n /**\n * Whether to create spans for incoming requests.\n * Errors are still captured and request data is still attached when this is `false`.\n * Defaults to the client's tracing configuration (`hasSpansEnabled`).\n */\n spans?: boolean;\n\n /**\n * A hook that can be used to mutate the span for incoming requests.\n * This is triggered after the span is created, before the request handler runs.\n */\n onSpanCreated?: (span: Span, request: Request) => void;\n\n /**\n * A hook that can be used to mutate the span one last time before it ends.\n * For a streamed response, this runs when the stream finishes.\n * It is not called when the request handler throws.\n */\n onSpanEnd?: (span: Span, request: Request, response: Response) => void;\n}\n\n// Checks these options against the shared `ServerRequestOptions`. A new\n// shared field fails to compile here, until this integration supports\n// it or lists it as unsupported.\ntype _ServerRequestOptionsCheck = AssertTrue<\n CheckServerRequestOptions<\n HttpServerIntegrationOptions,\n Request,\n Response,\n // Not supported. A worker has no long-lived process to run the timer\n // that flushes session aggregates.\n 'sessions' | 'sessionFlushingDelayMS'\n >\n>;\n\ntype SupportedServerRequestOptions = Omit<\n ServerRequestOptions<Request, Response>,\n 'sessions' | 'sessionFlushingDelayMS'\n>;\n\n// Every supported shared option is a required key, so a new one fails to compile below until the\n// integration passes it on.\ntype HttpServerRequestOptions = {\n [K in keyof Required<SupportedServerRequestOptions>]: SupportedServerRequestOptions[K];\n};\n\ninterface HttpServerIntegration extends Integration {\n requestOptions: HttpServerRequestOptions;\n}\n\n/**\n * The incoming request options of the client's `httpServerIntegration`. If the integration does not\n * set `maxRequestBodySize`, `dataCollection.httpBodies` decides. Without the integration, the SDK\n * attaches no request body.\n */\nexport function getHttpServerRequestOptions(client: Client): ServerRequestOptions<Request, Response> {\n return (\n client.getIntegrationByName<HttpServerIntegration>(INTEGRATION_NAME)?.requestOptions ?? {\n maxRequestBodySize: 'none',\n }\n );\n}\n\nconst _httpServerIntegration = ((options: HttpServerIntegrationOptions = {}): HttpServerIntegration => {\n return {\n name: INTEGRATION_NAME,\n requestOptions: {\n maxRequestBodySize: options.maxRequestBodySize,\n ignoreRequestBody: options.ignoreRequestBody,\n ignoreIncomingRequests: options.ignoreIncomingRequests,\n ignoreStaticAssets: options.ignoreStaticAssets ?? true,\n spans: options.spans,\n onSpanCreated: options.onSpanCreated,\n onSpanEnd: options.onSpanEnd,\n },\n };\n}) satisfies IntegrationFn;\n\n/**\n * Configures incoming HTTP request handling for Cloudflare Workers.\n *\n * This integration controls how incoming HTTP request data is captured,\n * matching the API of `httpServerIntegration` in Node.js.\n *\n * @example\n * ```ts\n * Sentry.init({\n * integrations: [\n * Sentry.httpServerIntegration({\n * maxRequestBodySize: 'medium',\n * ignoreRequestBody: (url) => url.includes('/health'),\n * }),\n * ],\n * });\n * ```\n */\nexport const httpServerIntegration = defineIntegration(_httpServerIntegration);\n"],"names":[],"mappings":";;AAIA,MAAM,gBAAA,GAAmB,YAAA;AA6GlB,SAAS,4BAA4B,MAAA,EAAyD;AACnG,EAAA,OACE,MAAA,CAAO,oBAAA,CAA4C,gBAAgB,CAAA,EAAG,cAAA,IAAkB;AAAA,IACtF,kBAAA,EAAoB;AAAA,GACtB;AAEJ;AAEA,MAAM,sBAAA,IAA0B,CAAC,OAAA,GAAwC,EAAC,KAA6B;AACrG,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,gBAAA;AAAA,IACN,cAAA,EAAgB;AAAA,MACd,oBAAoB,OAAA,CAAQ,kBAAA;AAAA,MAC5B,mBAAmB,OAAA,CAAQ,iBAAA;AAAA,MAC3B,wBAAwB,OAAA,CAAQ,sBAAA;AAAA,MAChC,kBAAA,EAAoB,QAAQ,kBAAA,IAAsB,IAAA;AAAA,MAClD,OAAO,OAAA,CAAQ,KAAA;AAAA,MACf,eAAe,OAAA,CAAQ,aAAA;AAAA,MACvB,WAAW,OAAA,CAAQ;AAAA;AACrB,GACF;AACF,CAAA,CAAA;AAoBO,MAAM,qBAAA,GAAwB,kBAAkB,sBAAsB;;;;"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"type":"module","version":"11.
|
|
1
|
+
{"type":"module","version":"11.12.0","sideEffects":false}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.js","sources":["../../../src/request.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareOptions } from './client';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation.\n *\n * The client
|
|
1
|
+
{"version":3,"file":"request.js","sources":["../../../src/request.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareOptions } from './client';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n/**\n * Wraps a cloudflare request handler in Sentry instrumentation.\n *\n * The client uses the same default integrations as `init`, without setting up an OpenTelemetry\n * tracer provider. This entry point also works on runtimes that cannot enable the `nodejs_compat`\n * compatibility flag, such as Shopify Oxygen.\n */\nexport function wrapRequestHandler(\n wrapperOptions: Omit<RequestHandlerWrapperOptions, 'options'> & {\n // `enableOpenTelemetrySetup` is only honored by `init` from `sdk.ts`; this entry point\n // initializes the SDK via `initBaseSdk`, where setting it would have no effect.\n options: Omit<CloudflareOptions, 'enableOpenTelemetrySetup'>;\n },\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, initBaseSdk);\n}\n\nexport { httpServerIntegration } from './integrations/httpServer';\n"],"names":[],"mappings":";;;;AAWO,SAAS,kBAAA,CACd,gBAKA,OAAA,EACmB;AACnB,EAAA,OAAO,0BAAA,CAA2B,cAAA,EAAgB,OAAA,EAAS,WAAW,CAAA;AACxE;;;;"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { CLOUD_PROVIDER } from '@sentry/conventions/attributes';
|
|
2
2
|
|
|
3
3
|
function addCloudResourceContext(scope) {
|
|
4
4
|
scope.setContext("cloud_resource", {
|
|
5
|
-
|
|
5
|
+
[CLOUD_PROVIDER]: "cloudflare"
|
|
6
6
|
});
|
|
7
7
|
}
|
|
8
8
|
function addCultureContext(scope, cf) {
|
|
@@ -10,9 +10,6 @@ function addCultureContext(scope, cf) {
|
|
|
10
10
|
timezone: cf.timezone
|
|
11
11
|
});
|
|
12
12
|
}
|
|
13
|
-
function addRequest(scope, request) {
|
|
14
|
-
scope.setSDKProcessingMetadata({ normalizedRequest: winterCGRequestToRequestData(request) });
|
|
15
|
-
}
|
|
16
13
|
|
|
17
|
-
export { addCloudResourceContext, addCultureContext
|
|
14
|
+
export { addCloudResourceContext, addCultureContext };
|
|
18
15
|
//# sourceMappingURL=scope-utils.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"scope-utils.js","sources":["../../../src/scope-utils.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"scope-utils.js","sources":["../../../src/scope-utils.ts"],"sourcesContent":["import { CLOUD_PROVIDER } from '@sentry/conventions/attributes';\nimport type { CfProperties, IncomingRequestCfProperties } from '@cloudflare/workers-types';\nimport type { Scope } from '@sentry/core';\n\n/**\n * Set cloud resource context on scope.\n */\nexport function addCloudResourceContext(scope: Scope): void {\n scope.setContext('cloud_resource', {\n [CLOUD_PROVIDER]: 'cloudflare',\n });\n}\n\n/**\n * Set culture context on scope\n */\nexport function addCultureContext(scope: Scope, cf: IncomingRequestCfProperties | CfProperties): void {\n scope.setContext('culture', {\n timezone: cf.timezone,\n });\n}\n"],"names":[],"mappings":";;AAOO,SAAS,wBAAwB,KAAA,EAAoB;AAC1D,EAAA,KAAA,CAAM,WAAW,gBAAA,EAAkB;AAAA,IACjC,CAAC,cAAc,GAAG;AAAA,GACnB,CAAA;AACH;AAKO,SAAS,iBAAA,CAAkB,OAAc,EAAA,EAAsD;AACpG,EAAA,KAAA,CAAM,WAAW,SAAA,EAAW;AAAA,IAC1B,UAAU,EAAA,CAAG;AAAA,GACd,CAAA;AACH;;;;"}
|
package/build/esm/prod/sdk.js
CHANGED
|
@@ -1,20 +1,18 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { initBaseSdk } from './baseSdk.js';
|
|
2
|
+
export { getDefaultIntegrations } from './baseSdk.js';
|
|
2
3
|
import { setupOpenTelemetryTracer } from './opentelemetry/tracer.js';
|
|
3
4
|
import { wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit.js';
|
|
4
5
|
|
|
5
|
-
function getDefaultIntegrations(options) {
|
|
6
|
-
return getBaseDefaultIntegrations(options);
|
|
7
|
-
}
|
|
8
6
|
function init(options) {
|
|
9
7
|
options.enableOpenTelemetrySetup ?? (options.enableOpenTelemetrySetup = false);
|
|
10
8
|
if (options.enableOpenTelemetrySetup) {
|
|
11
9
|
setupOpenTelemetryTracer();
|
|
12
10
|
}
|
|
13
|
-
return
|
|
11
|
+
return initBaseSdk(options);
|
|
14
12
|
}
|
|
15
13
|
function _INTERNAL_wrapRequestHandler(wrapperOptions, handler) {
|
|
16
14
|
return wrapRequestHandlerWithInit(wrapperOptions, handler, init);
|
|
17
15
|
}
|
|
18
16
|
|
|
19
|
-
export { _INTERNAL_wrapRequestHandler,
|
|
17
|
+
export { _INTERNAL_wrapRequestHandler, init };
|
|
20
18
|
//# sourceMappingURL=sdk.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import
|
|
1
|
+
{"version":3,"file":"sdk.js","sources":["../../../src/sdk.ts"],"sourcesContent":["import { initBaseSdk } from './baseSdk';\nimport type { CloudflareClient, CloudflareOptions } from './client';\nimport { setupOpenTelemetryTracer } from './opentelemetry/tracer';\nimport { type RequestHandlerWrapperOptions, wrapRequestHandlerWithInit } from './wrapRequestHandlerWithInit';\n\n// Test-only helper, re-exported here so tests can reset the global client cache.\nexport { _clearGlobalClientCache } from './clientCache';\n\nexport { getDefaultIntegrations } from './baseSdk';\n\n/**\n * Initializes the cloudflare SDK.\n */\nexport function init(options: CloudflareOptions): CloudflareClient | undefined {\n // Like most Node-based SDKs, Cloudflare defaults to running without a Sentry OpenTelemetry tracer\n // provider. Scope isolation is handled by the entrypoint wrappers' AsyncLocalStorage strategy.\n options.enableOpenTelemetrySetup ??= false;\n\n // Opt-in only: when `enableOpenTelemetrySetup` is `true`, set up a custom trace provider so spans\n // emitted via `@opentelemetry/api` are captured by Sentry. See the option's docs for the caveats.\n if (options.enableOpenTelemetrySetup) {\n setupOpenTelemetryTracer();\n }\n\n return initBaseSdk(options);\n}\n\n/**\n * `wrapRequestHandler` backed by `init`, so the request honors `enableOpenTelemetrySetup`. The\n * `@sentry/cloudflare/request` variant deliberately skips it to stay usable without `nodejs_compat`.\n *\n * For framework SDKs building on the main entry point, e.g. SvelteKit, whose OpenTelemetry spans\n * need the tracer provider.\n *\n * @internal\n */\nexport function _INTERNAL_wrapRequestHandler(\n wrapperOptions: RequestHandlerWrapperOptions,\n handler: (...args: unknown[]) => Response | Promise<Response>,\n): Promise<Response> {\n return wrapRequestHandlerWithInit(wrapperOptions, handler, init);\n}\n"],"names":[],"mappings":";;;;;AAaO,SAAS,KAAK,OAAA,EAA0D;AAG7E,EAAA,OAAA,CAAQ,wBAAA,KAAR,QAAQ,wBAAA,GAA6B,KAAA,CAAA;AAIrC,EAAA,IAAI,QAAQ,wBAAA,EAA0B;AACpC,IAAA,wBAAA,EAAyB;AAAA,EAC3B;AAEA,EAAA,OAAO,YAAY,OAAO,CAAA;AAC5B;AAWO,SAAS,4BAAA,CACd,gBACA,OAAA,EACmB;AACnB,EAAA,OAAO,0BAAA,CAA2B,cAAA,EAAgB,OAAA,EAAS,IAAI,CAAA;AACjE;;;;"}
|
|
@@ -1,13 +1,15 @@
|
|
|
1
1
|
import { matchesTracePropagationTargets } from '@sentry/core';
|
|
2
2
|
|
|
3
3
|
const PROPAGATE_TO_NONE = () => false;
|
|
4
|
-
function
|
|
5
|
-
const bindings = options?.rpcTracePropagationBindings;
|
|
4
|
+
function createBindingPropagationResolver(bindings) {
|
|
6
5
|
if (!bindings?.length) {
|
|
7
6
|
return PROPAGATE_TO_NONE;
|
|
8
7
|
}
|
|
9
8
|
return (bindingName) => matchesTracePropagationTargets(bindingName, bindings, true);
|
|
10
9
|
}
|
|
10
|
+
function createRpcPropagationResolver(options) {
|
|
11
|
+
return createBindingPropagationResolver(options?.rpcTracePropagationBindings);
|
|
12
|
+
}
|
|
11
13
|
|
|
12
|
-
export { createRpcPropagationResolver };
|
|
13
|
-
//# sourceMappingURL=
|
|
14
|
+
export { createBindingPropagationResolver, createRpcPropagationResolver };
|
|
15
|
+
//# sourceMappingURL=bindingPropagation.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"bindingPropagation.js","sources":["../../../../src/utils/bindingPropagation.ts"],"sourcesContent":["import { matchesTracePropagationTargets, type TracePropagationTargets } from '@sentry/core';\nimport type { CloudflareOptions } from '../client';\n\nconst PROPAGATE_TO_NONE = () => false;\n\n/**\n * Builds the per-binding predicate that decides whether a binding takes part in trace propagation.\n */\nexport function createBindingPropagationResolver(\n bindings: TracePropagationTargets | undefined,\n): (bindingName: string) => boolean {\n if (!bindings?.length) {\n return PROPAGATE_TO_NONE;\n }\n\n // Strings must match a binding name exactly, without this, an entry of `DB` would also enable\n // propagation for a binding named `MY_DB`. Regular expressions still give pattern matching.\n return (bindingName: string) => matchesTracePropagationTargets(bindingName, bindings, true);\n}\n\n/**\n * Builds the per-binding predicate that decides whether a binding takes part in RPC trace\n * propagation.\n *\n * Callers only. Receivers continue an incoming trace whenever one arrives, so they have nothing to\n * match against.\n */\nexport function createRpcPropagationResolver(options: CloudflareOptions | undefined): (bindingName: string) => boolean {\n return createBindingPropagationResolver(options?.rpcTracePropagationBindings);\n}\n"],"names":[],"mappings":";;AAGA,MAAM,oBAAoB,MAAM,KAAA;AAKzB,SAAS,iCACd,QAAA,EACkC;AAClC,EAAA,IAAI,CAAC,UAAU,MAAA,EAAQ;AACrB,IAAA,OAAO,iBAAA;AAAA,EACT;AAIA,EAAA,OAAO,CAAC,WAAA,KAAwB,8BAAA,CAA+B,WAAA,EAAa,UAAU,IAAI,CAAA;AAC5F;AASO,SAAS,6BAA6B,OAAA,EAA0E;AACrH,EAAA,OAAO,gCAAA,CAAiC,SAAS,2BAA2B,CAAA;AAC9E;;;;"}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { extractTraceparentData } from '@sentry/core';
|
|
2
|
+
|
|
3
|
+
const SENTRY_QUEUE_TRACE_KEY = "__sentry_queue_trace__";
|
|
4
|
+
function isQueueTraceCarrier(body) {
|
|
5
|
+
if (typeof body !== "object" || body === null || Array.isArray(body)) {
|
|
6
|
+
return false;
|
|
7
|
+
}
|
|
8
|
+
const prototype = Object.getPrototypeOf(body);
|
|
9
|
+
return prototype === Object.prototype || prototype === null;
|
|
10
|
+
}
|
|
11
|
+
function addQueueTraceContext(body, sentryTrace) {
|
|
12
|
+
if (!isQueueTraceCarrier(body) || !sentryTrace || Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {
|
|
13
|
+
return body;
|
|
14
|
+
}
|
|
15
|
+
return { ...body, [SENTRY_QUEUE_TRACE_KEY]: sentryTrace };
|
|
16
|
+
}
|
|
17
|
+
function extractQueueTraceContext(body) {
|
|
18
|
+
if (!isQueueTraceCarrier(body)) {
|
|
19
|
+
return void 0;
|
|
20
|
+
}
|
|
21
|
+
if (!Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {
|
|
22
|
+
return void 0;
|
|
23
|
+
}
|
|
24
|
+
const sentryTrace = body[SENTRY_QUEUE_TRACE_KEY];
|
|
25
|
+
Reflect.deleteProperty(body, SENTRY_QUEUE_TRACE_KEY);
|
|
26
|
+
if (typeof sentryTrace !== "string") {
|
|
27
|
+
return void 0;
|
|
28
|
+
}
|
|
29
|
+
const traceparentData = extractTraceparentData(sentryTrace);
|
|
30
|
+
if (!traceparentData?.traceId || !traceparentData.parentSpanId) {
|
|
31
|
+
return void 0;
|
|
32
|
+
}
|
|
33
|
+
return {
|
|
34
|
+
traceId: traceparentData.traceId,
|
|
35
|
+
spanId: traceparentData.parentSpanId,
|
|
36
|
+
sampled: traceparentData.parentSampled
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export { addQueueTraceContext, extractQueueTraceContext };
|
|
41
|
+
//# sourceMappingURL=queueTraceMeta.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"queueTraceMeta.js","sources":["../../../../src/utils/queueTraceMeta.ts"],"sourcesContent":["import { extractTraceparentData } from '@sentry/core';\n\nconst SENTRY_QUEUE_TRACE_KEY = '__sentry_queue_trace__';\n\nfunction isQueueTraceCarrier(body: unknown): body is Record<string, unknown> {\n if (typeof body !== 'object' || body === null || Array.isArray(body)) {\n return false;\n }\n\n // Cloudflare Queues has no message-header API. Only record-like bodies can carry a named field; binary data and\n // other structured-clone values must pass through untouched.\n const prototype = Object.getPrototypeOf(body);\n return prototype === Object.prototype || prototype === null;\n}\n\nexport function addQueueTraceContext(body: unknown, sentryTrace: string | undefined): unknown {\n if (\n !isQueueTraceCarrier(body) ||\n !sentryTrace ||\n Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)\n ) {\n return body;\n }\n\n // Cloudflare rejects messages over 128 KB (https://developers.cloudflare.com/queues/platform/limits/),\n // and the field adds about 80 bytes, so a payload right under the limit can start failing to send.\n // Span links only need `sentry-trace`, so baggage would only cost more of that budget. Copy instead\n // of mutating, because callers may reuse a payload after enqueueing it.\n return { ...body, [SENTRY_QUEUE_TRACE_KEY]: sentryTrace };\n}\n\nexport function extractQueueTraceContext(\n body: unknown,\n): { traceId: string; spanId: string; sampled: boolean | undefined } | undefined {\n if (!isQueueTraceCarrier(body)) {\n return undefined;\n }\n\n if (!Object.prototype.hasOwnProperty.call(body, SENTRY_QUEUE_TRACE_KEY)) {\n return undefined;\n }\n\n const sentryTrace = body[SENTRY_QUEUE_TRACE_KEY];\n\n // The key is reserved transport metadata, so strip it even if its value is not a valid trace.\n // Unlike `delete`, this returns false instead of throwing on frozen bodies, which keep the field.\n Reflect.deleteProperty(body, SENTRY_QUEUE_TRACE_KEY);\n\n if (typeof sentryTrace !== 'string') {\n return undefined;\n }\n\n const traceparentData = extractTraceparentData(sentryTrace);\n if (!traceparentData?.traceId || !traceparentData.parentSpanId) {\n return undefined;\n }\n\n return {\n traceId: traceparentData.traceId,\n spanId: traceparentData.parentSpanId,\n sampled: traceparentData.parentSampled,\n };\n}\n"],"names":[],"mappings":";;AAEA,MAAM,sBAAA,GAAyB,wBA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AAO,MAAA;AAAA,EACT;AAEA,EAAA,OAAO;AAAA,IACL,SAAS,eAAA,CAAgB,OAAA;AAAA,IACzB,QAAQ,eAAA,CAAgB,YAAA;AAAA,IACxB,SAAS,eAAA,CAAgB;AAAA,GAC3B;AACF;;;;"}
|
|
@@ -9,7 +9,8 @@ function sentryCloudflareVitePlugin(options = {}) {
|
|
|
9
9
|
buildTimeInstrumentation: options.buildTimeInstrumentation,
|
|
10
10
|
// Route the injected `tracingChannel` imports through the workerd-safe façade so a
|
|
11
11
|
// dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.
|
|
12
|
-
dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel"
|
|
12
|
+
dcModule: "@sentry/cloudflare/orchestrion-diagnostics-channel",
|
|
13
|
+
transformOptimizedDeps: true
|
|
13
14
|
}),
|
|
14
15
|
sentryMastraObservabilityProviderPlugin(),
|
|
15
16
|
sentryFlueRuntimeProviderPlugin(),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryFlueRuntimeProviderPlugin } from './flueRuntime';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n }),\n sentryMastraObservabilityProviderPlugin(),\n sentryFlueRuntimeProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;;;AAqFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACL,uBAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU;AAAA,
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../../../../src/vite/index.ts"],"sourcesContent":["// Published ESM-only via the `@sentry/cloudflare/vite` subpath export:\n// `@sentry/server-utils/orchestrion/vite` exposes no `require` condition, so a\n// CJS entry here would fail at resolution time (ERR_PACKAGE_PATH_NOT_EXPORTED).\n// The CJS rollup variant still emits this file, but `package.json` doesn't\n// expose it — same setup as `@sentry/server-utils/orchestrion/vite` itself.\nimport { sentryOrchestrionPlugin } from '@sentry/server-utils/orchestrion/vite';\nimport { sentryCloudflareAutoInstrumentPlugin } from './autoInstrument';\nimport { sentryFlueRuntimeProviderPlugin } from './flueRuntime';\nimport { sentryMastraObservabilityProviderPlugin } from './mastraObservability';\n\n/**\n * Options for {@link sentryCloudflareVitePlugin}.\n */\nexport interface SentryCloudflareVitePluginOptions {\n /**\n * Path to the wrangler config, relative to the Vite root (or absolute).\n * Set this when your config doesn't use a default name — e.g. when you\n * pass `configPath: './wrangler.agent.jsonc'` to `@cloudflare/vite-plugin`,\n * which the Sentry plugin cannot see. When set, only this file is read\n * (no default-name probing), and a warning is emitted if it is missing or\n * unparseable.\n *\n * @default undefined (probes `wrangler.json`, `wrangler.jsonc`, `wrangler.toml` at the Vite root)\n */\n wranglerConfigPath?: string;\n /**\n * Build-time automatic instrumentation of supported dependencies (e.g.\n * database clients like `mysql`) so the Sentry Cloudflare SDK can trace them\n * without monkey-patching, which wouldn't work in workerd anyway.\n *\n * When enabled, the plugin injects `diagnostics_channel.tracingChannel` calls\n * into the bundled packages and, next to each, a snippet that registers the\n * matching Sentry channel-subscriber factory on the global marker, which the\n * SDK picks up in `Sentry.withSentry()`. Both `vite build` and `vite dev` are\n * instrumented. Set to `false` to opt out.\n *\n * @default true\n */\n buildTimeInstrumentation?: boolean;\n /**\n * Automatically wraps your Worker at build time so you don't have to edit\n * your entry: the plugin reads your wrangler config, wraps the default\n * export with `Sentry.withSentry()` (sourcing options from a co-located\n * `instrument.*` file, falling back to env), and wraps any configured\n * Durable Object class with `instrumentDurableObjectWithSentry`. Both\n * `vite build` and `vite dev` are instrumented. Already-wrapped entries are\n * left alone, so this is safe alongside manual instrumentation. Set to\n * `false` to opt out.\n *\n * The plugin also adds the bindings that resolve to the wrapped classes (this worker's own\n * Durable Objects and self service bindings) to `rpcTracePropagationBindings`. Bindings to\n * other workers stay opt-in, their receivers may not run Sentry.\n *\n * @default true\n */\n autoInstrumentation?: boolean;\n}\n\n/**\n * Sentry Vite plugin for Cloudflare Workers.\n *\n * Add this plugin to your Vite configuration to enable additional Sentry\n * instrumentation for Cloudflare Workers built with Vite.\n *\n * By default, the plugin\n * - build-time instruments supported dependencies (such as database clients) so\n * they are traced without changing your application code — opt out with\n * `buildTimeInstrumentation: false`, and\n * - wraps your Worker entry (and any Durable Object, Workflow or\n * WorkerEntrypoint class in your wrangler config) with the matching Sentry\n * helper — opt out with `autoInstrumentation: false` and call\n * `Sentry.withSentry()` yourself.\n *\n * @example\n * ```ts\n * // vite.config.ts\n * import { cloudflare } from '@cloudflare/vite-plugin';\n * import { sentryCloudflareVitePlugin } from '@sentry/cloudflare/vite';\n * import { defineConfig } from 'vite';\n *\n * export default defineConfig({\n * plugins: [cloudflare(), sentryCloudflareVitePlugin()],\n * });\n * ```\n */\nexport function sentryCloudflareVitePlugin(options: SentryCloudflareVitePluginOptions = {}): Array<{ name: string }> {\n return [\n sentryOrchestrionPlugin({\n buildTimeInstrumentation: options.buildTimeInstrumentation,\n // Route the injected `tracingChannel` imports through the workerd-safe façade so a\n // dependency wrapped at module scope (`const app = new Hono()`) doesn't throw on workerd.\n dcModule: '@sentry/cloudflare/orchestrion-diagnostics-channel',\n transformOptimizedDeps: true,\n }),\n sentryMastraObservabilityProviderPlugin(),\n sentryFlueRuntimeProviderPlugin(),\n ...(options.autoInstrumentation !== false\n ? [sentryCloudflareAutoInstrumentPlugin({ wranglerConfigPath: options.wranglerConfigPath })]\n : []),\n ];\n}\n"],"names":[],"mappings":";;;;;AAqFO,SAAS,0BAAA,CAA2B,OAAA,GAA6C,EAAC,EAA4B;AACnH,EAAA,OAAO;AAAA,IACL,uBAAA,CAAwB;AAAA,MACtB,0BAA0B,OAAA,CAAQ,wBAAA;AAAA;AAAA;AAAA,MAGlC,QAAA,EAAU,oDAAA;AAAA,MACV,sBAAA,EAAwB;AAAA,KACzB,CAAA;AAAA,IACD,uCAAA,EAAwC;AAAA,IACxC,+BAAA,EAAgC;AAAA,IAChC,GAAI,OAAA,CAAQ,mBAAA,KAAwB,KAAA,GAChC,CAAC,oCAAA,CAAqC,EAAE,kBAAA,EAAoB,OAAA,CAAQ,kBAAA,EAAoB,CAAC,IACzF;AAAC,GACP;AACF;;;;"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';
|
|
1
|
+
import { SENTRY_SEGMENT_NAME_SOURCE, SENTRY_ORIGIN, CLOUDFLARE_WORKFLOW_ATTEMPT, CLOUDFLARE_WORKFLOW_RETRIES_LIMIT, CLOUDFLARE_WORKFLOW_RETRIES_DELAY, CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF, CLOUDFLARE_WORKFLOW_TIMEOUT, CODE_FUNCTION_NAME, SENTRY_OP } from '@sentry/conventions/attributes';
|
|
2
2
|
import { FUNCTION } from '@sentry/conventions/op';
|
|
3
|
-
import { withScope, getCurrentScope, withIsolationScope, startSpan, captureException, flush } from '@sentry/core';
|
|
3
|
+
import { withScope, getCurrentScope, withIsolationScope, startSpan, captureException, flush, isError } from '@sentry/core';
|
|
4
4
|
import { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy.js';
|
|
5
5
|
import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
|
|
6
6
|
import { markAsInstrumented } from './instrument.js';
|
|
@@ -24,6 +24,9 @@ async function propagationContextFromInstanceId(instanceId) {
|
|
|
24
24
|
sampleRand
|
|
25
25
|
};
|
|
26
26
|
}
|
|
27
|
+
function isNonRetryableError(error) {
|
|
28
|
+
return isError(error) && (error.name === "NonRetryableError" || String(error.message).startsWith("NonRetryableError"));
|
|
29
|
+
}
|
|
27
30
|
class WrappedWorkflowStep {
|
|
28
31
|
constructor(_instanceId, _options, _step, _waitUntil, _isolationScope) {
|
|
29
32
|
this._instanceId = _instanceId;
|
|
@@ -57,12 +60,12 @@ class WrappedWorkflowStep {
|
|
|
57
60
|
[SENTRY_OP]: FUNCTION,
|
|
58
61
|
[CODE_FUNCTION_NAME]: name,
|
|
59
62
|
"workflow.step.name": name,
|
|
60
|
-
|
|
61
|
-
|
|
63
|
+
[CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,
|
|
64
|
+
[CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,
|
|
62
65
|
// In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
+
[CLOUDFLARE_WORKFLOW_RETRIES_DELAY]: typeof config?.retries?.delay === "function" ? void 0 : config?.retries?.delay,
|
|
67
|
+
[CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,
|
|
68
|
+
[CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,
|
|
66
69
|
[SENTRY_ORIGIN]: "auto.faas.cloudflare.workflow",
|
|
67
70
|
[SENTRY_SEGMENT_NAME_SOURCE]: "task"
|
|
68
71
|
}
|
|
@@ -73,7 +76,7 @@ class WrappedWorkflowStep {
|
|
|
73
76
|
span.setStatus({ code: 1 });
|
|
74
77
|
return result;
|
|
75
78
|
} catch (error) {
|
|
76
|
-
if (isFinalAttempt) {
|
|
79
|
+
if (isFinalAttempt || isNonRetryableError(error)) {
|
|
77
80
|
captureException(error, { mechanism: { handled: true, type: "auto.faas.cloudflare.workflow" } });
|
|
78
81
|
}
|
|
79
82
|
throw error;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport { captureException, flush, getCurrentScope, startSpan, withIsolationScope, withScope } from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n 'cloudflare.workflow.timeout': config?.timeout,\n 'cloudflare.workflow.retries.backoff': config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n 'cloudflare.workflow.retries.delay':\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n 'cloudflare.workflow.retries.limit': config?.retries?.limit,\n 'cloudflare.workflow.attempt': attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AAiCA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MAAM,GAAA,GAAM,MAAM,MAAA,CAAO,MAAA,CAAO,MAAA,CAAO,OAAA,EAAS,IAAI,WAAA,EAAY,CAAE,MAAA,CAAO,UAAU,CAAC,CAAA;AACpF,EAAA,OACE,KAAA,CAAM,KAAK,IAAI,UAAA,CAAW,GAAG,CAAC,CAAA,CAE3B,KAAA,CAAM,CAAA,EAAG,EAAE,CAAA,CACX,IAAI,CAAA,CAAA,KAAK,CAAA,CAAE,QAAA,CAAS,EAAE,CAAA,CAAE,QAAA,CAAS,GAAG,GAAG,CAAC,CAAA,CACxC,IAAA,CAAK,EAAE,CAAA;AAEd;AAEA,eAAe,iCAAiC,UAAA,EAAiD;AAC/F,EAAA,MAAM,OAAA,GAAU,UAAA,CAAW,IAAA,CAAK,UAAU,CAAA,G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OAAO,SAAA,CAAU,OAAM,KAAA,KAAS;AAC9B,kBAAA,MAAM,kBAAA,GAAqB,MAAM,gCAAA,CAAiC,KAAA,CAAM,UAAU,CAAA;AAClF,kBAAA,KAAA,CAAM,sBAAsB,kBAAkB,CAAA;AAE9C,kBAAA,IAAI;AACF,oBAAA,OAAO,MAAM,IAAI,GAAA,CAAI,IAAA;AAAA,sBACnB,GAAA;AAAA,sBACA,KAAA;AAAA,sBACA,IAAI,mBAAA,CAAoB,KAAA,CAAM,YAAY,OAAA,EAAS,IAAA,EAAM,WAAW,cAAc;AAAA,qBACpF;AAAA,kBACF,CAAA,SAAE;AACA,oBAAA,SAAA,CAAU,eAAA,CAAgB,MAAM,CAAC,CAAA;AAAA,kBACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,GAAG,OAAO,CAAA;AAAA,YACZ,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
|
|
1
|
+
{"version":3,"file":"workflows.js","sources":["../../../src/workflows.ts"],"sourcesContent":["import {\n SENTRY_SEGMENT_NAME_SOURCE,\n CODE_FUNCTION_NAME,\n SENTRY_OP,\n SENTRY_ORIGIN,\n CLOUDFLARE_WORKFLOW_ATTEMPT,\n CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF,\n CLOUDFLARE_WORKFLOW_RETRIES_DELAY,\n CLOUDFLARE_WORKFLOW_RETRIES_LIMIT,\n CLOUDFLARE_WORKFLOW_TIMEOUT,\n} from '@sentry/conventions/attributes';\nimport { FUNCTION } from '@sentry/conventions/op';\nimport type { PropagationContext, Scope } from '@sentry/core';\nimport {\n captureException,\n flush,\n getCurrentScope,\n isError,\n startSpan,\n withIsolationScope,\n withScope,\n} from '@sentry/core';\nimport type {\n WorkflowDelayDuration,\n WorkflowEntrypoint,\n WorkflowEvent,\n WorkflowSleepDuration,\n WorkflowStep,\n WorkflowStepConfig,\n WorkflowStepContext,\n WorkflowStepEvent,\n WorkflowStepRollbackOptions,\n WorkflowTimeoutDuration,\n} from 'cloudflare:workers';\nimport { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy';\nimport type { CloudflareOptions } from './client';\nimport { flushAndDispose, getOriginalWaitUntil } from './flush';\nimport { markAsInstrumented } from './instrument';\nimport { instrumentEnv } from './instrumentations/worker/instrumentEnv';\nimport { addCloudResourceContext } from './scope-utils';\nimport { init } from './sdk';\nimport { instrumentContext } from './utils/instrumentContext';\nimport type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types';\nimport { getInvocationState } from './utils/invocationContext';\nimport { withInvocationIsolationScope } from './utils/invocationScope';\n\nconst UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;\n\n/**\n * Hashes a string to a UUID using SHA-1.\n */\nexport async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {\n const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));\n return (\n Array.from(new Uint8Array(buf))\n // We only need the first 16 bytes for the 32 characters\n .slice(0, 16)\n .map(b => b.toString(16).padStart(2, '0'))\n .join('')\n );\n}\n\nasync function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {\n const traceId = UUID_REGEX.test(instanceId)\n ? instanceId.replace(/-/g, '')\n : await deterministicTraceIdFromInstanceId(instanceId);\n\n // Derive sampleRand from last 4 characters of the random UUID\n //\n // We cannot store any state between workflow steps, so we derive the\n // sampleRand from the traceId itself. This ensures that the sampling is\n // consistent across all steps in the same workflow instance.\n const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff;\n\n return {\n traceId,\n sampleRand,\n };\n}\n\n// Same check the Workflows engine uses to stop retrying a step. Not `constructor.name`: a\n// `NonRetryableError` with a custom `name` is retried, so capturing it early would duplicate events.\nfunction isNonRetryableError(error: unknown): boolean {\n return (\n isError(error) && (error.name === 'NonRetryableError' || String(error.message).startsWith('NonRetryableError'))\n );\n}\n\nclass WrappedWorkflowStep implements WorkflowStep {\n public constructor(\n private _instanceId: string,\n private _options: CloudflareOptions,\n private _step: WorkflowStep,\n private _waitUntil: ExecutionContext['waitUntil'],\n private _isolationScope: Scope,\n ) {}\n\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n callback: (ctx: WorkflowStepContext) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>, const C extends WorkflowStepConfig>(\n name: string,\n config: C,\n callback: (\n ctx: WorkflowStepContext<C['retries'] extends { delay: infer D } ? D : WorkflowDelayDuration | number>,\n ) => Promise<T>,\n rollbackOptions?: WorkflowStepRollbackOptions<T>,\n ): Promise<T>;\n public async do<T extends Rpc.Serializable<T>>(\n name: string,\n configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise<T>),\n callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise<T>) | WorkflowStepRollbackOptions<T>,\n maybeRollback?: WorkflowStepRollbackOptions<T>,\n ): Promise<T> {\n // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved\n const scopeForStep = getCurrentScope();\n\n const hasConfig = typeof configOrCallback !== 'function';\n const config = hasConfig ? configOrCallback : undefined;\n const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as (\n ctx: WorkflowStepContext,\n ) => Promise<T>;\n const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as\n | WorkflowStepRollbackOptions<T>\n | undefined;\n\n const instrumentedCallback = async (...args: unknown[]): Promise<T> => {\n // Feature detection: Cloudflare Workflows (April 2026+) pass a step context\n // with `attempt` and `config.retries.limit`. When available, we only capture\n // errors on the final attempt to avoid duplicates during retries.\n const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined;\n const attempt = stepContext?.attempt;\n const retryLimit = stepContext?.config?.retries?.limit;\n const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number';\n\n // Only capture error on final attempt (attempt > retryLimit means no more retries left)\n // or when step context is unavailable (legacy behavior - capture all errors)\n const isFinalAttempt = !hasStepContext || attempt > retryLimit;\n\n // The engine invokes step callbacks outside the async context of `run`, so the\n // run's isolation scope (and with it the invocation state that ties eager sends\n // to this invocation's `waitUntil`) has to be restored explicitly.\n return withIsolationScope(this._isolationScope, () => {\n const invocationState = getInvocationState();\n\n if (invocationState) {\n invocationState.flushPointReached = false;\n }\n\n const stepResult = startSpan(\n {\n name,\n scope: scopeForStep,\n attributes: {\n [SENTRY_OP]: FUNCTION,\n [CODE_FUNCTION_NAME]: name,\n 'workflow.step.name': name,\n [CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout,\n [CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff,\n // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value.\n [CLOUDFLARE_WORKFLOW_RETRIES_DELAY]:\n typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay,\n [CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit,\n [CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt,\n [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',\n [SENTRY_SEGMENT_NAME_SOURCE]: 'task',\n },\n },\n async span => {\n try {\n const result = await (userCallback as (...args: unknown[]) => Promise<T>)(...args);\n span.setStatus({ code: 1 });\n return result;\n } catch (error) {\n if (isFinalAttempt || isNonRetryableError(error)) {\n captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });\n }\n throw error;\n }\n },\n );\n // Deliver after the step span has ended, so the span rides this flush instead of\n // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the\n // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has\n // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay.\n return stepResult.then(\n result => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n return result;\n },\n error => {\n this._waitUntil(withScope(scopeForStep, () => flush(2000)));\n throw error;\n },\n );\n });\n };\n\n if (config) {\n return rollbackOptions\n ? this._step.do(name, config, instrumentedCallback, rollbackOptions)\n : this._step.do(name, config, instrumentedCallback);\n }\n\n return rollbackOptions\n ? this._step.do(name, instrumentedCallback, rollbackOptions)\n : this._step.do(name, instrumentedCallback);\n }\n\n public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {\n return this._step.sleep(name, duration);\n }\n\n public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {\n return this._step.sleepUntil(name, timestamp);\n }\n\n public async waitForEvent<T extends Rpc.Serializable<T>>(\n name: string,\n options: { type: string; timeout?: WorkflowTimeoutDuration | number },\n ): Promise<WorkflowStepEvent<T>> {\n return this._step.waitForEvent<T>(name, options);\n }\n}\n\n/**\n * Instruments a Cloudflare Workflow class with Sentry.\n *\n * @example\n * ```typescript\n * const InstrumentedWorkflow = instrumentWorkflowWithSentry(\n * (env) => ({ dsn: env.SENTRY_DSN }),\n * MyWorkflowClass\n * );\n *\n * export default InstrumentedWorkflow;\n * ```\n *\n * @param optionsCallback - Function that returns Sentry options to initialize Sentry\n * @param WorkflowClass - The workflow class to instrument\n * @returns Instrumented workflow class with the same interface\n */\nexport function instrumentWorkflowWithSentry<\n E = DefaultEnv, // Environment type\n P = unknown, // Payload type\n // oxlint-disable-next-line typescript/no-explicit-any\n T extends WorkflowEntrypoint<any, any> = WorkflowEntrypoint<E, P>, // WorkflowEntrypoint type\n // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s\n // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to\n // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project.\n // The callback env is resolved from the inferred constructor via `ResolveEnv` instead.\n // oxlint-disable-next-line typescript/no-explicit-any\n C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any> = new (\n ctx: ExecutionContext,\n // oxlint-disable-next-line typescript/no-explicit-any\n env: any,\n ) => T, // Constructor type of the WorkflowEntrypoint class\n O = unknown,\n>(optionsCallback: (env: ResolveEnv<C, E>) => StrictCloudflareOptions<O>, WorkFlowClass: C): C {\n const InstrumentedClass = new Proxy(WorkFlowClass, {\n // oxlint-disable-next-line typescript/no-explicit-any\n construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) {\n const [ctx, env] = args;\n const context = instrumentContext(ctx);\n const options = optionsCallback(env);\n args[0] = context;\n args[1] = instrumentEnv(env as Record<string, unknown>, options) as E;\n const instance = Reflect.construct(target, args, newTarget) as T;\n return new Proxy(instance, {\n get(obj, prop, receiver) {\n if (prop === 'run') {\n return async function (event: WorkflowEvent<P>, step: WorkflowStep): Promise<unknown> {\n setAsyncLocalStorageAsyncContextStrategyForWorker();\n\n return withInvocationIsolationScope(async isolationScope => {\n const waitUntil = getOriginalWaitUntil(context).bind(context);\n const client = init({ ...options, ctx: context, enableDedupe: false });\n isolationScope.setClient(client);\n\n addCloudResourceContext(isolationScope);\n\n return withScope(async scope => {\n const propagationContext = await propagationContextFromInstanceId(event.instanceId);\n scope.setPropagationContext(propagationContext);\n\n try {\n return await obj.run.call(\n obj,\n event,\n new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope),\n );\n } finally {\n waitUntil(flushAndDispose(client));\n }\n });\n }, context);\n };\n }\n return Reflect.get(obj, prop, receiver);\n },\n });\n },\n });\n // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers.\n markAsInstrumented(InstrumentedClass);\n return InstrumentedClass;\n}\n"],"names":[],"mappings":";;;;;;;;;;;;;AA8CA,MAAM,UAAA,GAAa,qEAAA;AAKnB,eAAsB,mCAAmC,UAAA,EAAqC;AAC5F,EAAA,MA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ACnC;AAAA,gBACF,CAAC,CAAA;AAAA,cACH,GAAG,OAAO,CAAA;AAAA,YACZ,CAAA;AAAA,UACF;AACA,UAAA,OAAO,OAAA,CAAQ,GAAA,CAAI,GAAA,EAAK,IAAA,EAAM,QAAQ,CAAA;AAAA,QACxC;AAAA,OACD,CAAA;AAAA,IACH;AAAA,GACD,CAAA;AAED,EAAA,kBAAA,CAAmB,iBAAiB,CAAA;AACpC,EAAA,OAAO,iBAAA;AACT;;;;"}
|
|
@@ -1,17 +1,20 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
1
|
+
import { NETWORK_PROTOCOL_NAME, NETWORK_PROTOCOL_VERSION } from '@sentry/conventions/attributes';
|
|
2
|
+
import { safeCallback, getIsolationScope } from '@sentry/core';
|
|
3
|
+
import { _INTERNAL_handleServedTunnelRequest } from '@sentry/core/server';
|
|
4
|
+
import { wrapServerRequestHandler } from '@sentry/server-utils/request-handler';
|
|
5
5
|
import { DEBUG_BUILD } from './debug-build.js';
|
|
6
|
-
import {
|
|
6
|
+
import { getHttpServerRequestOptions } from './integrations/httpServer.js';
|
|
7
7
|
import { flushDeferredChannelEvents } from './orchestrion-deferred-channels.js';
|
|
8
8
|
import { getOriginalWaitUntil, flushAndDispose } from './flush.js';
|
|
9
|
-
import { addCloudResourceContext,
|
|
9
|
+
import { addCloudResourceContext, addCultureContext } from './scope-utils.js';
|
|
10
10
|
import { getInvocationState, getInvocationWaitUntil } from './utils/invocationContext.js';
|
|
11
11
|
import { withInvocationIsolationScope } from './utils/invocationScope.js';
|
|
12
12
|
|
|
13
|
+
function isDurableObjectContext(context) {
|
|
14
|
+
return !!context && "storage" in context;
|
|
15
|
+
}
|
|
13
16
|
function getRequestErrorMechanismType(context) {
|
|
14
|
-
return context
|
|
17
|
+
return isDurableObjectContext(context) ? "auto.faas.cloudflare.durable_object" : "auto.http.cloudflare";
|
|
15
18
|
}
|
|
16
19
|
function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
|
|
17
20
|
return withInvocationIsolationScope(async (isolationScope) => {
|
|
@@ -19,37 +22,15 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
|
|
|
19
22
|
const context = wrapperOptions.context;
|
|
20
23
|
const invocationState = getInvocationState();
|
|
21
24
|
const waitUntil = invocationState ? getInvocationWaitUntil(invocationState) : context ? getOriginalWaitUntil(context).bind(context) : void 0;
|
|
22
|
-
const errorMechanismType = getRequestErrorMechanismType(context);
|
|
23
25
|
const client = initSdk({ ...options, ctx: context });
|
|
24
26
|
isolationScope.setClient(client);
|
|
25
27
|
flushDeferredChannelEvents();
|
|
26
|
-
const
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
"server",
|
|
30
|
-
"auto.http.cloudflare",
|
|
31
|
-
request,
|
|
32
|
-
void 0,
|
|
33
|
-
client
|
|
34
|
-
);
|
|
35
|
-
const name = attributes[SENTRY_SEGMENT_NAME_SOURCE] === "route" || !client || !hasSpanStreamingEnabled(client) ? rawName : request.method?.toUpperCase() || HTTP_SPAN_NAME_FALLBACK;
|
|
36
|
-
const contentLength = request.headers.get("content-length");
|
|
37
|
-
if (contentLength) {
|
|
38
|
-
attributes["http.request.body.size"] = parseInt(contentLength, 10);
|
|
39
|
-
}
|
|
40
|
-
const userAgentHeader = request.headers.get("user-agent");
|
|
41
|
-
if (userAgentHeader) {
|
|
42
|
-
attributes["user_agent.original"] = userAgentHeader;
|
|
43
|
-
}
|
|
44
|
-
if (client) {
|
|
45
|
-
Object.assign(
|
|
46
|
-
attributes,
|
|
47
|
-
httpHeadersToSpanAttributes(winterCGHeadersToDict(request.headers), client.getDataCollectionOptions())
|
|
48
|
-
);
|
|
28
|
+
const tunnelResponse = !isDurableObjectContext(context) && _INTERNAL_handleServedTunnelRequest(request, client);
|
|
29
|
+
if (tunnelResponse) {
|
|
30
|
+
return tunnelResponse.finally(() => waitUntil?.(flushAndDispose(client)));
|
|
49
31
|
}
|
|
50
|
-
attributes[SENTRY_OP] = HTTP_SERVER;
|
|
51
32
|
addCloudResourceContext(isolationScope);
|
|
52
|
-
|
|
33
|
+
const attributes = {};
|
|
53
34
|
if (request.cf) {
|
|
54
35
|
addCultureContext(isolationScope, request.cf);
|
|
55
36
|
if (typeof request.cf.httpProtocol === "string") {
|
|
@@ -58,97 +39,42 @@ function wrapRequestHandlerWithInit(wrapperOptions, handler, initSdk) {
|
|
|
58
39
|
attributes[NETWORK_PROTOCOL_VERSION] = protocolVersion;
|
|
59
40
|
}
|
|
60
41
|
}
|
|
61
|
-
if (
|
|
42
|
+
if (!client) {
|
|
62
43
|
try {
|
|
63
44
|
return await handler();
|
|
64
|
-
} catch (e) {
|
|
65
|
-
if (captureErrors) {
|
|
66
|
-
captureException(e, { mechanism: { handled: false, type: errorMechanismType } });
|
|
67
|
-
}
|
|
68
|
-
throw e;
|
|
69
45
|
} finally {
|
|
70
46
|
waitUntil?.(flushAndDispose(client));
|
|
71
47
|
}
|
|
72
48
|
}
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
onSpanEnd(span, request, res);
|
|
98
|
-
span.end();
|
|
99
|
-
}
|
|
100
|
-
};
|
|
101
|
-
const userClassification = safeCallback(
|
|
102
|
-
DEBUG_BUILD ? "Error in `isStreamingResponse`, using the default classification:" : "",
|
|
103
|
-
() => options.isStreamingResponse?.(res, request),
|
|
104
|
-
() => void 0
|
|
105
|
-
);
|
|
106
|
-
const isStreaming = typeof userClassification === "boolean" ? userClassification : classifyResponseStreaming(res).isStreaming;
|
|
107
|
-
if (isStreaming && res.body) {
|
|
108
|
-
try {
|
|
109
|
-
let transformerUsed = false;
|
|
110
|
-
const endSpanOnce = () => {
|
|
111
|
-
if (ended) return;
|
|
112
|
-
endSpan();
|
|
49
|
+
return wrapServerRequestHandler(
|
|
50
|
+
{
|
|
51
|
+
request,
|
|
52
|
+
client,
|
|
53
|
+
// Without `AsyncLocalStorage`, `withInvocationIsolationScope` does not fork, and the scope it
|
|
54
|
+
// passes in is not the current one. The request data has to go on the current scope, where
|
|
55
|
+
// events captured in the handler read it.
|
|
56
|
+
isolationScope: getIsolationScope(),
|
|
57
|
+
options: getHttpServerRequestOptions(client),
|
|
58
|
+
origin: "auto.http.cloudflare",
|
|
59
|
+
mechanism: captureErrors ? { handled: false, type: getRequestErrorMechanismType(context) } : void 0,
|
|
60
|
+
attributes,
|
|
61
|
+
isStreamingResponse: (response) => {
|
|
62
|
+
const classification = safeCallback(
|
|
63
|
+
DEBUG_BUILD ? "Error in `isStreamingResponse`, using the default classification:" : "",
|
|
64
|
+
() => options.isStreamingResponse?.(response, request),
|
|
65
|
+
() => void 0
|
|
66
|
+
);
|
|
67
|
+
return typeof classification === "boolean" ? classification : void 0;
|
|
68
|
+
},
|
|
69
|
+
onDone: (response) => {
|
|
70
|
+
if (response?.status === 101) {
|
|
71
|
+
waitUntil?.(client.flush(2e3));
|
|
72
|
+
} else {
|
|
113
73
|
waitUntil?.(flushAndDispose(client));
|
|
114
|
-
};
|
|
115
|
-
const transform = new TransformStream({
|
|
116
|
-
start() {
|
|
117
|
-
transformerUsed = true;
|
|
118
|
-
},
|
|
119
|
-
flush() {
|
|
120
|
-
endSpanOnce();
|
|
121
|
-
},
|
|
122
|
-
cancel() {
|
|
123
|
-
endSpanOnce();
|
|
124
|
-
}
|
|
125
|
-
});
|
|
126
|
-
if (transformerUsed) {
|
|
127
|
-
return new Response(res.body.pipeThrough(transform), res);
|
|
128
74
|
}
|
|
129
|
-
} catch {
|
|
130
75
|
}
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
if (res.status === 101) {
|
|
134
|
-
waitUntil?.(client?.flush(2e3));
|
|
135
|
-
} else {
|
|
136
|
-
waitUntil?.(flushAndDispose(client));
|
|
137
|
-
}
|
|
138
|
-
return res;
|
|
139
|
-
};
|
|
140
|
-
const createSpan = shouldCreateIncomingRequestSpan(client, request);
|
|
141
|
-
return continueTrace(
|
|
142
|
-
{ sentryTrace: request.headers.get("sentry-trace") || "", baggage: request.headers.get("baggage") },
|
|
143
|
-
() => {
|
|
144
|
-
if (!createSpan) {
|
|
145
|
-
return respond(void 0);
|
|
146
|
-
}
|
|
147
|
-
return startSpanManual({ name, attributes }, (span) => {
|
|
148
|
-
onSpanCreated(span, request);
|
|
149
|
-
return respond(span);
|
|
150
|
-
});
|
|
151
|
-
}
|
|
76
|
+
},
|
|
77
|
+
() => handler()
|
|
152
78
|
);
|
|
153
79
|
}, wrapperOptions.context);
|
|
154
80
|
}
|