-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathmanagedRuntimeManager.ts
More file actions
235 lines (198 loc) · 6.79 KB
/
managedRuntimeManager.ts
File metadata and controls
235 lines (198 loc) · 6.79 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
import { clock } from "../clock-api.js";
import { lifecycleHooks } from "../lifecycle-hooks-api.js";
import {
BatchTaskRunExecutionResult,
CompletedWaitpoint,
TaskRunContext,
TaskRunExecutionResult,
TaskRunFailedExecutionResult,
TaskRunSuccessfulExecutionResult,
WaitpointTokenResult,
} from "../schemas/index.js";
import { ExecutorToWorkerProcessConnection } from "../zodIpc.js";
import { RuntimeManager } from "./manager.js";
import { preventMultipleWaits } from "./preventMultipleWaits.js";
type Resolver = (value: CompletedWaitpoint) => void;
export class ManagedRuntimeManager implements RuntimeManager {
// Maps a resolver ID to a resolver function
private readonly resolversByWaitId: Map<string, Resolver> = new Map();
// Maps a waitpoint ID to a wait ID
private readonly resolversByWaitpoint: Map<string, string> = new Map();
private _preventMultipleWaits = preventMultipleWaits();
constructor(
private ipc: ExecutorToWorkerProcessConnection,
private showLogs: boolean
) {
// Log out the runtime status on a long interval to help debug stuck executions
setInterval(() => {
this.log("[DEBUG] ManagedRuntimeManager status", this.status);
}, 300_000);
}
disable(): void {
// do nothing
}
async waitForTask(params: { id: string; ctx: TaskRunContext }): Promise<TaskRunExecutionResult> {
return this._preventMultipleWaits(async () => {
const promise = new Promise<CompletedWaitpoint>((resolve) => {
this.resolversByWaitId.set(params.id, resolve);
});
await lifecycleHooks.callOnWaitHookListeners({
type: "task",
runId: params.id,
});
const waitpoint = await promise;
const result = this.waitpointToTaskRunExecutionResult(waitpoint);
await lifecycleHooks.callOnResumeHookListeners({
type: "task",
runId: params.id,
});
return result;
});
}
async waitForBatch(params: {
id: string;
runCount: number;
ctx: TaskRunContext;
}): Promise<BatchTaskRunExecutionResult> {
return this._preventMultipleWaits(async () => {
if (!params.runCount) {
return Promise.resolve({ id: params.id, items: [] });
}
const promise = Promise.all(
Array.from({ length: params.runCount }, (_, index) => {
const resolverId = `${params.id}_${index}`;
return new Promise<CompletedWaitpoint>((resolve, reject) => {
this.resolversByWaitId.set(resolverId, resolve);
});
})
);
await lifecycleHooks.callOnWaitHookListeners({
type: "batch",
batchId: params.id,
runCount: params.runCount,
});
const waitpoints = await promise;
await lifecycleHooks.callOnResumeHookListeners({
type: "batch",
batchId: params.id,
runCount: params.runCount,
});
return {
id: params.id,
items: waitpoints.map(this.waitpointToTaskRunExecutionResult),
};
});
}
async waitForWaitpoint({
waitpointFriendlyId,
finishDate,
}: {
waitpointFriendlyId: string;
finishDate?: Date;
}): Promise<WaitpointTokenResult> {
return this._preventMultipleWaits(async () => {
const promise = new Promise<CompletedWaitpoint>((resolve) => {
this.resolversByWaitId.set(waitpointFriendlyId, resolve);
});
if (finishDate) {
await lifecycleHooks.callOnWaitHookListeners({
type: "duration",
date: finishDate,
});
} else {
await lifecycleHooks.callOnWaitHookListeners({
type: "token",
token: waitpointFriendlyId,
});
}
const waitpoint = await promise;
if (finishDate) {
await lifecycleHooks.callOnResumeHookListeners({
type: "duration",
date: finishDate,
});
} else {
await lifecycleHooks.callOnResumeHookListeners({
type: "token",
token: waitpointFriendlyId,
});
}
return {
ok: !waitpoint.outputIsError,
output: waitpoint.output,
outputType: waitpoint.outputType,
};
});
}
associateWaitWithWaitpoint(waitId: string, waitpointId: string) {
this.resolversByWaitpoint.set(waitpointId, waitId);
}
async completeWaitpoints(waitpoints: CompletedWaitpoint[]): Promise<void> {
await Promise.all(waitpoints.map((waitpoint) => this.completeWaitpoint(waitpoint)));
}
private completeWaitpoint(waitpoint: CompletedWaitpoint): void {
this.log("completeWaitpoint", waitpoint);
let waitId: string | undefined;
if (waitpoint.completedByTaskRun) {
if (waitpoint.completedByTaskRun.batch) {
waitId = `${waitpoint.completedByTaskRun.batch.friendlyId}_${waitpoint.index}`;
} else {
waitId = waitpoint.completedByTaskRun.friendlyId;
}
} else if (waitpoint.completedByBatch) {
//no waitpoint resolves associated with batch completions
//a batch completion isn't when all the runs from a batch are completed
return;
} else if (waitpoint.type === "MANUAL" || waitpoint.type === "DATETIME") {
waitId = waitpoint.friendlyId;
} else {
waitId = this.resolversByWaitpoint.get(waitpoint.id);
}
if (!waitId) {
this.log("No waitId found for waitpoint", { ...this.status, ...waitpoint });
return;
}
const resolve = this.resolversByWaitId.get(waitId);
if (!resolve) {
this.log("No resolver found for waitId", { ...this.status, waitId });
return;
}
this.log("Resolving waitpoint", waitpoint);
// Ensure current time is accurate before resolving the waitpoint
clock.reset();
resolve(waitpoint);
this.resolversByWaitId.delete(waitId);
}
private waitpointToTaskRunExecutionResult(waitpoint: CompletedWaitpoint): TaskRunExecutionResult {
if (!waitpoint.completedByTaskRun?.friendlyId) throw new Error("Missing completedByTaskRun");
if (waitpoint.outputIsError) {
return {
ok: false,
id: waitpoint.completedByTaskRun.friendlyId,
error: waitpoint.output
? JSON.parse(waitpoint.output)
: {
type: "STRING_ERROR",
message: "Missing error output",
},
} satisfies TaskRunFailedExecutionResult;
} else {
return {
ok: true,
id: waitpoint.completedByTaskRun.friendlyId,
output: waitpoint.output,
outputType: waitpoint.outputType ?? "application/json",
} satisfies TaskRunSuccessfulExecutionResult;
}
}
private log(message: string, ...args: any[]) {
if (!this.showLogs) return;
console.log(`[${new Date().toISOString()}] ${message}`, args);
}
private get status() {
return {
resolversbyWaitId: Array.from(this.resolversByWaitId.keys()),
resolversByWaitpoint: Array.from(this.resolversByWaitpoint.keys()),
};
}
}