tywrap 0.1.1 → 0.2.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/README.md +32 -5
- package/dist/cli.js +70 -3
- package/dist/cli.js.map +1 -1
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +47 -11
- package/dist/config/index.js.map +1 -1
- package/dist/core/generator.d.ts.map +1 -1
- package/dist/core/generator.js +6 -2
- package/dist/core/generator.js.map +1 -1
- package/dist/core/mapper.d.ts.map +1 -1
- package/dist/core/mapper.js +16 -4
- package/dist/core/mapper.js.map +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/runtime/bridge-core.d.ts +64 -0
- package/dist/runtime/bridge-core.d.ts.map +1 -0
- package/dist/runtime/bridge-core.js +344 -0
- package/dist/runtime/bridge-core.js.map +1 -0
- package/dist/runtime/node.d.ts +161 -15
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +542 -218
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/optimized-node.d.ts +19 -128
- package/dist/runtime/optimized-node.d.ts.map +1 -1
- package/dist/runtime/optimized-node.js +19 -627
- package/dist/runtime/optimized-node.js.map +1 -1
- package/dist/runtime/timed-out-request-tracker.d.ts +20 -0
- package/dist/runtime/timed-out-request-tracker.d.ts.map +1 -0
- package/dist/runtime/timed-out-request-tracker.js +48 -0
- package/dist/runtime/timed-out-request-tracker.js.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.d.ts.map +1 -1
- package/dist/tywrap.d.ts +17 -4
- package/dist/tywrap.d.ts.map +1 -1
- package/dist/tywrap.js +68 -35
- package/dist/tywrap.js.map +1 -1
- package/dist/utils/codec.d.ts +22 -0
- package/dist/utils/codec.d.ts.map +1 -1
- package/dist/utils/codec.js +245 -55
- package/dist/utils/codec.js.map +1 -1
- package/dist/utils/logger.d.ts.map +1 -1
- package/dist/utils/logger.js +1 -0
- package/dist/utils/logger.js.map +1 -1
- package/dist/utils/python.d.ts.map +1 -1
- package/dist/utils/python.js.map +1 -1
- package/package.json +11 -2
- package/runtime/python_bridge.py +450 -69
- package/src/cli.ts +75 -3
- package/src/config/index.ts +58 -15
- package/src/core/generator.ts +6 -2
- package/src/core/mapper.ts +16 -4
- package/src/index.ts +2 -1
- package/src/runtime/bridge-core.ts +454 -0
- package/src/runtime/node.ts +725 -253
- package/src/runtime/optimized-node.ts +19 -844
- package/src/runtime/timed-out-request-tracker.ts +58 -0
- package/src/types/index.ts +3 -0
- package/src/tywrap.ts +91 -36
- package/src/utils/codec.ts +299 -82
- package/src/utils/logger.ts +1 -0
- package/src/utils/python.ts +0 -1
|
@@ -1,630 +1,22 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
2
|
+
* @deprecated Import from './node.js' instead.
|
|
3
|
+
*
|
|
4
|
+
* OptimizedNodeBridge has been unified with NodeBridge. The NodeBridge class
|
|
5
|
+
* now supports both single-process mode (default) and multi-process pooling
|
|
6
|
+
* via the minProcesses/maxProcesses options.
|
|
7
|
+
*
|
|
8
|
+
* Migration:
|
|
9
|
+
* ```typescript
|
|
10
|
+
* // Before
|
|
11
|
+
* import { OptimizedNodeBridge, ProcessPoolOptions } from './optimized-node.js';
|
|
12
|
+
* const bridge = new OptimizedNodeBridge({ minProcesses: 2, maxProcesses: 4 });
|
|
13
|
+
*
|
|
14
|
+
* // After
|
|
15
|
+
* import { NodeBridge, NodeBridgeOptions } from './node.js';
|
|
16
|
+
* const bridge = new NodeBridge({ minProcesses: 2, maxProcesses: 4 });
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* This file is maintained for backward compatibility only.
|
|
4
20
|
*/
|
|
5
|
-
|
|
6
|
-
import { fileURLToPath } from 'node:url';
|
|
7
|
-
import { EventEmitter } from 'events';
|
|
8
|
-
import { globalCache } from '../utils/cache.js';
|
|
9
|
-
import { decodeValueAsync } from '../utils/codec.js';
|
|
10
|
-
import { getDefaultPythonPath } from '../utils/python.js';
|
|
11
|
-
import { getVenvBinDir, getVenvPythonExe } from '../utils/runtime.js';
|
|
12
|
-
import { RuntimeBridge } from './base.js';
|
|
13
|
-
import { BridgeExecutionError, BridgeProtocolError } from './errors.js';
|
|
14
|
-
import { TYWRAP_PROTOCOL } from './protocol.js';
|
|
15
|
-
import { getComponentLogger } from '../utils/logger.js';
|
|
16
|
-
const log = getComponentLogger('OptimizedBridge');
|
|
17
|
-
function resolveDefaultScriptPath() {
|
|
18
|
-
try {
|
|
19
|
-
return fileURLToPath(new URL('../../runtime/python_bridge.py', import.meta.url));
|
|
20
|
-
}
|
|
21
|
-
catch {
|
|
22
|
-
return 'runtime/python_bridge.py';
|
|
23
|
-
}
|
|
24
|
-
}
|
|
25
|
-
function resolveVirtualEnv(virtualEnv, cwd) {
|
|
26
|
-
const venvPath = resolve(cwd, virtualEnv);
|
|
27
|
-
const binDir = join(venvPath, getVenvBinDir());
|
|
28
|
-
const pythonPath = join(binDir, getVenvPythonExe());
|
|
29
|
-
return { venvPath, binDir, pythonPath };
|
|
30
|
-
}
|
|
31
|
-
export class OptimizedNodeBridge extends RuntimeBridge {
|
|
32
|
-
processPool = [];
|
|
33
|
-
roundRobinIndex = 0;
|
|
34
|
-
nextId = 1;
|
|
35
|
-
cleanupTimer;
|
|
36
|
-
options;
|
|
37
|
-
emitter = new EventEmitter();
|
|
38
|
-
disposed = false;
|
|
39
|
-
// Performance monitoring
|
|
40
|
-
stats = {
|
|
41
|
-
totalRequests: 0,
|
|
42
|
-
totalTime: 0,
|
|
43
|
-
cacheHits: 0,
|
|
44
|
-
poolHits: 0,
|
|
45
|
-
poolMisses: 0,
|
|
46
|
-
processSpawns: 0,
|
|
47
|
-
processDeaths: 0,
|
|
48
|
-
memoryPeak: 0,
|
|
49
|
-
averageTime: 0,
|
|
50
|
-
cacheHitRate: 0,
|
|
51
|
-
};
|
|
52
|
-
constructor(options = {}) {
|
|
53
|
-
super();
|
|
54
|
-
const cwd = options.cwd ?? process.cwd();
|
|
55
|
-
const virtualEnv = options.virtualEnv ? resolve(cwd, options.virtualEnv) : '';
|
|
56
|
-
const venv = virtualEnv ? resolveVirtualEnv(virtualEnv, cwd) : undefined;
|
|
57
|
-
const scriptPath = options.scriptPath ?? resolveDefaultScriptPath();
|
|
58
|
-
const resolvedScriptPath = isAbsolute(scriptPath) ? scriptPath : resolve(cwd, scriptPath);
|
|
59
|
-
this.options = {
|
|
60
|
-
minProcesses: options.minProcesses ?? 2,
|
|
61
|
-
maxProcesses: options.maxProcesses ?? 8,
|
|
62
|
-
maxIdleTime: options.maxIdleTime ?? 300000, // 5 minutes
|
|
63
|
-
maxRequestsPerProcess: options.maxRequestsPerProcess ?? 1000,
|
|
64
|
-
pythonPath: options.pythonPath ?? venv?.pythonPath ?? getDefaultPythonPath(),
|
|
65
|
-
scriptPath: resolvedScriptPath,
|
|
66
|
-
virtualEnv,
|
|
67
|
-
cwd,
|
|
68
|
-
timeoutMs: options.timeoutMs ?? 30000,
|
|
69
|
-
enableJsonFallback: options.enableJsonFallback ?? false,
|
|
70
|
-
env: options.env ?? {},
|
|
71
|
-
warmupCommands: options.warmupCommands ?? [],
|
|
72
|
-
};
|
|
73
|
-
// Start with minimum processes
|
|
74
|
-
this.startCleanupScheduler();
|
|
75
|
-
}
|
|
76
|
-
async init() {
|
|
77
|
-
if (this.disposed) {
|
|
78
|
-
throw new Error('Bridge has been disposed');
|
|
79
|
-
}
|
|
80
|
-
// Ensure minimum processes are available
|
|
81
|
-
while (this.processPool.length < this.options.minProcesses) {
|
|
82
|
-
await this.spawnProcess();
|
|
83
|
-
}
|
|
84
|
-
// Warm up processes if configured
|
|
85
|
-
if (this.options.warmupCommands.length > 0) {
|
|
86
|
-
await this.warmupProcesses();
|
|
87
|
-
}
|
|
88
|
-
}
|
|
89
|
-
async call(module, functionName, args, kwargs) {
|
|
90
|
-
const startTime = performance.now();
|
|
91
|
-
// Try cache first for pure functions
|
|
92
|
-
const cacheKey = globalCache.generateKey('runtime_call', module, functionName, args, kwargs);
|
|
93
|
-
const cached = await globalCache.get(cacheKey);
|
|
94
|
-
if (cached !== null) {
|
|
95
|
-
this.stats.cacheHits++;
|
|
96
|
-
// Runtime cache HIT for ${module}.${functionName}
|
|
97
|
-
return cached;
|
|
98
|
-
}
|
|
99
|
-
try {
|
|
100
|
-
const result = await this.executeRequest({
|
|
101
|
-
method: 'call',
|
|
102
|
-
params: { module, functionName, args, kwargs },
|
|
103
|
-
});
|
|
104
|
-
const duration = performance.now() - startTime;
|
|
105
|
-
// Cache result for pure functions (simple heuristic)
|
|
106
|
-
if (this.isPureFunctionCandidate(functionName, args)) {
|
|
107
|
-
await globalCache.set(cacheKey, result, {
|
|
108
|
-
computeTime: duration,
|
|
109
|
-
dependencies: [module],
|
|
110
|
-
});
|
|
111
|
-
}
|
|
112
|
-
this.updateStats(duration);
|
|
113
|
-
return result;
|
|
114
|
-
}
|
|
115
|
-
catch (error) {
|
|
116
|
-
this.updateStats(performance.now() - startTime, true);
|
|
117
|
-
throw error;
|
|
118
|
-
}
|
|
119
|
-
}
|
|
120
|
-
async instantiate(module, className, args, kwargs) {
|
|
121
|
-
const startTime = performance.now();
|
|
122
|
-
try {
|
|
123
|
-
const result = await this.executeRequest({
|
|
124
|
-
method: 'instantiate',
|
|
125
|
-
params: { module, className, args, kwargs },
|
|
126
|
-
});
|
|
127
|
-
this.updateStats(performance.now() - startTime);
|
|
128
|
-
return result;
|
|
129
|
-
}
|
|
130
|
-
catch (error) {
|
|
131
|
-
this.updateStats(performance.now() - startTime, true);
|
|
132
|
-
throw error;
|
|
133
|
-
}
|
|
134
|
-
}
|
|
135
|
-
async callMethod(handle, methodName, args, kwargs) {
|
|
136
|
-
const startTime = performance.now();
|
|
137
|
-
try {
|
|
138
|
-
const result = await this.executeRequest({
|
|
139
|
-
method: 'call_method',
|
|
140
|
-
params: { handle, methodName, args, kwargs },
|
|
141
|
-
});
|
|
142
|
-
this.updateStats(performance.now() - startTime);
|
|
143
|
-
return result;
|
|
144
|
-
}
|
|
145
|
-
catch (error) {
|
|
146
|
-
this.updateStats(performance.now() - startTime, true);
|
|
147
|
-
throw error;
|
|
148
|
-
}
|
|
149
|
-
}
|
|
150
|
-
async disposeInstance(handle) {
|
|
151
|
-
await this.executeRequest({
|
|
152
|
-
method: 'dispose_instance',
|
|
153
|
-
params: { handle },
|
|
154
|
-
});
|
|
155
|
-
}
|
|
156
|
-
/**
|
|
157
|
-
* Execute request with intelligent process selection
|
|
158
|
-
*/
|
|
159
|
-
async executeRequest(payload) {
|
|
160
|
-
let worker = this.selectOptimalWorker();
|
|
161
|
-
// Spawn new process if none available and under limit
|
|
162
|
-
if (!worker && this.processPool.length < this.options.maxProcesses) {
|
|
163
|
-
try {
|
|
164
|
-
worker = await this.spawnProcess();
|
|
165
|
-
this.stats.poolMisses++;
|
|
166
|
-
}
|
|
167
|
-
catch (error) {
|
|
168
|
-
throw new Error(`Failed to spawn worker process: ${error}`);
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
// Wait for worker if all are busy
|
|
172
|
-
worker ??= await this.waitForAvailableWorker();
|
|
173
|
-
this.stats.poolHits++;
|
|
174
|
-
return this.sendToWorker(worker, payload);
|
|
175
|
-
}
|
|
176
|
-
/**
|
|
177
|
-
* Select optimal worker based on load and performance
|
|
178
|
-
*/
|
|
179
|
-
selectOptimalWorker() {
|
|
180
|
-
const availableWorkers = this.processPool.filter(w => !w.busy && w.process.connected);
|
|
181
|
-
if (availableWorkers.length === 0) {
|
|
182
|
-
return null;
|
|
183
|
-
}
|
|
184
|
-
// Simple round-robin for now, could be enhanced with load-based selection
|
|
185
|
-
const worker = availableWorkers[this.roundRobinIndex % availableWorkers.length];
|
|
186
|
-
this.roundRobinIndex = (this.roundRobinIndex + 1) % availableWorkers.length;
|
|
187
|
-
return worker ?? null;
|
|
188
|
-
}
|
|
189
|
-
/**
|
|
190
|
-
* Wait for any worker to become available
|
|
191
|
-
*/
|
|
192
|
-
async waitForAvailableWorker(timeoutMs = 5000) {
|
|
193
|
-
return new Promise((resolvePromise, reject) => {
|
|
194
|
-
const timeout = setTimeout(() => {
|
|
195
|
-
reject(new Error('Timeout waiting for available worker'));
|
|
196
|
-
}, timeoutMs);
|
|
197
|
-
const checkWorker = () => {
|
|
198
|
-
const worker = this.selectOptimalWorker();
|
|
199
|
-
if (worker) {
|
|
200
|
-
clearTimeout(timeout);
|
|
201
|
-
resolvePromise(worker);
|
|
202
|
-
}
|
|
203
|
-
else {
|
|
204
|
-
// Check again in 10ms
|
|
205
|
-
setTimeout(checkWorker, 10);
|
|
206
|
-
}
|
|
207
|
-
};
|
|
208
|
-
checkWorker();
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
/**
|
|
212
|
-
* Send request to specific worker
|
|
213
|
-
*/
|
|
214
|
-
async sendToWorker(worker, payload) {
|
|
215
|
-
const id = this.nextId++;
|
|
216
|
-
const message = { id, protocol: TYWRAP_PROTOCOL, ...payload };
|
|
217
|
-
const text = `${JSON.stringify(message)}\n`;
|
|
218
|
-
worker.busy = true;
|
|
219
|
-
worker.requestCount++;
|
|
220
|
-
worker.lastUsed = Date.now();
|
|
221
|
-
return new Promise((resolvePromise, reject) => {
|
|
222
|
-
const startTime = performance.now();
|
|
223
|
-
const timer = setTimeout(() => {
|
|
224
|
-
worker.pendingRequests.delete(id);
|
|
225
|
-
worker.busy = false;
|
|
226
|
-
reject(new Error(`Request ${id} timed out after ${this.options.timeoutMs}ms`));
|
|
227
|
-
}, this.options.timeoutMs);
|
|
228
|
-
worker.pendingRequests.set(id, {
|
|
229
|
-
resolve: (value) => {
|
|
230
|
-
const duration = performance.now() - startTime;
|
|
231
|
-
worker.stats.totalTime += duration;
|
|
232
|
-
worker.stats.totalRequests++;
|
|
233
|
-
worker.stats.averageTime = worker.stats.totalTime / worker.stats.totalRequests;
|
|
234
|
-
worker.busy = false;
|
|
235
|
-
resolvePromise(value);
|
|
236
|
-
},
|
|
237
|
-
reject: (error) => {
|
|
238
|
-
worker.stats.errorCount++;
|
|
239
|
-
worker.busy = false;
|
|
240
|
-
reject(error);
|
|
241
|
-
},
|
|
242
|
-
timer,
|
|
243
|
-
startTime,
|
|
244
|
-
});
|
|
245
|
-
if (!worker.process.stdin?.writable) {
|
|
246
|
-
worker.pendingRequests.delete(id);
|
|
247
|
-
worker.busy = false;
|
|
248
|
-
clearTimeout(timer);
|
|
249
|
-
reject(new Error('Worker process stdin not writable'));
|
|
250
|
-
return;
|
|
251
|
-
}
|
|
252
|
-
try {
|
|
253
|
-
worker.process.stdin.write(text);
|
|
254
|
-
}
|
|
255
|
-
catch (error) {
|
|
256
|
-
worker.pendingRequests.delete(id);
|
|
257
|
-
worker.busy = false;
|
|
258
|
-
clearTimeout(timer);
|
|
259
|
-
reject(error);
|
|
260
|
-
}
|
|
261
|
-
});
|
|
262
|
-
}
|
|
263
|
-
/**
|
|
264
|
-
* Spawn new worker process with optimizations
|
|
265
|
-
*/
|
|
266
|
-
async spawnProcess() {
|
|
267
|
-
const { spawn } = await import('child_process');
|
|
268
|
-
const workerId = `worker_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
|
|
269
|
-
const env = {
|
|
270
|
-
...process.env,
|
|
271
|
-
...this.options.env,
|
|
272
|
-
PYTHONUNBUFFERED: '1', // Ensure immediate output
|
|
273
|
-
PYTHONDONTWRITEBYTECODE: '1', // Skip .pyc files for faster startup
|
|
274
|
-
};
|
|
275
|
-
if (!env.PYTHONUTF8) {
|
|
276
|
-
env.PYTHONUTF8 = '1';
|
|
277
|
-
}
|
|
278
|
-
if (!env.PYTHONIOENCODING) {
|
|
279
|
-
env.PYTHONIOENCODING = 'UTF-8';
|
|
280
|
-
}
|
|
281
|
-
if (this.options.virtualEnv) {
|
|
282
|
-
const venv = resolveVirtualEnv(this.options.virtualEnv, this.options.cwd);
|
|
283
|
-
env.VIRTUAL_ENV = venv.venvPath;
|
|
284
|
-
env.PATH = `${venv.binDir}${delimiter}${env.PATH ?? ''}`;
|
|
285
|
-
}
|
|
286
|
-
if (this.options.enableJsonFallback && !env.TYWRAP_CODEC_FALLBACK) {
|
|
287
|
-
env.TYWRAP_CODEC_FALLBACK = 'json';
|
|
288
|
-
}
|
|
289
|
-
const childProcess = spawn(this.options.pythonPath, [this.options.scriptPath], {
|
|
290
|
-
cwd: this.options.cwd,
|
|
291
|
-
stdio: ['pipe', 'pipe', 'pipe'],
|
|
292
|
-
env,
|
|
293
|
-
});
|
|
294
|
-
const worker = {
|
|
295
|
-
process: childProcess,
|
|
296
|
-
id: workerId,
|
|
297
|
-
requestCount: 0,
|
|
298
|
-
lastUsed: Date.now(),
|
|
299
|
-
busy: false,
|
|
300
|
-
buffer: '',
|
|
301
|
-
pendingRequests: new Map(),
|
|
302
|
-
stats: {
|
|
303
|
-
totalRequests: 0,
|
|
304
|
-
totalTime: 0,
|
|
305
|
-
averageTime: 0,
|
|
306
|
-
errorCount: 0,
|
|
307
|
-
},
|
|
308
|
-
};
|
|
309
|
-
// Setup process event handlers
|
|
310
|
-
this.setupProcessHandlers(worker);
|
|
311
|
-
this.processPool.push(worker);
|
|
312
|
-
this.stats.processSpawns++;
|
|
313
|
-
// Spawned Python worker process ${workerId} (pool size: ${this.processPool.length})
|
|
314
|
-
return worker;
|
|
315
|
-
}
|
|
316
|
-
/**
|
|
317
|
-
* Setup event handlers for worker process
|
|
318
|
-
*/
|
|
319
|
-
setupProcessHandlers(worker) {
|
|
320
|
-
const childProcess = worker.process;
|
|
321
|
-
// Handle stdout data with efficient buffering
|
|
322
|
-
childProcess.stdout?.on('data', (chunk) => {
|
|
323
|
-
worker.buffer += chunk.toString();
|
|
324
|
-
let idx;
|
|
325
|
-
while ((idx = worker.buffer.indexOf('\n')) !== -1) {
|
|
326
|
-
const line = worker.buffer.slice(0, idx).trim();
|
|
327
|
-
worker.buffer = worker.buffer.slice(idx + 1);
|
|
328
|
-
if (!line) {
|
|
329
|
-
continue;
|
|
330
|
-
}
|
|
331
|
-
this.handleWorkerResponse(worker, line).catch(error => {
|
|
332
|
-
log.error('Error handling worker response', {
|
|
333
|
-
workerId: worker.id,
|
|
334
|
-
error: String(error),
|
|
335
|
-
});
|
|
336
|
-
});
|
|
337
|
-
}
|
|
338
|
-
});
|
|
339
|
-
// Handle stderr for debugging
|
|
340
|
-
childProcess.stderr?.on('data', (chunk) => {
|
|
341
|
-
const errorText = chunk.toString().trim();
|
|
342
|
-
if (errorText) {
|
|
343
|
-
log.warn('Worker stderr', { workerId: worker.id, output: errorText });
|
|
344
|
-
}
|
|
345
|
-
});
|
|
346
|
-
// Handle process exit
|
|
347
|
-
childProcess.on('exit', code => {
|
|
348
|
-
log.warn('Worker exited', { workerId: worker.id, code });
|
|
349
|
-
this.handleWorkerExit(worker, code);
|
|
350
|
-
});
|
|
351
|
-
// Handle process errors
|
|
352
|
-
childProcess.on('error', error => {
|
|
353
|
-
log.error('Worker error', { workerId: worker.id, error: String(error) });
|
|
354
|
-
this.handleWorkerExit(worker, -1);
|
|
355
|
-
});
|
|
356
|
-
}
|
|
357
|
-
/**
|
|
358
|
-
* Handle response from worker process
|
|
359
|
-
*/
|
|
360
|
-
async handleWorkerResponse(worker, line) {
|
|
361
|
-
try {
|
|
362
|
-
const msg = JSON.parse(line);
|
|
363
|
-
if (msg.protocol !== TYWRAP_PROTOCOL) {
|
|
364
|
-
this.handleProtocolError(worker, line, new BridgeProtocolError(`Invalid protocol. Expected ${TYWRAP_PROTOCOL} but received ${String(msg.protocol)}`));
|
|
365
|
-
return;
|
|
366
|
-
}
|
|
367
|
-
if (typeof msg.id !== 'number') {
|
|
368
|
-
this.handleProtocolError(worker, line, new BridgeProtocolError('Invalid response id'));
|
|
369
|
-
return;
|
|
370
|
-
}
|
|
371
|
-
const pending = worker.pendingRequests.get(msg.id);
|
|
372
|
-
if (!pending) {
|
|
373
|
-
this.handleProtocolError(worker, line, new BridgeProtocolError(`Unexpected response id ${msg.id}`));
|
|
374
|
-
return;
|
|
375
|
-
}
|
|
376
|
-
worker.pendingRequests.delete(msg.id);
|
|
377
|
-
if (pending.timer) {
|
|
378
|
-
clearTimeout(pending.timer);
|
|
379
|
-
}
|
|
380
|
-
if (msg.error) {
|
|
381
|
-
pending.reject(this.errorFrom(msg.error));
|
|
382
|
-
}
|
|
383
|
-
else {
|
|
384
|
-
try {
|
|
385
|
-
const decoded = await decodeValueAsync(msg.result);
|
|
386
|
-
pending.resolve(decoded);
|
|
387
|
-
}
|
|
388
|
-
catch (decodeError) {
|
|
389
|
-
pending.reject(new BridgeProtocolError(`Failed to decode response: ${decodeError}`));
|
|
390
|
-
}
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
catch (parseError) {
|
|
394
|
-
this.handleProtocolError(worker, line, parseError);
|
|
395
|
-
}
|
|
396
|
-
}
|
|
397
|
-
/**
|
|
398
|
-
* Handle worker process exit
|
|
399
|
-
*/
|
|
400
|
-
handleWorkerExit(worker, code) {
|
|
401
|
-
// Reject all pending requests
|
|
402
|
-
for (const [, pending] of worker.pendingRequests) {
|
|
403
|
-
if (pending.timer) {
|
|
404
|
-
clearTimeout(pending.timer);
|
|
405
|
-
}
|
|
406
|
-
pending.reject(new Error(`Worker process exited with code ${code}`));
|
|
407
|
-
}
|
|
408
|
-
worker.pendingRequests.clear();
|
|
409
|
-
// Remove from pool
|
|
410
|
-
const index = this.processPool.indexOf(worker);
|
|
411
|
-
if (index >= 0) {
|
|
412
|
-
this.processPool.splice(index, 1);
|
|
413
|
-
this.stats.processDeaths++;
|
|
414
|
-
}
|
|
415
|
-
// Spawn replacement if needed and not disposing
|
|
416
|
-
if (!this.disposed && this.processPool.length < this.options.minProcesses) {
|
|
417
|
-
this.spawnProcess().catch(error => {
|
|
418
|
-
log.error('Failed to spawn replacement worker', { error: String(error) });
|
|
419
|
-
});
|
|
420
|
-
}
|
|
421
|
-
}
|
|
422
|
-
/**
|
|
423
|
-
* Warm up processes with configured commands
|
|
424
|
-
*/
|
|
425
|
-
async warmupProcesses() {
|
|
426
|
-
const warmupPromises = this.processPool.map(async (worker) => {
|
|
427
|
-
for (const cmd of this.options.warmupCommands) {
|
|
428
|
-
try {
|
|
429
|
-
await this.sendToWorker(worker, {
|
|
430
|
-
method: cmd.method,
|
|
431
|
-
params: cmd.params,
|
|
432
|
-
});
|
|
433
|
-
}
|
|
434
|
-
catch (error) {
|
|
435
|
-
log.warn('Warmup command failed', { workerId: worker.id, error: String(error) });
|
|
436
|
-
}
|
|
437
|
-
}
|
|
438
|
-
});
|
|
439
|
-
await Promise.all(warmupPromises);
|
|
440
|
-
// Warmed up ${this.processPool.length} worker processes
|
|
441
|
-
}
|
|
442
|
-
/**
|
|
443
|
-
* Heuristic to determine if function result should be cached
|
|
444
|
-
*/
|
|
445
|
-
isPureFunctionCandidate(functionName, args) {
|
|
446
|
-
// Simple heuristics - could be made more sophisticated
|
|
447
|
-
const pureFunctionPatterns = [
|
|
448
|
-
/^(get|fetch|read|load|find|search|query|select)_/i,
|
|
449
|
-
/^(compute|calculate|process|transform|convert)_/i,
|
|
450
|
-
/^(encode|decode|serialize|deserialize)_/i,
|
|
451
|
-
];
|
|
452
|
-
const impureFunctionPatterns = [
|
|
453
|
-
/^(set|save|write|update|insert|delete|create|modify)_/i,
|
|
454
|
-
/^(send|post|put|patch)_/i,
|
|
455
|
-
/random|uuid|timestamp|now|current/i,
|
|
456
|
-
];
|
|
457
|
-
// Don't cache if function name suggests mutation
|
|
458
|
-
if (impureFunctionPatterns.some(pattern => pattern.test(functionName))) {
|
|
459
|
-
return false;
|
|
460
|
-
}
|
|
461
|
-
// Cache if function name suggests pure computation
|
|
462
|
-
if (pureFunctionPatterns.some(pattern => pattern.test(functionName))) {
|
|
463
|
-
return true;
|
|
464
|
-
}
|
|
465
|
-
// Don't cache if args contain mutable objects (very basic check)
|
|
466
|
-
const hasComplexArgs = args.some(arg => arg !== null && typeof arg === 'object' && !(arg instanceof Date));
|
|
467
|
-
return !hasComplexArgs && args.length <= 3; // Cache simple calls with few args
|
|
468
|
-
}
|
|
469
|
-
/**
|
|
470
|
-
* Update performance statistics
|
|
471
|
-
*/
|
|
472
|
-
updateStats(duration, _error = false) {
|
|
473
|
-
this.stats.totalRequests++;
|
|
474
|
-
this.stats.totalTime += duration;
|
|
475
|
-
const currentMemory = process.memoryUsage().heapUsed;
|
|
476
|
-
if (currentMemory > this.stats.memoryPeak) {
|
|
477
|
-
this.stats.memoryPeak = currentMemory;
|
|
478
|
-
}
|
|
479
|
-
}
|
|
480
|
-
/**
|
|
481
|
-
* Get performance statistics
|
|
482
|
-
*/
|
|
483
|
-
getStats() {
|
|
484
|
-
const avgTime = this.stats.totalRequests > 0 ? this.stats.totalTime / this.stats.totalRequests : 0;
|
|
485
|
-
const hitRate = this.stats.totalRequests > 0 ? this.stats.cacheHits / this.stats.totalRequests : 0;
|
|
486
|
-
return {
|
|
487
|
-
...this.stats,
|
|
488
|
-
averageTime: avgTime,
|
|
489
|
-
cacheHitRate: hitRate,
|
|
490
|
-
poolSize: this.processPool.length,
|
|
491
|
-
busyWorkers: this.processPool.filter(w => w.busy).length,
|
|
492
|
-
memoryUsage: process.memoryUsage(),
|
|
493
|
-
workerStats: this.processPool.map(w => ({
|
|
494
|
-
id: w.id,
|
|
495
|
-
requestCount: w.requestCount,
|
|
496
|
-
averageTime: w.stats.averageTime,
|
|
497
|
-
errorCount: w.stats.errorCount,
|
|
498
|
-
busy: w.busy,
|
|
499
|
-
pendingRequests: w.pendingRequests.size,
|
|
500
|
-
})),
|
|
501
|
-
};
|
|
502
|
-
}
|
|
503
|
-
/**
|
|
504
|
-
* Cleanup idle processes
|
|
505
|
-
*/
|
|
506
|
-
async cleanup() {
|
|
507
|
-
const now = Date.now();
|
|
508
|
-
const idleWorkers = this.processPool.filter(w => !w.busy &&
|
|
509
|
-
now - w.lastUsed > this.options.maxIdleTime &&
|
|
510
|
-
this.processPool.length > this.options.minProcesses);
|
|
511
|
-
for (const worker of idleWorkers) {
|
|
512
|
-
await this.terminateWorker(worker);
|
|
513
|
-
}
|
|
514
|
-
// Restart workers that have handled too many requests
|
|
515
|
-
const overusedWorkers = this.processPool.filter(w => !w.busy && w.requestCount >= this.options.maxRequestsPerProcess);
|
|
516
|
-
for (const worker of overusedWorkers) {
|
|
517
|
-
await this.terminateWorker(worker);
|
|
518
|
-
if (this.processPool.length < this.options.minProcesses) {
|
|
519
|
-
await this.spawnProcess();
|
|
520
|
-
}
|
|
521
|
-
}
|
|
522
|
-
}
|
|
523
|
-
/**
|
|
524
|
-
* Gracefully terminate a worker
|
|
525
|
-
*/
|
|
526
|
-
async terminateWorker(worker) {
|
|
527
|
-
const index = this.processPool.indexOf(worker);
|
|
528
|
-
if (index >= 0) {
|
|
529
|
-
this.processPool.splice(index, 1);
|
|
530
|
-
}
|
|
531
|
-
// Reject pending requests
|
|
532
|
-
for (const [, pending] of worker.pendingRequests) {
|
|
533
|
-
if (pending.timer) {
|
|
534
|
-
clearTimeout(pending.timer);
|
|
535
|
-
}
|
|
536
|
-
pending.reject(new Error('Worker process terminated'));
|
|
537
|
-
}
|
|
538
|
-
// Graceful termination
|
|
539
|
-
try {
|
|
540
|
-
if (worker.process.connected) {
|
|
541
|
-
worker.process.kill('SIGTERM');
|
|
542
|
-
// Force kill if not terminated in 5 seconds
|
|
543
|
-
setTimeout(() => {
|
|
544
|
-
if (!worker.process.killed) {
|
|
545
|
-
worker.process.kill('SIGKILL');
|
|
546
|
-
}
|
|
547
|
-
}, 5000);
|
|
548
|
-
}
|
|
549
|
-
}
|
|
550
|
-
catch (error) {
|
|
551
|
-
log.warn('Error terminating worker', { workerId: worker.id, error: String(error) });
|
|
552
|
-
}
|
|
553
|
-
// Terminated worker ${worker.id}
|
|
554
|
-
}
|
|
555
|
-
/**
|
|
556
|
-
* Start cleanup scheduler
|
|
557
|
-
*/
|
|
558
|
-
startCleanupScheduler() {
|
|
559
|
-
this.cleanupTimer = setInterval(async () => {
|
|
560
|
-
try {
|
|
561
|
-
await this.cleanup();
|
|
562
|
-
}
|
|
563
|
-
catch (error) {
|
|
564
|
-
log.error('Cleanup error', { error: String(error) });
|
|
565
|
-
}
|
|
566
|
-
}, 60000); // Cleanup every minute
|
|
567
|
-
}
|
|
568
|
-
/**
|
|
569
|
-
* Dispose all resources
|
|
570
|
-
*/
|
|
571
|
-
async dispose() {
|
|
572
|
-
if (this.disposed) {
|
|
573
|
-
return;
|
|
574
|
-
}
|
|
575
|
-
this.disposed = true;
|
|
576
|
-
if (this.cleanupTimer) {
|
|
577
|
-
clearInterval(this.cleanupTimer);
|
|
578
|
-
this.cleanupTimer = undefined;
|
|
579
|
-
}
|
|
580
|
-
// Terminate all workers
|
|
581
|
-
const terminationPromises = this.processPool.map(worker => this.terminateWorker(worker));
|
|
582
|
-
await Promise.all(terminationPromises);
|
|
583
|
-
this.processPool.length = 0;
|
|
584
|
-
this.emitter.removeAllListeners();
|
|
585
|
-
// Disposed optimized Node.js bridge
|
|
586
|
-
}
|
|
587
|
-
errorFrom(err) {
|
|
588
|
-
const e = new BridgeExecutionError(`${err.type}: ${err.message}`);
|
|
589
|
-
e.traceback = err.traceback;
|
|
590
|
-
return e;
|
|
591
|
-
}
|
|
592
|
-
handleProtocolError(worker, line, error) {
|
|
593
|
-
const snippet = line.length > 500 ? `${line.slice(0, 500)}…` : line;
|
|
594
|
-
const detail = error instanceof Error ? error.message : String(error);
|
|
595
|
-
const hint = 'Ensure your Python code does not print to stdout and that the bridge outputs only JSON lines.';
|
|
596
|
-
const msg = `Protocol error from Python bridge. ${detail}\n${hint}\nOffending line: ${snippet}`;
|
|
597
|
-
const bridgeError = new BridgeProtocolError(msg);
|
|
598
|
-
for (const [, pending] of worker.pendingRequests) {
|
|
599
|
-
if (pending.timer) {
|
|
600
|
-
clearTimeout(pending.timer);
|
|
601
|
-
}
|
|
602
|
-
pending.reject(bridgeError);
|
|
603
|
-
}
|
|
604
|
-
worker.pendingRequests.clear();
|
|
605
|
-
try {
|
|
606
|
-
if (worker.process.connected) {
|
|
607
|
-
worker.process.kill('SIGTERM');
|
|
608
|
-
}
|
|
609
|
-
}
|
|
610
|
-
catch (killError) {
|
|
611
|
-
log.warn('Error terminating worker after protocol error', {
|
|
612
|
-
workerId: worker.id,
|
|
613
|
-
error: String(killError),
|
|
614
|
-
});
|
|
615
|
-
}
|
|
616
|
-
const index = this.processPool.indexOf(worker);
|
|
617
|
-
if (index >= 0) {
|
|
618
|
-
this.processPool.splice(index, 1);
|
|
619
|
-
this.stats.processDeaths++;
|
|
620
|
-
}
|
|
621
|
-
if (!this.disposed && this.processPool.length < this.options.minProcesses) {
|
|
622
|
-
this.spawnProcess().catch(spawnError => {
|
|
623
|
-
log.error('Failed to spawn replacement worker after protocol error', {
|
|
624
|
-
error: String(spawnError),
|
|
625
|
-
});
|
|
626
|
-
});
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
}
|
|
21
|
+
export { NodeBridge as OptimizedNodeBridge } from './node.js';
|
|
630
22
|
//# sourceMappingURL=optimized-node.js.map
|