-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathworkflows.ts
More file actions
216 lines (194 loc) · 7.51 KB
/
workflows.ts
File metadata and controls
216 lines (194 loc) · 7.51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
import type { PropagationContext } from '@sentry/core';
import {
captureException,
flush,
getCurrentScope,
SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN,
SEMANTIC_ATTRIBUTE_SENTRY_SOURCE,
startSpan,
withIsolationScope,
withScope,
} from '@sentry/core';
import type {
WorkflowEntrypoint,
WorkflowEvent,
WorkflowSleepDuration,
WorkflowStep,
WorkflowStepConfig,
WorkflowStepEvent,
WorkflowTimeoutDuration,
} from 'cloudflare:workers';
import { setAsyncLocalStorageAsyncContextStrategy } from './async';
import type { CloudflareOptions } from './client';
import { addCloudResourceContext } from './scope-utils';
import { init } from './sdk';
import { copyExecutionContext } from './utils/copyExecutionContext';
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<string> {
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<PropagationContext> {
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,
};
}
class WrappedWorkflowStep implements WorkflowStep {
public constructor(
private _instanceId: string,
private _ctx: ExecutionContext,
private _options: CloudflareOptions,
private _step: WorkflowStep,
) {}
public async do<T extends Rpc.Serializable<T>>(name: string, callback: () => Promise<T>): Promise<T>;
public async do<T extends Rpc.Serializable<T>>(
name: string,
config: WorkflowStepConfig,
callback: () => Promise<T>,
): Promise<T>;
public async do<T extends Rpc.Serializable<T>>(
name: string,
configOrCallback: WorkflowStepConfig | (() => Promise<T>),
maybeCallback?: () => Promise<T>,
): Promise<T> {
// Capture the current scope, so parent span (e.g., a startSpan surrounding step.do) is preserved
const scopeForStep = getCurrentScope();
const userCallback = (maybeCallback || configOrCallback) as () => Promise<T>;
const config = typeof configOrCallback === 'function' ? undefined : configOrCallback;
const instrumentedCallback: () => Promise<T> = async () => {
return startSpan(
{
op: 'function.step.do',
name,
scope: scopeForStep,
attributes: {
'cloudflare.workflow.timeout': config?.timeout,
'cloudflare.workflow.retries.backoff': config?.retries?.backoff,
'cloudflare.workflow.retries.delay': config?.retries?.delay,
'cloudflare.workflow.retries.limit': config?.retries?.limit,
[SEMANTIC_ATTRIBUTE_SENTRY_ORIGIN]: 'auto.faas.cloudflare.workflow',
[SEMANTIC_ATTRIBUTE_SENTRY_SOURCE]: 'task',
},
},
async span => {
try {
const result = await userCallback();
span.setStatus({ code: 1 });
return result;
} catch (error) {
captureException(error, { mechanism: { handled: true, type: 'auto.faas.cloudflare.workflow' } });
throw error;
} finally {
this._ctx.waitUntil(flush(2000));
}
},
);
};
return config ? this._step.do(name, config, instrumentedCallback) : this._step.do(name, instrumentedCallback);
}
public async sleep(name: string, duration: WorkflowSleepDuration): Promise<void> {
return this._step.sleep(name, duration);
}
public async sleepUntil(name: string, timestamp: Date | number): Promise<void> {
return this._step.sleepUntil(name, timestamp);
}
public async waitForEvent<T extends Rpc.Serializable<T>>(
name: string,
options: { type: string; timeout?: WorkflowTimeoutDuration | number },
): Promise<WorkflowStepEvent<T>> {
return this._step.waitForEvent<T>(name, options);
}
}
/**
* Helper type to extract the environment type from a WorkflowEntrypoint constructor.
* This extracts the second parameter type (env) from the constructor signature.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ExtractEnv<C> = C extends new (ctx: any, env: infer E) => any ? E : never;
/**
* Helper type to extract the payload type from a WorkflowEntrypoint constructor.
* This extracts the second parameter type (P) from the constructor signature.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type ExtractPayload<C> = C extends new (ctx: any, env: any, payload: infer P) => any ? P : never;
/**
* 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<
// eslint-disable-next-line @typescript-eslint/no-explicit-any
C extends new (ctx: ExecutionContext, env: any) => WorkflowEntrypoint<any, any>,
>(optionsCallback: (env: ExtractEnv<C>) => CloudflareOptions, WorkFlowClass: C): C {
type Env = ExtractEnv<C>;
type Payload = ExtractPayload<C>;
type T = WorkflowEntrypoint<Env, Payload>;
return new Proxy(WorkFlowClass, {
construct(target: C, args: [ctx: ExecutionContext, env: Env], newTarget) {
const [ctx, env] = args;
const context = copyExecutionContext(ctx);
args[0] = context;
const options = optionsCallback(env);
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<Payload>, step: WorkflowStep): Promise<unknown> {
setAsyncLocalStorageAsyncContextStrategy();
return withIsolationScope(async isolationScope => {
const client = init({ ...options, 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, context, options, step),
);
} finally {
context.waitUntil(flush(2000));
}
});
});
};
}
return Reflect.get(obj, prop, receiver);
},
});
},
});
}