-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathrunStream.ts
More file actions
785 lines (687 loc) · 21.3 KB
/
runStream.ts
File metadata and controls
785 lines (687 loc) · 21.3 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
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
import { EventSourceMessage, EventSourceParserStream } from "eventsource-parser/stream";
import { DeserializedJson } from "../../schemas/json.js";
import { createJsonErrorObject } from "../errors.js";
import { RunStatus, SubscribeRunRawShape } from "../schemas/api.js";
import { SerializedError } from "../schemas/common.js";
import {
AsyncIterableStream,
createAsyncIterableReadable,
} from "../streams/asyncIterableStream.js";
import { AnyRunTypes, AnyTask, InferRunTypes } from "../types/tasks.js";
import { getEnvVar } from "../utils/getEnv.js";
import {
conditionallyImportAndParsePacket,
IOPacket,
parsePacket,
} from "../utils/ioSerialization.js";
import { ApiError, isTriggerRealtimeAuthError } from "./errors.js";
import { ApiClient } from "./index.js";
import { zodShapeStream } from "./stream.js";
export type RunShape<TRunTypes extends AnyRunTypes> = TRunTypes extends AnyRunTypes
? {
id: string;
taskIdentifier: TRunTypes["taskIdentifier"];
payload: TRunTypes["payload"];
output?: TRunTypes["output"];
createdAt: Date;
updatedAt: Date;
status: RunStatus;
durationMs: number;
costInCents: number;
baseCostInCents: number;
tags: string[];
idempotencyKey?: string;
expiredAt?: Date;
ttl?: string;
finishedAt?: Date;
startedAt?: Date;
delayedUntil?: Date;
queuedAt?: Date;
metadata?: Record<string, DeserializedJson>;
error?: SerializedError;
isTest: boolean;
isQueued: boolean;
isExecuting: boolean;
isWaiting: boolean;
isCompleted: boolean;
isFailed: boolean;
isSuccess: boolean;
isCancelled: boolean;
realtimeStreams: string[];
}
: never;
export type AnyRunShape = RunShape<AnyRunTypes>;
export type TaskRunShape<TTask extends AnyTask> = RunShape<InferRunTypes<TTask>>;
export type RealtimeRun<TTask extends AnyTask> = TaskRunShape<TTask>;
export type AnyRealtimeRun = RealtimeRun<AnyTask>;
export type RealtimeRunSkipColumns = Array<
| "startedAt"
| "delayUntil"
| "queuedAt"
| "expiredAt"
| "completedAt"
| "number"
| "isTest"
| "usageDurationMs"
| "costInCents"
| "baseCostInCents"
| "ttl"
| "payload"
| "payloadType"
| "metadata"
| "output"
| "outputType"
| "runTags"
| "error"
>;
export type RunStreamCallback<TRunTypes extends AnyRunTypes> = (
run: RunShape<TRunTypes>
) => void | Promise<void>;
export type RunShapeStreamOptions = {
headers?: Record<string, string>;
fetchClient?: typeof fetch;
closeOnComplete?: boolean;
signal?: AbortSignal;
client?: ApiClient;
onFetchError?: (e: Error) => void;
};
export type StreamPartResult<TRun, TStreams extends Record<string, any>> = {
[K in keyof TStreams]: {
type: K;
chunk: TStreams[K];
run: TRun;
};
}[keyof TStreams];
export type RunWithStreamsResult<TRun, TStreams extends Record<string, any>> =
| {
type: "run";
run: TRun;
}
| StreamPartResult<TRun, TStreams>;
export function runShapeStream<TRunTypes extends AnyRunTypes>(
url: string,
options?: RunShapeStreamOptions
): RunSubscription<TRunTypes> {
const abortController = new AbortController();
const streamFactory = new SSEStreamSubscriptionFactory(
getEnvVar("TRIGGER_STREAM_URL", getEnvVar("TRIGGER_API_URL")) ?? "https://api.trigger.dev",
{
headers: options?.headers,
signal: abortController.signal,
}
);
// If the user supplied AbortSignal is aborted, we should abort the internal controller
options?.signal?.addEventListener(
"abort",
() => {
if (!abortController.signal.aborted) {
abortController.abort();
}
},
{ once: true }
);
const runStreamInstance = zodShapeStream(SubscribeRunRawShape, url, {
...options,
signal: abortController.signal,
onError: (e) => {
options?.onFetchError?.(e);
},
});
const $options: RunSubscriptionOptions = {
runShapeStream: runStreamInstance.stream,
stopRunShapeStream: () => runStreamInstance.stop(30 * 1000),
streamFactory: streamFactory,
abortController,
...options,
};
return new RunSubscription<TRunTypes>($options);
}
// First, define interfaces for the stream handling
export interface StreamSubscription {
subscribe(): Promise<ReadableStream<SSEStreamPart<unknown>>>;
}
export type CreateStreamSubscriptionOptions = {
baseUrl?: string;
onComplete?: () => void;
onError?: (error: Error) => void;
timeoutInSeconds?: number;
lastEventId?: string;
};
export interface StreamSubscriptionFactory {
createSubscription(
runId: string,
streamKey: string,
options?: CreateStreamSubscriptionOptions
): StreamSubscription;
}
export type SSEStreamPart<TChunk = unknown> = {
id: string;
chunk: TChunk;
timestamp: number;
};
// Real implementation for production
export class SSEStreamSubscription implements StreamSubscription {
private lastEventId: string | undefined;
private retryCount = 0;
private maxRetries = 5;
private retryDelayMs = 1000;
constructor(
private url: string,
private options: {
headers?: Record<string, string>;
signal?: AbortSignal;
onComplete?: () => void;
onError?: (error: Error) => void;
timeoutInSeconds?: number;
lastEventId?: string;
}
) {
this.lastEventId = options.lastEventId;
}
async subscribe(): Promise<ReadableStream<SSEStreamPart>> {
const self = this;
return new ReadableStream({
async start(controller) {
await self.connectStream(controller);
},
cancel(reason) {
self.options.onComplete?.();
},
});
}
private async connectStream(
controller: ReadableStreamDefaultController<SSEStreamPart>
): Promise<void> {
try {
const headers: Record<string, string> = {
Accept: "text/event-stream",
...this.options.headers,
};
// Include Last-Event-ID header if we're resuming
if (this.lastEventId) {
headers["Last-Event-ID"] = this.lastEventId;
}
if (this.options.timeoutInSeconds) {
headers["Timeout-Seconds"] = this.options.timeoutInSeconds.toString();
}
const response = await fetch(this.url, {
headers,
signal: this.options.signal,
});
if (!response.ok) {
const error = ApiError.generate(
response.status,
{},
"Could not subscribe to stream",
Object.fromEntries(response.headers)
);
this.options.onError?.(error);
throw error;
}
if (!response.body) {
const error = new Error("No response body");
this.options.onError?.(error);
throw error;
}
const streamVersion = response.headers.get("X-Stream-Version") ?? "v1";
// Reset retry count on successful connection
this.retryCount = 0;
const seenIds = new Set<string>();
const stream = response.body
.pipeThrough(new TextDecoderStream())
.pipeThrough(new EventSourceParserStream())
.pipeThrough(
new TransformStream<EventSourceMessage, SSEStreamPart>({
transform: (chunk, chunkController) => {
if (streamVersion === "v1") {
// Track the last event ID for resume support
if (chunk.id) {
this.lastEventId = chunk.id;
}
const timestamp = parseRedisStreamIdTimestamp(chunk.id);
chunkController.enqueue({
id: chunk.id ?? "unknown",
chunk: safeParseJSON(chunk.data),
timestamp,
});
} else {
if (chunk.event === "batch") {
const data = safeParseJSON(chunk.data) as {
records: Array<{ body: string; seq_num: number; timestamp: number }>;
};
for (const record of data.records) {
this.lastEventId = record.seq_num.toString();
const parsedBody = safeParseJSON(record.body) as { data: unknown; id: string };
if (seenIds.has(parsedBody.id)) {
continue;
}
seenIds.add(parsedBody.id);
chunkController.enqueue({
id: record.seq_num.toString(),
chunk: parsedBody.data,
timestamp: record.timestamp,
});
}
}
}
},
})
);
const reader = stream.getReader();
try {
let chunkCount = 0;
while (true) {
const { done, value } = await reader.read();
if (done) {
reader.releaseLock();
controller.close();
this.options.onComplete?.();
return;
}
if (this.options.signal?.aborted) {
reader.cancel();
reader.releaseLock();
controller.close();
this.options.onComplete?.();
return;
}
chunkCount++;
controller.enqueue(value);
}
} catch (error) {
reader.releaseLock();
throw error;
}
} catch (error) {
if (this.options.signal?.aborted) {
// Don't retry if aborted
controller.close();
this.options.onComplete?.();
return;
}
if (isTriggerRealtimeAuthError(error)) {
this.options.onError?.(error as Error);
controller.error(error as Error);
return;
}
// Retry on error
await this.retryConnection(controller, error as Error);
}
}
private async retryConnection(
controller: ReadableStreamDefaultController,
error?: Error
): Promise<void> {
if (this.options.signal?.aborted) {
controller.close();
this.options.onComplete?.();
return;
}
if (this.retryCount >= this.maxRetries) {
const finalError = error || new Error("Max retries reached");
controller.error(finalError);
this.options.onError?.(finalError);
return;
}
this.retryCount++;
const delay = this.retryDelayMs * Math.pow(2, this.retryCount - 1);
// Wait before retrying
await new Promise((resolve) => setTimeout(resolve, delay));
if (this.options.signal?.aborted) {
controller.close();
this.options.onComplete?.();
return;
}
// Reconnect
await this.connectStream(controller);
}
}
export class SSEStreamSubscriptionFactory implements StreamSubscriptionFactory {
constructor(
private baseUrl: string,
private options: {
headers?: Record<string, string>;
signal?: AbortSignal;
}
) {}
createSubscription(
runId: string,
streamKey: string,
options?: CreateStreamSubscriptionOptions
): StreamSubscription {
if (!runId || !streamKey) {
throw new Error("runId and streamKey are required");
}
const url = `${options?.baseUrl ?? this.baseUrl}/realtime/v1/streams/${runId}/${streamKey}`;
return new SSEStreamSubscription(url, {
...this.options,
...options,
});
}
}
export interface RunShapeProvider {
onShape(callback: (shape: SubscribeRunRawShape) => Promise<void>): Promise<() => void>;
}
export type RunSubscriptionOptions = RunShapeStreamOptions & {
runShapeStream: ReadableStream<SubscribeRunRawShape>;
stopRunShapeStream: () => void;
streamFactory: StreamSubscriptionFactory;
abortController: AbortController;
};
export class RunSubscription<TRunTypes extends AnyRunTypes> {
private stream: AsyncIterableStream<RunShape<TRunTypes>>;
private packetCache = new Map<string, any>();
private _closeOnComplete: boolean;
private _isRunComplete = false;
constructor(private options: RunSubscriptionOptions) {
this._closeOnComplete =
typeof options.closeOnComplete === "undefined" ? true : options.closeOnComplete;
this.stream = createAsyncIterableReadable(
this.options.runShapeStream,
{
transform: async (chunk, controller) => {
const run = await this.transformRunShape(chunk);
controller.enqueue(run);
// only set the run to complete when finishedAt is set
this._isRunComplete = !!run.finishedAt;
if (
this._closeOnComplete &&
this._isRunComplete &&
!this.options.abortController.signal.aborted
) {
this.options.stopRunShapeStream();
}
},
},
this.options.abortController.signal
);
}
unsubscribe(): void {
if (!this.options.abortController.signal.aborted) {
this.options.abortController.abort();
}
this.options.stopRunShapeStream();
}
[Symbol.asyncIterator](): AsyncIterator<RunShape<TRunTypes>> {
return this.stream[Symbol.asyncIterator]();
}
getReader(): ReadableStreamDefaultReader<RunShape<TRunTypes>> {
return this.stream.getReader();
}
withStreams<TStreams extends Record<string, any>>(): AsyncIterableStream<
RunWithStreamsResult<RunShape<TRunTypes>, TStreams>
> {
// Keep track of which streams we've already subscribed to
const activeStreams = new Set<string>();
return createAsyncIterableReadable(
this.stream,
{
transform: async (run, controller) => {
controller.enqueue({
type: "run",
run,
});
const streams = getStreamsFromRunShape(run);
// Check for stream metadata
if (streams.length > 0) {
for (const streamKey of streams) {
if (typeof streamKey !== "string") {
continue;
}
if (!activeStreams.has(streamKey)) {
activeStreams.add(streamKey);
const subscription = this.options.streamFactory.createSubscription(
run.id,
streamKey,
{
baseUrl: this.options.client?.baseUrl,
}
);
// Start stream processing in the background
subscription.subscribe().then((stream) => {
stream
.pipeThrough(
new TransformStream({
transform(chunk, controller) {
controller.enqueue({
type: streamKey,
chunk: chunk.chunk as TStreams[typeof streamKey],
run,
});
},
})
)
.pipeTo(
new WritableStream({
write(chunk) {
controller.enqueue(chunk);
},
})
);
});
}
}
}
},
},
this.options.abortController.signal
);
}
private async transformRunShape(row: SubscribeRunRawShape): Promise<RunShape<TRunTypes>> {
const payloadPacket = row.payloadType
? ({ data: row.payload ?? undefined, dataType: row.payloadType } satisfies IOPacket)
: undefined;
const outputPacket = row.outputType
? ({ data: row.output ?? undefined, dataType: row.outputType } satisfies IOPacket)
: undefined;
const [payload, output] = await Promise.all(
[
{ packet: payloadPacket, key: "payload" },
{ packet: outputPacket, key: "output" },
].map(async ({ packet, key }) => {
if (!packet) {
return;
}
const cachedResult = this.packetCache.get(`${row.friendlyId}/${key}`);
if (typeof cachedResult !== "undefined") {
return cachedResult;
}
const result = await conditionallyImportAndParsePacket(packet, this.options.client);
this.packetCache.set(`${row.friendlyId}/${key}`, result);
return result;
})
);
const metadata =
row.metadata && row.metadataType
? await parsePacket({ data: row.metadata, dataType: row.metadataType })
: undefined;
const status = apiStatusFromRunStatus(row.status);
return {
id: row.friendlyId,
createdAt: row.createdAt,
updatedAt: row.updatedAt,
taskIdentifier: row.taskIdentifier,
status,
payload,
output,
durationMs: row.usageDurationMs ?? 0,
costInCents: row.costInCents ?? 0,
baseCostInCents: row.baseCostInCents ?? 0,
tags: row.runTags ?? [],
idempotencyKey: row.idempotencyKey ?? undefined,
expiredAt: row.expiredAt ?? undefined,
finishedAt: row.completedAt ?? undefined,
startedAt: row.startedAt ?? undefined,
delayedUntil: row.delayUntil ?? undefined,
queuedAt: row.queuedAt ?? undefined,
error: row.error ? createJsonErrorObject(row.error) : undefined,
isTest: row.isTest ?? false,
metadata,
realtimeStreams: row.realtimeStreams ?? [],
...booleanHelpersFromRunStatus(status),
} as RunShape<TRunTypes>;
}
}
const queuedStatuses = ["PENDING_VERSION", "QUEUED", "PENDING", "DELAYED"];
const waitingStatuses = ["WAITING"];
const executingStatuses = ["DEQUEUED", "EXECUTING"];
const failedStatuses = ["FAILED", "CRASHED", "SYSTEM_FAILURE", "EXPIRED", "TIMED_OUT"];
const successfulStatuses = ["COMPLETED"];
function booleanHelpersFromRunStatus(status: RunStatus) {
return {
isQueued: queuedStatuses.includes(status),
isWaiting: waitingStatuses.includes(status),
isExecuting: executingStatuses.includes(status),
isCompleted: successfulStatuses.includes(status) || failedStatuses.includes(status),
isFailed: failedStatuses.includes(status),
isSuccess: successfulStatuses.includes(status),
isCancelled: status === "CANCELED",
};
}
function apiStatusFromRunStatus(status: string): RunStatus {
switch (status) {
case "DELAYED": {
return "DELAYED";
}
case "WAITING_FOR_DEPLOY":
case "PENDING_VERSION": {
return "PENDING_VERSION";
}
case "PENDING": {
return "QUEUED";
}
case "PAUSED":
case "WAITING_TO_RESUME": {
return "WAITING";
}
case "DEQUEUED": {
return "DEQUEUED";
}
case "RETRYING_AFTER_FAILURE":
case "EXECUTING": {
return "EXECUTING";
}
case "CANCELED": {
return "CANCELED";
}
case "COMPLETED_SUCCESSFULLY": {
return "COMPLETED";
}
case "SYSTEM_FAILURE": {
return "SYSTEM_FAILURE";
}
case "CRASHED": {
return "CRASHED";
}
case "INTERRUPTED":
case "COMPLETED_WITH_ERRORS": {
return "FAILED";
}
case "EXPIRED": {
return "EXPIRED";
}
case "TIMED_OUT": {
return "TIMED_OUT";
}
default: {
return "QUEUED";
}
}
}
function safeParseJSON(data: string): unknown {
try {
return JSON.parse(data);
} catch (error) {
return data;
}
}
const isSafari = () => {
// Check if we're in a browser environment
if (
typeof window !== "undefined" &&
typeof navigator !== "undefined" &&
typeof navigator.userAgent === "string"
) {
return (
/^((?!chrome|android).)*safari/i.test(navigator.userAgent) ||
/iPad|iPhone|iPod/.test(navigator.userAgent)
);
}
// If we're not in a browser environment, return false
return false;
};
/**
* A polyfill for `ReadableStream.protototype[Symbol.asyncIterator]`,
* aligning as closely as possible to the specification.
*
* @see https://streams.spec.whatwg.org/#rs-asynciterator
* @see https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream#async_iteration
*
* This is needed for Safari: https://bugs.webkit.org/show_bug.cgi?id=194379
*
* From https://gist.github.com/MattiasBuelens/496fc1d37adb50a733edd43853f2f60e
*
*/
if (isSafari()) {
// @ts-ignore-error
ReadableStream.prototype.values ??= function ({ preventCancel = false } = {}) {
const reader = this.getReader();
return {
async next(): Promise<IteratorResult<any>> {
try {
const result = await reader.read();
if (result.done) {
reader.releaseLock();
}
return {
done: result.done,
value: result.value,
};
} catch (e) {
reader.releaseLock();
throw e;
}
},
async return(value: any): Promise<IteratorResult<any>> {
if (!preventCancel) {
const cancelPromise = reader.cancel(value);
reader.releaseLock();
await cancelPromise;
} else {
reader.releaseLock();
}
return { done: true, value };
},
[Symbol.asyncIterator]() {
return this;
},
};
};
// @ts-ignore-error
ReadableStream.prototype[Symbol.asyncIterator] ??= ReadableStream.prototype.values;
}
function getStreamsFromRunShape(run: AnyRunShape): string[] {
const metadataStreams =
run.metadata &&
"$$streams" in run.metadata &&
Array.isArray(run.metadata.$$streams) &&
run.metadata.$$streams.length > 0 &&
run.metadata.$$streams.every((stream) => typeof stream === "string")
? run.metadata.$$streams
: undefined;
if (metadataStreams) {
return metadataStreams;
}
return run.realtimeStreams;
}
// Redis stream IDs are in the format: <timestamp>-<sequence>
function parseRedisStreamIdTimestamp(id?: string): number {
if (!id) {
return Date.now();
}
const timestamp = parseInt(id.split("-")[0] as string, 10);
if (isNaN(timestamp)) {
return Date.now();
}
return timestamp;
}