Skip to content

Commit 59a1166

Browse files
committed
PR review
1 parent f16fca8 commit 59a1166

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

packages/cloudflare/src/workflows.ts

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,11 @@ import { init } from './sdk';
2424

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

27-
async function hashStringToUuid(input: string): Promise<string> {
28-
const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(input));
27+
/**
28+
* Hashes a string to a UUID using SHA-1.
29+
*/
30+
export async function deterministicTraceIdFromInstanceId(instanceId: string): Promise<string> {
31+
const buf = await crypto.subtle.digest('SHA-1', new TextEncoder().encode(instanceId));
2932
return (
3033
Array.from(new Uint8Array(buf))
3134
// We only need the first 16 bytes for the 32 characters
@@ -36,7 +39,9 @@ async function hashStringToUuid(input: string): Promise<string> {
3639
}
3740

3841
async function propagationContextFromInstanceId(instanceId: string): Promise<PropagationContext> {
39-
const traceId = UUID_REGEX.test(instanceId) ? instanceId.replace(/-/g, '') : await hashStringToUuid(instanceId);
42+
const traceId = UUID_REGEX.test(instanceId)
43+
? instanceId.replace(/-/g, '')
44+
: await deterministicTraceIdFromInstanceId(instanceId);
4045

4146
// Derive sampleRand from last 4 characters of the random UUID
4247
//

packages/cloudflare/test/workflow.test.ts

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
/* eslint-disable @typescript-eslint/unbound-method */
22
import type { WorkflowEvent, WorkflowStep, WorkflowStepConfig } from 'cloudflare:workers';
33
import { beforeEach, describe, expect, test, vi } from 'vitest';
4-
import { instrumentWorkflowWithSentry } from '../src/workflows';
4+
import { deterministicTraceIdFromInstanceId, instrumentWorkflowWithSentry } from '../src/workflows';
55

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

@@ -74,6 +74,13 @@ describe('workflows', () => {
7474
vi.clearAllMocks();
7575
});
7676

77+
test('hashStringToUuid hashes a string to a UUID for Sentry trace ID', async () => {
78+
const UUID_WITHOUT_HYPHENS_REGEX = /^[0-9a-f]{32}$/i;
79+
expect(await deterministicTraceIdFromInstanceId('s')).toMatch(UUID_WITHOUT_HYPHENS_REGEX);
80+
expect(await deterministicTraceIdFromInstanceId('test-string')).toMatch(UUID_WITHOUT_HYPHENS_REGEX);
81+
expect(await deterministicTraceIdFromInstanceId(INSTANCE_ID)).toMatch(UUID_WITHOUT_HYPHENS_REGEX);
82+
});
83+
7784
test('Calls expected functions', async () => {
7885
class BasicTestWorkflow {
7986
constructor(_ctx: ExecutionContext, _env: unknown) {}

0 commit comments

Comments
 (0)