-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathexample.ts
More file actions
330 lines (278 loc) · 9.18 KB
/
example.ts
File metadata and controls
330 lines (278 loc) · 9.18 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
import { batch, logger, task, tasks, timeout, wait } from "@trigger.dev/sdk";
import { setTimeout } from "timers/promises";
import { ResourceMonitor } from "../resourceMonitor.js";
export const helloWorldTask = task({
id: "hello-world",
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 from the init", { ctx, payload });
logger.info("env vars", {
env: process.env,
});
logger.debug("debug: Hello, world!", { 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 ?? 180_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 });
await childTask.triggerAndWait(
{ message: "Hello, world!" },
{
releaseConcurrency: true,
}
);
},
});
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,
}: { message?: string; failureChance?: number; duration?: number },
{ ctx }
) => {
logger.info("Hello, world from the child", { message, failureChance });
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,
};
},
});