-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathtaskRunProcessPool.ts
More file actions
342 lines (293 loc) · 11.2 KB
/
taskRunProcessPool.ts
File metadata and controls
342 lines (293 loc) · 11.2 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
import {
MachinePresetResources,
ServerBackgroundWorker,
WorkerManifest,
generateFriendlyId,
} from "@trigger.dev/core/v3";
import { TaskRunProcess } from "../executions/taskRunProcess.js";
import { logger } from "../utilities/logger.js";
export type TaskRunProcessPoolOptions = {
env: Record<string, string>;
cwd: string;
enableProcessReuse: boolean;
maxPoolSize?: number;
maxExecutionsPerProcess?: number;
};
export class TaskRunProcessPool {
// Group processes by worker version
private availableProcessesByVersion: Map<string, TaskRunProcess[]> = new Map();
private busyProcessesByVersion: Map<string, Set<TaskRunProcess>> = new Map();
private readonly options: TaskRunProcessPoolOptions;
private readonly maxPoolSize: number;
private readonly maxExecutionsPerProcess: number;
private readonly executionCountsPerProcess: Map<number, number> = new Map();
private readonly deprecatedVersions: Set<string> = new Set();
private readonly idleTimers: Map<TaskRunProcess, NodeJS.Timeout> = new Map();
private static readonly IDLE_TIMEOUT_MS = 30_000;
constructor(options: TaskRunProcessPoolOptions) {
this.options = options;
this.maxPoolSize = options.maxPoolSize ?? 3;
this.maxExecutionsPerProcess = options.maxExecutionsPerProcess ?? 50;
}
deprecateVersion(version: string) {
this.deprecatedVersions.add(version);
logger.debug("[TaskRunProcessPool] Deprecating version", { version });
const versionProcesses = this.availableProcessesByVersion.get(version) || [];
const processesToKill = versionProcesses.filter((process) => !process.isExecuting());
processesToKill.forEach((process) => this.clearIdleTimer(process));
Promise.all(processesToKill.map((process) => this.killProcess(process))).then(() => {
this.availableProcessesByVersion.delete(version);
});
}
async getProcess(
workerManifest: WorkerManifest,
serverWorker: ServerBackgroundWorker,
machineResources: MachinePresetResources,
env?: Record<string, string>,
cwd?: string
): Promise<{ taskRunProcess: TaskRunProcess; isReused: boolean }> {
const version = serverWorker.version || "unknown";
// Try to reuse an existing process if enabled
if (this.options.enableProcessReuse) {
const reusableProcess = this.findReusableProcess(version);
if (reusableProcess) {
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
logger.debug("[TaskRunProcessPool] Reusing existing process", {
version,
availableCount,
busyCount,
});
// Remove from available and add to busy for this version
const availableProcesses = this.availableProcessesByVersion.get(version) || [];
this.availableProcessesByVersion.set(
version,
availableProcesses.filter((p) => p !== reusableProcess)
);
this.clearIdleTimer(reusableProcess);
if (!this.busyProcessesByVersion.has(version)) {
this.busyProcessesByVersion.set(version, new Set());
}
this.busyProcessesByVersion.get(version)!.add(reusableProcess);
return { taskRunProcess: reusableProcess, isReused: true };
} else {
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
logger.debug("[TaskRunProcessPool] No reusable process found", {
version,
availableCount,
busyCount,
});
}
}
// Create new process
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
logger.debug("[TaskRunProcessPool] Creating new process", {
version,
availableCount,
busyCount,
workerManifest,
});
const newProcess = new TaskRunProcess({
workerManifest,
env: {
...this.options.env,
...env,
TRIGGER_MACHINE_ID: generateFriendlyId("machine"),
},
serverWorker,
machineResources,
cwd: cwd ?? this.options.cwd,
}).initialize();
// Add to busy processes for this version
if (!this.busyProcessesByVersion.has(version)) {
this.busyProcessesByVersion.set(version, new Set());
}
this.busyProcessesByVersion.get(version)!.add(newProcess);
return { taskRunProcess: newProcess, isReused: false };
}
async returnProcess(process: TaskRunProcess, version: string): Promise<void> {
// Remove from busy processes for this version
const busyProcesses = this.busyProcessesByVersion.get(version);
if (busyProcesses) {
busyProcesses.delete(process);
}
if (process.pid) {
this.executionCountsPerProcess.set(
process.pid,
(this.executionCountsPerProcess.get(process.pid) ?? 0) + 1
);
}
if (this.shouldReuseProcess(process, version)) {
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
logger.debug("[TaskRunProcessPool] Returning process to pool", {
version,
availableCount,
busyCount,
});
// Clean up but don't kill the process
try {
await process.cleanup(false);
// Add to available processes for this version
if (!this.availableProcessesByVersion.has(version)) {
this.availableProcessesByVersion.set(version, []);
}
this.availableProcessesByVersion.get(version)!.push(process);
this.startIdleTimer(process, version);
} catch (error) {
logger.debug("[TaskRunProcessPool] Failed to cleanup process for reuse, killing it", {
error,
});
await this.killProcess(process);
}
} else {
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
logger.debug("[TaskRunProcessPool] Killing process", {
version,
availableCount,
busyCount,
});
await this.killProcess(process);
}
}
private findReusableProcess(version: string): TaskRunProcess | undefined {
const availableProcesses = this.availableProcessesByVersion.get(version) || [];
return availableProcesses.find((process) => this.isProcessHealthy(process));
}
private shouldReuseProcess(process: TaskRunProcess, version: string): boolean {
const isHealthy = this.isProcessHealthy(process);
const isBeingKilled = process.isBeingKilled;
const pid = process.pid;
const executionCount = this.executionCountsPerProcess.get(pid ?? 0) ?? 0;
const availableCount = this.availableProcessesByVersion.get(version)?.length || 0;
const busyCount = this.busyProcessesByVersion.get(version)?.size || 0;
const isDeprecated = this.deprecatedVersions.has(version);
logger.debug("[TaskRunProcessPool] Checking if process should be reused", {
version,
isHealthy,
isBeingKilled,
pid,
availableCount,
busyCount,
maxPoolSize: this.maxPoolSize,
executionCount,
isDeprecated,
});
return (
this.options.enableProcessReuse &&
this.isProcessHealthy(process) &&
availableCount < this.maxPoolSize &&
executionCount < this.maxExecutionsPerProcess &&
!isDeprecated
);
}
private isProcessHealthy(process: TaskRunProcess): boolean {
// Basic health checks - we can expand this later
return process.isHealthy;
}
private startIdleTimer(process: TaskRunProcess, version: string): void {
this.clearIdleTimer(process);
const timer = setTimeout(() => {
// Synchronously remove from available pool before async kill to prevent race with getProcess()
const available = this.availableProcessesByVersion.get(version);
if (available) {
const index = available.indexOf(process);
if (index !== -1) {
available.splice(index, 1);
}
}
this.idleTimers.delete(process);
logger.debug("[TaskRunProcessPool] Idle timeout reached, killing process", {
pid: process.pid,
version,
});
this.killProcess(process);
}, TaskRunProcessPool.IDLE_TIMEOUT_MS);
this.idleTimers.set(process, timer);
}
private clearIdleTimer(process: TaskRunProcess): void {
const timer = this.idleTimers.get(process);
if (timer) {
clearTimeout(timer);
this.idleTimers.delete(process);
}
}
private async killProcess(process: TaskRunProcess): Promise<void> {
this.clearIdleTimer(process);
if (!process.isHealthy) {
logger.debug("[TaskRunProcessPool] Process is not healthy, skipping cleanup", {
processId: process.pid,
});
return;
}
try {
await process.cleanup(true);
} catch (error) {
logger.debug("[TaskRunProcessPool] Error killing process", { error });
}
}
async shutdown(): Promise<void> {
const totalAvailable = Array.from(this.availableProcessesByVersion.values()).reduce(
(sum, processes) => sum + processes.length,
0
);
const totalBusy = Array.from(this.busyProcessesByVersion.values()).reduce(
(sum, processes) => sum + processes.size,
0
);
logger.debug("[TaskRunProcessPool] Shutting down pool", {
availableCount: totalAvailable,
busyCount: totalBusy,
versions: Array.from(this.availableProcessesByVersion.keys()),
});
// Clear all idle timers
for (const timer of this.idleTimers.values()) {
clearTimeout(timer);
}
this.idleTimers.clear();
// Kill all available processes across all versions
const allAvailableProcesses = Array.from(this.availableProcessesByVersion.values()).flat();
await Promise.all(allAvailableProcesses.map((process) => this.killProcess(process)));
this.availableProcessesByVersion.clear();
// Kill all busy processes across all versions
const allBusyProcesses = Array.from(this.busyProcessesByVersion.values())
.map((processSet) => Array.from(processSet))
.flat();
await Promise.all(allBusyProcesses.map((process) => this.killProcess(process)));
this.busyProcessesByVersion.clear();
}
getStats() {
const totalAvailable = Array.from(this.availableProcessesByVersion.values()).reduce(
(sum, processes) => sum + processes.length,
0
);
const totalBusy = Array.from(this.busyProcessesByVersion.values()).reduce(
(sum, processes) => sum + processes.size,
0
);
const statsByVersion: Record<string, { available: number; busy: number }> = {};
for (const [version, processes] of this.availableProcessesByVersion.entries()) {
statsByVersion[version] = {
available: processes.length,
busy: this.busyProcessesByVersion.get(version)?.size || 0,
};
}
for (const [version, processes] of this.busyProcessesByVersion.entries()) {
if (!statsByVersion[version]) {
statsByVersion[version] = {
available: 0,
busy: processes.size,
};
}
}
return {
availableCount: totalAvailable,
busyCount: totalBusy,
totalCount: totalAvailable + totalBusy,
byVersion: statsByVersion,
};
}
}