-
-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathmanaged-run-controller.ts
More file actions
1350 lines (1121 loc) · 38.6 KB
/
Copy pathmanaged-run-controller.ts
File metadata and controls
1350 lines (1121 loc) · 38.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import { logger } from "../utilities/logger.js";
import { TaskRunProcess } from "../executions/taskRunProcess.js";
import { env as stdEnv } from "std-env";
import { z } from "zod";
import { randomUUID } from "crypto";
import { readJSONFile } from "../utilities/fileSystem.js";
import {
type CompleteRunAttemptResult,
HeartbeatService,
type RunExecutionData,
type TaskRunExecutionMetrics,
type TaskRunExecutionResult,
type TaskRunFailedExecutionResult,
WorkerManifest,
} from "@trigger.dev/core/v3";
import {
WarmStartClient,
WORKLOAD_HEADERS,
type WorkloadClientToServerEvents,
type WorkloadDebugLogRequestBody,
WorkloadHttpClient,
type WorkloadServerToClientEvents,
type WorkloadRunAttemptStartResponseBody,
} from "@trigger.dev/core/v3/workers";
import { assertExhaustive } from "../utilities/assertExhaustive.js";
import { setTimeout as sleep } from "timers/promises";
import { io, type Socket } from "socket.io-client";
const DateEnv = z
.string()
.transform((val) => new Date(parseInt(val, 10)))
.pipe(z.date());
// All IDs are friendly IDs
const Env = z.object({
// Set at build time
TRIGGER_CONTENT_HASH: z.string(),
TRIGGER_DEPLOYMENT_ID: z.string(),
TRIGGER_DEPLOYMENT_VERSION: z.string(),
TRIGGER_PROJECT_ID: z.string(),
TRIGGER_PROJECT_REF: z.string(),
NODE_ENV: z.string().default("production"),
NODE_EXTRA_CA_CERTS: z.string().optional(),
// Set at runtime
TRIGGER_WORKLOAD_CONTROLLER_ID: z.string().default(`controller_${randomUUID()}`),
TRIGGER_ENV_ID: z.string(),
TRIGGER_RUN_ID: z.string().optional(), // This is only useful for cold starts
TRIGGER_SNAPSHOT_ID: z.string().optional(), // This is only useful for cold starts
OTEL_EXPORTER_OTLP_ENDPOINT: z.string().url(),
TRIGGER_WARM_START_URL: z.string().optional(),
TRIGGER_WARM_START_CONNECTION_TIMEOUT_MS: z.coerce.number().default(30_000),
TRIGGER_WARM_START_KEEPALIVE_MS: z.coerce.number().default(300_000),
TRIGGER_MACHINE_CPU: z.string().default("0"),
TRIGGER_MACHINE_MEMORY: z.string().default("0"),
TRIGGER_RUNNER_ID: z.string(),
TRIGGER_METADATA_URL: z.string().optional(),
// Timeline metrics
TRIGGER_POD_SCHEDULED_AT_MS: DateEnv,
TRIGGER_DEQUEUED_AT_MS: DateEnv,
// May be overridden
TRIGGER_SUPERVISOR_API_PROTOCOL: z.enum(["http", "https"]),
TRIGGER_SUPERVISOR_API_DOMAIN: z.string(),
TRIGGER_SUPERVISOR_API_PORT: z.coerce.number(),
TRIGGER_WORKER_INSTANCE_NAME: z.string(),
TRIGGER_HEARTBEAT_INTERVAL_SECONDS: z.coerce.number().default(30),
TRIGGER_SNAPSHOT_POLL_INTERVAL_SECONDS: z.coerce.number().default(5),
TRIGGER_SUCCESS_EXIT_CODE: z.coerce.number().default(0),
TRIGGER_FAILURE_EXIT_CODE: z.coerce.number().default(1),
});
const env = Env.parse(stdEnv);
logger.loggerLevel = "debug";
type ManagedRunControllerOptions = {
workerManifest: WorkerManifest;
};
type Run = {
friendlyId: string;
attemptNumber?: number | null;
};
type Snapshot = {
friendlyId: string;
};
type Metadata = {
TRIGGER_SUPERVISOR_API_PROTOCOL: string | undefined;
TRIGGER_SUPERVISOR_API_DOMAIN: string | undefined;
TRIGGER_SUPERVISOR_API_PORT: number | undefined;
TRIGGER_WORKER_INSTANCE_NAME: string | undefined;
TRIGGER_HEARTBEAT_INTERVAL_SECONDS: number | undefined;
TRIGGER_SNAPSHOT_POLL_INTERVAL_SECONDS: number | undefined;
TRIGGER_SUCCESS_EXIT_CODE: number | undefined;
TRIGGER_FAILURE_EXIT_CODE: number | undefined;
TRIGGER_RUNNER_ID: string | undefined;
};
class MetadataClient {
private readonly url: URL;
constructor(url: string) {
this.url = new URL(url);
}
async getEnvOverrides(): Promise<Metadata | null> {
try {
const response = await fetch(new URL("/env", this.url));
return response.json();
} catch (error) {
console.error("Failed to fetch metadata", { error });
return null;
}
}
}
class ManagedRunController {
private taskRunProcess?: TaskRunProcess;
private workerManifest: WorkerManifest;
private readonly httpClient: WorkloadHttpClient;
private readonly warmStartClient: WarmStartClient | undefined;
private readonly metadataClient?: MetadataClient;
private socket: Socket<WorkloadServerToClientEvents, WorkloadClientToServerEvents>;
private readonly runHeartbeat: HeartbeatService;
private heartbeatIntervalSeconds: number;
private readonly snapshotPoller: HeartbeatService;
private snapshotPollIntervalSeconds: number;
private workerApiUrl: string;
private workerInstanceName: string;
private runnerId: string;
private successExitCode = env.TRIGGER_SUCCESS_EXIT_CODE;
private failureExitCode = env.TRIGGER_FAILURE_EXIT_CODE;
private state:
| {
phase: "RUN";
run: Run;
snapshot: Snapshot;
}
| {
phase: "IDLE" | "WARM_START";
} = { phase: "IDLE" };
constructor(opts: ManagedRunControllerOptions) {
logger.debug("[ManagedRunController] Creating controller", { env });
this.workerManifest = opts.workerManifest;
this.runnerId = env.TRIGGER_RUNNER_ID;
this.heartbeatIntervalSeconds = env.TRIGGER_HEARTBEAT_INTERVAL_SECONDS;
this.snapshotPollIntervalSeconds = env.TRIGGER_SNAPSHOT_POLL_INTERVAL_SECONDS;
if (env.TRIGGER_METADATA_URL) {
this.metadataClient = new MetadataClient(env.TRIGGER_METADATA_URL);
}
this.workerApiUrl = `${env.TRIGGER_SUPERVISOR_API_PROTOCOL}://${env.TRIGGER_SUPERVISOR_API_DOMAIN}:${env.TRIGGER_SUPERVISOR_API_PORT}`;
this.workerInstanceName = env.TRIGGER_WORKER_INSTANCE_NAME;
this.httpClient = new WorkloadHttpClient({
workerApiUrl: this.workerApiUrl,
runnerId: this.runnerId,
deploymentId: env.TRIGGER_DEPLOYMENT_ID,
deploymentVersion: env.TRIGGER_DEPLOYMENT_VERSION,
projectRef: env.TRIGGER_PROJECT_REF,
});
if (env.TRIGGER_WARM_START_URL) {
this.warmStartClient = new WarmStartClient({
apiUrl: new URL(env.TRIGGER_WARM_START_URL),
controllerId: env.TRIGGER_WORKLOAD_CONTROLLER_ID,
deploymentId: env.TRIGGER_DEPLOYMENT_ID,
deploymentVersion: env.TRIGGER_DEPLOYMENT_VERSION,
machineCpu: env.TRIGGER_MACHINE_CPU,
machineMemory: env.TRIGGER_MACHINE_MEMORY,
});
}
this.snapshotPoller = new HeartbeatService({
heartbeat: async () => {
if (!this.runFriendlyId) {
logger.debug("[ManagedRunController] Skipping snapshot poll, no run ID");
return;
}
console.debug("[ManagedRunController] Polling for latest snapshot");
this.sendDebugLog({
runId: this.runFriendlyId,
message: `snapshot poll: started`,
properties: {
snapshotId: this.snapshotFriendlyId,
},
});
const response = await this.httpClient.getRunExecutionData(this.runFriendlyId);
if (!response.success) {
console.error("[ManagedRunController] Snapshot poll failed", { error: response.error });
this.sendDebugLog({
runId: this.runFriendlyId,
message: `snapshot poll: failed`,
properties: {
snapshotId: this.snapshotFriendlyId,
error: response.error,
},
});
return;
}
await this.handleSnapshotChange(response.data.execution);
},
intervalMs: this.snapshotPollIntervalSeconds * 1000,
leadingEdge: false,
onError: async (error) => {
console.error("[ManagedRunController] Failed to poll for snapshot", { error });
},
});
this.runHeartbeat = new HeartbeatService({
heartbeat: async () => {
if (!this.runFriendlyId || !this.snapshotFriendlyId) {
logger.debug("[ManagedRunController] Skipping heartbeat, no run ID or snapshot ID");
return;
}
console.debug("[ManagedRunController] Sending heartbeat");
const response = await this.httpClient.heartbeatRun(
this.runFriendlyId,
this.snapshotFriendlyId
);
if (!response.success) {
console.error("[ManagedRunController] Heartbeat failed", { error: response.error });
this.sendDebugLog({
runId: this.runFriendlyId,
message: "heartbeat: failed",
properties: {
error: response.error,
},
});
}
},
intervalMs: this.heartbeatIntervalSeconds * 1000,
leadingEdge: false,
onError: async (error) => {
console.error("[ManagedRunController] Failed to send heartbeat", { error });
},
});
process.on("SIGTERM", async () => {
logger.debug("[ManagedRunController] Received SIGTERM, stopping worker");
await this.stop();
});
}
private enterRunPhase(run: Run, snapshot: Snapshot) {
this.onExitRunPhase(run);
this.state = { phase: "RUN", run, snapshot };
this.runHeartbeat.start();
this.snapshotPoller.start();
}
private enterWarmStartPhase() {
this.onExitRunPhase();
this.state = { phase: "WARM_START" };
}
// This should only be used when we're already executing a run. Attempt number changes are not allowed.
private updateRunPhase(run: Run, snapshot: Snapshot) {
if (this.state.phase !== "RUN") {
this.sendDebugLog({
runId: run.friendlyId,
message: `updateRunPhase: Invalid phase for updating snapshot: ${this.state.phase}`,
properties: {
currentPhase: this.state.phase,
snapshotId: snapshot.friendlyId,
},
});
throw new Error(`Invalid phase for updating snapshot: ${this.state.phase}`);
}
if (this.state.run.friendlyId !== run.friendlyId) {
this.sendDebugLog({
runId: run.friendlyId,
message: `updateRunPhase: Mismatched run IDs`,
properties: {
currentRunId: this.state.run.friendlyId,
newRunId: run.friendlyId,
currentSnapshotId: this.state.snapshot.friendlyId,
newSnapshotId: snapshot.friendlyId,
},
});
throw new Error("Mismatched run IDs");
}
if (this.state.snapshot.friendlyId === snapshot.friendlyId) {
logger.debug("updateRunPhase: Snapshot not changed", { run, snapshot });
this.sendDebugLog({
runId: run.friendlyId,
message: `updateRunPhase: Snapshot not changed`,
properties: {
snapshotId: snapshot.friendlyId,
},
});
return;
}
if (this.state.run.attemptNumber !== run.attemptNumber) {
this.sendDebugLog({
runId: run.friendlyId,
message: `updateRunPhase: Attempt number changed`,
properties: {
oldAttemptNumber: this.state.run.attemptNumber ?? undefined,
newAttemptNumber: run.attemptNumber ?? undefined,
},
});
throw new Error("Attempt number changed");
}
this.state = {
phase: "RUN",
run: {
friendlyId: run.friendlyId,
attemptNumber: run.attemptNumber,
},
snapshot: {
friendlyId: snapshot.friendlyId,
},
};
}
private onExitRunPhase(newRun: Run | undefined = undefined) {
// We're not in a run phase, nothing to do
if (this.state.phase !== "RUN") {
logger.debug("onExitRunPhase: Not in run phase, skipping", { phase: this.state.phase });
return;
}
// This is still the same run, so we're not exiting the phase
if (newRun?.friendlyId === this.state.run.friendlyId) {
logger.debug("onExitRunPhase: Same run, skipping", { newRun });
return;
}
logger.debug("onExitRunPhase: Exiting run phase", { newRun });
this.runHeartbeat.stop();
this.snapshotPoller.stop();
const { run, snapshot } = this.state;
this.unsubscribeFromRunNotifications({ run, snapshot });
}
private subscribeToRunNotifications({ run, snapshot }: { run: Run; snapshot: Snapshot }) {
this.socket.emit("run:start", {
version: "1",
run: {
friendlyId: run.friendlyId,
},
snapshot: {
friendlyId: snapshot.friendlyId,
},
});
}
private unsubscribeFromRunNotifications({ run, snapshot }: { run: Run; snapshot: Snapshot }) {
this.socket.emit("run:stop", {
version: "1",
run: {
friendlyId: run.friendlyId,
},
snapshot: {
friendlyId: snapshot.friendlyId,
},
});
}
private get runFriendlyId() {
if (this.state.phase !== "RUN") {
return undefined;
}
return this.state.run.friendlyId;
}
private get snapshotFriendlyId() {
if (this.state.phase !== "RUN") {
return;
}
return this.state.snapshot.friendlyId;
}
private handleSnapshotChangeLock = false;
private async handleSnapshotChange({
run,
snapshot,
completedWaitpoints,
}: Pick<RunExecutionData, "run" | "snapshot" | "completedWaitpoints">) {
if (this.handleSnapshotChangeLock) {
console.warn("handleSnapshotChange: already in progress");
return;
}
this.handleSnapshotChangeLock = true;
try {
if (!this.snapshotFriendlyId) {
console.error("handleSnapshotChange: Missing snapshot ID", {
runId: run.friendlyId,
snapshotId: this.snapshotFriendlyId,
});
this.sendDebugLog({
runId: run.friendlyId,
message: "snapshot change: missing snapshot ID",
properties: {
newSnapshotId: snapshot.friendlyId,
newSnapshotStatus: snapshot.executionStatus,
},
});
return;
}
if (this.snapshotFriendlyId === snapshot.friendlyId) {
console.debug("handleSnapshotChange: snapshot not changed, skipping", { snapshot });
this.sendDebugLog({
runId: run.friendlyId,
message: "snapshot change: skipping, no change",
properties: {
snapshotId: this.snapshotFriendlyId,
snapshotStatus: snapshot.executionStatus,
},
});
return;
}
console.log(`handleSnapshotChange: ${snapshot.executionStatus}`, {
run,
oldSnapshotId: this.snapshotFriendlyId,
newSnapshot: snapshot,
completedWaitpoints: completedWaitpoints.length,
});
this.sendDebugLog({
runId: run.friendlyId,
message: `snapshot change: ${snapshot.executionStatus}`,
properties: {
oldSnapshotId: this.snapshotFriendlyId,
newSnapshotId: snapshot.friendlyId,
completedWaitpoints: completedWaitpoints.length,
},
});
try {
this.updateRunPhase(run, snapshot);
} catch (error) {
console.error("handleSnapshotChange: failed to update run phase", {
run,
snapshot,
error,
});
this.sendDebugLog({
runId: run.friendlyId,
message: "snapshot change: failed to update run phase",
properties: {
currentPhase: this.state.phase,
error: error instanceof Error ? error.message : String(error),
},
});
this.waitForNextRun();
return;
}
switch (snapshot.executionStatus) {
case "PENDING_CANCEL": {
try {
await this.cancelAttempt(run.friendlyId);
} catch (error) {
console.error("Failed to cancel attempt, shutting down", {
error,
});
this.waitForNextRun();
return;
}
return;
}
case "FINISHED": {
console.log("Run is finished, will wait for next run");
this.waitForNextRun();
return;
}
case "QUEUED_EXECUTING":
case "EXECUTING_WITH_WAITPOINTS": {
console.log("Run is executing with waitpoints", { snapshot });
try {
await this.taskRunProcess?.cleanup(false);
} catch (error) {
console.error("Failed to cleanup task run process", { error });
}
if (snapshot.friendlyId !== this.snapshotFriendlyId) {
console.debug("Snapshot changed after cleanup, abort", {
oldSnapshotId: snapshot.friendlyId,
newSnapshotId: this.snapshotFriendlyId,
});
return;
}
// TODO: Make this configurable and add wait debounce
await sleep(200);
if (snapshot.friendlyId !== this.snapshotFriendlyId) {
console.debug("Snapshot changed after suspend threshold, abort", {
oldSnapshotId: snapshot.friendlyId,
newSnapshotId: this.snapshotFriendlyId,
});
return;
}
if (!this.runFriendlyId || !this.snapshotFriendlyId) {
console.error(
"handleSnapshotChange: Missing run ID or snapshot ID after suspension, abort",
{
runId: this.runFriendlyId,
snapshotId: this.snapshotFriendlyId,
}
);
return;
}
const suspendResult = await this.httpClient.suspendRun(
this.runFriendlyId,
this.snapshotFriendlyId
);
if (!suspendResult.success) {
console.error("Failed to suspend run, staying alive 🎶", {
error: suspendResult.error,
});
this.sendDebugLog({
runId: run.friendlyId,
message: "checkpoint: suspend request failed",
properties: {
snapshotId: snapshot.friendlyId,
error: suspendResult.error,
},
});
return;
}
if (!suspendResult.data.ok) {
console.error("Failed to suspend run, staying alive 🎶🎶", {
suspendResult: suspendResult.data,
});
this.sendDebugLog({
runId: run.friendlyId,
message: "checkpoint: failed to suspend run",
properties: {
snapshotId: snapshot.friendlyId,
error: suspendResult.data.error,
},
});
return;
}
console.log("Suspending, any day now 🚬", { suspendResult: suspendResult.data });
return;
}
case "SUSPENDED": {
console.log("Run was suspended, kill the process and wait for more runs", {
run,
snapshot,
});
this.waitForNextRun();
return;
}
case "PENDING_EXECUTING": {
console.log("Run is pending execution", { run, snapshot });
if (completedWaitpoints.length === 0) {
console.log("No waitpoints to complete, nothing to do");
return;
}
// There are waitpoints to complete so we've been restored after being suspended
// Short delay to give websocket time to reconnect
await sleep(100);
// Env may have changed after restore
await this.processEnvOverrides();
// We need to let the platform know we're ready to continue
const continuationResult = await this.httpClient.continueRunExecution(
run.friendlyId,
snapshot.friendlyId
);
if (!continuationResult.success) {
console.error("Failed to continue execution", { error: continuationResult.error });
this.sendDebugLog({
runId: run.friendlyId,
message: "failed to continue execution",
properties: {
error: continuationResult.error,
},
});
this.waitForNextRun();
return;
}
return;
}
case "EXECUTING": {
console.log("Run is now executing", { run, snapshot });
if (completedWaitpoints.length === 0) {
return;
}
console.log("Processing completed waitpoints", { completedWaitpoints });
if (!this.taskRunProcess) {
console.error("No task run process, ignoring completed waitpoints", {
completedWaitpoints,
});
return;
}
for (const waitpoint of completedWaitpoints) {
this.taskRunProcess.waitpointCompleted(waitpoint);
}
return;
}
case "RUN_CREATED":
case "QUEUED": {
console.log("Status change not handled", { status: snapshot.executionStatus });
return;
}
default: {
assertExhaustive(snapshot.executionStatus);
}
}
} catch (error) {
console.error("handleSnapshotChange: unexpected error", { error });
this.sendDebugLog({
runId: run.friendlyId,
message: "snapshot change: unexpected error",
properties: {
snapshotId: snapshot.friendlyId,
error: error instanceof Error ? error.message : String(error),
},
});
} finally {
this.handleSnapshotChangeLock = false;
}
}
private async processEnvOverrides() {
if (!this.metadataClient) {
logger.log("No metadata client, skipping env overrides");
return;
}
const overrides = await this.metadataClient.getEnvOverrides();
if (!overrides) {
logger.log("No env overrides, skipping");
return;
}
logger.log("Processing env overrides", { env: overrides });
if (overrides.TRIGGER_SUCCESS_EXIT_CODE) {
this.successExitCode = overrides.TRIGGER_SUCCESS_EXIT_CODE;
}
if (overrides.TRIGGER_FAILURE_EXIT_CODE) {
this.failureExitCode = overrides.TRIGGER_FAILURE_EXIT_CODE;
}
if (overrides.TRIGGER_HEARTBEAT_INTERVAL_SECONDS) {
this.heartbeatIntervalSeconds = overrides.TRIGGER_HEARTBEAT_INTERVAL_SECONDS;
this.runHeartbeat.updateInterval(this.heartbeatIntervalSeconds * 1000);
}
if (overrides.TRIGGER_SNAPSHOT_POLL_INTERVAL_SECONDS) {
this.snapshotPollIntervalSeconds = overrides.TRIGGER_SNAPSHOT_POLL_INTERVAL_SECONDS;
this.snapshotPoller.updateInterval(this.snapshotPollIntervalSeconds * 1000);
}
if (overrides.TRIGGER_WORKER_INSTANCE_NAME) {
this.workerInstanceName = overrides.TRIGGER_WORKER_INSTANCE_NAME;
}
if (
overrides.TRIGGER_SUPERVISOR_API_PROTOCOL ||
overrides.TRIGGER_SUPERVISOR_API_DOMAIN ||
overrides.TRIGGER_SUPERVISOR_API_PORT
) {
const protocol =
overrides.TRIGGER_SUPERVISOR_API_PROTOCOL ?? env.TRIGGER_SUPERVISOR_API_PROTOCOL;
const domain = overrides.TRIGGER_SUPERVISOR_API_DOMAIN ?? env.TRIGGER_SUPERVISOR_API_DOMAIN;
const port = overrides.TRIGGER_SUPERVISOR_API_PORT ?? env.TRIGGER_SUPERVISOR_API_PORT;
this.workerApiUrl = `${protocol}://${domain}:${port}`;
this.httpClient.updateApiUrl(this.workerApiUrl);
}
if (overrides.TRIGGER_RUNNER_ID) {
this.runnerId = overrides.TRIGGER_RUNNER_ID;
this.httpClient.updateRunnerId(this.runnerId);
}
}
private async startAndExecuteRunAttempt({
runFriendlyId,
snapshotFriendlyId,
dequeuedAt,
podScheduledAt,
isWarmStart = false,
}: {
runFriendlyId: string;
snapshotFriendlyId: string;
dequeuedAt?: Date;
podScheduledAt?: Date;
isWarmStart?: boolean;
}) {
if (!this.socket) {
console.warn("[ManagedRunController] Starting run without socket connection");
}
this.subscribeToRunNotifications({
run: { friendlyId: runFriendlyId },
snapshot: { friendlyId: snapshotFriendlyId },
});
const attemptStartedAt = Date.now();
const start = await this.httpClient.startRunAttempt(runFriendlyId, snapshotFriendlyId, {
isWarmStart,
});
if (!start.success) {
console.error("[ManagedRunController] Failed to start run", { error: start.error });
this.sendDebugLog({
runId: runFriendlyId,
message: "failed to start run attempt",
properties: {
error: start.error,
},
});
this.waitForNextRun();
return;
}
const attemptDuration = Date.now() - attemptStartedAt;
const { run, snapshot, execution, envVars } = start.data;
logger.debug("[ManagedRunController] Started run", {
runId: run.friendlyId,
snapshot: snapshot.friendlyId,
});
this.enterRunPhase(run, snapshot);
const metrics = [
{
name: "start",
event: "create_attempt",
timestamp: attemptStartedAt,
duration: attemptDuration,
},
]
.concat(
dequeuedAt
? [
{
name: "start",
event: "dequeue",
timestamp: dequeuedAt.getTime(),
duration: 0,
},
]
: []
)
.concat(
podScheduledAt
? [
{
name: "start",
event: "pod_scheduled",
timestamp: podScheduledAt.getTime(),
duration: 0,
},
]
: []
) satisfies TaskRunExecutionMetrics;
const taskRunEnv = {
...gatherProcessEnv(),
...envVars,
};
try {
return await this.executeRun({ run, snapshot, envVars: taskRunEnv, execution, metrics });
} catch (error) {
console.error("Error while executing attempt", {
error,
});
console.log("Submitting attempt completion", {
runId: run.friendlyId,
snapshotId: snapshot.friendlyId,
updatedSnapshotId: this.snapshotFriendlyId,
});
const completion = {
id: execution.run.id,
ok: false,
retry: undefined,
error: TaskRunProcess.parseExecuteError(error),
} satisfies TaskRunFailedExecutionResult;
const completionResult = await this.httpClient.completeRunAttempt(
run.friendlyId,
this.snapshotFriendlyId ?? snapshot.friendlyId,
{ completion }
);
if (!completionResult.success) {
console.error("Failed to submit completion after error", {
error: completionResult.error,
});
this.sendDebugLog({
runId: run.friendlyId,
message: "completion: failed to submit after error",
properties: {
error: completionResult.error,
},
});
this.waitForNextRun();
return;
}
logger.log("Attempt completion submitted after error", completionResult.data.result);
try {
await this.handleCompletionResult(completion, completionResult.data.result);
} catch (error) {
console.error("Failed to handle completion result after error", { error });
this.waitForNextRun();
return;
}
}
}
private waitForNextRunLock = false;
/** This will kill the child process before spinning up a new one. It will never throw,
* but may exit the process on any errors or when no runs are available after the
* configured duration. */
private async waitForNextRun() {
if (this.waitForNextRunLock) {
console.warn("waitForNextRun: already in progress");
return;
}
this.waitForNextRunLock = true;
const previousRunId = this.runFriendlyId;
try {
logger.debug("waitForNextRun: waiting for next run");
this.enterWarmStartPhase();
// Kill the run process
await this.taskRunProcess?.kill("SIGKILL");
if (!this.warmStartClient) {
console.error("waitForNextRun: warm starts disabled, shutting down");
this.exitProcess(this.successExitCode);
}
if (this.taskRunProcess) {
logger.debug("waitForNextRun: eagerly recreating task run process with options");
this.taskRunProcess = new TaskRunProcess({
...this.taskRunProcess.options,
isWarmStart: true,
}).initialize();
} else {
logger.debug(
"waitForNextRun: no existing task run process, so we can't eagerly recreate it"
);
}
// Check the service is up and get additional warm start config
const connect = await this.warmStartClient.connect();
if (!connect.success) {
console.error("waitForNextRun: failed to connect to warm start service", {
warmStartUrl: env.TRIGGER_WARM_START_URL,
error: connect.error,
});
this.exitProcess(this.successExitCode);
}
const connectionTimeoutMs =
connect.data.connectionTimeoutMs ?? env.TRIGGER_WARM_START_CONNECTION_TIMEOUT_MS;
const keepaliveMs = connect.data.keepaliveMs ?? env.TRIGGER_WARM_START_KEEPALIVE_MS;
console.log("waitForNextRun: connected to warm start service", {
connectionTimeoutMs,
keepaliveMs,
});
if (previousRunId) {
this.sendDebugLog({
runId: previousRunId,
message: "warm start: received config",
properties: {
connectionTimeoutMs,
keepaliveMs,
},
});
}
if (!connectionTimeoutMs || !keepaliveMs) {
console.error("waitForNextRun: warm starts disabled after connect", {
connectionTimeoutMs,
keepaliveMs,
});
this.exitProcess(this.successExitCode);
}
const nextRun = await this.warmStartClient.warmStart({
workerInstanceName: this.workerInstanceName,
connectionTimeoutMs,
keepaliveMs,
});
if (!nextRun) {
console.error("waitForNextRun: warm start failed, shutting down");
this.exitProcess(this.successExitCode);
}
console.log("waitForNextRun: got next run", { nextRun });
this.startAndExecuteRunAttempt({
runFriendlyId: nextRun.run.friendlyId,