trigger.dev 3.0.0-beta.0 → 3.0.0-beta.1

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