trigger.dev 1.0.7 → 1.0.8

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1214 @@
1
+ // src/workers/prod/entry-point.ts
2
+ import {
3
+ CoordinatorToProdWorkerMessages,
4
+ PostStartCauses,
5
+ PreStopCauses,
6
+ ProdWorkerToCoordinatorMessages
7
+ } from "@trigger.dev/core/v3";
8
+ import { ZodSocketConnection as ZodSocketConnection2 } from "@trigger.dev/core/v3/zodSocket";
9
+
10
+ // ../core-apps/src/http.ts
11
+ var HttpReply = class {
12
+ constructor(response) {
13
+ this.response = response;
14
+ }
15
+ empty(status) {
16
+ return this.response.writeHead(status ?? 200).end();
17
+ }
18
+ text(text, status, contentType) {
19
+ return this.response.writeHead(status ?? 200, { "Content-Type": contentType || "text/plain" }).end(text.endsWith("\n") ? text : `${text}
20
+ `);
21
+ }
22
+ json(value, pretty) {
23
+ return this.text(
24
+ JSON.stringify(value, void 0, pretty ? 2 : void 0),
25
+ 200,
26
+ "application/json"
27
+ );
28
+ }
29
+ };
30
+ function getRandomInteger(min, max) {
31
+ const intMin = Math.ceil(min);
32
+ const intMax = Math.floor(max);
33
+ return Math.floor(Math.random() * (intMax - intMin + 1)) + intMin;
34
+ }
35
+ function getRandomPortNumber() {
36
+ return getRandomInteger(8e3, 9999);
37
+ }
38
+
39
+ // ../core-apps/src/logger.ts
40
+ var SimpleLogger = class {
41
+ constructor(prefix) {
42
+ this.prefix = prefix;
43
+ }
44
+ #debugEnabled = ["1", "true"].includes(process.env.DEBUG ?? "");
45
+ log(arg0, ...argN) {
46
+ console.log(...this.#getPrefixedArgs(arg0, ...argN));
47
+ return arg0;
48
+ }
49
+ debug(arg0, ...argN) {
50
+ if (!this.#debugEnabled) {
51
+ return arg0;
52
+ }
53
+ console.debug(...this.#getPrefixedArgs("DEBUG", arg0, ...argN));
54
+ return arg0;
55
+ }
56
+ error(arg0, ...argN) {
57
+ console.error(...this.#getPrefixedArgs(arg0, ...argN));
58
+ return arg0;
59
+ }
60
+ #getPrefixedArgs(...args) {
61
+ if (!this.prefix) {
62
+ return args;
63
+ }
64
+ return [this.prefix, ...args];
65
+ }
66
+ };
67
+
68
+ // ../core-apps/src/provider.ts
69
+ import {
70
+ ClientToSharedQueueMessages,
71
+ clientWebsocketMessages,
72
+ PlatformToProviderMessages,
73
+ ProviderToPlatformMessages,
74
+ SharedQueueToClientMessages
75
+ } from "@trigger.dev/core/v3";
76
+ import { ZodMessageSender } from "@trigger.dev/core/v3/zodMessageHandler";
77
+ import { ZodSocketConnection } from "@trigger.dev/core/v3/zodSocket";
78
+ var HTTP_SERVER_PORT = Number(process.env.HTTP_SERVER_PORT || getRandomPortNumber());
79
+ var MACHINE_NAME = process.env.MACHINE_NAME || "local";
80
+ var PLATFORM_HOST = process.env.PLATFORM_HOST || "127.0.0.1";
81
+ var PLATFORM_WS_PORT = process.env.PLATFORM_WS_PORT || 3030;
82
+ var PLATFORM_SECRET = process.env.PLATFORM_SECRET || "provider-secret";
83
+ var SECURE_CONNECTION = ["1", "true"].includes(process.env.SECURE_CONNECTION ?? "false");
84
+ var logger = new SimpleLogger(`[${MACHINE_NAME}]`);
85
+
86
+ // src/workers/prod/entry-point.ts
87
+ import { readFile } from "node:fs/promises";
88
+ import { createServer } from "node:http";
89
+
90
+ // src/workers/prod/backgroundWorker.ts
91
+ import {
92
+ ProdChildToWorkerMessages,
93
+ ProdWorkerToChildMessages,
94
+ SemanticInternalAttributes,
95
+ TaskRunErrorCodes,
96
+ correctErrorStackTrace
97
+ } from "@trigger.dev/core/v3";
98
+ import { ZodIpcConnection } from "@trigger.dev/core/v3/zodIpc";
99
+ import { Evt } from "evt";
100
+ import { fork } from "node:child_process";
101
+
102
+ // src/workers/common/errors.ts
103
+ var UncaughtExceptionError = class extends Error {
104
+ constructor(originalError, origin) {
105
+ super(`Uncaught exception: ${originalError.message}`);
106
+ this.originalError = originalError;
107
+ this.origin = origin;
108
+ this.name = "UncaughtExceptionError";
109
+ }
110
+ };
111
+ var TaskMetadataParseError = class extends Error {
112
+ constructor(zodIssues, tasks) {
113
+ super(`Failed to parse task metadata`);
114
+ this.zodIssues = zodIssues;
115
+ this.tasks = tasks;
116
+ this.name = "TaskMetadataParseError";
117
+ }
118
+ };
119
+
120
+ // src/workers/prod/backgroundWorker.ts
121
+ var UnexpectedExitError = class extends Error {
122
+ constructor(code) {
123
+ super(`Unexpected exit with code ${code}`);
124
+ this.code = code;
125
+ this.name = "UnexpectedExitError";
126
+ }
127
+ };
128
+ var CleanupProcessError = class extends Error {
129
+ constructor() {
130
+ super("Cancelled");
131
+ this.name = "CleanupProcessError";
132
+ }
133
+ };
134
+ var CancelledProcessError = class extends Error {
135
+ constructor() {
136
+ super("Cancelled");
137
+ this.name = "CancelledProcessError";
138
+ }
139
+ };
140
+ var ProdBackgroundWorker = class {
141
+ constructor(path, params) {
142
+ this.path = path;
143
+ this.params = params;
144
+ }
145
+ _initialized = false;
146
+ onTaskHeartbeat = new Evt();
147
+ onWaitForBatch = new Evt();
148
+ onWaitForDuration = new Evt();
149
+ onWaitForTask = new Evt();
150
+ preCheckpointNotification = Evt.create();
151
+ checkpointCanceledNotification = Evt.create();
152
+ onReadyForCheckpoint = Evt.create();
153
+ onCancelCheckpoint = Evt.create();
154
+ _onClose = new Evt();
155
+ tasks = [];
156
+ _taskRunProcess;
157
+ _closed = false;
158
+ async close() {
159
+ if (this._closed) {
160
+ return;
161
+ }
162
+ this._closed = true;
163
+ this.onTaskHeartbeat.detach();
164
+ await this._taskRunProcess?.cleanup(true);
165
+ }
166
+ async flushTelemetry() {
167
+ await this._taskRunProcess?.cleanup(false);
168
+ }
169
+ async initialize(options) {
170
+ if (this._initialized) {
171
+ throw new Error("Worker already initialized");
172
+ }
173
+ let resolved = false;
174
+ this.tasks = await new Promise((resolve, reject) => {
175
+ const child = fork(this.path, {
176
+ stdio: [
177
+ /*stdin*/
178
+ "ignore",
179
+ /*stdout*/
180
+ "pipe",
181
+ /*stderr*/
182
+ "pipe",
183
+ "ipc"
184
+ ],
185
+ env: {
186
+ ...this.params.env,
187
+ ...options?.env
188
+ }
189
+ });
190
+ const timeout = setTimeout(() => {
191
+ if (resolved) {
192
+ return;
193
+ }
194
+ resolved = true;
195
+ child.kill();
196
+ reject(new Error("Worker timed out"));
197
+ }, 1e4);
198
+ new ZodIpcConnection({
199
+ listenSchema: ProdChildToWorkerMessages,
200
+ emitSchema: ProdWorkerToChildMessages,
201
+ process: child,
202
+ handlers: {
203
+ TASKS_READY: async (message) => {
204
+ if (!resolved) {
205
+ clearTimeout(timeout);
206
+ resolved = true;
207
+ resolve(message.tasks);
208
+ child.kill();
209
+ }
210
+ },
211
+ UNCAUGHT_EXCEPTION: async (message) => {
212
+ if (!resolved) {
213
+ clearTimeout(timeout);
214
+ resolved = true;
215
+ reject(new UncaughtExceptionError(message.error, message.origin));
216
+ child.kill();
217
+ }
218
+ },
219
+ TASKS_FAILED_TO_PARSE: async (message) => {
220
+ if (!resolved) {
221
+ clearTimeout(timeout);
222
+ resolved = true;
223
+ reject(new TaskMetadataParseError(message.zodIssues, message.tasks));
224
+ child.kill();
225
+ }
226
+ }
227
+ }
228
+ });
229
+ child.stdout?.on("data", (data) => {
230
+ console.log(data.toString());
231
+ });
232
+ child.stderr?.on("data", (data) => {
233
+ console.error(data.toString());
234
+ });
235
+ child.on("exit", (code) => {
236
+ if (!resolved) {
237
+ clearTimeout(timeout);
238
+ resolved = true;
239
+ reject(new Error(`Worker exited with code ${code}`));
240
+ }
241
+ });
242
+ });
243
+ this._initialized = true;
244
+ }
245
+ getMetadata(workerId, version) {
246
+ return {
247
+ contentHash: this.params.contentHash,
248
+ id: workerId,
249
+ version
250
+ };
251
+ }
252
+ // We need to notify all the task run processes that a task run has completed,
253
+ // in case they are waiting for it through triggerAndWait
254
+ async taskRunCompletedNotification(completion, execution) {
255
+ this._taskRunProcess?.taskRunCompletedNotification(completion, execution);
256
+ }
257
+ async waitCompletedNotification() {
258
+ this._taskRunProcess?.waitCompletedNotification();
259
+ }
260
+ async #initializeTaskRunProcess(payload) {
261
+ const metadata = this.getMetadata(
262
+ payload.execution.worker.id,
263
+ payload.execution.worker.version
264
+ );
265
+ if (!this._taskRunProcess) {
266
+ const taskRunProcess = new TaskRunProcess(
267
+ payload.execution,
268
+ this.path,
269
+ {
270
+ ...this.params.env,
271
+ ...payload.environment ?? {}
272
+ },
273
+ metadata,
274
+ this.params
275
+ );
276
+ taskRunProcess.onExit.attach(() => {
277
+ this._taskRunProcess = void 0;
278
+ });
279
+ taskRunProcess.onTaskHeartbeat.attach((id) => {
280
+ this.onTaskHeartbeat.post(id);
281
+ });
282
+ taskRunProcess.onWaitForBatch.attach((message) => {
283
+ this.onWaitForBatch.post(message);
284
+ });
285
+ taskRunProcess.onWaitForDuration.attach((message) => {
286
+ this.onWaitForDuration.post(message);
287
+ });
288
+ taskRunProcess.onWaitForTask.attach((message) => {
289
+ this.onWaitForTask.post(message);
290
+ });
291
+ taskRunProcess.onReadyForCheckpoint.attach((message) => {
292
+ this.onReadyForCheckpoint.post(message);
293
+ });
294
+ taskRunProcess.onCancelCheckpoint.attach((message) => {
295
+ this.onCancelCheckpoint.post(message);
296
+ });
297
+ this.preCheckpointNotification.attach((message) => {
298
+ taskRunProcess.preCheckpointNotification.post(message);
299
+ });
300
+ this.checkpointCanceledNotification.attach((message) => {
301
+ taskRunProcess.checkpointCanceledNotification.post(message);
302
+ });
303
+ await taskRunProcess.initialize();
304
+ this._taskRunProcess = taskRunProcess;
305
+ }
306
+ return this._taskRunProcess;
307
+ }
308
+ // We need to fork the process before we can execute any tasks
309
+ async executeTaskRun(payload) {
310
+ try {
311
+ const taskRunProcess = await this.#initializeTaskRunProcess(payload);
312
+ const result = await taskRunProcess.executeTaskRun(payload);
313
+ if (result.ok) {
314
+ return result;
315
+ }
316
+ const error = result.error;
317
+ if (error.type === "BUILT_IN_ERROR") {
318
+ const mappedError = await this.#correctError(error, payload.execution);
319
+ return {
320
+ ...result,
321
+ error: mappedError
322
+ };
323
+ }
324
+ return result;
325
+ } catch (e) {
326
+ if (e instanceof CancelledProcessError) {
327
+ return {
328
+ id: payload.execution.attempt.id,
329
+ ok: false,
330
+ retry: void 0,
331
+ error: {
332
+ type: "INTERNAL_ERROR",
333
+ code: TaskRunErrorCodes.TASK_RUN_CANCELLED
334
+ }
335
+ };
336
+ }
337
+ if (e instanceof CleanupProcessError) {
338
+ return {
339
+ id: payload.execution.attempt.id,
340
+ ok: false,
341
+ retry: void 0,
342
+ error: {
343
+ type: "INTERNAL_ERROR",
344
+ code: TaskRunErrorCodes.TASK_EXECUTION_ABORTED
345
+ }
346
+ };
347
+ }
348
+ if (e instanceof UnexpectedExitError) {
349
+ return {
350
+ id: payload.execution.attempt.id,
351
+ ok: false,
352
+ retry: void 0,
353
+ error: {
354
+ type: "INTERNAL_ERROR",
355
+ code: TaskRunErrorCodes.TASK_PROCESS_EXITED_WITH_NON_ZERO_CODE
356
+ }
357
+ };
358
+ }
359
+ return {
360
+ id: payload.execution.attempt.id,
361
+ ok: false,
362
+ retry: void 0,
363
+ error: {
364
+ type: "INTERNAL_ERROR",
365
+ code: TaskRunErrorCodes.TASK_EXECUTION_FAILED
366
+ }
367
+ };
368
+ }
369
+ }
370
+ async cancelAttempt(attemptId) {
371
+ await this._taskRunProcess?.cancel();
372
+ }
373
+ async #correctError(error, execution) {
374
+ return {
375
+ ...error,
376
+ stackTrace: correctErrorStackTrace(error.stackTrace, this.params.projectConfig.projectDir)
377
+ };
378
+ }
379
+ };
380
+ var TaskRunProcess = class {
381
+ constructor(execution, path, env, metadata, worker) {
382
+ this.execution = execution;
383
+ this.path = path;
384
+ this.env = env;
385
+ this.metadata = metadata;
386
+ this.worker = worker;
387
+ }
388
+ _ipc;
389
+ _child;
390
+ _attemptPromises = /* @__PURE__ */ new Map();
391
+ _attemptStatuses = /* @__PURE__ */ new Map();
392
+ _currentExecution;
393
+ _isBeingKilled = false;
394
+ _isBeingCancelled = false;
395
+ onTaskHeartbeat = new Evt();
396
+ onExit = new Evt();
397
+ onWaitForBatch = new Evt();
398
+ onWaitForDuration = new Evt();
399
+ onWaitForTask = new Evt();
400
+ preCheckpointNotification = Evt.create();
401
+ checkpointCanceledNotification = Evt.create();
402
+ onReadyForCheckpoint = Evt.create();
403
+ onCancelCheckpoint = Evt.create();
404
+ async initialize() {
405
+ this._child = fork(this.path, {
406
+ stdio: [
407
+ /*stdin*/
408
+ "ignore",
409
+ /*stdout*/
410
+ "pipe",
411
+ /*stderr*/
412
+ "pipe",
413
+ "ipc"
414
+ ],
415
+ env: {
416
+ ...this.execution.run.isTest ? { TRIGGER_LOG_LEVEL: "debug" } : {},
417
+ ...this.env,
418
+ OTEL_RESOURCE_ATTRIBUTES: JSON.stringify({
419
+ [SemanticInternalAttributes.PROJECT_DIR]: this.worker.projectConfig.projectDir
420
+ }),
421
+ ...this.worker.debugOtel ? { OTEL_LOG_LEVEL: "debug" } : {}
422
+ }
423
+ });
424
+ this._ipc = new ZodIpcConnection({
425
+ listenSchema: ProdChildToWorkerMessages,
426
+ emitSchema: ProdWorkerToChildMessages,
427
+ process: this._child,
428
+ handlers: {
429
+ TASK_RUN_COMPLETED: async (message) => {
430
+ const { result, execution } = message;
431
+ const promiseStatus = this._attemptStatuses.get(execution.attempt.id);
432
+ if (promiseStatus !== "PENDING") {
433
+ return;
434
+ }
435
+ this._attemptStatuses.set(execution.attempt.id, "RESOLVED");
436
+ const attemptPromise = this._attemptPromises.get(execution.attempt.id);
437
+ if (!attemptPromise) {
438
+ return;
439
+ }
440
+ const { resolver } = attemptPromise;
441
+ resolver(result);
442
+ },
443
+ READY_TO_DISPOSE: async (message) => {
444
+ process.exit(0);
445
+ },
446
+ TASK_HEARTBEAT: async (message) => {
447
+ this.onTaskHeartbeat.post(message.id);
448
+ },
449
+ TASKS_READY: async (message) => {
450
+ },
451
+ WAIT_FOR_TASK: async (message) => {
452
+ this.onWaitForTask.post(message);
453
+ },
454
+ WAIT_FOR_BATCH: async (message) => {
455
+ this.onWaitForBatch.post(message);
456
+ },
457
+ WAIT_FOR_DURATION: async (message) => {
458
+ this.onWaitForDuration.post(message);
459
+ try {
460
+ const { willCheckpointAndRestore } = await this.preCheckpointNotification.waitFor(
461
+ 3e4
462
+ );
463
+ return {
464
+ willCheckpointAndRestore
465
+ };
466
+ } catch (error) {
467
+ console.error("Error while waiting for pre-checkpoint notification", error);
468
+ return {
469
+ willCheckpointAndRestore: false
470
+ };
471
+ }
472
+ },
473
+ READY_FOR_CHECKPOINT: async (message) => {
474
+ this.onReadyForCheckpoint.post(message);
475
+ },
476
+ CANCEL_CHECKPOINT: async (message) => {
477
+ const version = "v2";
478
+ this.onCancelCheckpoint.post(message);
479
+ try {
480
+ const { checkpointCanceled } = await this.checkpointCanceledNotification.waitFor(
481
+ 3e4
482
+ );
483
+ return {
484
+ version,
485
+ checkpointCanceled
486
+ };
487
+ } catch (error) {
488
+ console.error("Error while waiting for checkpoint cancellation", error);
489
+ return {
490
+ version,
491
+ checkpointCanceled: true
492
+ };
493
+ }
494
+ }
495
+ }
496
+ });
497
+ this._child.on("exit", this.#handleExit.bind(this));
498
+ this._child.stdout?.on("data", this.#handleLog.bind(this));
499
+ this._child.stderr?.on("data", this.#handleStdErr.bind(this));
500
+ }
501
+ async cancel() {
502
+ this._isBeingCancelled = true;
503
+ await this.cleanup(true);
504
+ }
505
+ async cleanup(kill = false) {
506
+ if (kill && this._isBeingKilled) {
507
+ return;
508
+ }
509
+ this._isBeingKilled = kill;
510
+ await this._ipc?.sendWithAck("CLEANUP", {
511
+ flush: true,
512
+ kill
513
+ });
514
+ }
515
+ async executeTaskRun(payload) {
516
+ let resolver;
517
+ let rejecter;
518
+ const promise = new Promise((resolve, reject) => {
519
+ resolver = resolve;
520
+ rejecter = reject;
521
+ });
522
+ this._attemptStatuses.set(payload.execution.attempt.id, "PENDING");
523
+ this._attemptPromises.set(payload.execution.attempt.id, { resolver, rejecter });
524
+ const { execution, traceContext } = payload;
525
+ this._currentExecution = execution;
526
+ if (this._child?.connected && !this._isBeingKilled && !this._child.killed) {
527
+ await this._ipc?.send("EXECUTE_TASK_RUN", {
528
+ execution,
529
+ traceContext,
530
+ metadata: this.metadata
531
+ });
532
+ }
533
+ const result = await promise;
534
+ this._currentExecution = void 0;
535
+ return result;
536
+ }
537
+ taskRunCompletedNotification(completion, execution) {
538
+ if (!completion.ok && typeof completion.retry !== "undefined") {
539
+ return;
540
+ }
541
+ if (this._child?.connected && !this._isBeingKilled && !this._child.killed) {
542
+ this._ipc?.send("TASK_RUN_COMPLETED_NOTIFICATION", {
543
+ completion,
544
+ execution
545
+ });
546
+ }
547
+ }
548
+ waitCompletedNotification() {
549
+ if (this._child?.connected && !this._isBeingKilled && !this._child.killed) {
550
+ this._ipc?.send("WAIT_COMPLETED_NOTIFICATION", {});
551
+ }
552
+ }
553
+ async #handleExit(code) {
554
+ for (const [id, status] of this._attemptStatuses.entries()) {
555
+ if (status === "PENDING") {
556
+ this._attemptStatuses.set(id, "REJECTED");
557
+ const attemptPromise = this._attemptPromises.get(id);
558
+ if (!attemptPromise) {
559
+ continue;
560
+ }
561
+ const { rejecter } = attemptPromise;
562
+ if (this._isBeingCancelled) {
563
+ rejecter(new CancelledProcessError());
564
+ } else if (this._isBeingKilled) {
565
+ rejecter(new CleanupProcessError());
566
+ } else {
567
+ rejecter(new UnexpectedExitError(code));
568
+ }
569
+ }
570
+ }
571
+ this.onExit.post(code);
572
+ }
573
+ #handleLog(data) {
574
+ if (!this._currentExecution) {
575
+ return;
576
+ }
577
+ console.log(
578
+ `[${this.metadata.version}][${this._currentExecution.run.id}.${this._currentExecution.attempt.number}] ${data.toString()}`
579
+ );
580
+ }
581
+ #handleStdErr(data) {
582
+ if (this._isBeingKilled) {
583
+ return;
584
+ }
585
+ if (!this._currentExecution) {
586
+ console.error(`[${this.metadata.version}] ${data.toString()}`);
587
+ return;
588
+ }
589
+ console.error(
590
+ `[${this.metadata.version}][${this._currentExecution.run.id}.${this._currentExecution.attempt.number}] ${data.toString()}`
591
+ );
592
+ }
593
+ #kill() {
594
+ if (this._child && !this._child.killed) {
595
+ this._child?.kill();
596
+ }
597
+ }
598
+ };
599
+
600
+ // src/workers/prod/entry-point.ts
601
+ import { setTimeout as setTimeout2 } from "node:timers/promises";
602
+ var HTTP_SERVER_PORT2 = Number(process.env.HTTP_SERVER_PORT || getRandomPortNumber());
603
+ var COORDINATOR_HOST = process.env.COORDINATOR_HOST || "127.0.0.1";
604
+ var COORDINATOR_PORT = Number(process.env.COORDINATOR_PORT || 50080);
605
+ var MACHINE_NAME2 = process.env.MACHINE_NAME || "local";
606
+ var POD_NAME = process.env.POD_NAME || "some-pod";
607
+ var SHORT_HASH = process.env.TRIGGER_CONTENT_HASH.slice(0, 9);
608
+ var logger2 = new SimpleLogger(`[${MACHINE_NAME2}][${SHORT_HASH}]`);
609
+ var ProdWorker = class {
610
+ constructor(port, host = "0.0.0.0") {
611
+ this.host = host;
612
+ process.on("SIGTERM", this.#handleSignal.bind(this, "SIGTERM"));
613
+ this.#coordinatorSocket = this.#createCoordinatorSocket(COORDINATOR_HOST);
614
+ this.#backgroundWorker = new ProdBackgroundWorker("worker.js", {
615
+ projectConfig: __PROJECT_CONFIG__,
616
+ env: {
617
+ ...gatherProcessEnv(),
618
+ TRIGGER_API_URL: this.apiUrl,
619
+ TRIGGER_SECRET_KEY: this.apiKey,
620
+ OTEL_EXPORTER_OTLP_ENDPOINT: process.env.OTEL_EXPORTER_OTLP_ENDPOINT ?? "http://0.0.0.0:4318"
621
+ },
622
+ contentHash: this.contentHash
623
+ });
624
+ this.#backgroundWorker.onTaskHeartbeat.attach((attemptFriendlyId) => {
625
+ this.#coordinatorSocket.socket.emit("TASK_HEARTBEAT", { version: "v1", attemptFriendlyId });
626
+ });
627
+ this.#backgroundWorker.onReadyForCheckpoint.attach(async (message) => {
628
+ await this.#backgroundWorker.flushTelemetry();
629
+ this.#coordinatorSocket.socket.emit("READY_FOR_CHECKPOINT", { version: "v1" });
630
+ });
631
+ this.#backgroundWorker.onCancelCheckpoint.attach(async (message) => {
632
+ logger2.log("onCancelCheckpoint", { message });
633
+ const { checkpointCanceled } = await this.#coordinatorSocket.socket.emitWithAck(
634
+ "CANCEL_CHECKPOINT",
635
+ {
636
+ version: "v2",
637
+ reason: message.reason
638
+ }
639
+ );
640
+ if (checkpointCanceled) {
641
+ if (message.reason === "WAIT_FOR_DURATION") {
642
+ this.paused = false;
643
+ this.nextResumeAfter = void 0;
644
+ this.waitForPostStart = false;
645
+ }
646
+ }
647
+ this.#backgroundWorker.checkpointCanceledNotification.post({ checkpointCanceled });
648
+ });
649
+ this.#backgroundWorker.onWaitForDuration.attach(async (message) => {
650
+ if (!this.attemptFriendlyId) {
651
+ logger2.error("Failed to send wait message, attempt friendly ID not set", { message });
652
+ return;
653
+ }
654
+ const { willCheckpointAndRestore } = await this.#coordinatorSocket.socket.emitWithAck(
655
+ "WAIT_FOR_DURATION",
656
+ {
657
+ ...message,
658
+ attemptFriendlyId: this.attemptFriendlyId
659
+ }
660
+ );
661
+ this.#prepareForWait("WAIT_FOR_DURATION", willCheckpointAndRestore);
662
+ });
663
+ this.#backgroundWorker.onWaitForTask.attach(async (message) => {
664
+ if (!this.attemptFriendlyId) {
665
+ logger2.error("Failed to send wait message, attempt friendly ID not set", { message });
666
+ return;
667
+ }
668
+ const { willCheckpointAndRestore } = await this.#coordinatorSocket.socket.emitWithAck(
669
+ "WAIT_FOR_TASK",
670
+ {
671
+ ...message,
672
+ attemptFriendlyId: this.attemptFriendlyId
673
+ }
674
+ );
675
+ this.#prepareForWait("WAIT_FOR_TASK", willCheckpointAndRestore);
676
+ });
677
+ this.#backgroundWorker.onWaitForBatch.attach(async (message) => {
678
+ if (!this.attemptFriendlyId) {
679
+ logger2.error("Failed to send wait message, attempt friendly ID not set", { message });
680
+ return;
681
+ }
682
+ const { willCheckpointAndRestore } = await this.#coordinatorSocket.socket.emitWithAck(
683
+ "WAIT_FOR_BATCH",
684
+ {
685
+ ...message,
686
+ attemptFriendlyId: this.attemptFriendlyId
687
+ }
688
+ );
689
+ this.#prepareForWait("WAIT_FOR_BATCH", willCheckpointAndRestore);
690
+ });
691
+ this.#httpPort = port;
692
+ this.#httpServer = this.#createHttpServer();
693
+ }
694
+ apiUrl = process.env.TRIGGER_API_URL;
695
+ apiKey = process.env.TRIGGER_SECRET_KEY;
696
+ contentHash = process.env.TRIGGER_CONTENT_HASH;
697
+ projectRef = process.env.TRIGGER_PROJECT_REF;
698
+ envId = process.env.TRIGGER_ENV_ID;
699
+ runId = process.env.TRIGGER_RUN_ID || "index-only";
700
+ deploymentId = process.env.TRIGGER_DEPLOYMENT_ID;
701
+ deploymentVersion = process.env.TRIGGER_DEPLOYMENT_VERSION;
702
+ runningInKubernetes = !!process.env.KUBERNETES_PORT;
703
+ executing = false;
704
+ completed = /* @__PURE__ */ new Set();
705
+ paused = false;
706
+ attemptFriendlyId;
707
+ nextResumeAfter;
708
+ waitForPostStart = false;
709
+ #httpPort;
710
+ #backgroundWorker;
711
+ #httpServer;
712
+ #coordinatorSocket;
713
+ async #handleSignal(signal) {
714
+ logger2.log("Received signal", { signal });
715
+ if (signal === "SIGTERM") {
716
+ if (this.executing) {
717
+ const terminationGracePeriodSeconds = 60 * 60;
718
+ logger2.log("Waiting for attempt to complete before exiting", {
719
+ terminationGracePeriodSeconds
720
+ });
721
+ await setTimeout2(terminationGracePeriodSeconds * 1e3 - 5e3);
722
+ logger2.log("Termination timeout reached, exiting gracefully.");
723
+ } else {
724
+ logger2.log("Not executing, exiting immediately.");
725
+ }
726
+ await this.#exitGracefully();
727
+ }
728
+ logger2.log("Unhandled signal", { signal });
729
+ }
730
+ async #exitGracefully() {
731
+ await this.#backgroundWorker.close();
732
+ process.exit(0);
733
+ }
734
+ async #reconnect(isPostStart = false, reconnectImmediately = false) {
735
+ if (isPostStart) {
736
+ this.waitForPostStart = false;
737
+ }
738
+ this.#coordinatorSocket.close();
739
+ if (!reconnectImmediately) {
740
+ await setTimeout2(1e3);
741
+ }
742
+ let coordinatorHost = COORDINATOR_HOST;
743
+ try {
744
+ if (this.runningInKubernetes) {
745
+ coordinatorHost = (await readFile("/etc/taskinfo/coordinator-host", "utf-8")).replace(
746
+ "\n",
747
+ ""
748
+ );
749
+ logger2.log("reconnecting", {
750
+ coordinatorHost: {
751
+ fromEnv: COORDINATOR_HOST,
752
+ fromVolume: coordinatorHost,
753
+ current: this.#coordinatorSocket.socket.io.opts.hostname
754
+ }
755
+ });
756
+ }
757
+ } catch (error) {
758
+ logger2.error("taskinfo read error during reconnect", { error });
759
+ } finally {
760
+ this.#coordinatorSocket = this.#createCoordinatorSocket(coordinatorHost);
761
+ }
762
+ }
763
+ async #prepareForWait(reason, willCheckpointAndRestore) {
764
+ logger2.log(`prepare for ${reason}`, { willCheckpointAndRestore });
765
+ this.#backgroundWorker.preCheckpointNotification.post({ willCheckpointAndRestore });
766
+ if (willCheckpointAndRestore) {
767
+ this.paused = true;
768
+ this.nextResumeAfter = reason;
769
+ this.waitForPostStart = true;
770
+ if (reason === "WAIT_FOR_TASK" || reason === "WAIT_FOR_BATCH") {
771
+ await this.#backgroundWorker.flushTelemetry();
772
+ }
773
+ }
774
+ }
775
+ async #prepareForRetry(willCheckpointAndRestore, shouldExit) {
776
+ logger2.log("prepare for retry", { willCheckpointAndRestore, shouldExit });
777
+ if (shouldExit) {
778
+ if (willCheckpointAndRestore) {
779
+ logger2.log("WARNING: Will checkpoint but also requested exit. This won't end well.");
780
+ }
781
+ await this.#exitGracefully();
782
+ }
783
+ this.executing = false;
784
+ this.attemptFriendlyId = void 0;
785
+ if (willCheckpointAndRestore) {
786
+ this.waitForPostStart = true;
787
+ this.#coordinatorSocket.socket.emit("READY_FOR_CHECKPOINT", { version: "v1" });
788
+ return;
789
+ }
790
+ }
791
+ #resumeAfterDuration() {
792
+ this.paused = false;
793
+ this.nextResumeAfter = void 0;
794
+ this.waitForPostStart = false;
795
+ this.#backgroundWorker.waitCompletedNotification();
796
+ }
797
+ #returnValidatedExtraHeaders(headers) {
798
+ for (const [key, value] of Object.entries(headers)) {
799
+ if (value === void 0) {
800
+ throw new Error(`Extra header is undefined: ${key}`);
801
+ }
802
+ }
803
+ return headers;
804
+ }
805
+ // FIXME: If the the worker can't connect for a while, this runs MANY times - it should only run once
806
+ #createCoordinatorSocket(host) {
807
+ const extraHeaders = this.#returnValidatedExtraHeaders({
808
+ "x-machine-name": MACHINE_NAME2,
809
+ "x-pod-name": POD_NAME,
810
+ "x-trigger-content-hash": this.contentHash,
811
+ "x-trigger-project-ref": this.projectRef,
812
+ "x-trigger-env-id": this.envId,
813
+ "x-trigger-deployment-id": this.deploymentId,
814
+ "x-trigger-run-id": this.runId,
815
+ "x-trigger-deployment-version": this.deploymentVersion
816
+ });
817
+ if (this.attemptFriendlyId) {
818
+ extraHeaders["x-trigger-attempt-friendly-id"] = this.attemptFriendlyId;
819
+ }
820
+ logger2.log("connecting to coordinator", {
821
+ host,
822
+ port: COORDINATOR_PORT,
823
+ extraHeaders
824
+ });
825
+ const coordinatorConnection = new ZodSocketConnection2({
826
+ namespace: "prod-worker",
827
+ host,
828
+ port: COORDINATOR_PORT,
829
+ clientMessages: ProdWorkerToCoordinatorMessages,
830
+ serverMessages: CoordinatorToProdWorkerMessages,
831
+ extraHeaders,
832
+ handlers: {
833
+ RESUME_AFTER_DEPENDENCY: async (message) => {
834
+ if (!this.paused) {
835
+ logger2.error("worker not paused", {
836
+ completions: message.completions,
837
+ executions: message.executions
838
+ });
839
+ return;
840
+ }
841
+ if (message.completions.length !== message.executions.length) {
842
+ logger2.error("did not receive the same number of completions and executions", {
843
+ completions: message.completions,
844
+ executions: message.executions
845
+ });
846
+ return;
847
+ }
848
+ if (message.completions.length === 0 || message.executions.length === 0) {
849
+ logger2.error("no completions or executions", {
850
+ completions: message.completions,
851
+ executions: message.executions
852
+ });
853
+ return;
854
+ }
855
+ if (this.nextResumeAfter !== "WAIT_FOR_TASK" && this.nextResumeAfter !== "WAIT_FOR_BATCH") {
856
+ logger2.error("not waiting to resume after dependency", {
857
+ nextResumeAfter: this.nextResumeAfter
858
+ });
859
+ return;
860
+ }
861
+ if (this.nextResumeAfter === "WAIT_FOR_TASK" && message.completions.length > 1) {
862
+ logger2.error("waiting for single task but got multiple completions", {
863
+ completions: message.completions,
864
+ executions: message.executions
865
+ });
866
+ return;
867
+ }
868
+ this.paused = false;
869
+ this.nextResumeAfter = void 0;
870
+ this.waitForPostStart = false;
871
+ for (let i = 0; i < message.completions.length; i++) {
872
+ const completion = message.completions[i];
873
+ const execution = message.executions[i];
874
+ if (!completion || !execution)
875
+ continue;
876
+ this.#backgroundWorker.taskRunCompletedNotification(completion, execution);
877
+ }
878
+ },
879
+ RESUME_AFTER_DURATION: async (message) => {
880
+ if (!this.paused) {
881
+ logger2.error("worker not paused", {
882
+ attemptId: message.attemptId
883
+ });
884
+ return;
885
+ }
886
+ if (this.nextResumeAfter !== "WAIT_FOR_DURATION") {
887
+ logger2.error("not waiting to resume after duration", {
888
+ nextResumeAfter: this.nextResumeAfter
889
+ });
890
+ return;
891
+ }
892
+ this.#resumeAfterDuration();
893
+ },
894
+ EXECUTE_TASK_RUN: async ({ executionPayload }) => {
895
+ if (this.executing) {
896
+ logger2.error("dropping execute request, already executing");
897
+ return;
898
+ }
899
+ if (this.completed.has(executionPayload.execution.attempt.id)) {
900
+ logger2.error("dropping execute request, already completed");
901
+ return;
902
+ }
903
+ this.executing = true;
904
+ this.attemptFriendlyId = executionPayload.execution.attempt.id;
905
+ const completion = await this.#backgroundWorker.executeTaskRun(executionPayload);
906
+ logger2.log("completed", completion);
907
+ this.completed.add(executionPayload.execution.attempt.id);
908
+ const { willCheckpointAndRestore, shouldExit } = await this.#coordinatorSocket.socket.emitWithAck("TASK_RUN_COMPLETED", {
909
+ version: "v1",
910
+ execution: executionPayload.execution,
911
+ completion
912
+ });
913
+ logger2.log("completion acknowledged", { willCheckpointAndRestore, shouldExit });
914
+ this.#prepareForRetry(willCheckpointAndRestore, shouldExit);
915
+ },
916
+ REQUEST_ATTEMPT_CANCELLATION: async (message) => {
917
+ if (!this.executing) {
918
+ return;
919
+ }
920
+ await this.#backgroundWorker.cancelAttempt(message.attemptId);
921
+ },
922
+ REQUEST_EXIT: async () => {
923
+ this.#coordinatorSocket.close();
924
+ process.exit(0);
925
+ },
926
+ READY_FOR_RETRY: async (message) => {
927
+ if (this.completed.size < 1) {
928
+ return;
929
+ }
930
+ this.#coordinatorSocket.socket.emit("READY_FOR_EXECUTION", {
931
+ version: "v1",
932
+ runId: this.runId,
933
+ totalCompletions: this.completed.size
934
+ });
935
+ }
936
+ },
937
+ onConnection: async (socket, handler, sender, logger3) => {
938
+ if (this.waitForPostStart) {
939
+ logger3.log("skip connection handler, waiting for post start hook");
940
+ return;
941
+ }
942
+ if (this.paused) {
943
+ if (!this.nextResumeAfter) {
944
+ return;
945
+ }
946
+ if (!this.attemptFriendlyId) {
947
+ logger3.error("Missing friendly ID");
948
+ return;
949
+ }
950
+ socket.emit("READY_FOR_RESUME", {
951
+ version: "v1",
952
+ attemptFriendlyId: this.attemptFriendlyId,
953
+ type: this.nextResumeAfter
954
+ });
955
+ return;
956
+ }
957
+ if (process.env.INDEX_TASKS === "true") {
958
+ try {
959
+ const taskResources = await this.#initializeWorker();
960
+ const { success } = await socket.emitWithAck("INDEX_TASKS", {
961
+ version: "v1",
962
+ deploymentId: this.deploymentId,
963
+ ...taskResources
964
+ });
965
+ if (success) {
966
+ logger3.info("indexing done, shutting down..");
967
+ process.exit(0);
968
+ } else {
969
+ logger3.info("indexing failure, shutting down..");
970
+ process.exit(1);
971
+ }
972
+ } catch (e) {
973
+ if (e instanceof TaskMetadataParseError) {
974
+ logger3.error("tasks metadata parse error", {
975
+ zodIssues: e.zodIssues,
976
+ tasks: e.tasks
977
+ });
978
+ socket.emit("INDEXING_FAILED", {
979
+ version: "v1",
980
+ deploymentId: this.deploymentId,
981
+ error: {
982
+ name: "TaskMetadataParseError",
983
+ message: "There was an error parsing the task metadata",
984
+ stack: JSON.stringify({ zodIssues: e.zodIssues, tasks: e.tasks })
985
+ }
986
+ });
987
+ } else if (e instanceof UncaughtExceptionError) {
988
+ const error = {
989
+ name: e.originalError.name,
990
+ message: e.originalError.message,
991
+ stack: e.originalError.stack
992
+ };
993
+ logger3.error("uncaught exception", { originalError: error });
994
+ socket.emit("INDEXING_FAILED", {
995
+ version: "v1",
996
+ deploymentId: this.deploymentId,
997
+ error
998
+ });
999
+ } else if (e instanceof Error) {
1000
+ const error = {
1001
+ name: e.name,
1002
+ message: e.message,
1003
+ stack: e.stack
1004
+ };
1005
+ logger3.error("error", { error });
1006
+ socket.emit("INDEXING_FAILED", {
1007
+ version: "v1",
1008
+ deploymentId: this.deploymentId,
1009
+ error
1010
+ });
1011
+ } else if (typeof e === "string") {
1012
+ logger3.error("string error", { error: { message: e } });
1013
+ socket.emit("INDEXING_FAILED", {
1014
+ version: "v1",
1015
+ deploymentId: this.deploymentId,
1016
+ error: {
1017
+ name: "Error",
1018
+ message: e
1019
+ }
1020
+ });
1021
+ } else {
1022
+ logger3.error("unknown error", { error: e });
1023
+ socket.emit("INDEXING_FAILED", {
1024
+ version: "v1",
1025
+ deploymentId: this.deploymentId,
1026
+ error: {
1027
+ name: "Error",
1028
+ message: "Unknown error"
1029
+ }
1030
+ });
1031
+ }
1032
+ await setTimeout2(200);
1033
+ process.exit(111);
1034
+ }
1035
+ }
1036
+ if (this.executing) {
1037
+ return;
1038
+ }
1039
+ socket.emit("READY_FOR_EXECUTION", {
1040
+ version: "v1",
1041
+ runId: this.runId,
1042
+ totalCompletions: this.completed.size
1043
+ });
1044
+ },
1045
+ onError: async (socket, err, logger3) => {
1046
+ logger3.error("onError", {
1047
+ error: {
1048
+ name: err.name,
1049
+ message: err.message
1050
+ }
1051
+ });
1052
+ await this.#reconnect();
1053
+ },
1054
+ onDisconnect: async (socket, reason, description, logger3) => {
1055
+ }
1056
+ });
1057
+ return coordinatorConnection;
1058
+ }
1059
+ #createHttpServer() {
1060
+ const httpServer = createServer(async (req, res) => {
1061
+ logger2.log(`[${req.method}]`, req.url);
1062
+ const reply = new HttpReply(res);
1063
+ try {
1064
+ const url = new URL(req.url ?? "", `http://${req.headers.host}`);
1065
+ switch (url.pathname) {
1066
+ case "/health": {
1067
+ return reply.text("ok");
1068
+ }
1069
+ case "/status": {
1070
+ return reply.json({
1071
+ executing: this.executing,
1072
+ paused: this.paused,
1073
+ completed: this.completed.size,
1074
+ nextResumeAfter: this.nextResumeAfter
1075
+ });
1076
+ }
1077
+ case "/connect": {
1078
+ this.#coordinatorSocket.connect();
1079
+ return reply.text("Connected to coordinator");
1080
+ }
1081
+ case "/close": {
1082
+ await this.#coordinatorSocket.sendWithAck("LOG", {
1083
+ version: "v1",
1084
+ text: `[${req.method}] ${req.url}`
1085
+ });
1086
+ this.#coordinatorSocket.close();
1087
+ return reply.text("Disconnected from coordinator");
1088
+ }
1089
+ case "/test": {
1090
+ await this.#coordinatorSocket.sendWithAck("LOG", {
1091
+ version: "v1",
1092
+ text: `[${req.method}] ${req.url}`
1093
+ });
1094
+ return reply.text("Received ACK from coordinator");
1095
+ }
1096
+ case "/preStop": {
1097
+ const cause = PreStopCauses.safeParse(url.searchParams.get("cause"));
1098
+ if (!cause.success) {
1099
+ logger2.error("Failed to parse cause", { cause });
1100
+ return reply.text("Failed to parse cause", 400);
1101
+ }
1102
+ switch (cause.data) {
1103
+ case "terminate": {
1104
+ break;
1105
+ }
1106
+ default: {
1107
+ logger2.error("Unhandled cause", { cause: cause.data });
1108
+ break;
1109
+ }
1110
+ }
1111
+ return reply.text("preStop ok");
1112
+ }
1113
+ case "/postStart": {
1114
+ const cause = PostStartCauses.safeParse(url.searchParams.get("cause"));
1115
+ if (!cause.success) {
1116
+ logger2.error("Failed to parse cause", { cause });
1117
+ return reply.text("Failed to parse cause", 400);
1118
+ }
1119
+ switch (cause.data) {
1120
+ case "index": {
1121
+ break;
1122
+ }
1123
+ case "create": {
1124
+ break;
1125
+ }
1126
+ case "restore": {
1127
+ await this.#reconnect(true, true);
1128
+ break;
1129
+ }
1130
+ default: {
1131
+ logger2.error("Unhandled cause", { cause: cause.data });
1132
+ break;
1133
+ }
1134
+ }
1135
+ return reply.text("postStart ok");
1136
+ }
1137
+ default: {
1138
+ return reply.empty(404);
1139
+ }
1140
+ }
1141
+ } catch (error) {
1142
+ logger2.error("HTTP server error", { error });
1143
+ reply.empty(500);
1144
+ }
1145
+ });
1146
+ httpServer.on("clientError", (err, socket) => {
1147
+ socket.end("HTTP/1.1 400 Bad Request\r\n\r\n");
1148
+ });
1149
+ httpServer.on("listening", () => {
1150
+ logger2.log("http server listening on port", this.#httpPort);
1151
+ });
1152
+ httpServer.on("error", async (error) => {
1153
+ if (error.code != "EADDRINUSE") {
1154
+ return;
1155
+ }
1156
+ logger2.error(`port ${this.#httpPort} already in use, retrying with random port..`);
1157
+ this.#httpPort = getRandomPortNumber();
1158
+ await setTimeout2(100);
1159
+ this.start();
1160
+ });
1161
+ return httpServer;
1162
+ }
1163
+ async #initializeWorker() {
1164
+ const envVars = await this.#fetchEnvironmentVariables();
1165
+ await this.#backgroundWorker.initialize({ env: envVars });
1166
+ let packageVersion;
1167
+ const taskResources = [];
1168
+ if (!this.#backgroundWorker.tasks) {
1169
+ throw new Error(`Background Worker started without tasks`);
1170
+ }
1171
+ for (const task of this.#backgroundWorker.tasks) {
1172
+ taskResources.push(task);
1173
+ packageVersion = task.packageVersion;
1174
+ }
1175
+ if (!packageVersion) {
1176
+ throw new Error(`Background Worker started without package version`);
1177
+ }
1178
+ return {
1179
+ packageVersion,
1180
+ tasks: taskResources
1181
+ };
1182
+ }
1183
+ async #fetchEnvironmentVariables() {
1184
+ const response = await fetch(`${this.apiUrl}/api/v1/projects/${this.projectRef}/envvars`, {
1185
+ method: "GET",
1186
+ headers: {
1187
+ Authorization: `Bearer ${this.apiKey}`
1188
+ }
1189
+ });
1190
+ if (!response.ok) {
1191
+ return {};
1192
+ }
1193
+ const data = await response.json();
1194
+ return data?.variables ?? {};
1195
+ }
1196
+ start() {
1197
+ this.#httpServer.listen(this.#httpPort, this.host);
1198
+ }
1199
+ };
1200
+ var prodWorker = new ProdWorker(HTTP_SERVER_PORT2);
1201
+ prodWorker.start();
1202
+ function gatherProcessEnv() {
1203
+ const env = {
1204
+ NODE_ENV: process.env.NODE_ENV ?? "production",
1205
+ PATH: process.env.PATH,
1206
+ USER: process.env.USER,
1207
+ SHELL: process.env.SHELL,
1208
+ LANG: process.env.LANG,
1209
+ TERM: process.env.TERM,
1210
+ NODE_PATH: process.env.NODE_PATH,
1211
+ HOME: process.env.HOME
1212
+ };
1213
+ return Object.fromEntries(Object.entries(env).filter(([key, value]) => value !== void 0));
1214
+ }