import { SENTRY_SEGMENT_NAME_SOURCE, CODE_FUNCTION_NAME, SENTRY_OP, SENTRY_ORIGIN, CLOUDFLARE_WORKFLOW_ATTEMPT, CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF, CLOUDFLARE_WORKFLOW_RETRIES_DELAY, CLOUDFLARE_WORKFLOW_RETRIES_LIMIT, CLOUDFLARE_WORKFLOW_TIMEOUT, } from '@sentry/conventions/attributes'; import { FUNCTION } from '@sentry/conventions/op'; import type { PropagationContext, Scope } from '@sentry/core'; import { captureException, checkOrSetAlreadyCaught, flush, getCurrentScope, isError, startSpan, withIsolationScope, withScope, } from '@sentry/core'; import type { WorkflowDelayDuration, WorkflowEntrypoint, WorkflowEvent, WorkflowSleepDuration, WorkflowStep, WorkflowStepConfig, WorkflowStepContext, WorkflowStepEvent, WorkflowStepRollbackOptions, WorkflowTimeoutDuration, } from 'cloudflare:workers'; import { setAsyncLocalStorageAsyncContextStrategyForWorker } from './utils/asyncContextStrategy'; import type { CloudflareOptions } from './client'; import { flushAndDispose, getOriginalWaitUntil } from './flush'; import { markAsInstrumented } from './instrument'; import { instrumentEnv } from './instrumentations/worker/instrumentEnv'; import { addCloudResourceContext } from './scope-utils'; import { init } from './sdk'; import { instrumentContext } from './utils/instrumentContext'; import type { DefaultEnv, ResolveEnv, StrictCloudflareOptions } from './types'; import { getInvocationState } from './utils/invocationContext'; import { withInvocationIsolationScope } from './utils/invocationScope'; const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i; /** * Hashes a string to a UUID using SHA-1. */ export async function deterministicTraceIdFromInstanceId(instanceId: string): Promise { const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId)); return ( Array.from(new Uint8Array(buf)) // We only need the first 16 bytes for the 32 characters .slice(0, 16) .map(b => b.toString(16).padStart(2, '0')) .join('') ); } async function propagationContextFromInstanceId(instanceId: string): Promise { const traceId = UUID_REGEX.test(instanceId) ? instanceId.replace(/-/g, '') : await deterministicTraceIdFromInstanceId(instanceId); // Derive sampleRand from last 4 characters of the random UUID // // We cannot store any state between workflow steps, so we derive the // sampleRand from the traceId itself. This ensures that the sampling is // consistent across all steps in the same workflow instance. const sampleRand = parseInt(traceId.slice(-4), 16) / 0xffff; return { traceId, sampleRand, }; } // Same check the Workflows engine uses to stop retrying a step. Not `constructor.name`: a // `NonRetryableError` with a custom `name` is retried, so capturing it early would duplicate events. function isNonRetryableError(error: unknown): boolean { return ( isError(error) && (error.name === 'NonRetryableError' || String(error.message).startsWith('NonRetryableError')) ); } class WrappedWorkflowStep implements WorkflowStep { public constructor( private _instanceId: string, private _options: CloudflareOptions, private _step: WorkflowStep, private _waitUntil: ExecutionContext['waitUntil'], private _isolationScope: Scope, ) {} public async do>( name: string, callback: (ctx: WorkflowStepContext) => Promise, rollbackOptions?: WorkflowStepRollbackOptions, ): Promise; public async do, const C extends WorkflowStepConfig>( name: string, config: C, callback: ( ctx: WorkflowStepContext, ) => Promise, rollbackOptions?: WorkflowStepRollbackOptions, ): Promise; public async do>( name: string, configOrCallback: WorkflowStepConfig | ((ctx: WorkflowStepContext) => Promise), callbackOrRollback?: ((ctx: WorkflowStepContext) => Promise) | WorkflowStepRollbackOptions, maybeRollback?: WorkflowStepRollbackOptions, ): Promise { // Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved const scopeForStep = getCurrentScope(); const hasConfig = typeof configOrCallback !== 'function'; const config = hasConfig ? configOrCallback : undefined; const userCallback = (hasConfig ? callbackOrRollback : configOrCallback) as ( ctx: WorkflowStepContext, ) => Promise; const rollbackOptions = (hasConfig ? maybeRollback : callbackOrRollback) as | WorkflowStepRollbackOptions | undefined; let capturedByCallback = false; const instrumentedCallback = async (...args: unknown[]): Promise => { // Feature detection: Cloudflare Workflows (April 2026+) pass a step context // with `attempt` and `config.retries.limit`. When available, we only capture // errors on the final attempt to avoid duplicates during retries. const stepContext = args[0] as { attempt?: number; config?: { retries?: { limit?: number } } } | undefined; const attempt = stepContext?.attempt; const retryLimit = stepContext?.config?.retries?.limit; const hasStepContext = typeof attempt === 'number' && typeof retryLimit === 'number'; // Only capture error on final attempt (attempt > retryLimit means no more retries left) // or when step context is unavailable (legacy behavior - capture all errors) const isFinalAttempt = !hasStepContext || attempt > retryLimit; // The engine invokes step callbacks outside the async context of `run`, so the // run's isolation scope (and with it the invocation state that ties eager sends // to this invocation's `waitUntil`) has to be restored explicitly. return withIsolationScope(this._isolationScope, () => { const invocationState = getInvocationState(); if (invocationState) { invocationState.flushPointReached = false; } const stepResult = startSpan( { name, scope: scopeForStep, attributes: { [SENTRY_OP]: FUNCTION, [CODE_FUNCTION_NAME]: name, 'workflow.step.name': name, [CLOUDFLARE_WORKFLOW_TIMEOUT]: config?.timeout, [CLOUDFLARE_WORKFLOW_RETRIES_BACKOFF]: config?.retries?.backoff, // In workers-types v5, `delay` may be a `WorkflowDelayFunction`, which isn't a valid span attribute value. [CLOUDFLARE_WORKFLOW_RETRIES_DELAY]: typeof config?.retries?.delay === 'function' ? undefined : config?.retries?.delay, [CLOUDFLARE_WORKFLOW_RETRIES_LIMIT]: config?.retries?.limit, [CLOUDFLARE_WORKFLOW_ATTEMPT]: attempt, [SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow', [SENTRY_SEGMENT_NAME_SOURCE]: 'task', }, }, async span => { try { const result = await (userCallback as (...args: unknown[]) => Promise)(...args); span.setStatus({ code: 1 }); return result; } catch (error) { if (isFinalAttempt || isNonRetryableError(error)) { captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } }); capturedByCallback = true; } throw error; } }, ); // Deliver after the step span has ended, so the span rides this flush instead of // starting an eager drain (same ordering as `wrapMethodWithSentry`'s teardown). The flush runs on the // step's scope: the engine calls the step callback outside of `run()`, so the current scope here has // neither the client nor the run's trace, and envelopes without a DSC are dropped by Relay. return stepResult.then( result => { this._waitUntil(withScope(scopeForStep, () => flush(2000))); return result; }, error => { this._waitUntil(withScope(scopeForStep, () => flush(2000))); throw error; }, ); }); }; let stepResult: Promise; if (config) { stepResult = rollbackOptions ? this._step.do(name, config, instrumentedCallback, rollbackOptions) : this._step.do(name, config, instrumentedCallback); } else { stepResult = rollbackOptions ? this._step.do(name, instrumentedCallback, rollbackOptions) : this._step.do(name, instrumentedCallback); } return stepResult.catch(error => { // The engine rejects with a copy of the error the callback threw. `checkOrSetAlreadyCaught` is used // only to mark that copy as captured, so `run` does not report the same failure a second time. // Rejections the callback did not capture (step timeout, engine failure) stay unmarked. if (capturedByCallback) { checkOrSetAlreadyCaught(error); } throw error; }); } public async sleep(name: string, duration: WorkflowSleepDuration): Promise { return this._step.sleep(name, duration); } public async sleepUntil(name: string, timestamp: Date | number): Promise { return this._step.sleepUntil(name, timestamp); } public async waitForEvent>( name: string, options: { type: string; timeout?: WorkflowTimeoutDuration | number }, ): Promise> { return this._step.waitForEvent(name, options); } } /** * Instruments a Cloudflare Workflow class with Sentry. * * @example * ```typescript * const InstrumentedWorkflow = instrumentWorkflowWithSentry( * (env) => ({ dsn: env.SENTRY_DSN }), * MyWorkflowClass * ); * * export default InstrumentedWorkflow; * ``` * * @param optionsCallback - Function that returns Sentry options to initialize Sentry * @param WorkflowClass - The workflow class to instrument * @returns Instrumented workflow class with the same interface */ export function instrumentWorkflowWithSentry< E = DefaultEnv, // Environment type P = unknown, // Payload type // oxlint-disable-next-line typescript/no-explicit-any T extends WorkflowEntrypoint = WorkflowEntrypoint, // WorkflowEntrypoint type // The constraint must not route through `T`: workers-types defaults `WorkflowEntrypoint`'s // `Env` to `unknown` (unlike `WorkerEntrypoint`/`DurableObject`, which default to // `Cloudflare.Env`), so a bare subclass would be rejected in a `wrangler types` project. // The callback env is resolved from the inferred constructor via `ResolveEnv` instead. // oxlint-disable-next-line typescript/no-explicit-any C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint = new ( ctx: ExecutionContext, // oxlint-disable-next-line typescript/no-explicit-any env: any, ) => T, // Constructor type of the WorkflowEntrypoint class O = unknown, >(optionsCallback: (env: ResolveEnv) => StrictCloudflareOptions, WorkFlowClass: C): C { const InstrumentedClass = new Proxy(WorkFlowClass, { // oxlint-disable-next-line typescript/no-explicit-any construct(target: C, args: [ctx: ExecutionContext, env: any], newTarget) { const [ctx, env] = args; const context = instrumentContext(ctx); const options = optionsCallback(env); args[0] = context; args[1] = instrumentEnv(env as Record, options) as E; const instance = Reflect.construct(target, args, newTarget) as T; return new Proxy(instance, { get(obj, prop, receiver) { if (prop === 'run') { return async function (event: WorkflowEvent

, step: WorkflowStep): Promise { setAsyncLocalStorageAsyncContextStrategyForWorker(); return withInvocationIsolationScope(async isolationScope => { const waitUntil = getOriginalWaitUntil(context).bind(context); const client = init({ ...options, ctx: context, enableDedupe: false }); isolationScope.setClient(client); addCloudResourceContext(isolationScope); return withScope(async scope => { const propagationContext = await propagationContextFromInstanceId(event.instanceId); scope.setPropagationContext(propagationContext); try { return await obj.run.call( obj, event, new WrappedWorkflowStep(event.instanceId, options, step, waitUntil, isolationScope), ); } catch (error) { captureException(error, { mechanism: { handled: false, type: 'auto.faas.cloudflare.workflow' } }); throw error; } finally { waitUntil(flushAndDispose(client)); } }); }, context); }; } return Reflect.get(obj, prop, receiver); }, }); }, }); // Recognizable for `_INTERNAL_wrapUnlessInstrumented`, so auto-instrumentation never nests wrappers. markAsInstrumented(InstrumentedClass); return InstrumentedClass; }