Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 13 additions & 8 deletions packages/cloudflare/src/workflows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,14 +24,19 @@ import { init } from './sdk';

const UUID_REGEX = /^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}$/i;

function propagationContextFromInstanceId(instanceId: string): PropagationContext {
// Validate and normalize traceId - should be a valid UUID with or without hyphens
if (!UUID_REGEX.test(instanceId)) {
throw new Error("Invalid 'instanceId' for workflow: Sentry requires random UUIDs for instanceId.");
}
async function hashStringToUuid(input: string): Promise<string> {
Copy link
Member

@AbhiPrasad AbhiPrasad Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we add some unit tests for this? Lets test some different kind of inputs.

Copy link
Collaborator Author

@timfish timfish Jul 23, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also changed this to be called deterministicTraceIdFromInstanceId since that's what it actually does!

const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(input));
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('')
);
}

// Remove hyphens to get UUID without hyphens
const traceId = instanceId.replace(/-/g, '');
async function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {
const traceId = UUID_REGEX.test(instanceId) ? instanceId.replace(/-/g, '') : await hashStringToUuid(instanceId);

// Derive sampleRand from last 4 characters of the random UUID
//
Expand Down Expand Up @@ -60,7 +65,7 @@ async function workflowStepWithSentry<V>(
addCloudResourceContext(isolationScope);

return withScope(async scope => {
const propagationContext = propagationContextFromInstanceId(instanceId);
const propagationContext = await propagationContextFromInstanceId(instanceId);
scope.setPropagationContext(propagationContext);

// eslint-disable-next-line no-return-await
Expand Down
71 changes: 71 additions & 0 deletions packages/cloudflare/test/workflow.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,12 @@
import { beforeEach, describe, expect, test, vi } from 'vitest';
import { instrumentWorkflowWithSentry } from '../src/workflows';

const NODE_MAJOR_VERSION = parseInt(process.versions.node.split('.')[0]!);

if (NODE_MAJOR_VERSION < 20) {
process.exit(0); // Skip tests for Node.js versions below 20

Check failure on line 9 in packages/cloudflare/test/workflow.test.ts

View workflow job for this annotation

GitHub Actions / Node (18) Unit Tests

test/workflow.test.ts

Error: process.exit unexpectedly called with "0" ❯ test/workflow.test.ts:9:11
}

const mockStep: WorkflowStep = {
do: vi
.fn()
Expand Down Expand Up @@ -133,6 +139,71 @@
]);
});

test('Calls expected functions with non-uuid instance id', async () => {
class BasicTestWorkflow {
constructor(_ctx: ExecutionContext, _env: unknown) {}

async run(_event: Readonly<WorkflowEvent<Params>>, step: WorkflowStep): Promise<void> {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const files = await step.do('first step', async () => {
return { files: ['doc_7392_rev3.pdf', 'report_x29_final.pdf'] };
});
}
}

const TestWorkflowInstrumented = instrumentWorkflowWithSentry(getSentryOptions, BasicTestWorkflow as any);
const workflow = new TestWorkflowInstrumented(mockContext, {}) as BasicTestWorkflow;
const event = { payload: {}, timestamp: new Date(), instanceId: 'ae0ee067' };
await workflow.run(event, mockStep);

expect(mockStep.do).toHaveBeenCalledTimes(1);
expect(mockStep.do).toHaveBeenCalledWith('first step', expect.any(Function));
expect(mockContext.waitUntil).toHaveBeenCalledTimes(1);
expect(mockContext.waitUntil).toHaveBeenCalledWith(expect.any(Promise));
expect(mockTransport.send).toHaveBeenCalledTimes(1);
expect(mockTransport.send).toHaveBeenCalledWith([
expect.objectContaining({
trace: expect.objectContaining({
transaction: 'first step',
trace_id: '0d2b6d1743ce6d53af4f5ee416ad5d1b',
sample_rand: '0.3636987869077592',
}),
}),
[
[
{
type: 'transaction',
},
expect.objectContaining({
event_id: expect.any(String),
contexts: {
trace: {
parent_span_id: undefined,
span_id: expect.any(String),
trace_id: '0d2b6d1743ce6d53af4f5ee416ad5d1b',
data: {
'sentry.origin': 'auto.faas.cloudflare.workflow',
'sentry.op': 'function.step.do',
'sentry.source': 'task',
'sentry.sample_rate': 1,
},
op: 'function.step.do',
status: 'ok',
origin: 'auto.faas.cloudflare.workflow',
},
cloud_resource: { 'cloud.provider': 'cloudflare' },
runtime: { name: 'cloudflare' },
},
type: 'transaction',
transaction_info: { source: 'task' },
start_timestamp: expect.any(Number),
timestamp: expect.any(Number),
}),
],
],
]);
});

class ErrorTestWorkflow {
count = 0;
constructor(_ctx: ExecutionContext, _env: unknown) {}
Expand Down
Loading