-
Notifications
You must be signed in to change notification settings - Fork 236
Expand file tree
/
Copy pathhelpers.ts
More file actions
427 lines (385 loc) · 12.5 KB
/
helpers.ts
File metadata and controls
427 lines (385 loc) · 12.5 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
import type {
Event,
HealthCheckPayload,
ValidQueueName,
World,
} from '@workflow/world';
import { HealthCheckPayloadSchema, SPEC_VERSION_CURRENT } from '@workflow/world';
import { monotonicFactory } from 'ulid';
import { runtimeLogger } from '../logger.js';
import * as Attribute from '../telemetry/semantic-conventions.js';
import { getSpanKind, trace } from '../telemetry.js';
import { getWorld } from './world.js';
/** Default timeout for health checks in milliseconds */
const DEFAULT_HEALTH_CHECK_TIMEOUT = 30_000;
/**
* Pattern for safe workflow names. Only allows alphanumeric characters,
* underscores, hyphens, dots, forward slashes (for namespaced workflows),
* and at signs (for scoped packages).
*/
const SAFE_WORKFLOW_NAME_PATTERN = /^[a-zA-Z0-9_\-./@]+$/;
/**
* Validates a workflow name and returns the corresponding queue name.
* Ensures the workflow name only contains safe characters before
* interpolating it into the queue name string.
*/
export function getWorkflowQueueName(workflowName: string): ValidQueueName {
if (!SAFE_WORKFLOW_NAME_PATTERN.test(workflowName)) {
throw new Error(
`Invalid workflow name "${workflowName}": must only contain alphanumeric characters, underscores, hyphens, dots, forward slashes, or at signs`
);
}
return `__wkf_workflow_${workflowName}` as ValidQueueName;
}
const generateId = monotonicFactory();
/**
* Returns the stream name for a health check with the given correlation ID.
*/
function getHealthCheckStreamName(correlationId: string): string {
return `__health_check__${correlationId}`;
}
/**
* Result of a health check operation.
*/
export interface HealthCheckResult {
healthy: boolean;
/** Error message if health check failed */
error?: string;
/** Latency if the health check was successful */
latencyMs?: number;
}
/**
* Checks if the given message is a health check payload.
* If so, returns the parsed payload. Otherwise returns undefined.
*/
export function parseHealthCheckPayload(
message: unknown
): HealthCheckPayload | undefined {
const result = HealthCheckPayloadSchema.safeParse(message);
if (result.success) {
return result.data;
}
return undefined;
}
/**
* Generates a fake runId for health check streams.
* This runId passes server validation but is not associated with a real run.
* The server skips run validation for streams starting with `__health_check__`.
*/
function generateHealthCheckRunId(): string {
return `wrun_${generateId()}`;
}
/**
* Handles a health check message by writing the result to the world's stream.
* The caller can listen to this stream to get the health check response.
*
* @param healthCheck - The parsed health check payload
* @param endpoint - Which endpoint is responding ('workflow' or 'step')
*/
export async function handleHealthCheckMessage(
healthCheck: HealthCheckPayload,
endpoint: 'workflow' | 'step'
): Promise<void> {
const world = getWorld();
const streamName = getHealthCheckStreamName(healthCheck.correlationId);
const response = JSON.stringify({
healthy: true,
endpoint,
correlationId: healthCheck.correlationId,
specVersion: SPEC_VERSION_CURRENT,
timestamp: Date.now(),
});
// Use a fake runId that passes validation.
// The stream name includes the correlationId for identification.
// The server skips run validation for health check streams.
const fakeRunId = generateHealthCheckRunId();
await world.writeToStream(streamName, fakeRunId, response);
await world.closeStream(streamName, fakeRunId);
}
export type HealthCheckEndpoint = 'workflow' | 'step';
export interface HealthCheckOptions {
/** Timeout in milliseconds to wait for health check response. Default: 30000 (30s) */
timeout?: number;
}
/**
* Performs a health check by sending a message through the queue pipeline
* and verifying it is processed by the specified endpoint.
*
* This function bypasses Deployment Protection on Vercel because it goes
* through the queue infrastructure rather than direct HTTP.
*
* @param world - The World instance to use for the health check
* @param endpoint - Which endpoint to health check: 'workflow' or 'step'
* @param options - Optional configuration for the health check
* @returns Promise resolving to health check result
*/
// Poll interval for health check retries (ms)
const HEALTH_CHECK_POLL_INTERVAL = 100;
// Per-read timeout to prevent blocking forever on local world's EventEmitter
// (which doesn't work across processes)
const HEALTH_CHECK_READ_TIMEOUT = 500;
/**
* Read chunks from a stream with a timeout per read operation.
* Returns { chunks, timedOut } where timedOut indicates if a read timed out.
*/
async function readStreamWithTimeout(
reader: ReadableStreamDefaultReader<Uint8Array>,
readTimeout: number
): Promise<{ chunks: Uint8Array[]; timedOut: boolean }> {
const chunks: Uint8Array[] = [];
let done = false;
let timedOut = false;
while (!done && !timedOut) {
const readPromise = reader.read();
const timeoutPromise = new Promise<{ done: true; value: undefined }>(
(resolve) =>
setTimeout(() => {
timedOut = true;
resolve({ done: true, value: undefined });
}, readTimeout)
);
const result = await Promise.race([readPromise, timeoutPromise]);
done = result.done;
if (result.value) chunks.push(result.value);
}
return { chunks, timedOut };
}
/**
* Parse and validate a health check response from stream chunks.
* Returns the parsed response or null if invalid.
*/
function parseHealthCheckResponse(
chunks: Uint8Array[]
): { healthy: boolean } | null {
if (chunks.length === 0) return null;
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
const combined = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
combined.set(chunk, offset);
offset += chunk.length;
}
const responseText = new TextDecoder().decode(combined);
let response: unknown;
try {
response = JSON.parse(responseText);
} catch {
return null;
}
if (
typeof response !== 'object' ||
response === null ||
!('healthy' in response) ||
typeof (response as { healthy: unknown }).healthy !== 'boolean'
) {
return null;
}
return { healthy: (response as { healthy: boolean }).healthy };
}
export async function healthCheck(
world: World,
endpoint: HealthCheckEndpoint,
options?: HealthCheckOptions
): Promise<HealthCheckResult> {
const timeout = options?.timeout ?? DEFAULT_HEALTH_CHECK_TIMEOUT;
const correlationId = `hc_${generateId()}`;
const streamName = getHealthCheckStreamName(correlationId);
const queueName: ValidQueueName =
endpoint === 'workflow'
? '__wkf_workflow_health_check'
: '__wkf_step_health_check';
const startTime = Date.now();
try {
await world.queue(queueName, {
__healthCheck: true,
correlationId,
});
while (Date.now() - startTime < timeout) {
try {
const stream = await world.readFromStream(streamName);
const reader = stream.getReader();
const { chunks, timedOut } = await readStreamWithTimeout(
reader,
HEALTH_CHECK_READ_TIMEOUT
);
if (timedOut) {
try {
reader.cancel();
} catch {
// Ignore cancel errors
}
await new Promise((resolve) =>
setTimeout(resolve, HEALTH_CHECK_POLL_INTERVAL)
);
continue;
}
const response = parseHealthCheckResponse(chunks);
if (response) {
return {
...response,
latencyMs: Date.now() - startTime,
};
}
await new Promise((resolve) =>
setTimeout(resolve, HEALTH_CHECK_POLL_INTERVAL)
);
} catch {
await new Promise((resolve) =>
setTimeout(resolve, HEALTH_CHECK_POLL_INTERVAL)
);
}
}
return {
healthy: false,
error: `Health check timed out after ${timeout}ms`,
};
} catch (error) {
return {
healthy: false,
error: error instanceof Error ? error.message : String(error),
};
}
}
/**
* Loads all workflow run events by iterating through all pages of paginated results.
* This ensures that *all* events are loaded into memory before running the workflow.
* Events must be in chronological order (ascending) for proper workflow replay.
*/
export async function getAllWorkflowRunEvents(runId: string): Promise<Event[]> {
return trace('workflow.loadEvents', async (span) => {
span?.setAttributes({
...Attribute.WorkflowRunId(runId),
});
const allEvents: Event[] = [];
let cursor: string | null = null;
let hasMore = true;
let pagesLoaded = 0;
const world = getWorld();
const loadStart = Date.now();
while (hasMore) {
// TODO: we're currently loading all the data with resolveRef behaviour. We need to update this
// to lazyload the data from the world instead so that we can optimize and make the event log loading
// much faster and memory efficient
const pageStart = Date.now();
const response = await world.events.list({
runId,
pagination: {
sortOrder: 'asc', // Required: events must be in chronological order for replay
cursor: cursor ?? undefined,
},
});
allEvents.push(...response.data);
hasMore = response.hasMore;
cursor = response.cursor;
pagesLoaded++;
runtimeLogger.debug('Loaded event page', {
workflowRunId: runId,
page: pagesLoaded,
pageEvents: response.data.length,
totalEvents: allEvents.length,
hasMore,
pageMs: Date.now() - pageStart,
});
}
runtimeLogger.debug('Event loading complete', {
workflowRunId: runId,
totalEvents: allEvents.length,
pagesLoaded,
totalMs: Date.now() - loadStart,
});
span?.setAttributes({
...Attribute.WorkflowEventsCount(allEvents.length),
...Attribute.WorkflowEventsPagesLoaded(pagesLoaded),
});
return allEvents;
});
}
/**
* CORS headers for health check responses.
* Allows the observability UI to check endpoint health from a different origin.
*/
const HEALTH_CHECK_CORS_HEADERS = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Methods': 'POST, OPTIONS, GET, HEAD',
'Access-Control-Allow-Headers': 'Content-Type',
};
/**
* Wraps a request/response handler and adds a health check "mode"
* based on the presence of a `__health` query parameter.
*/
export function withHealthCheck(
handler: (req: Request) => Promise<Response>
): (req: Request) => Promise<Response> {
return async (req: Request) => {
const url = new URL(req.url);
const isHealthCheck = url.searchParams.has('__health');
if (isHealthCheck) {
// Handle CORS preflight for health check
if (req.method === 'OPTIONS') {
return new Response(null, {
status: 204,
headers: HEALTH_CHECK_CORS_HEADERS,
});
}
return new Response(
JSON.stringify({
healthy: true,
specVersion: SPEC_VERSION_CURRENT,
}),
{
status: 200,
headers: {
'Content-Type': 'application/json',
...HEALTH_CHECK_CORS_HEADERS,
},
}
);
}
return await handler(req);
};
}
/**
* Queues a message to the specified queue with tracing.
*/
export async function queueMessage(
world: World,
...args: Parameters<typeof world.queue>
) {
const queueName = args[0];
await trace(
'queue.publish',
{
// Standard OTEL messaging conventions
attributes: {
...Attribute.MessagingSystem('vercel-queue'),
...Attribute.MessagingDestinationName(queueName),
...Attribute.MessagingOperationType('publish'),
// Peer service for Datadog service maps
...Attribute.PeerService('vercel-queue'),
...Attribute.RpcSystem('vercel-queue'),
...Attribute.RpcService('vqs'),
...Attribute.RpcMethod('publish'),
},
kind: await getSpanKind('PRODUCER'),
},
async (span) => {
const { messageId } = await world.queue(...args);
if (messageId) {
span?.setAttributes(Attribute.MessagingMessageId(messageId));
}
}
);
}
/**
* Calculates the queue overhead time in milliseconds for a given message.
*/
export function getQueueOverhead(message: { requestedAt?: Date }) {
if (!message.requestedAt) return;
try {
return Attribute.QueueOverheadMs(
Date.now() - message.requestedAt.getTime()
);
} catch {
return;
}
}