-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtaskRunProcess.ts
More file actions
523 lines (424 loc) · 14.6 KB
/
taskRunProcess.ts
File metadata and controls
523 lines (424 loc) · 14.6 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
import {
attemptKey,
CompletedWaitpoint,
ExecutorToWorkerMessageCatalog,
MachinePresetResources,
ServerBackgroundWorker,
TaskRunErrorCodes,
TaskRunExecution,
TaskRunExecutionPayload,
TaskRunExecutionResult,
type TaskRunInternalError,
WorkerManifest,
WorkerToExecutorMessageCatalog,
} from "@trigger.dev/core/v3";
import {
type WorkerToExecutorProcessConnection,
ZodIpcConnection,
} from "@trigger.dev/core/v3/zodIpc";
import { Evt } from "evt";
import { ChildProcess, fork } from "node:child_process";
import { chalkError, chalkGrey, chalkRun, prettyPrintDate } from "../utilities/cliOutput.js";
import { execOptionsForRuntime, execPathForRuntime } from "@trigger.dev/core/v3/build";
import { nodeOptionsWithMaxOldSpaceSize } from "@trigger.dev/core/v3/machines";
import { InferSocketMessageSchema } from "@trigger.dev/core/v3/zodSocket";
import { logger } from "../utilities/logger.js";
import {
CancelledProcessError,
CleanupProcessError,
internalErrorFromUnexpectedExit,
GracefulExitTimeoutError,
UnexpectedExitError,
SuspendedProcessError,
} from "@trigger.dev/core/v3/errors";
export type OnWaitForDurationMessage = InferSocketMessageSchema<
typeof ExecutorToWorkerMessageCatalog,
"WAIT_FOR_DURATION"
>;
export type OnWaitForTaskMessage = InferSocketMessageSchema<
typeof ExecutorToWorkerMessageCatalog,
"WAIT_FOR_TASK"
>;
export type OnWaitForBatchMessage = InferSocketMessageSchema<
typeof ExecutorToWorkerMessageCatalog,
"WAIT_FOR_BATCH"
>;
export type OnWaitMessage = InferSocketMessageSchema<typeof ExecutorToWorkerMessageCatalog, "WAIT">;
export type TaskRunProcessOptions = {
workerManifest: WorkerManifest;
serverWorker: ServerBackgroundWorker;
env: Record<string, string>;
machineResources: MachinePresetResources;
isWarmStart?: boolean;
cwd?: string;
};
export type TaskRunProcessExecuteParams = {
payload: TaskRunExecutionPayload;
messageId: string;
env?: Record<string, string>;
};
export class TaskRunProcess {
private _ipc?: WorkerToExecutorProcessConnection;
private _child: ChildProcess | undefined;
private _childPid?: number;
private _attemptPromises: Map<
string,
{ resolver: (value: TaskRunExecutionResult) => void; rejecter: (err?: any) => void }
> = new Map();
private _attemptStatuses: Map<string, "PENDING" | "REJECTED" | "RESOLVED"> = new Map();
private _currentExecution: TaskRunExecution | undefined;
private _gracefulExitTimeoutElapsed: boolean = false;
private _isBeingKilled: boolean = false;
private _isBeingCancelled: boolean = false;
private _isBeingSuspended: boolean = false;
private _stderr: Array<string> = [];
public onTaskRunHeartbeat: Evt<string> = new Evt();
public onExit: Evt<{ code: number | null; signal: NodeJS.Signals | null; pid?: number }> =
new Evt();
public onIsBeingKilled: Evt<TaskRunProcess> = new Evt();
public onReadyToDispose: Evt<TaskRunProcess> = new Evt();
public onWaitForTask: Evt<OnWaitForTaskMessage> = new Evt();
public onWaitForBatch: Evt<OnWaitForBatchMessage> = new Evt();
public onWait: Evt<OnWaitMessage> = new Evt();
private _isPreparedForNextRun: boolean = false;
private _isPreparedForNextAttempt: boolean = false;
constructor(public readonly options: TaskRunProcessOptions) {
this._isPreparedForNextRun = true;
this._isPreparedForNextAttempt = true;
}
get isPreparedForNextRun() {
return this._isPreparedForNextRun;
}
get isPreparedForNextAttempt() {
return this._isPreparedForNextAttempt;
}
async cancel() {
this._isPreparedForNextRun = false;
this._isBeingCancelled = true;
try {
await this.#cancel();
} catch (err) {
console.error("Error cancelling task run process", { err });
}
await this.kill();
}
async cleanup(kill = true) {
this._isPreparedForNextRun = false;
if (this._isBeingCancelled) {
return;
}
try {
await this.#flush();
} catch (err) {
console.error("Error flushing task run process", { err });
}
if (kill) {
await this.kill("SIGKILL");
}
}
initialize() {
const { env: $env, workerManifest, cwd, machineResources: machine } = this.options;
const maxOldSpaceSize = nodeOptionsWithMaxOldSpaceSize(undefined, machine);
const fullEnv = {
...$env,
OTEL_IMPORT_HOOK_INCLUDES: workerManifest.otelImportHook?.include?.join(","),
// TODO: this will probably need to use something different for bun (maybe --preload?)
NODE_OPTIONS: execOptionsForRuntime(workerManifest.runtime, workerManifest, maxOldSpaceSize),
PATH: process.env.PATH,
TRIGGER_PROCESS_FORK_START_TIME: String(Date.now()),
TRIGGER_WARM_START: this.options.isWarmStart ? "true" : "false",
};
logger.debug(`initializing task run process`, {
env: fullEnv,
path: workerManifest.workerEntryPoint,
cwd,
});
this._child = fork(workerManifest.workerEntryPoint, executorArgs(workerManifest), {
stdio: [/*stdin*/ "ignore", /*stdout*/ "pipe", /*stderr*/ "pipe", "ipc"],
cwd,
env: fullEnv,
execArgv: ["--trace-uncaught", "--no-warnings=ExperimentalWarning"],
execPath: execPathForRuntime(workerManifest.runtime),
serialization: "json",
});
this._childPid = this._child?.pid;
this._ipc = new ZodIpcConnection({
listenSchema: ExecutorToWorkerMessageCatalog,
emitSchema: WorkerToExecutorMessageCatalog,
process: this._child,
handlers: {
TASK_RUN_COMPLETED: async (message) => {
const { result, execution } = message;
const key = attemptKey(execution);
const promiseStatus = this._attemptStatuses.get(key);
if (promiseStatus !== "PENDING") {
return;
}
this._attemptStatuses.set(key, "RESOLVED");
const attemptPromise = this._attemptPromises.get(key);
if (!attemptPromise) {
return;
}
const { resolver } = attemptPromise;
resolver(result);
},
READY_TO_DISPOSE: async () => {
logger.debug(`task run process is ready to dispose`);
this.onReadyToDispose.post(this);
},
TASK_HEARTBEAT: async (message) => {
this.onTaskRunHeartbeat.post(message.id);
},
WAIT_FOR_TASK: async (message) => {
this.onWaitForTask.post(message);
},
WAIT_FOR_BATCH: async (message) => {
this.onWaitForBatch.post(message);
},
UNCAUGHT_EXCEPTION: async (message) => {
logger.debug("uncaught exception in task run process", { ...message });
},
},
});
this._child.on("exit", this.#handleExit.bind(this));
this._child.stdout?.on("data", this.#handleLog.bind(this));
this._child.stderr?.on("data", this.#handleStdErr.bind(this));
return this;
}
async #flush(timeoutInMs: number = 5_000) {
logger.debug("flushing task run process", { pid: this.pid });
await this._ipc?.sendWithAck("FLUSH", { timeoutInMs }, timeoutInMs + 1_000);
}
async #cancel(timeoutInMs: number = 30_000) {
logger.debug("sending cancel message to task run process", { pid: this.pid, timeoutInMs });
await this._ipc?.sendWithAck("CANCEL", { timeoutInMs }, timeoutInMs + 1_000);
}
async execute(
params: TaskRunProcessExecuteParams,
isWarmStart?: boolean
): Promise<TaskRunExecutionResult> {
this._isBeingCancelled = false;
this._isPreparedForNextRun = false;
this._isPreparedForNextAttempt = false;
let resolver: (value: TaskRunExecutionResult) => void;
let rejecter: (err?: any) => void;
const promise = new Promise<TaskRunExecutionResult>((resolve, reject) => {
resolver = resolve;
rejecter = reject;
});
const key = attemptKey(params.payload.execution);
this._attemptStatuses.set(key, "PENDING");
// @ts-expect-error - We know that the resolver and rejecter are defined
this._attemptPromises.set(key, { resolver, rejecter });
const { execution, traceContext, metrics } = params.payload;
this._currentExecution = execution;
if (this._child?.connected && !this._isBeingKilled && !this._child.killed) {
logger.debug(
`[${new Date().toISOString()}][${
params.payload.execution.run.id
}] sending EXECUTE_TASK_RUN message to task run process`,
{
pid: this.pid,
}
);
await this._ipc?.send("EXECUTE_TASK_RUN", {
execution,
traceContext,
metadata: this.options.serverWorker,
metrics,
env: params.env,
isWarmStart: isWarmStart ?? this.options.isWarmStart,
});
}
const result = await promise;
this._currentExecution = undefined;
this._isPreparedForNextAttempt = true;
return result;
}
taskRunCompletedNotification(completion: TaskRunExecutionResult) {
if (!completion.ok && typeof completion.retry !== "undefined") {
logger.debug(
"Task run completed with error and wants to retry, won't send task run completed notification"
);
return;
}
if (!this._child?.connected || this._isBeingKilled || this._child.killed) {
logger.debug(
"Child process not connected or being killed, can't send task run completed notification"
);
return;
}
this._ipc?.send("TASK_RUN_COMPLETED_NOTIFICATION", {
version: "v2",
completion,
});
}
waitCompletedNotification() {
if (!this._child?.connected || this._isBeingKilled || this._child.killed) {
console.error(
"Child process not connected or being killed, can't send wait completed notification"
);
return;
}
this._ipc?.send("WAIT_COMPLETED_NOTIFICATION", {});
}
waitpointCreated(waitId: string, waitpointId: string) {
if (!this._child?.connected || this._isBeingKilled || this._child.killed) {
console.error(
"Child process not connected or being killed, can't send waitpoint created notification"
);
return;
}
this._ipc?.send("WAITPOINT_CREATED", {
wait: {
id: waitId,
},
waitpoint: {
id: waitpointId,
},
});
}
waitpointCompleted(waitpoint: CompletedWaitpoint) {
if (!this._child?.connected || this._isBeingKilled || this._child.killed) {
console.error(
"Child process not connected or being killed, can't send waitpoint completed notification"
);
return;
}
this._ipc?.send("WAITPOINT_COMPLETED", {
waitpoint,
});
}
async #handleExit(code: number | null, signal: NodeJS.Signals | null) {
logger.debug("handling child exit", { code, signal });
// Go through all the attempts currently pending and reject them
for (const [id, status] of this._attemptStatuses.entries()) {
if (status === "PENDING") {
logger.debug("found pending attempt", { id });
this._attemptStatuses.set(id, "REJECTED");
const attemptPromise = this._attemptPromises.get(id);
if (!attemptPromise) {
continue;
}
const { rejecter } = attemptPromise;
if (this._isBeingCancelled) {
rejecter(new CancelledProcessError());
} else if (this._gracefulExitTimeoutElapsed) {
// Order matters, this has to be before the graceful exit timeout
rejecter(new GracefulExitTimeoutError());
} else if (this._isBeingKilled) {
if (this._isBeingSuspended) {
rejecter(new SuspendedProcessError());
} else {
rejecter(new CleanupProcessError());
}
} else {
rejecter(
new UnexpectedExitError(
code ?? -1,
signal,
this._stderr.length ? this._stderr.join("\n") : undefined
)
);
}
}
}
logger.debug("Task run process exited, posting onExit", { code, signal, pid: this.pid });
this.onExit.post({ code, signal, pid: this.pid });
}
#handleLog(data: Buffer) {
if (!this._currentExecution) {
logger.log(`${chalkGrey("○")} ${chalkGrey(prettyPrintDate(new Date()))} ${data.toString()}`);
return;
}
const runId = chalkRun(
`${this._currentExecution.run.id}.${this._currentExecution.attempt.number}`
);
logger.log(
`${chalkGrey("○")} ${chalkGrey(prettyPrintDate(new Date()))} ${runId} ${data.toString()}`
);
}
#handleStdErr(data: Buffer) {
if (this._isBeingKilled) {
return;
}
if (!this._currentExecution) {
logger.log(`${chalkError("○")} ${chalkGrey(prettyPrintDate(new Date()))} ${data.toString()}`);
return;
}
const runId = chalkRun(
`${this._currentExecution.run.id}.${this._currentExecution.attempt.number}`
);
const errorLine = data.toString();
logger.log(
`${chalkError("○")} ${chalkGrey(prettyPrintDate(new Date()))} ${runId} ${errorLine}`
);
if (this._stderr.length > 100) {
this._stderr.shift();
}
this._stderr.push(errorLine);
}
async kill(signal?: number | NodeJS.Signals, timeoutInMs?: number) {
logger.debug(`killing task run process`, {
signal,
timeoutInMs,
pid: this.pid,
});
this._isBeingKilled = true;
const killTimeout = this.onExit.waitFor(timeoutInMs);
this.onIsBeingKilled.post(this);
this._child?.kill(signal);
if (timeoutInMs) {
await killTimeout;
}
}
async suspend() {
this._isBeingSuspended = true;
await this.kill("SIGKILL");
}
forceExit() {
try {
this._isBeingKilled = true;
this._child?.kill("SIGKILL");
} catch (error) {
logger.debug("forceExit: failed to kill child process", { error });
}
}
get isBeingKilled() {
return this._isBeingKilled || this._child?.killed;
}
get pid() {
return this._childPid;
}
static parseExecuteError(error: unknown, dockerMode = true): TaskRunInternalError {
if (error instanceof CancelledProcessError) {
return {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.TASK_RUN_CANCELLED,
};
}
if (error instanceof CleanupProcessError) {
return {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.TASK_EXECUTION_ABORTED,
};
}
if (error instanceof UnexpectedExitError) {
return internalErrorFromUnexpectedExit(error, dockerMode);
}
if (error instanceof GracefulExitTimeoutError) {
return {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.GRACEFUL_EXIT_TIMEOUT,
};
}
return {
type: "INTERNAL_ERROR",
code: TaskRunErrorCodes.TASK_EXECUTION_FAILED,
message: String(error),
};
}
}
function executorArgs(workerManifest: WorkerManifest): string[] {
return [];
}