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

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