@memberjunction/code-execution 2.112.0 → 2.113.0
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.
- package/.turbo/turbo-build.log +1 -1
- package/CHANGELOG.md +9 -0
- package/dist/WorkerPool.d.ts.map +1 -1
- package/dist/WorkerPool.js +27 -26
- package/dist/WorkerPool.js.map +1 -1
- package/package.json +3 -2
- package/src/CodeExecutionService.ts.backup +21 -21
- package/src/WorkerPool.ts +307 -310
package/.turbo/turbo-build.log
CHANGED
package/CHANGELOG.md
CHANGED
|
@@ -1,11 +1,20 @@
|
|
|
1
1
|
# @memberjunction/code-execution
|
|
2
2
|
|
|
3
|
+
## 2.113.0
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- Updated dependencies [7f8390e]
|
|
8
|
+
- @memberjunction/global@2.113.0
|
|
9
|
+
- @memberjunction/core@2.113.0
|
|
10
|
+
|
|
3
11
|
## 2.112.0
|
|
4
12
|
|
|
5
13
|
### Patch Changes
|
|
6
14
|
|
|
7
15
|
- Updated dependencies [c126b59]
|
|
8
16
|
- @memberjunction/global@2.112.0
|
|
17
|
+
- @memberjunction/core@2.112.0
|
|
9
18
|
|
|
10
19
|
## 2.110.1
|
|
11
20
|
|
package/dist/WorkerPool.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerPool.d.ts","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAoBnE;;GAEG;AACH,MAAM,WAAW,iBAAiB;
|
|
1
|
+
{"version":3,"file":"WorkerPool.d.ts","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAIH,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,SAAS,CAAC;AAoBnE;;GAEG;AACH,MAAM,WAAW,iBAAiB;IAC9B,0DAA0D;IAC1D,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,uEAAuE;IACvE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,uEAAuE;IACvE,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,kEAAkE;IAClE,YAAY,CAAC,EAAE,MAAM,CAAC;CACzB;AAED;;GAEG;AACH,qBAAa,UAAU;IACnB,OAAO,CAAC,OAAO,CAAgB;IAC/B,OAAO,CAAC,YAAY,CAAwB;IAC5C,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,QAAQ,CAAS;IACzB,OAAO,CAAC,mBAAmB,CAAS;IACpC,OAAO,CAAC,eAAe,CAAS;IAChC,OAAO,CAAC,YAAY,CAAS;IAC7B,OAAO,CAAC,cAAc,CAAS;gBAEnB,OAAO,GAAE,iBAAsB;IAO3C;;OAEG;IACG,UAAU,IAAI,OAAO,CAAC,IAAI,CAAC;IAQjC;;OAEG;YACW,YAAY;IAiD1B;;OAEG;IACH,OAAO,CAAC,mBAAmB;IA0B3B;;OAEG;IACH,OAAO,CAAC,iBAAiB;IA8CzB;;OAEG;IACG,OAAO,CAAC,MAAM,EAAE,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,CAAC;IAoDxE;;OAEG;IACH,OAAO,CAAC,YAAY;IAkCpB;;OAEG;IACH,QAAQ,IAAI;QACR,YAAY,EAAE,MAAM,CAAC;QACrB,aAAa,EAAE,MAAM,CAAC;QACtB,WAAW,EAAE,MAAM,CAAC;QACpB,WAAW,EAAE,MAAM,CAAC;KACvB;IAYD;;OAEG;IACG,QAAQ,IAAI,OAAO,CAAC,IAAI,CAAC;CAyClC"}
|
package/dist/WorkerPool.js
CHANGED
|
@@ -39,7 +39,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
39
39
|
exports.WorkerPool = void 0;
|
|
40
40
|
const child_process_1 = require("child_process");
|
|
41
41
|
const path = __importStar(require("path"));
|
|
42
|
-
const
|
|
42
|
+
const core_1 = require("@memberjunction/core");
|
|
43
43
|
/**
|
|
44
44
|
* Manages a pool of worker processes for code execution
|
|
45
45
|
*/
|
|
@@ -62,7 +62,7 @@ class WorkerPool {
|
|
|
62
62
|
* Initialize the worker pool
|
|
63
63
|
*/
|
|
64
64
|
async initialize() {
|
|
65
|
-
(0,
|
|
65
|
+
(0, core_1.LogStatus)('Initializing code execution worker pool with ' + this.poolSize + ' workers');
|
|
66
66
|
for (let i = 0; i < this.poolSize; i++) {
|
|
67
67
|
await this.createWorker(i);
|
|
68
68
|
}
|
|
@@ -73,7 +73,7 @@ class WorkerPool {
|
|
|
73
73
|
async createWorker(id) {
|
|
74
74
|
const workerPath = path.join(__dirname, 'worker.js'); // Use .js because worker.ts is compiled
|
|
75
75
|
const childProcess = (0, child_process_1.fork)(workerPath, [], {
|
|
76
|
-
stdio: ['ignore', 'inherit', 'inherit', 'ipc']
|
|
76
|
+
stdio: ['ignore', 'inherit', 'inherit', 'ipc'] // Inherit stdout/stderr for debugging
|
|
77
77
|
});
|
|
78
78
|
const worker = {
|
|
79
79
|
process: childProcess,
|
|
@@ -81,7 +81,7 @@ class WorkerPool {
|
|
|
81
81
|
busy: false,
|
|
82
82
|
currentRequest: null,
|
|
83
83
|
crashCount: 0,
|
|
84
|
-
lastCrashTime: 0
|
|
84
|
+
lastCrashTime: 0
|
|
85
85
|
};
|
|
86
86
|
this.workers[id] = worker;
|
|
87
87
|
// Wait for ready message
|
|
@@ -108,7 +108,7 @@ class WorkerPool {
|
|
|
108
108
|
childProcess.on('exit', (code, signal) => {
|
|
109
109
|
this.handleWorkerCrash(worker, code, signal);
|
|
110
110
|
});
|
|
111
|
-
(0,
|
|
111
|
+
(0, core_1.LogStatus)(`Worker ${id} initialized and ready`);
|
|
112
112
|
}
|
|
113
113
|
/**
|
|
114
114
|
* Handle messages from worker process
|
|
@@ -119,7 +119,7 @@ class WorkerPool {
|
|
|
119
119
|
return;
|
|
120
120
|
}
|
|
121
121
|
if (!worker.currentRequest) {
|
|
122
|
-
(0,
|
|
122
|
+
(0, core_1.LogError)(new Error(`Worker ${worker.id} sent message but has no current request`));
|
|
123
123
|
return;
|
|
124
124
|
}
|
|
125
125
|
const request = worker.currentRequest;
|
|
@@ -149,7 +149,8 @@ class WorkerPool {
|
|
|
149
149
|
worker.crashCount++;
|
|
150
150
|
}
|
|
151
151
|
worker.lastCrashTime = now;
|
|
152
|
-
(0,
|
|
152
|
+
(0, core_1.LogError)(new Error(`Worker ${worker.id} crashed (code: ${code}, signal: ${signal}). ` +
|
|
153
|
+
`Crash count: ${worker.crashCount}/${this.maxCrashesPerWorker}`));
|
|
153
154
|
// Reject current request if any
|
|
154
155
|
if (worker.currentRequest) {
|
|
155
156
|
clearTimeout(worker.currentRequest.timeout);
|
|
@@ -158,7 +159,7 @@ class WorkerPool {
|
|
|
158
159
|
}
|
|
159
160
|
// Check if worker should be restarted
|
|
160
161
|
if (worker.crashCount >= this.maxCrashesPerWorker) {
|
|
161
|
-
(0,
|
|
162
|
+
(0, core_1.LogError)(new Error(`Worker ${worker.id} has crashed ${worker.crashCount} times within ${this.crashTimeWindow}ms. ` +
|
|
162
163
|
'Not restarting to prevent crash loop. Code execution capacity reduced.'));
|
|
163
164
|
// Remove from pool
|
|
164
165
|
this.workers[worker.id] = null;
|
|
@@ -166,9 +167,9 @@ class WorkerPool {
|
|
|
166
167
|
}
|
|
167
168
|
// Restart worker if not shutting down
|
|
168
169
|
if (!this.isShuttingDown) {
|
|
169
|
-
(0,
|
|
170
|
-
this.createWorker(worker.id).catch(
|
|
171
|
-
(0,
|
|
170
|
+
(0, core_1.LogStatus)(`Restarting worker ${worker.id}...`);
|
|
171
|
+
this.createWorker(worker.id).catch(error => {
|
|
172
|
+
(0, core_1.LogError)(new Error(`Failed to restart worker ${worker.id}: ${error.message}`));
|
|
172
173
|
});
|
|
173
174
|
}
|
|
174
175
|
}
|
|
@@ -180,7 +181,7 @@ class WorkerPool {
|
|
|
180
181
|
return {
|
|
181
182
|
success: false,
|
|
182
183
|
error: 'Worker pool is shutting down',
|
|
183
|
-
errorType: 'RUNTIME_ERROR'
|
|
184
|
+
errorType: 'RUNTIME_ERROR'
|
|
184
185
|
};
|
|
185
186
|
}
|
|
186
187
|
// Check if queue is full
|
|
@@ -188,7 +189,7 @@ class WorkerPool {
|
|
|
188
189
|
return {
|
|
189
190
|
success: false,
|
|
190
191
|
error: `Request queue is full (${this.maxQueueSize} pending requests). Please try again later.`,
|
|
191
|
-
errorType: 'RUNTIME_ERROR'
|
|
192
|
+
errorType: 'RUNTIME_ERROR'
|
|
192
193
|
};
|
|
193
194
|
}
|
|
194
195
|
const requestId = `req-${this.nextRequestId++}`;
|
|
@@ -197,14 +198,14 @@ class WorkerPool {
|
|
|
197
198
|
const totalTimeout = ((params.timeoutSeconds || 30) + 5) * 1000; // Add 5s buffer for overhead
|
|
198
199
|
const timeout = setTimeout(() => {
|
|
199
200
|
// Remove from queue if still there
|
|
200
|
-
const queueIndex = this.requestQueue.findIndex(
|
|
201
|
+
const queueIndex = this.requestQueue.findIndex(r => r.requestId === requestId);
|
|
201
202
|
if (queueIndex >= 0) {
|
|
202
203
|
this.requestQueue.splice(queueIndex, 1);
|
|
203
204
|
}
|
|
204
205
|
resolve({
|
|
205
206
|
success: false,
|
|
206
207
|
error: 'Request timed out waiting for worker availability',
|
|
207
|
-
errorType: 'TIMEOUT'
|
|
208
|
+
errorType: 'TIMEOUT'
|
|
208
209
|
});
|
|
209
210
|
}, totalTimeout);
|
|
210
211
|
const request = {
|
|
@@ -212,7 +213,7 @@ class WorkerPool {
|
|
|
212
213
|
params,
|
|
213
214
|
resolve,
|
|
214
215
|
reject,
|
|
215
|
-
timeout
|
|
216
|
+
timeout
|
|
216
217
|
};
|
|
217
218
|
// Add to queue
|
|
218
219
|
this.requestQueue.push(request);
|
|
@@ -228,7 +229,7 @@ class WorkerPool {
|
|
|
228
229
|
return;
|
|
229
230
|
}
|
|
230
231
|
// Find an available worker
|
|
231
|
-
const worker = this.workers.find(
|
|
232
|
+
const worker = this.workers.find(w => w && !w.busy);
|
|
232
233
|
if (!worker) {
|
|
233
234
|
return; // All workers busy, wait for one to finish
|
|
234
235
|
}
|
|
@@ -244,7 +245,7 @@ class WorkerPool {
|
|
|
244
245
|
worker.process.send({
|
|
245
246
|
type: 'execute',
|
|
246
247
|
requestId: request.requestId,
|
|
247
|
-
params: request.params
|
|
248
|
+
params: request.params
|
|
248
249
|
});
|
|
249
250
|
// Try to process more if queue has items
|
|
250
251
|
if (this.requestQueue.length > 0) {
|
|
@@ -255,13 +256,13 @@ class WorkerPool {
|
|
|
255
256
|
* Get pool statistics
|
|
256
257
|
*/
|
|
257
258
|
getStats() {
|
|
258
|
-
const activeWorkers = this.workers.filter(
|
|
259
|
-
const busyWorkers = this.workers.filter(
|
|
259
|
+
const activeWorkers = this.workers.filter(w => w !== null).length;
|
|
260
|
+
const busyWorkers = this.workers.filter(w => w && w.busy).length;
|
|
260
261
|
return {
|
|
261
262
|
totalWorkers: this.poolSize,
|
|
262
263
|
activeWorkers,
|
|
263
264
|
busyWorkers,
|
|
264
|
-
queueLength: this.requestQueue.length
|
|
265
|
+
queueLength: this.requestQueue.length
|
|
265
266
|
};
|
|
266
267
|
}
|
|
267
268
|
/**
|
|
@@ -269,21 +270,21 @@ class WorkerPool {
|
|
|
269
270
|
*/
|
|
270
271
|
async shutdown() {
|
|
271
272
|
this.isShuttingDown = true;
|
|
272
|
-
(0,
|
|
273
|
+
(0, core_1.LogStatus)('Shutting down code execution worker pool...');
|
|
273
274
|
// Reject all queued requests
|
|
274
275
|
for (const request of this.requestQueue) {
|
|
275
276
|
clearTimeout(request.timeout);
|
|
276
277
|
request.resolve({
|
|
277
278
|
success: false,
|
|
278
279
|
error: 'Worker pool is shutting down',
|
|
279
|
-
errorType: 'RUNTIME_ERROR'
|
|
280
|
+
errorType: 'RUNTIME_ERROR'
|
|
280
281
|
});
|
|
281
282
|
}
|
|
282
283
|
this.requestQueue = [];
|
|
283
284
|
// Kill all workers
|
|
284
285
|
const killPromises = this.workers
|
|
285
|
-
.filter(
|
|
286
|
-
.map(
|
|
286
|
+
.filter(w => w !== null)
|
|
287
|
+
.map(worker => {
|
|
287
288
|
return new Promise((resolve) => {
|
|
288
289
|
if (worker.process.killed) {
|
|
289
290
|
resolve();
|
|
@@ -301,7 +302,7 @@ class WorkerPool {
|
|
|
301
302
|
});
|
|
302
303
|
});
|
|
303
304
|
await Promise.all(killPromises);
|
|
304
|
-
(0,
|
|
305
|
+
(0, core_1.LogStatus)('Worker pool shutdown complete');
|
|
305
306
|
}
|
|
306
307
|
}
|
|
307
308
|
exports.WorkerPool = WorkerPool;
|
package/dist/WorkerPool.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"WorkerPool.js","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,iDAAmD;AACnD,2CAA6B;AAE7B
|
|
1
|
+
{"version":3,"file":"WorkerPool.js","sourceRoot":"","sources":["../src/WorkerPool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;GAYG;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,iDAAmD;AACnD,2CAA6B;AAE7B,+CAA2D;AAiC3D;;GAEG;AACH,MAAa,UAAU;IACX,OAAO,GAAa,EAAE,CAAC;IACvB,YAAY,GAAqB,EAAE,CAAC;IACpC,aAAa,GAAG,CAAC,CAAC;IAClB,QAAQ,CAAS;IACjB,mBAAmB,CAAS;IAC5B,eAAe,CAAS;IACxB,YAAY,CAAS;IACrB,cAAc,GAAG,KAAK,CAAC;IAE/B,YAAY,UAA6B,EAAE;QACvC,IAAI,CAAC,QAAQ,GAAG,OAAO,CAAC,QAAQ,IAAI,CAAC,CAAC;QACtC,IAAI,CAAC,mBAAmB,GAAG,OAAO,CAAC,mBAAmB,I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GED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@memberjunction/code-execution",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.113.0",
|
|
4
4
|
"description": "Sandboxed code execution service for MemberJunction actions and agents",
|
|
5
5
|
"main": "dist/index.js",
|
|
6
6
|
"types": "dist/index.d.ts",
|
|
@@ -9,7 +9,8 @@
|
|
|
9
9
|
"watch": "tsc --watch"
|
|
10
10
|
},
|
|
11
11
|
"dependencies": {
|
|
12
|
-
"@memberjunction/
|
|
12
|
+
"@memberjunction/core": "2.113.0",
|
|
13
|
+
"@memberjunction/global": "2.113.0",
|
|
13
14
|
"isolated-vm": "^6.0.2",
|
|
14
15
|
"lodash": "^4.17.21",
|
|
15
16
|
"date-fns": "^3.0.0",
|
|
@@ -1,24 +1,24 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* @fileoverview Sandboxed code execution service for MemberJunction
|
|
3
|
-
*
|
|
3
|
+
*
|
|
4
4
|
* Provides secure execution of JavaScript code in a controlled environment using vm2.
|
|
5
5
|
* Supports a curated list of safe npm packages for data manipulation and analysis.
|
|
6
|
-
*
|
|
6
|
+
*
|
|
7
7
|
* @module @memberjunction/code-execution
|
|
8
8
|
* @author MemberJunction.com
|
|
9
9
|
* @since 2.46.0
|
|
10
10
|
*/
|
|
11
11
|
|
|
12
|
-
import { LogError, LogStatus } from '@memberjunction/
|
|
13
|
-
import {
|
|
14
|
-
CodeExecutionParams,
|
|
15
|
-
CodeExecutionResult,
|
|
16
|
-
JavaScriptExecutionOptions
|
|
12
|
+
import { LogError, LogStatus } from '@memberjunction/core';
|
|
13
|
+
import {
|
|
14
|
+
CodeExecutionParams,
|
|
15
|
+
CodeExecutionResult,
|
|
16
|
+
JavaScriptExecutionOptions
|
|
17
17
|
} from './types';
|
|
18
18
|
|
|
19
19
|
/**
|
|
20
20
|
* Service for executing code in a sandboxed environment
|
|
21
|
-
*
|
|
21
|
+
*
|
|
22
22
|
* Security features:
|
|
23
23
|
* - Isolated VM using vm2's NodeVM
|
|
24
24
|
* - Timeout protection
|
|
@@ -26,7 +26,7 @@ import {
|
|
|
26
26
|
* - No network access (http, https, net modules blocked)
|
|
27
27
|
* - Allowlist-only npm package imports
|
|
28
28
|
* - Memory limits (requires Node.js process flags)
|
|
29
|
-
*
|
|
29
|
+
*
|
|
30
30
|
* Supported libraries:
|
|
31
31
|
* - lodash: Data manipulation
|
|
32
32
|
* - date-fns: Date utilities
|
|
@@ -34,7 +34,7 @@ import {
|
|
|
34
34
|
* - papaparse: CSV parsing
|
|
35
35
|
* - uuid: ID generation
|
|
36
36
|
* - validator: Input validation
|
|
37
|
-
*
|
|
37
|
+
*
|
|
38
38
|
* @example
|
|
39
39
|
* ```typescript
|
|
40
40
|
* const service = new CodeExecutionService();
|
|
@@ -63,7 +63,7 @@ export class CodeExecutionService {
|
|
|
63
63
|
|
|
64
64
|
/**
|
|
65
65
|
* Execute code in a sandboxed environment
|
|
66
|
-
*
|
|
66
|
+
*
|
|
67
67
|
* @param params - Execution parameters including code and input data
|
|
68
68
|
* @returns Promise resolving to execution result
|
|
69
69
|
*/
|
|
@@ -108,20 +108,20 @@ export class CodeExecutionService {
|
|
|
108
108
|
|
|
109
109
|
/**
|
|
110
110
|
* Execute JavaScript code using vm2 NodeVM sandbox
|
|
111
|
-
*
|
|
111
|
+
*
|
|
112
112
|
* The code has access to:
|
|
113
113
|
* - input: The inputData parameter
|
|
114
114
|
* - output: Variable where code should store result
|
|
115
115
|
* - console: Limited console API (log, error, warn, info)
|
|
116
116
|
* - Safe libraries: Can require() packages from allowlist
|
|
117
117
|
* - Safe built-ins: JSON, Math, Date, Array, Object, String, Number, Boolean
|
|
118
|
-
*
|
|
118
|
+
*
|
|
119
119
|
* The code does NOT have access to:
|
|
120
120
|
* - File system (fs module is mocked)
|
|
121
121
|
* - Network (http, https, net, axios, etc. are blocked)
|
|
122
122
|
* - Process control (child_process, cluster blocked)
|
|
123
123
|
* - Dangerous APIs (eval, Function constructor are disabled)
|
|
124
|
-
*
|
|
124
|
+
*
|
|
125
125
|
* @private
|
|
126
126
|
*/
|
|
127
127
|
private async executeJavaScript(
|
|
@@ -179,18 +179,18 @@ export class CodeExecutionService {
|
|
|
179
179
|
const vm = new NodeVM({
|
|
180
180
|
timeout: options.timeout * 1000, // Convert to milliseconds
|
|
181
181
|
sandbox,
|
|
182
|
-
|
|
182
|
+
|
|
183
183
|
// Disable dangerous features
|
|
184
184
|
eval: false, // Disable eval()
|
|
185
185
|
wasm: false, // Disable WebAssembly
|
|
186
186
|
fixAsync: true, // Prevent async abuse
|
|
187
|
-
|
|
187
|
+
|
|
188
188
|
// Configure module imports
|
|
189
189
|
require: {
|
|
190
190
|
external: options.allowedLibraries || this.SAFE_LIBRARIES,
|
|
191
191
|
builtin: [], // No built-in Node modules (like fs, path, etc.)
|
|
192
192
|
root: './node_modules',
|
|
193
|
-
|
|
193
|
+
|
|
194
194
|
// Mock dangerous modules
|
|
195
195
|
mock: {
|
|
196
196
|
fs: {}, // Block filesystem
|
|
@@ -253,7 +253,7 @@ export class CodeExecutionService {
|
|
|
253
253
|
}
|
|
254
254
|
|
|
255
255
|
// Check for security violations
|
|
256
|
-
if (error.message?.includes('not allowed') ||
|
|
256
|
+
if (error.message?.includes('not allowed') ||
|
|
257
257
|
error.message?.includes('access denied') ||
|
|
258
258
|
error.message?.includes('Cannot find module')) {
|
|
259
259
|
return {
|
|
@@ -278,13 +278,13 @@ export class CodeExecutionService {
|
|
|
278
278
|
/**
|
|
279
279
|
* Format console arguments for logging
|
|
280
280
|
* Handles objects, arrays, and primitives
|
|
281
|
-
*
|
|
281
|
+
*
|
|
282
282
|
* @private
|
|
283
283
|
*/
|
|
284
284
|
private formatConsoleArg(arg: any): string {
|
|
285
285
|
if (arg === null) return 'null';
|
|
286
286
|
if (arg === undefined) return 'undefined';
|
|
287
|
-
|
|
287
|
+
|
|
288
288
|
if (typeof arg === 'object') {
|
|
289
289
|
try {
|
|
290
290
|
return JSON.stringify(arg, null, 2);
|
|
@@ -292,7 +292,7 @@ export class CodeExecutionService {
|
|
|
292
292
|
return String(arg);
|
|
293
293
|
}
|
|
294
294
|
}
|
|
295
|
-
|
|
295
|
+
|
|
296
296
|
return String(arg);
|
|
297
297
|
}
|
|
298
298
|
}
|
package/src/WorkerPool.ts
CHANGED
|
@@ -15,357 +15,354 @@
|
|
|
15
15
|
import { fork, ChildProcess } from 'child_process';
|
|
16
16
|
import * as path from 'path';
|
|
17
17
|
import { CodeExecutionParams, CodeExecutionResult } from './types';
|
|
18
|
-
import { LogError, LogStatus } from '@memberjunction/
|
|
18
|
+
import { LogError, LogStatus } from '@memberjunction/core';
|
|
19
19
|
|
|
20
20
|
interface PendingRequest {
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
21
|
+
requestId: string;
|
|
22
|
+
params: CodeExecutionParams;
|
|
23
|
+
resolve: (result: CodeExecutionResult) => void;
|
|
24
|
+
reject: (error: Error) => void;
|
|
25
|
+
timeout: NodeJS.Timeout;
|
|
26
26
|
}
|
|
27
27
|
|
|
28
28
|
interface Worker {
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
29
|
+
process: ChildProcess;
|
|
30
|
+
id: number;
|
|
31
|
+
busy: boolean;
|
|
32
|
+
currentRequest: PendingRequest | null;
|
|
33
|
+
crashCount: number;
|
|
34
|
+
lastCrashTime: number;
|
|
35
35
|
}
|
|
36
36
|
|
|
37
37
|
/**
|
|
38
38
|
* Configuration options for worker pool
|
|
39
39
|
*/
|
|
40
40
|
export interface WorkerPoolOptions {
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
41
|
+
/** Number of worker processes to maintain (default: 2) */
|
|
42
|
+
poolSize?: number;
|
|
43
|
+
/** Maximum crashes per worker before marking unhealthy (default: 3) */
|
|
44
|
+
maxCrashesPerWorker?: number;
|
|
45
|
+
/** Time window in ms for crash counting (default: 60000 = 1 minute) */
|
|
46
|
+
crashTimeWindow?: number;
|
|
47
|
+
/** Maximum queue size before rejecting requests (default: 100) */
|
|
48
|
+
maxQueueSize?: number;
|
|
49
49
|
}
|
|
50
50
|
|
|
51
51
|
/**
|
|
52
52
|
* Manages a pool of worker processes for code execution
|
|
53
53
|
*/
|
|
54
54
|
export class WorkerPool {
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
/**
|
|
72
|
-
* Initialize the worker pool
|
|
73
|
-
*/
|
|
74
|
-
async initialize(): Promise<void> {
|
|
75
|
-
LogStatus('Initializing code execution worker pool with ' + this.poolSize + ' workers');
|
|
76
|
-
|
|
77
|
-
for (let i = 0; i < this.poolSize; i++) {
|
|
78
|
-
await this.createWorker(i);
|
|
55
|
+
private workers: Worker[] = [];
|
|
56
|
+
private requestQueue: PendingRequest[] = [];
|
|
57
|
+
private nextRequestId = 0;
|
|
58
|
+
private poolSize: number;
|
|
59
|
+
private maxCrashesPerWorker: number;
|
|
60
|
+
private crashTimeWindow: number;
|
|
61
|
+
private maxQueueSize: number;
|
|
62
|
+
private isShuttingDown = false;
|
|
63
|
+
|
|
64
|
+
constructor(options: WorkerPoolOptions = {}) {
|
|
65
|
+
this.poolSize = options.poolSize || 2;
|
|
66
|
+
this.maxCrashesPerWorker = options.maxCrashesPerWorker || 3;
|
|
67
|
+
this.crashTimeWindow = options.crashTimeWindow || 60000; // 1 minute
|
|
68
|
+
this.maxQueueSize = options.maxQueueSize || 100;
|
|
79
69
|
}
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
});
|
|
90
|
-
|
|
91
|
-
const worker: Worker = {
|
|
92
|
-
process: childProcess,
|
|
93
|
-
id,
|
|
94
|
-
busy: false,
|
|
95
|
-
currentRequest: null,
|
|
96
|
-
crashCount: 0,
|
|
97
|
-
lastCrashTime: 0,
|
|
98
|
-
};
|
|
99
|
-
|
|
100
|
-
this.workers[id] = worker;
|
|
101
|
-
|
|
102
|
-
// Wait for ready message
|
|
103
|
-
await new Promise<void>((resolve, reject) => {
|
|
104
|
-
const timeout = setTimeout(() => {
|
|
105
|
-
reject(new Error(`Worker ${id} failed to start within 5 seconds`));
|
|
106
|
-
}, 5000);
|
|
107
|
-
|
|
108
|
-
childProcess.once('message', (msg: any) => {
|
|
109
|
-
if (msg.type === 'ready') {
|
|
110
|
-
clearTimeout(timeout);
|
|
111
|
-
resolve();
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Initialize the worker pool
|
|
73
|
+
*/
|
|
74
|
+
async initialize(): Promise<void> {
|
|
75
|
+
LogStatus('Initializing code execution worker pool with ' + this.poolSize + ' workers');
|
|
76
|
+
|
|
77
|
+
for (let i = 0; i < this.poolSize; i++) {
|
|
78
|
+
await this.createWorker(i);
|
|
112
79
|
}
|
|
113
|
-
});
|
|
114
|
-
|
|
115
|
-
childProcess.once('error', (error) => {
|
|
116
|
-
clearTimeout(timeout);
|
|
117
|
-
reject(error);
|
|
118
|
-
});
|
|
119
|
-
});
|
|
120
|
-
|
|
121
|
-
// Set up message handler for responses
|
|
122
|
-
childProcess.on('message', (message: any) => {
|
|
123
|
-
this.handleWorkerMessage(worker, message);
|
|
124
|
-
});
|
|
125
|
-
|
|
126
|
-
// Set up crash handler
|
|
127
|
-
childProcess.on('exit', (code, signal) => {
|
|
128
|
-
this.handleWorkerCrash(worker, code, signal);
|
|
129
|
-
});
|
|
130
|
-
|
|
131
|
-
LogStatus(`Worker ${id} initialized and ready`);
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
/**
|
|
135
|
-
* Handle messages from worker process
|
|
136
|
-
*/
|
|
137
|
-
private handleWorkerMessage(worker: Worker, message: any): void {
|
|
138
|
-
if (message.type === 'ready') {
|
|
139
|
-
// Worker is ready (initial startup or after restart)
|
|
140
|
-
return;
|
|
141
80
|
}
|
|
142
81
|
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
82
|
+
/**
|
|
83
|
+
* Create a new worker process
|
|
84
|
+
*/
|
|
85
|
+
private async createWorker(id: number): Promise<void> {
|
|
86
|
+
const workerPath = path.join(__dirname, 'worker.js'); // Use .js because worker.ts is compiled
|
|
87
|
+
const childProcess = fork(workerPath, [], {
|
|
88
|
+
stdio: ['ignore', 'inherit', 'inherit', 'ipc'] // Inherit stdout/stderr for debugging
|
|
89
|
+
});
|
|
147
90
|
|
|
148
|
-
|
|
149
|
-
|
|
91
|
+
const worker: Worker = {
|
|
92
|
+
process: childProcess,
|
|
93
|
+
id,
|
|
94
|
+
busy: false,
|
|
95
|
+
currentRequest: null,
|
|
96
|
+
crashCount: 0,
|
|
97
|
+
lastCrashTime: 0
|
|
98
|
+
};
|
|
99
|
+
|
|
100
|
+
this.workers[id] = worker;
|
|
101
|
+
|
|
102
|
+
// Wait for ready message
|
|
103
|
+
await new Promise<void>((resolve, reject) => {
|
|
104
|
+
const timeout = setTimeout(() => {
|
|
105
|
+
reject(new Error(`Worker ${id} failed to start within 5 seconds`));
|
|
106
|
+
}, 5000);
|
|
107
|
+
|
|
108
|
+
childProcess.once('message', (msg: any) => {
|
|
109
|
+
if (msg.type === 'ready') {
|
|
110
|
+
clearTimeout(timeout);
|
|
111
|
+
resolve();
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
|
|
115
|
+
childProcess.once('error', (error) => {
|
|
116
|
+
clearTimeout(timeout);
|
|
117
|
+
reject(error);
|
|
118
|
+
});
|
|
119
|
+
});
|
|
150
120
|
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
}
|
|
121
|
+
// Set up message handler for responses
|
|
122
|
+
childProcess.on('message', (message: any) => {
|
|
123
|
+
this.handleWorkerMessage(worker, message);
|
|
124
|
+
});
|
|
156
125
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
162
|
-
|
|
163
|
-
/**
|
|
164
|
-
* Handle worker process crash
|
|
165
|
-
*/
|
|
166
|
-
private handleWorkerCrash(worker: Worker, code: number | null, signal: string | null): void {
|
|
167
|
-
const now = Date.now();
|
|
168
|
-
|
|
169
|
-
// Update crash tracking
|
|
170
|
-
if (now - worker.lastCrashTime > this.crashTimeWindow) {
|
|
171
|
-
// Outside time window, reset count
|
|
172
|
-
worker.crashCount = 1;
|
|
173
|
-
} else {
|
|
174
|
-
worker.crashCount++;
|
|
175
|
-
}
|
|
176
|
-
worker.lastCrashTime = now;
|
|
177
|
-
|
|
178
|
-
LogError(
|
|
179
|
-
new Error(
|
|
180
|
-
`Worker ${worker.id} crashed (code: ${code}, signal: ${signal}). ` + `Crash count: ${worker.crashCount}/${this.maxCrashesPerWorker}`
|
|
181
|
-
)
|
|
182
|
-
);
|
|
183
|
-
|
|
184
|
-
// Reject current request if any
|
|
185
|
-
if (worker.currentRequest) {
|
|
186
|
-
clearTimeout(worker.currentRequest.timeout);
|
|
187
|
-
worker.currentRequest.reject(
|
|
188
|
-
new Error('Worker process crashed during code execution. This may indicate a severe error in the code.')
|
|
189
|
-
);
|
|
190
|
-
worker.currentRequest = null;
|
|
191
|
-
}
|
|
126
|
+
// Set up crash handler
|
|
127
|
+
childProcess.on('exit', (code, signal) => {
|
|
128
|
+
this.handleWorkerCrash(worker, code, signal);
|
|
129
|
+
});
|
|
192
130
|
|
|
193
|
-
|
|
194
|
-
if (worker.crashCount >= this.maxCrashesPerWorker) {
|
|
195
|
-
LogError(
|
|
196
|
-
new Error(
|
|
197
|
-
`Worker ${worker.id} has crashed ${worker.crashCount} times within ${this.crashTimeWindow}ms. ` +
|
|
198
|
-
'Not restarting to prevent crash loop. Code execution capacity reduced.'
|
|
199
|
-
)
|
|
200
|
-
);
|
|
201
|
-
// Remove from pool
|
|
202
|
-
this.workers[worker.id] = null as any;
|
|
203
|
-
return;
|
|
131
|
+
LogStatus(`Worker ${id} initialized and ready`);
|
|
204
132
|
}
|
|
205
133
|
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
134
|
+
/**
|
|
135
|
+
* Handle messages from worker process
|
|
136
|
+
*/
|
|
137
|
+
private handleWorkerMessage(worker: Worker, message: any): void {
|
|
138
|
+
if (message.type === 'ready') {
|
|
139
|
+
// Worker is ready (initial startup or after restart)
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
if (!worker.currentRequest) {
|
|
144
|
+
LogError(new Error(`Worker ${worker.id} sent message but has no current request`));
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const request = worker.currentRequest;
|
|
149
|
+
clearTimeout(request.timeout);
|
|
150
|
+
|
|
151
|
+
if (message.type === 'result') {
|
|
152
|
+
request.resolve(message.result);
|
|
153
|
+
} else if (message.type === 'error') {
|
|
154
|
+
request.reject(new Error(message.error));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
// Mark worker as available and process queue
|
|
158
|
+
worker.busy = false;
|
|
159
|
+
worker.currentRequest = null;
|
|
160
|
+
this.processQueue();
|
|
225
161
|
}
|
|
226
162
|
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
163
|
+
/**
|
|
164
|
+
* Handle worker process crash
|
|
165
|
+
*/
|
|
166
|
+
private handleWorkerCrash(worker: Worker, code: number | null, signal: string | null): void {
|
|
167
|
+
const now = Date.now();
|
|
168
|
+
|
|
169
|
+
// Update crash tracking
|
|
170
|
+
if (now - worker.lastCrashTime > this.crashTimeWindow) {
|
|
171
|
+
// Outside time window, reset count
|
|
172
|
+
worker.crashCount = 1;
|
|
173
|
+
} else {
|
|
174
|
+
worker.crashCount++;
|
|
175
|
+
}
|
|
176
|
+
worker.lastCrashTime = now;
|
|
177
|
+
|
|
178
|
+
LogError(new Error(
|
|
179
|
+
`Worker ${worker.id} crashed (code: ${code}, signal: ${signal}). ` +
|
|
180
|
+
`Crash count: ${worker.crashCount}/${this.maxCrashesPerWorker}`
|
|
181
|
+
));
|
|
182
|
+
|
|
183
|
+
// Reject current request if any
|
|
184
|
+
if (worker.currentRequest) {
|
|
185
|
+
clearTimeout(worker.currentRequest.timeout);
|
|
186
|
+
worker.currentRequest.reject(new Error(
|
|
187
|
+
'Worker process crashed during code execution. This may indicate a severe error in the code.'
|
|
188
|
+
));
|
|
189
|
+
worker.currentRequest = null;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Check if worker should be restarted
|
|
193
|
+
if (worker.crashCount >= this.maxCrashesPerWorker) {
|
|
194
|
+
LogError(new Error(
|
|
195
|
+
`Worker ${worker.id} has crashed ${worker.crashCount} times within ${this.crashTimeWindow}ms. ` +
|
|
196
|
+
'Not restarting to prevent crash loop. Code execution capacity reduced.'
|
|
197
|
+
));
|
|
198
|
+
// Remove from pool
|
|
199
|
+
this.workers[worker.id] = null as any;
|
|
200
|
+
return;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
// Restart worker if not shutting down
|
|
204
|
+
if (!this.isShuttingDown) {
|
|
205
|
+
LogStatus(`Restarting worker ${worker.id}...`);
|
|
206
|
+
this.createWorker(worker.id).catch(error => {
|
|
207
|
+
LogError(new Error(`Failed to restart worker ${worker.id}: ${error.message}`));
|
|
208
|
+
});
|
|
209
|
+
}
|
|
234
210
|
}
|
|
235
211
|
|
|
236
|
-
|
|
212
|
+
/**
|
|
213
|
+
* Execute code in an available worker
|
|
214
|
+
*/
|
|
215
|
+
async execute(params: CodeExecutionParams): Promise<CodeExecutionResult> {
|
|
216
|
+
if (this.isShuttingDown) {
|
|
217
|
+
return {
|
|
218
|
+
success: false,
|
|
219
|
+
error: 'Worker pool is shutting down',
|
|
220
|
+
errorType: 'RUNTIME_ERROR'
|
|
221
|
+
};
|
|
222
|
+
}
|
|
237
223
|
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
this.requestQueue.splice(queueIndex, 1);
|
|
224
|
+
// Check if queue is full
|
|
225
|
+
if (this.requestQueue.length >= this.maxQueueSize) {
|
|
226
|
+
return {
|
|
227
|
+
success: false,
|
|
228
|
+
error: `Request queue is full (${this.maxQueueSize} pending requests). Please try again later.`,
|
|
229
|
+
errorType: 'RUNTIME_ERROR'
|
|
230
|
+
};
|
|
246
231
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
232
|
+
|
|
233
|
+
const requestId = `req-${this.nextRequestId++}`;
|
|
234
|
+
|
|
235
|
+
return new Promise<CodeExecutionResult>((resolve, reject) => {
|
|
236
|
+
// Create timeout for entire request (includes queue time + execution)
|
|
237
|
+
const totalTimeout = ((params.timeoutSeconds || 30) + 5) * 1000; // Add 5s buffer for overhead
|
|
238
|
+
const timeout = setTimeout(() => {
|
|
239
|
+
// Remove from queue if still there
|
|
240
|
+
const queueIndex = this.requestQueue.findIndex(r => r.requestId === requestId);
|
|
241
|
+
if (queueIndex >= 0) {
|
|
242
|
+
this.requestQueue.splice(queueIndex, 1);
|
|
243
|
+
}
|
|
244
|
+
resolve({
|
|
245
|
+
success: false,
|
|
246
|
+
error: 'Request timed out waiting for worker availability',
|
|
247
|
+
errorType: 'TIMEOUT'
|
|
248
|
+
});
|
|
249
|
+
}, totalTimeout);
|
|
250
|
+
|
|
251
|
+
const request: PendingRequest = {
|
|
252
|
+
requestId,
|
|
253
|
+
params,
|
|
254
|
+
resolve,
|
|
255
|
+
reject,
|
|
256
|
+
timeout
|
|
257
|
+
};
|
|
258
|
+
|
|
259
|
+
// Add to queue
|
|
260
|
+
this.requestQueue.push(request);
|
|
261
|
+
|
|
262
|
+
// Try to process immediately
|
|
263
|
+
this.processQueue();
|
|
251
264
|
});
|
|
252
|
-
}, totalTimeout);
|
|
253
|
-
|
|
254
|
-
const request: PendingRequest = {
|
|
255
|
-
requestId,
|
|
256
|
-
params,
|
|
257
|
-
resolve,
|
|
258
|
-
reject,
|
|
259
|
-
timeout,
|
|
260
|
-
};
|
|
261
|
-
|
|
262
|
-
// Add to queue
|
|
263
|
-
this.requestQueue.push(request);
|
|
264
|
-
|
|
265
|
-
// Try to process immediately
|
|
266
|
-
this.processQueue();
|
|
267
|
-
});
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
/**
|
|
271
|
-
* Process queued requests by assigning them to available workers
|
|
272
|
-
*/
|
|
273
|
-
private processQueue(): void {
|
|
274
|
-
if (this.requestQueue.length === 0) {
|
|
275
|
-
return;
|
|
276
265
|
}
|
|
277
266
|
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
267
|
+
/**
|
|
268
|
+
* Process queued requests by assigning them to available workers
|
|
269
|
+
*/
|
|
270
|
+
private processQueue(): void {
|
|
271
|
+
if (this.requestQueue.length === 0) {
|
|
272
|
+
return;
|
|
273
|
+
}
|
|
283
274
|
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
275
|
+
// Find an available worker
|
|
276
|
+
const worker = this.workers.find(w => w && !w.busy);
|
|
277
|
+
if (!worker) {
|
|
278
|
+
return; // All workers busy, wait for one to finish
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Get next request from queue
|
|
282
|
+
const request = this.requestQueue.shift();
|
|
283
|
+
if (!request) {
|
|
284
|
+
return;
|
|
285
|
+
}
|
|
289
286
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
287
|
+
// Assign request to worker
|
|
288
|
+
worker.busy = true;
|
|
289
|
+
worker.currentRequest = request;
|
|
293
290
|
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
291
|
+
// Send execution request to worker
|
|
292
|
+
worker.process.send({
|
|
293
|
+
type: 'execute',
|
|
294
|
+
requestId: request.requestId,
|
|
295
|
+
params: request.params
|
|
296
|
+
});
|
|
300
297
|
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
298
|
+
// Try to process more if queue has items
|
|
299
|
+
if (this.requestQueue.length > 0) {
|
|
300
|
+
setImmediate(() => this.processQueue());
|
|
301
|
+
}
|
|
304
302
|
}
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
};
|
|
325
|
-
}
|
|
326
|
-
|
|
327
|
-
/**
|
|
328
|
-
* Shutdown the worker pool gracefully
|
|
329
|
-
*/
|
|
330
|
-
async shutdown(): Promise<void> {
|
|
331
|
-
this.isShuttingDown = true;
|
|
332
|
-
LogStatus('Shutting down code execution worker pool...');
|
|
333
|
-
|
|
334
|
-
// Reject all queued requests
|
|
335
|
-
for (const request of this.requestQueue) {
|
|
336
|
-
clearTimeout(request.timeout);
|
|
337
|
-
request.resolve({
|
|
338
|
-
success: false,
|
|
339
|
-
error: 'Worker pool is shutting down',
|
|
340
|
-
errorType: 'RUNTIME_ERROR',
|
|
341
|
-
});
|
|
303
|
+
|
|
304
|
+
/**
|
|
305
|
+
* Get pool statistics
|
|
306
|
+
*/
|
|
307
|
+
getStats(): {
|
|
308
|
+
totalWorkers: number;
|
|
309
|
+
activeWorkers: number;
|
|
310
|
+
busyWorkers: number;
|
|
311
|
+
queueLength: number;
|
|
312
|
+
} {
|
|
313
|
+
const activeWorkers = this.workers.filter(w => w !== null).length;
|
|
314
|
+
const busyWorkers = this.workers.filter(w => w && w.busy).length;
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
totalWorkers: this.poolSize,
|
|
318
|
+
activeWorkers,
|
|
319
|
+
busyWorkers,
|
|
320
|
+
queueLength: this.requestQueue.length
|
|
321
|
+
};
|
|
342
322
|
}
|
|
343
|
-
this.requestQueue = [];
|
|
344
|
-
|
|
345
|
-
// Kill all workers
|
|
346
|
-
const killPromises = this.workers
|
|
347
|
-
.filter((w) => w !== null)
|
|
348
|
-
.map((worker) => {
|
|
349
|
-
return new Promise<void>((resolve) => {
|
|
350
|
-
if (worker.process.killed) {
|
|
351
|
-
resolve();
|
|
352
|
-
return;
|
|
353
|
-
}
|
|
354
|
-
|
|
355
|
-
worker.process.once('exit', () => resolve());
|
|
356
|
-
worker.process.kill('SIGTERM');
|
|
357
|
-
|
|
358
|
-
// Force kill after 5 seconds
|
|
359
|
-
setTimeout(() => {
|
|
360
|
-
if (!worker.process.killed) {
|
|
361
|
-
worker.process.kill('SIGKILL');
|
|
362
|
-
}
|
|
363
|
-
resolve();
|
|
364
|
-
}, 5000);
|
|
365
|
-
});
|
|
366
|
-
});
|
|
367
323
|
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
324
|
+
/**
|
|
325
|
+
* Shutdown the worker pool gracefully
|
|
326
|
+
*/
|
|
327
|
+
async shutdown(): Promise<void> {
|
|
328
|
+
this.isShuttingDown = true;
|
|
329
|
+
LogStatus('Shutting down code execution worker pool...');
|
|
330
|
+
|
|
331
|
+
// Reject all queued requests
|
|
332
|
+
for (const request of this.requestQueue) {
|
|
333
|
+
clearTimeout(request.timeout);
|
|
334
|
+
request.resolve({
|
|
335
|
+
success: false,
|
|
336
|
+
error: 'Worker pool is shutting down',
|
|
337
|
+
errorType: 'RUNTIME_ERROR'
|
|
338
|
+
});
|
|
339
|
+
}
|
|
340
|
+
this.requestQueue = [];
|
|
341
|
+
|
|
342
|
+
// Kill all workers
|
|
343
|
+
const killPromises = this.workers
|
|
344
|
+
.filter(w => w !== null)
|
|
345
|
+
.map(worker => {
|
|
346
|
+
return new Promise<void>((resolve) => {
|
|
347
|
+
if (worker.process.killed) {
|
|
348
|
+
resolve();
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
worker.process.once('exit', () => resolve());
|
|
353
|
+
worker.process.kill('SIGTERM');
|
|
354
|
+
|
|
355
|
+
// Force kill after 5 seconds
|
|
356
|
+
setTimeout(() => {
|
|
357
|
+
if (!worker.process.killed) {
|
|
358
|
+
worker.process.kill('SIGKILL');
|
|
359
|
+
}
|
|
360
|
+
resolve();
|
|
361
|
+
}, 5000);
|
|
362
|
+
});
|
|
363
|
+
});
|
|
364
|
+
|
|
365
|
+
await Promise.all(killPromises);
|
|
366
|
+
LogStatus('Worker pool shutdown complete');
|
|
367
|
+
}
|
|
371
368
|
}
|