-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathruns.ts
More file actions
522 lines (475 loc) · 14.3 KB
/
Copy pathruns.ts
File metadata and controls
522 lines (475 loc) · 14.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
import type {
AnyRetrieveRunResult,
AnyRunShape,
ApiRequestOptions,
InferRunTypes,
ListProjectRunsQueryParams,
ListRunsQueryParams,
RescheduleRunRequestBody,
RetrieveRunResult,
RunShape,
RealtimeRun,
AnyRealtimeRun,
RunSubscription,
TaskRunShape,
AnyBatchedRunHandle,
AsyncIterableStream,
ApiPromise,
RealtimeRunSkipColumns,
TriggerApiRequestOptions,
} from "@trigger.dev/core/v3";
import {
CanceledRunResponse,
CursorPagePromise,
ListRunResponseItem,
ReplayRunResponse,
RetrieveRunResponse,
accessoryAttributes,
apiClientManager,
flattenAttributes,
isRequestOptions,
mergeRequestOptions,
} from "@trigger.dev/core/v3";
import { resolvePresignedPacketUrl } from "@trigger.dev/core/v3/utils/ioSerialization";
import { AnyRunHandle, AnyTask } from "./shared.js";
import { tracer } from "./tracer.js";
export type {
AnyRetrieveRunResult,
AnyRunShape,
RetrieveRunResult,
RunShape,
TaskRunShape,
RealtimeRun,
AnyRealtimeRun,
};
export const runs = {
replay: replayRun,
cancel: cancelRun,
retrieve: retrieveRun,
list: listRuns,
reschedule: rescheduleRun,
poll,
subscribeToRun,
subscribeToRunsWithTag,
subscribeToBatch: subscribeToRunsInBatch,
fetchStream,
};
export type ListRunsItem = ListRunResponseItem;
function listRuns(
projectRef: string,
params?: ListProjectRunsQueryParams,
requestOptions?: ApiRequestOptions
): CursorPagePromise<typeof ListRunResponseItem>;
function listRuns(
params?: ListRunsQueryParams,
requestOptions?: ApiRequestOptions
): CursorPagePromise<typeof ListRunResponseItem>;
function listRuns(
paramsOrProjectRef?: ListRunsQueryParams | string,
paramsOrOptions?: ListRunsQueryParams | ListProjectRunsQueryParams | ApiRequestOptions,
requestOptions?: ApiRequestOptions
): CursorPagePromise<typeof ListRunResponseItem> {
const apiClient = apiClientManager.clientOrThrow();
const $requestOptions = listRunsRequestOptions(
paramsOrProjectRef,
paramsOrOptions,
requestOptions
);
if (typeof paramsOrProjectRef === "string") {
if (isRequestOptions(paramsOrOptions)) {
return apiClient.listProjectRuns(paramsOrProjectRef, {}, $requestOptions);
} else {
return apiClient.listProjectRuns(paramsOrProjectRef, paramsOrOptions, $requestOptions);
}
}
return apiClient.listRuns(paramsOrProjectRef, $requestOptions);
}
function listRunsRequestOptions(
paramsOrProjectRef?: ListRunsQueryParams | string,
paramsOrOptions?: ListRunsQueryParams | ListProjectRunsQueryParams | ApiRequestOptions,
requestOptions?: ApiRequestOptions
): ApiRequestOptions {
if (typeof paramsOrProjectRef === "string") {
if (isRequestOptions(paramsOrOptions)) {
return mergeRequestOptions(
{
tracer,
name: "runs.list()",
icon: "runs",
attributes: {
projectRef: paramsOrProjectRef,
...accessoryAttributes({
items: [
{
text: paramsOrProjectRef,
variant: "normal",
},
],
style: "codepath",
}),
},
},
paramsOrOptions
);
} else {
return mergeRequestOptions(
{
tracer,
name: "runs.list()",
icon: "runs",
attributes: {
projectRef: paramsOrProjectRef,
...flattenAttributes(paramsOrOptions as Record<string, unknown>, "queryParams"),
...accessoryAttributes({
items: [
{
text: paramsOrProjectRef,
variant: "normal",
},
],
style: "codepath",
}),
},
},
requestOptions
);
}
}
return mergeRequestOptions(
{
tracer,
name: "runs.list()",
icon: "runs",
attributes: {
...flattenAttributes(paramsOrProjectRef as Record<string, unknown>, "queryParams"),
},
},
isRequestOptions(paramsOrOptions) ? paramsOrOptions : requestOptions
);
}
// Extract out the expected type of the id, can be either a string or a RunHandle
type RunId<TRunId> = TRunId extends AnyRunHandle | AnyBatchedRunHandle
? TRunId
: TRunId extends AnyTask
? string
: TRunId extends string
? TRunId
: never;
function retrieveRun<TRunId extends AnyRunHandle | AnyBatchedRunHandle | AnyTask | string>(
runId: RunId<TRunId>,
requestOptions?: TriggerApiRequestOptions
): ApiPromise<RetrieveRunResult<TRunId>> {
const apiClient = apiClientManager.clientOrThrow(requestOptions?.clientConfig);
const $requestOptions = mergeRequestOptions(
{
tracer,
name: "runs.retrieve()",
icon: "runs",
attributes: {
runId: typeof runId === "string" ? runId : runId.id,
...accessoryAttributes({
items: [
{
text: typeof runId === "string" ? runId : runId.id,
variant: "normal",
},
],
style: "codepath",
}),
},
prepareData: resolvePayloadAndOutputUrls,
},
requestOptions
);
const $runId = typeof runId === "string" ? runId : runId.id;
return apiClient.retrieveRun($runId, $requestOptions) as ApiPromise<RetrieveRunResult<TRunId>>;
}
async function resolvePayloadAndOutputUrls(run: AnyRetrieveRunResult) {
const resolvedRun = { ...run };
if (run.payloadPresignedUrl && run.outputPresignedUrl) {
const [payload, output] = await Promise.all([
resolvePresignedPacketUrl(run.payloadPresignedUrl, tracer),
resolvePresignedPacketUrl(run.outputPresignedUrl, tracer),
]);
resolvedRun.payload = payload;
resolvedRun.output = output;
} else if (run.payloadPresignedUrl) {
resolvedRun.payload = await resolvePresignedPacketUrl(run.payloadPresignedUrl, tracer);
} else if (run.outputPresignedUrl) {
resolvedRun.output = await resolvePresignedPacketUrl(run.outputPresignedUrl, tracer);
}
return resolvedRun;
}
function replayRun(
runId: string,
requestOptions?: ApiRequestOptions
): ApiPromise<ReplayRunResponse> {
const apiClient = apiClientManager.clientOrThrow();
const $requestOptions = mergeRequestOptions(
{
tracer,
name: "runs.replay()",
icon: "runs",
attributes: {
runId,
...accessoryAttributes({
items: [
{
text: runId,
variant: "normal",
},
],
style: "codepath",
}),
},
},
requestOptions
);
return apiClient.replayRun(runId, $requestOptions);
}
function cancelRun(
runId: string,
requestOptions?: ApiRequestOptions
): ApiPromise<CanceledRunResponse> {
const apiClient = apiClientManager.clientOrThrow();
const $requestOptions = mergeRequestOptions(
{
tracer,
name: "runs.cancel()",
icon: "runs",
attributes: {
runId,
...accessoryAttributes({
items: [
{
text: runId,
variant: "normal",
},
],
style: "codepath",
}),
},
},
requestOptions
);
return apiClient.cancelRun(runId, $requestOptions);
}
function rescheduleRun(
runId: string,
body: RescheduleRunRequestBody,
requestOptions?: ApiRequestOptions
): ApiPromise<RetrieveRunResponse> {
const apiClient = apiClientManager.clientOrThrow();
const $requestOptions = mergeRequestOptions(
{
tracer,
name: "runs.reschedule()",
icon: "runs",
attributes: {
runId,
...accessoryAttributes({
items: [
{
text: runId,
variant: "normal",
},
],
style: "codepath",
}),
},
},
requestOptions
);
return apiClient.rescheduleRun(runId, body, $requestOptions);
}
export type PollOptions = { pollIntervalMs?: number };
const MAX_POLL_ATTEMPTS = 500;
async function poll<TRunId extends AnyRunHandle | AnyTask | string>(
runId: RunId<TRunId>,
options?: { pollIntervalMs?: number },
requestOptions?: TriggerApiRequestOptions
) {
let attempts = 0;
while (attempts++ < MAX_POLL_ATTEMPTS) {
const run = await runs.retrieve(runId, requestOptions);
if (run.isCompleted) {
return run;
}
await new Promise((resolve) => setTimeout(resolve, options?.pollIntervalMs ?? 1000));
}
throw new Error(
`Run ${
typeof runId === "string" ? runId : runId.id
} did not complete after ${MAX_POLL_ATTEMPTS} attempts`
);
}
export type SubscribeToRunOptions = {
/**
* Whether to close the subscription when the run completes
*
* @default true
*
* Set this to false if you are making updates to the run metadata after completion through child runs
*/
stopOnCompletion?: boolean;
/**
* Skip columns from the subscription.
*
* @default []
*
* @example
* ```ts
* runs.subscribeToRun("123", { skipColumns: ["payload", "output"] });
* ```
*/
skipColumns?: RealtimeRunSkipColumns;
};
/**
* Subscribes to real-time updates for a specific run.
*
* This function allows you to receive real-time updates whenever a run changes, including:
* - Status changes in the run lifecycle
* - Tag additions or removals
* - Metadata updates
*
* @template TRunId - The type parameter extending AnyRunHandle, AnyTask, or string
* @param {RunId<TRunId>} runId - The ID of the run to subscribe to. Can be a string ID, RunHandle, or Task
* @param {SubscribeToRunOptions} [options] - Optional configuration for the subscription
* @param {boolean} [options.stopOnCompletion=true] - Whether to close the subscription when the run completes
* @returns {RunSubscription<InferRunTypes<TRunId>>} An async iterator that yields updated run objects
*
* @example
* ```ts
* // Subscribe using a run handle
* const handle = await tasks.trigger("my-task", { some: "data" });
* for await (const run of runs.subscribeToRun(handle.id)) {
* console.log("Run updated:", run);
* }
*
* // Subscribe with type safety
* for await (const run of runs.subscribeToRun<typeof myTask>(runId)) {
* console.log("Payload:", run.payload.some);
* if (run.output) {
* console.log("Output:", run.output);
* }
* }
* ```
*/
function subscribeToRun<TRunId extends AnyRunHandle | AnyTask | string>(
runId: RunId<TRunId>,
options?: SubscribeToRunOptions
): RunSubscription<InferRunTypes<TRunId>> {
const $runId = typeof runId === "string" ? runId : runId.id;
const apiClient = apiClientManager.clientOrThrow();
return apiClient.subscribeToRun($runId, {
closeOnComplete:
typeof options?.stopOnCompletion === "boolean" ? options.stopOnCompletion : true,
skipColumns: options?.skipColumns,
});
}
export type SubscribeToRunsFilterOptions = {
/**
* Filter runs by the time they were created. You must specify the duration string like "1h", "10s", "30m", etc.
*
* @example
* "1h" - 1 hour ago
* "10s" - 10 seconds ago
* "30m" - 30 minutes ago
* "1d" - 1 day ago
* "1w" - 1 week ago
*
* The maximum duration is 1 week
*
* @note The timestamp will be calculated on the server side when you first subscribe to the runs.
*
*/
createdAt?: string;
/**
* Skip columns from the subscription.
*
* @default []
*/
skipColumns?: RealtimeRunSkipColumns;
};
/**
* Subscribes to real-time updates for all runs that have specific tags.
*
* This function allows you to monitor multiple runs simultaneously by filtering on tags.
* You'll receive updates whenever any run with the specified tag(s) changes.
*
* @template TTasks - The type parameter extending AnyTask for type-safe payload and output
* @param {string | string[]} tag - A single tag or array of tags to filter runs
* @returns {RunSubscription<InferRunTypes<TTasks>>} An async iterator that yields updated run objects
*
* @example
* ```ts
* // Subscribe to runs with a single tag
* for await (const run of runs.subscribeToRunsWithTag("user:1234")) {
* console.log("Run updated:", run);
* }
*
* // Subscribe with multiple tags and type safety
* for await (const run of runs.subscribeToRunsWithTag<typeof myTask | typeof otherTask>(["tag1", "tag2"])) {
* switch (run.taskIdentifier) {
* case "my-task":
* console.log("MyTask output:", run.output.foo);
* break;
* case "other-task":
* console.log("OtherTask output:", run.output.bar);
* break;
* }
* }
* ```
*/
function subscribeToRunsWithTag<TTasks extends AnyTask>(
tag: string | string[],
filters?: SubscribeToRunsFilterOptions,
options?: { signal?: AbortSignal }
): RunSubscription<InferRunTypes<TTasks>> {
const apiClient = apiClientManager.clientOrThrow();
return apiClient.subscribeToRunsWithTag<InferRunTypes<TTasks>>(tag, filters, {
...(options ? { signal: options.signal } : {}),
});
}
/**
* Subscribes to real-time updates for all runs within a specific batch.
*
* Use this function when you've triggered multiple runs using `batchTrigger` and want
* to monitor all runs in that batch. You'll receive updates whenever any run in the batch changes.
*
* @template TTasks - The type parameter extending AnyTask for type-safe payload and output
* @param {string} batchId - The ID of the batch to subscribe to
* @returns {RunSubscription<InferRunTypes<TTasks>>} An async iterator that yields updated run objects
*
* @example
* ```ts
* // Subscribe to all runs in a batch
* for await (const run of runs.subscribeToRunsInBatch("batch-123")) {
* console.log("Batch run updated:", run);
* }
*
* // Subscribe with type safety
* for await (const run of runs.subscribeToRunsInBatch<typeof myTask>("batch-123")) {
* console.log("Run payload:", run.payload);
* if (run.output) {
* console.log("Run output:", run.output);
* }
* }
* ```
*
* @note The run objects received will include standard fields like id, status, payload, output,
* createdAt, updatedAt, tags, and more. See the Run object documentation for full details.
*/
function subscribeToRunsInBatch<TTasks extends AnyTask>(
batchId: string
): RunSubscription<InferRunTypes<TTasks>> {
const apiClient = apiClientManager.clientOrThrow();
return apiClient.subscribeToBatch<InferRunTypes<TTasks>>(batchId);
}
/**
* Fetches a stream of data from a run's stream key.
*/
async function fetchStream<T>(runId: string, streamKey: string): Promise<AsyncIterableStream<T>> {
const apiClient = apiClientManager.clientOrThrow();
return await apiClient.fetchStream(runId, streamKey);
}