-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathexample.ts
More file actions
532 lines (445 loc) · 15.5 KB
/
example.ts
File metadata and controls
532 lines (445 loc) · 15.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
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
import { batch, logger, task, tasks, timeout, wait } from "@trigger.dev/sdk";
import { setTimeout } from "timers/promises";
import { ResourceMonitor } from "../resourceMonitor.js";
import { fixedLengthTask } from "./batches.js";
export const helloWorldTask = task({
id: "hello-world",
ttl: "10m",
retry: {
maxAttempts: 3,
minTimeoutInMs: 500,
maxTimeoutInMs: 1000,
factor: 1.5,
},
onStart: async ({ payload, ctx, init }) => {
logger.info("Hello, world from the onStart hook", { payload, init });
},
run: async (payload: any, { ctx }) => {
logger.info("Hello, world froms the init", { ctx, payload });
logger.info("env vars", {
env: process.env,
});
logger.debug("debug: Hello, worlds!", { payload });
logger.info("info: Hello, world!", { payload });
logger.log("log: Hello, world!", { payload });
logger.warn("warn: Hello, world!", { payload });
logger.error("error: Hello, world!", { payload });
logger.trace("my trace", async (span) => {
logger.debug("some log", { span });
});
await setTimeout(payload.sleepFor ?? 5_000);
if (payload.throwError) {
throw new Error("Forced error to cause a retry");
}
logger.trace(
"my trace",
async (span) => {
logger.debug("some log", { span });
},
{
icon: "tabler-ad-circle",
}
);
await wait.for({ seconds: 5 });
return {
message: "Hello, world!",
};
},
});
export const parentTask = task({
id: "parent",
machine: "medium-1x",
run: async (payload: any, { ctx }) => {
logger.log("Hello, world from the parent", { payload, ctx });
await childTask.triggerAndWait({ message: "Hello, world!", aReallyBigInt: BigInt(10000) });
},
});
export const batchParentTask = task({
id: "batch-parent",
run: async (payload: any, { ctx }) => {
logger.log("Hello, world from the parent", { payload });
const results = await childTask.batchTriggerAndWait([
{ payload: { message: "Hello, world!" } },
{ payload: { message: "Hello, world 2!" } },
]);
logger.log("Results", { results });
const results2 = await batch.triggerAndWait<typeof childTask>([
{ id: "child", payload: { message: "Hello, world !" } },
{ id: "child", payload: { message: "Hello, world 2!" } },
]);
logger.log("Results 2", { results2 });
const results3 = await batch.triggerByTask([
{ task: childTask, payload: { message: "Hello, world !" } },
{ task: childTask, payload: { message: "Hello, world 2!" } },
]);
logger.log("Results 3", { results3 });
const results4 = await batch.triggerByTaskAndWait([
{
task: childTask,
payload: { message: "Hello, world !" },
},
{ task: childTask, payload: { message: "Hello, world 2!" } },
]);
logger.log("Results 4", { results4 });
},
});
export const childTask = task({
id: "child",
run: async (
{
message,
failureChance = 0.3,
duration = 3_000,
aReallyBigInt,
}: { message?: string; failureChance?: number; duration?: number; aReallyBigInt?: bigint },
{ ctx }
) => {
logger.info("Hello, world from the child", { ctx, failureChance, aReallyBigInt });
if (Math.random() < failureChance) {
throw new Error("Random error at start");
}
await setTimeout(duration);
if (Math.random() < failureChance) {
throw new Error("Random error at end");
}
return {
message,
};
},
});
export const maxDurationTask = task({
id: "max-duration",
retry: {
maxAttempts: 5,
minTimeoutInMs: 1_000,
maxTimeoutInMs: 2_000,
factor: 1.4,
},
maxDuration: 5,
run: async (payload: { sleepFor: number }, { signal, ctx }) => {
await setTimeout(payload.sleepFor * 1000, { signal });
},
});
export const maxDurationParentTask = task({
id: "max-duration-parent",
run: async (payload: { sleepFor?: number; maxDuration?: number }, { ctx, signal }) => {
const result = await maxDurationTask.triggerAndWait(
{ sleepFor: payload.sleepFor ?? 10 },
{ maxDuration: timeout.None }
);
return result;
},
});
export const batchTask = task({
id: "batch",
run: async (payload: { count: number }, { ctx }) => {
logger.info("Starting batch task", { count: payload.count });
const items = Array.from({ length: payload.count }, (_, i) => ({
payload: { message: `Batch item ${i + 1}` },
}));
const results = await childTask.batchTriggerAndWait(items);
logger.info("Batch task complete", { results });
return {
batchCount: payload.count,
results,
};
},
});
const nonExportedTask = task({
id: "non-exported",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the non-exported task", { message: payload.message });
},
});
export const hooksTask = task({
id: "hooks",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the hooks task", { message: payload.message });
await wait.for({ seconds: 5 });
return {
message: "Hello, world!",
};
},
init: async () => {
return {
foobar: "baz",
};
},
onWait: async ({ payload, wait, ctx, init }) => {
logger.info("Hello, world from the onWait hook", { payload, init, wait });
},
onResume: async ({ payload, wait, ctx, init }) => {
logger.info("Hello, world from the onResume hook", { payload, init, wait });
},
onStart: async ({ payload, ctx, init }) => {
logger.info("Hello, world from the onStart hook", { payload, init });
},
onSuccess: async ({ payload, output, ctx }) => {
logger.info("Hello, world from the onSuccess hook", { payload, output });
},
onFailure: async ({ payload, error, ctx }) => {
logger.info("Hello, world from the onFailure hook", { payload, error });
},
onComplete: async ({ ctx, payload, result }) => {
logger.info("Hello, world from the onComplete hook", { payload, result });
},
handleError: async ({ payload, error, ctx, retry }) => {
logger.info("Hello, world from the handleError hook", { payload, error, retry });
},
catchError: async ({ ctx, payload, error, retry }) => {
logger.info("Hello, world from the catchError hook", { payload, error, retry });
},
cleanup: async ({ ctx, payload }) => {
logger.info("Hello, world from the cleanup hook", { payload });
},
onCancel: async ({ payload }) => {
logger.info("Hello, world from the onCancel hook", { payload });
},
});
export const cancelExampleTask = task({
id: "cancel-example",
// Signal will be aborted when the task is cancelled 👇
run: async (payload: { timeoutInSeconds: number }, { signal }) => {
logger.info("Hello, world from the cancel task", {
timeoutInSeconds: payload.timeoutInSeconds,
});
// This is a global hook that will be called if the task is cancelled
tasks.onCancel(async () => {
logger.info("global task onCancel hook but inside of the run function baby!");
});
await logger.trace("timeout", async (span) => {
try {
// We pass the signal to setTimeout to abort the timeout if the task is cancelled
await setTimeout(payload.timeoutInSeconds * 1000, undefined, { signal });
} catch (error) {
// If the timeout is aborted, this error will be thrown, we can handle it here
logger.error("Timeout error", { error });
}
});
logger.info("Hello, world from the cancel task after the timeout", {
timeoutInSeconds: payload.timeoutInSeconds,
});
return {
message: "Hello, world!",
};
},
onCancel: async ({ payload, runPromise }) => {
logger.info("Hello, world from the onCancel hook", { payload });
// You can await the runPromise to get the output of the task
const output = await runPromise;
logger.info("Hello, world from the onCancel hook after the run", { payload, output });
// You can do work inside the onCancel hook, up to 30 seconds
await setTimeout(10_000);
logger.info("Hello, world from the onCancel hook after the timeout", { payload });
},
});
export const resourceMonitorTest = task({
id: "resource-monitor-test",
run: async (payload: { dirName?: string; processName?: string }, { ctx }) => {
logger.info("Hello, resources!", { payload });
const resMon = new ResourceMonitor({
ctx,
dirName: payload.dirName ?? "/tmp",
processName: payload.processName ?? "node",
});
resMon.startMonitoring(1_000);
await resMon.logResourceSnapshot();
await wait.for({ seconds: 5 });
await resMon.logResourceSnapshot();
resMon.stopMonitoring();
return {
message: "Hello, resources!",
};
},
});
export const circularReferenceTask = task({
id: "circular-reference",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the circular reference task", { message: payload.message });
// Create an object
const user = {
name: "Alice",
details: {
age: 30,
email: "alice@example.com",
},
};
// Create the circular reference
// @ts-expect-error - This is a circular reference
user.details.user = user;
// Now user.details.user points back to the user object itself
// This creates a circular reference that standard JSON can't handle
return {
user,
};
},
});
export const largeAttributesTask = task({
id: "large-attributes",
machine: "large-1x",
run: async ({ length = 100000 }: { length: number }, { signal, ctx }) => {
// Create a large deeply nested object/array of objects that have more than 10k attributes when flattened
const start = performance.now();
const largeObject = Array.from({ length }, (_, i) => ({
a: i,
b: i,
c: i,
}));
const end = performance.now();
console.log(`[${length}] Time taken to create the large object: ${end - start}ms`);
const start2 = performance.now();
logger.info("Hello, world from the large attributes task", { largeObject });
const end2 = performance.now();
console.log(`[${length}] Time taken to log the large object: ${end2 - start2}ms`);
class MyClass {
constructor(public name: string) {}
}
logger.info("Lets log some weird stuff", {
error: new Error("This is an error"),
func: () => {
logger.info("This is a function");
},
date: new Date(),
bigInt: BigInt(1000000000000000000),
symbol: Symbol("symbol"),
myClass: new MyClass("MyClass"),
file: new File([], "test.txt"),
stream: new ReadableStream(),
map: new Map([["key", "value"]]),
set: new Set([1, 2, 3]),
promise: Promise.resolve("Hello, world!"),
promiseRejected: Promise.reject(new Error("This is a rejected promise")),
promisePending: Promise.resolve("Hello, world!"),
});
},
});
export const lotsOfLogsParentTask = task({
id: "lots-of-logs-parent",
run: async (payload: { count: number }, { ctx }) => {
logger.info("Hello, world from the lots of logs parent task", { count: payload.count });
await lotsOfLogsTask.batchTriggerAndWait(
Array.from({ length: 20 }, (_, i) => ({
payload: { count: payload.count },
}))
);
},
});
export const lotsOfLogsTask = task({
id: "lots-of-logs",
run: async (payload: { count: number }, { ctx }) => {
logger.info("Hello, world from the lots of logs task", { count: payload.count });
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
await setTimeout(1000);
for (let i = 0; i < payload.count; i++) {
logger.info("Hello, world from the lots of logs task", { count: i });
}
},
});
export const throwErrorInOnSuccessHookTask = task({
id: "throw-error-in-on-success-hook",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the throw error in on success hook task", {
message: payload.message,
});
},
onSuccess: async ({ payload, output, ctx }) => {
logger.info("Hello, world from the on success hook", { payload, output });
throw new Error("Forced error to cause a retry");
},
});
export const throwErrorInOnStartHookTask = task({
id: "throw-error-in-on-start-hook",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the throw error in on start hook task", {
message: payload.message,
});
},
onStart: async ({ payload, ctx }) => {
logger.info("Hello, world from the on start hook", { payload });
throw new Error("Forced error to cause a retry");
},
});
export const throwErrorInOnCompleteHookTask = task({
id: "throw-error-in-on-complete-hook",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the throw error in on complete hook task", {
message: payload.message,
});
},
onComplete: async ({ payload, result, ctx }) => {
logger.info("Hello, world from the on complete hook", { payload, result });
throw new Error("Forced error to cause a retry");
},
});
export const throwErrorInOnFailureHookTask = task({
id: "throw-error-in-on-failure-hook",
retry: {
maxAttempts: 1,
},
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the throw error in on failure hook task", {
message: payload.message,
});
throw new Error("Forced error to cause a retry");
},
onFailure: async ({ payload, error, ctx }) => {
logger.info("Hello, world from the on failure hook", { payload, error });
throw new Error("Forced error to cause a retry in on failure hook");
},
});
export const throwErrorInInitHookTask = task({
id: "throw-error-in-init-hook",
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the throw error in init hook task", {
message: payload.message,
});
},
init: async ({ payload, ctx }) => {
logger.info("Hello, world from the init hook", { payload });
throw new Error("Forced error to cause a retry");
},
});
export const testStartAttemptHookTask = task({
id: "test-start-attempt-hook",
retry: {
maxAttempts: 3,
},
run: async (payload: { message: string }, { ctx }) => {
logger.info("Hello, world from the test start attempt hook task", { message: payload.message });
if (ctx.attempt.number === 1) {
throw new Error("Forced error to cause a retry so we can test the onStartAttempt hook");
}
},
onStartAttempt: async ({ payload, ctx }) => {
console.log(`onStartAttempt hook called ${ctx.attempt.number}`);
},
});
tasks.onStartAttempt(({ payload, ctx }) => {
console.log(`global onStartAttempt hook called ${ctx.attempt.number}`);
});