tywrap 0.1.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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +319 -0
  3. package/dist/cli.d.ts +3 -0
  4. package/dist/cli.d.ts.map +1 -0
  5. package/dist/cli.js +263 -0
  6. package/dist/cli.js.map +1 -0
  7. package/dist/config/index.d.ts +41 -0
  8. package/dist/config/index.d.ts.map +1 -0
  9. package/dist/config/index.js +234 -0
  10. package/dist/config/index.js.map +1 -0
  11. package/dist/core/analyzer.d.ts +63 -0
  12. package/dist/core/analyzer.d.ts.map +1 -0
  13. package/dist/core/analyzer.js +676 -0
  14. package/dist/core/analyzer.js.map +1 -0
  15. package/dist/core/discovery.d.ts +85 -0
  16. package/dist/core/discovery.d.ts.map +1 -0
  17. package/dist/core/discovery.js +344 -0
  18. package/dist/core/discovery.js.map +1 -0
  19. package/dist/core/generator.d.ts +37 -0
  20. package/dist/core/generator.d.ts.map +1 -0
  21. package/dist/core/generator.js +368 -0
  22. package/dist/core/generator.js.map +1 -0
  23. package/dist/core/mapper.d.ts +40 -0
  24. package/dist/core/mapper.d.ts.map +1 -0
  25. package/dist/core/mapper.js +401 -0
  26. package/dist/core/mapper.js.map +1 -0
  27. package/dist/core/validation.d.ts +79 -0
  28. package/dist/core/validation.d.ts.map +1 -0
  29. package/dist/core/validation.js +486 -0
  30. package/dist/core/validation.js.map +1 -0
  31. package/dist/index.d.ts +26 -0
  32. package/dist/index.d.ts.map +1 -0
  33. package/dist/index.js +29 -0
  34. package/dist/index.js.map +1 -0
  35. package/dist/runtime/base.d.ts +12 -0
  36. package/dist/runtime/base.d.ts.map +1 -0
  37. package/dist/runtime/base.js +6 -0
  38. package/dist/runtime/base.js.map +1 -0
  39. package/dist/runtime/errors.d.ts +17 -0
  40. package/dist/runtime/errors.d.ts.map +1 -0
  41. package/dist/runtime/errors.js +21 -0
  42. package/dist/runtime/errors.js.map +1 -0
  43. package/dist/runtime/http.d.ts +22 -0
  44. package/dist/runtime/http.d.ts.map +1 -0
  45. package/dist/runtime/http.js +79 -0
  46. package/dist/runtime/http.js.map +1 -0
  47. package/dist/runtime/index.d.ts +8 -0
  48. package/dist/runtime/index.d.ts.map +1 -0
  49. package/dist/runtime/index.js +17 -0
  50. package/dist/runtime/index.js.map +1 -0
  51. package/dist/runtime/node.d.ts +48 -0
  52. package/dist/runtime/node.d.ts.map +1 -0
  53. package/dist/runtime/node.js +328 -0
  54. package/dist/runtime/node.js.map +1 -0
  55. package/dist/runtime/optimized-node.d.ts +131 -0
  56. package/dist/runtime/optimized-node.d.ts.map +1 -0
  57. package/dist/runtime/optimized-node.js +622 -0
  58. package/dist/runtime/optimized-node.js.map +1 -0
  59. package/dist/runtime/protocol.d.ts +3 -0
  60. package/dist/runtime/protocol.d.ts.map +1 -0
  61. package/dist/runtime/protocol.js +3 -0
  62. package/dist/runtime/protocol.js.map +1 -0
  63. package/dist/runtime/pyodide.d.ts +27 -0
  64. package/dist/runtime/pyodide.d.ts.map +1 -0
  65. package/dist/runtime/pyodide.js +191 -0
  66. package/dist/runtime/pyodide.js.map +1 -0
  67. package/dist/tools/python_suite.js +173 -0
  68. package/dist/tools/python_suite.js.map +1 -0
  69. package/dist/types/index.d.ts +299 -0
  70. package/dist/types/index.d.ts.map +1 -0
  71. package/dist/types/index.js +5 -0
  72. package/dist/types/index.js.map +1 -0
  73. package/dist/tywrap.d.ts +29 -0
  74. package/dist/tywrap.d.ts.map +1 -0
  75. package/dist/tywrap.js +589 -0
  76. package/dist/tywrap.js.map +1 -0
  77. package/dist/utils/bundle-optimizer.d.ts +182 -0
  78. package/dist/utils/bundle-optimizer.d.ts.map +1 -0
  79. package/dist/utils/bundle-optimizer.js +680 -0
  80. package/dist/utils/bundle-optimizer.js.map +1 -0
  81. package/dist/utils/cache.d.ts +149 -0
  82. package/dist/utils/cache.d.ts.map +1 -0
  83. package/dist/utils/cache.js +492 -0
  84. package/dist/utils/cache.js.map +1 -0
  85. package/dist/utils/codec.d.ts +94 -0
  86. package/dist/utils/codec.d.ts.map +1 -0
  87. package/dist/utils/codec.js +150 -0
  88. package/dist/utils/codec.js.map +1 -0
  89. package/dist/utils/logger.d.ts +42 -0
  90. package/dist/utils/logger.d.ts.map +1 -0
  91. package/dist/utils/logger.js +140 -0
  92. package/dist/utils/logger.js.map +1 -0
  93. package/dist/utils/memory-profiler.d.ts +123 -0
  94. package/dist/utils/memory-profiler.d.ts.map +1 -0
  95. package/dist/utils/memory-profiler.js +426 -0
  96. package/dist/utils/memory-profiler.js.map +1 -0
  97. package/dist/utils/parallel-processor.d.ts +146 -0
  98. package/dist/utils/parallel-processor.d.ts.map +1 -0
  99. package/dist/utils/parallel-processor.js +636 -0
  100. package/dist/utils/parallel-processor.js.map +1 -0
  101. package/dist/utils/python.d.ts +8 -0
  102. package/dist/utils/python.d.ts.map +1 -0
  103. package/dist/utils/python.js +56 -0
  104. package/dist/utils/python.js.map +1 -0
  105. package/dist/utils/runtime.d.ts +153 -0
  106. package/dist/utils/runtime.d.ts.map +1 -0
  107. package/dist/utils/runtime.js +519 -0
  108. package/dist/utils/runtime.js.map +1 -0
  109. package/package.json +136 -0
  110. package/runtime/python_bridge.py +476 -0
  111. package/src/cli.ts +331 -0
  112. package/src/config/index.ts +289 -0
  113. package/src/core/analyzer.ts +788 -0
  114. package/src/core/discovery.ts +415 -0
  115. package/src/core/generator.ts +447 -0
  116. package/src/core/mapper.ts +504 -0
  117. package/src/core/validation.ts +693 -0
  118. package/src/index.ts +83 -0
  119. package/src/runtime/base.ts +32 -0
  120. package/src/runtime/errors.ts +19 -0
  121. package/src/runtime/http.ts +132 -0
  122. package/src/runtime/index.ts +24 -0
  123. package/src/runtime/node.ts +431 -0
  124. package/src/runtime/optimized-node.ts +838 -0
  125. package/src/runtime/protocol.ts +2 -0
  126. package/src/runtime/pyodide.ts +228 -0
  127. package/src/types/global.d.ts +60 -0
  128. package/src/types/index.ts +410 -0
  129. package/src/tywrap.ts +669 -0
  130. package/src/utils/bundle-optimizer.ts +876 -0
  131. package/src/utils/cache.ts +634 -0
  132. package/src/utils/codec.ts +275 -0
  133. package/src/utils/logger.ts +201 -0
  134. package/src/utils/memory-profiler.ts +582 -0
  135. package/src/utils/parallel-processor.ts +879 -0
  136. package/src/utils/python.ts +79 -0
  137. package/src/utils/runtime.ts +616 -0
@@ -0,0 +1,838 @@
1
+ /**
2
+ * Optimized Node.js Runtime Bridge with Connection Pooling and Memory Management
3
+ * High-performance Python subprocess management for production workloads
4
+ */
5
+
6
+ import { delimiter, isAbsolute, join, resolve } from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
8
+ import type { ChildProcess } from 'child_process';
9
+ import { EventEmitter } from 'events';
10
+
11
+ import { globalCache } from '../utils/cache.js';
12
+ import { decodeValueAsync } from '../utils/codec.js';
13
+ import { getDefaultPythonPath } from '../utils/python.js';
14
+ import { getVenvBinDir, getVenvPythonExe } from '../utils/runtime.js';
15
+
16
+ import { RuntimeBridge } from './base.js';
17
+ import { BridgeExecutionError, BridgeProtocolError } from './errors.js';
18
+ import { TYWRAP_PROTOCOL } from './protocol.js';
19
+ import { getComponentLogger } from '../utils/logger.js';
20
+
21
+ const log = getComponentLogger('OptimizedBridge');
22
+
23
+ interface RpcRequest {
24
+ id: number;
25
+ protocol: string;
26
+ method: 'call' | 'instantiate' | 'call_method' | 'dispose_instance';
27
+ params: unknown;
28
+ }
29
+
30
+ interface RpcResponse<T = unknown> {
31
+ id: number;
32
+ protocol: string;
33
+ result?: T;
34
+ error?: { type: string; message: string; traceback?: string };
35
+ }
36
+
37
+ interface ProcessPoolOptions {
38
+ minProcesses?: number;
39
+ maxProcesses?: number;
40
+ maxIdleTime?: number; // ms to keep idle processes alive
41
+ maxRequestsPerProcess?: number; // restart process after N requests
42
+ pythonPath?: string;
43
+ scriptPath?: string;
44
+ virtualEnv?: string | undefined;
45
+ cwd?: string;
46
+ timeoutMs?: number;
47
+ enableJsonFallback?: boolean;
48
+ env?: Record<string, string | undefined>;
49
+ warmupCommands?: Array<{ method: string; params: unknown }>; // Commands to warm up processes
50
+ }
51
+
52
+ interface WorkerProcess {
53
+ process: ChildProcess;
54
+ id: string;
55
+ requestCount: number;
56
+ lastUsed: number;
57
+ busy: boolean;
58
+ buffer: string;
59
+ pendingRequests: Map<
60
+ number,
61
+ {
62
+ resolve: (value: unknown) => void;
63
+ reject: (error: unknown) => void;
64
+ timer?: NodeJS.Timeout;
65
+ startTime: number;
66
+ }
67
+ >;
68
+ stats: {
69
+ totalRequests: number;
70
+ totalTime: number;
71
+ averageTime: number;
72
+ errorCount: number;
73
+ };
74
+ }
75
+
76
+ interface OptimizedBridgeStats {
77
+ totalRequests: number;
78
+ totalTime: number;
79
+ cacheHits: number;
80
+ poolHits: number;
81
+ poolMisses: number;
82
+ processSpawns: number;
83
+ processDeaths: number;
84
+ memoryPeak: number;
85
+ averageTime: number;
86
+ cacheHitRate: number;
87
+ }
88
+
89
+ interface OptimizedBridgeStatsSnapshot extends OptimizedBridgeStats {
90
+ poolSize: number;
91
+ busyWorkers: number;
92
+ memoryUsage: NodeJS.MemoryUsage;
93
+ workerStats: Array<{
94
+ id: string;
95
+ requestCount: number;
96
+ averageTime: number;
97
+ errorCount: number;
98
+ busy: boolean;
99
+ pendingRequests: number;
100
+ }>;
101
+ }
102
+
103
+ function resolveDefaultScriptPath(): string {
104
+ try {
105
+ return fileURLToPath(new URL('../../runtime/python_bridge.py', import.meta.url));
106
+ } catch {
107
+ return 'runtime/python_bridge.py';
108
+ }
109
+ }
110
+
111
+ function resolveVirtualEnv(
112
+ virtualEnv: string,
113
+ cwd: string
114
+ ): {
115
+ venvPath: string;
116
+ binDir: string;
117
+ pythonPath: string;
118
+ } {
119
+ const venvPath = resolve(cwd, virtualEnv);
120
+ const binDir = join(venvPath, getVenvBinDir());
121
+ const pythonPath = join(binDir, getVenvPythonExe());
122
+ return { venvPath, binDir, pythonPath };
123
+ }
124
+
125
+ export class OptimizedNodeBridge extends RuntimeBridge {
126
+ private processPool: WorkerProcess[] = [];
127
+ private roundRobinIndex = 0;
128
+ private nextId = 1;
129
+ private cleanupTimer?: NodeJS.Timeout;
130
+ private options: Required<ProcessPoolOptions>;
131
+ private emitter = new EventEmitter();
132
+ private disposed = false;
133
+
134
+ // Performance monitoring
135
+ private stats: OptimizedBridgeStats = {
136
+ totalRequests: 0,
137
+ totalTime: 0,
138
+ cacheHits: 0,
139
+ poolHits: 0,
140
+ poolMisses: 0,
141
+ processSpawns: 0,
142
+ processDeaths: 0,
143
+ memoryPeak: 0,
144
+ averageTime: 0,
145
+ cacheHitRate: 0,
146
+ };
147
+
148
+ constructor(options: ProcessPoolOptions = {}) {
149
+ super();
150
+ const cwd = options.cwd ?? process.cwd();
151
+ const virtualEnv = options.virtualEnv ? resolve(cwd, options.virtualEnv) : '';
152
+ const venv = virtualEnv ? resolveVirtualEnv(virtualEnv, cwd) : undefined;
153
+ const scriptPath = options.scriptPath ?? resolveDefaultScriptPath();
154
+ const resolvedScriptPath = isAbsolute(scriptPath) ? scriptPath : resolve(cwd, scriptPath);
155
+ this.options = {
156
+ minProcesses: options.minProcesses ?? 2,
157
+ maxProcesses: options.maxProcesses ?? 8,
158
+ maxIdleTime: options.maxIdleTime ?? 300000, // 5 minutes
159
+ maxRequestsPerProcess: options.maxRequestsPerProcess ?? 1000,
160
+ pythonPath: options.pythonPath ?? venv?.pythonPath ?? getDefaultPythonPath(),
161
+ scriptPath: resolvedScriptPath,
162
+ virtualEnv,
163
+ cwd,
164
+ timeoutMs: options.timeoutMs ?? 30000,
165
+ enableJsonFallback: options.enableJsonFallback ?? false,
166
+ env: options.env ?? {},
167
+ warmupCommands: options.warmupCommands ?? [],
168
+ };
169
+
170
+ // Start with minimum processes
171
+ this.startCleanupScheduler();
172
+ }
173
+
174
+ async init(): Promise<void> {
175
+ if (this.disposed) {
176
+ throw new Error('Bridge has been disposed');
177
+ }
178
+
179
+ // Ensure minimum processes are available
180
+ while (this.processPool.length < this.options.minProcesses) {
181
+ await this.spawnProcess();
182
+ }
183
+
184
+ // Warm up processes if configured
185
+ if (this.options.warmupCommands.length > 0) {
186
+ await this.warmupProcesses();
187
+ }
188
+ }
189
+
190
+ async call<T = unknown>(
191
+ module: string,
192
+ functionName: string,
193
+ args: unknown[],
194
+ kwargs?: Record<string, unknown>
195
+ ): Promise<T> {
196
+ const startTime = performance.now();
197
+
198
+ // Try cache first for pure functions
199
+ const cacheKey = globalCache.generateKey('runtime_call', module, functionName, args, kwargs);
200
+ const cached = await globalCache.get<T>(cacheKey);
201
+ if (cached !== null) {
202
+ this.stats.cacheHits++;
203
+ // Runtime cache HIT for ${module}.${functionName}
204
+ return cached;
205
+ }
206
+
207
+ try {
208
+ const result = await this.executeRequest<T>({
209
+ method: 'call',
210
+ params: { module, functionName, args, kwargs },
211
+ });
212
+
213
+ const duration = performance.now() - startTime;
214
+
215
+ // Cache result for pure functions (simple heuristic)
216
+ if (this.isPureFunctionCandidate(functionName, args)) {
217
+ await globalCache.set(cacheKey, result, {
218
+ computeTime: duration,
219
+ dependencies: [module],
220
+ });
221
+ }
222
+
223
+ this.updateStats(duration);
224
+ return result;
225
+ } catch (error) {
226
+ this.updateStats(performance.now() - startTime, true);
227
+ throw error;
228
+ }
229
+ }
230
+
231
+ async instantiate<T = unknown>(
232
+ module: string,
233
+ className: string,
234
+ args: unknown[],
235
+ kwargs?: Record<string, unknown>
236
+ ): Promise<T> {
237
+ const startTime = performance.now();
238
+
239
+ try {
240
+ const result = await this.executeRequest<T>({
241
+ method: 'instantiate',
242
+ params: { module, className, args, kwargs },
243
+ });
244
+
245
+ this.updateStats(performance.now() - startTime);
246
+ return result;
247
+ } catch (error) {
248
+ this.updateStats(performance.now() - startTime, true);
249
+ throw error;
250
+ }
251
+ }
252
+
253
+ async callMethod<T = unknown>(
254
+ handle: string,
255
+ methodName: string,
256
+ args: unknown[],
257
+ kwargs?: Record<string, unknown>
258
+ ): Promise<T> {
259
+ const startTime = performance.now();
260
+
261
+ try {
262
+ const result = await this.executeRequest<T>({
263
+ method: 'call_method',
264
+ params: { handle, methodName, args, kwargs },
265
+ });
266
+
267
+ this.updateStats(performance.now() - startTime);
268
+ return result;
269
+ } catch (error) {
270
+ this.updateStats(performance.now() - startTime, true);
271
+ throw error;
272
+ }
273
+ }
274
+
275
+ async disposeInstance(handle: string): Promise<void> {
276
+ await this.executeRequest<void>({
277
+ method: 'dispose_instance',
278
+ params: { handle },
279
+ });
280
+ }
281
+
282
+ /**
283
+ * Execute request with intelligent process selection
284
+ */
285
+ private async executeRequest<T>(payload: Omit<RpcRequest, 'id' | 'protocol'>): Promise<T> {
286
+ let worker = this.selectOptimalWorker();
287
+
288
+ // Spawn new process if none available and under limit
289
+ if (!worker && this.processPool.length < this.options.maxProcesses) {
290
+ try {
291
+ worker = await this.spawnProcess();
292
+ this.stats.poolMisses++;
293
+ } catch (error) {
294
+ throw new Error(`Failed to spawn worker process: ${error}`);
295
+ }
296
+ }
297
+
298
+ // Wait for worker if all are busy
299
+ worker ??= await this.waitForAvailableWorker();
300
+
301
+ this.stats.poolHits++;
302
+ return this.sendToWorker<T>(worker, payload);
303
+ }
304
+
305
+ /**
306
+ * Select optimal worker based on load and performance
307
+ */
308
+ private selectOptimalWorker(): WorkerProcess | null {
309
+ const availableWorkers = this.processPool.filter(w => !w.busy && w.process.connected);
310
+
311
+ if (availableWorkers.length === 0) {
312
+ return null;
313
+ }
314
+
315
+ // Simple round-robin for now, could be enhanced with load-based selection
316
+ const worker = availableWorkers[this.roundRobinIndex % availableWorkers.length];
317
+ this.roundRobinIndex = (this.roundRobinIndex + 1) % availableWorkers.length;
318
+
319
+ return worker ?? null;
320
+ }
321
+
322
+ /**
323
+ * Wait for any worker to become available
324
+ */
325
+ private async waitForAvailableWorker(timeoutMs: number = 5000): Promise<WorkerProcess> {
326
+ return new Promise((resolvePromise, reject) => {
327
+ const timeout = setTimeout(() => {
328
+ reject(new Error('Timeout waiting for available worker'));
329
+ }, timeoutMs);
330
+
331
+ const checkWorker = (): void => {
332
+ const worker = this.selectOptimalWorker();
333
+ if (worker) {
334
+ clearTimeout(timeout);
335
+ resolvePromise(worker);
336
+ } else {
337
+ // Check again in 10ms
338
+ setTimeout(checkWorker, 10);
339
+ }
340
+ };
341
+
342
+ checkWorker();
343
+ });
344
+ }
345
+
346
+ /**
347
+ * Send request to specific worker
348
+ */
349
+ private async sendToWorker<T>(
350
+ worker: WorkerProcess,
351
+ payload: Omit<RpcRequest, 'id' | 'protocol'>
352
+ ): Promise<T> {
353
+ const id = this.nextId++;
354
+ const message: RpcRequest = { id, protocol: TYWRAP_PROTOCOL, ...payload } as RpcRequest;
355
+ const text = `${JSON.stringify(message)}\n`;
356
+
357
+ worker.busy = true;
358
+ worker.requestCount++;
359
+ worker.lastUsed = Date.now();
360
+
361
+ return new Promise<T>((resolvePromise, reject) => {
362
+ const startTime = performance.now();
363
+
364
+ const timer = setTimeout(() => {
365
+ worker.pendingRequests.delete(id);
366
+ worker.busy = false;
367
+ reject(new Error(`Request ${id} timed out after ${this.options.timeoutMs}ms`));
368
+ }, this.options.timeoutMs);
369
+
370
+ worker.pendingRequests.set(id, {
371
+ resolve: (value: unknown) => {
372
+ const duration = performance.now() - startTime;
373
+ worker.stats.totalTime += duration;
374
+ worker.stats.totalRequests++;
375
+ worker.stats.averageTime = worker.stats.totalTime / worker.stats.totalRequests;
376
+ worker.busy = false;
377
+ resolvePromise(value as T);
378
+ },
379
+ reject: (error: unknown) => {
380
+ worker.stats.errorCount++;
381
+ worker.busy = false;
382
+ reject(error);
383
+ },
384
+ timer,
385
+ startTime,
386
+ });
387
+
388
+ if (!worker.process.stdin?.writable) {
389
+ worker.pendingRequests.delete(id);
390
+ worker.busy = false;
391
+ clearTimeout(timer);
392
+ reject(new Error('Worker process stdin not writable'));
393
+ return;
394
+ }
395
+
396
+ try {
397
+ worker.process.stdin.write(text);
398
+ } catch (error) {
399
+ worker.pendingRequests.delete(id);
400
+ worker.busy = false;
401
+ clearTimeout(timer);
402
+ reject(error);
403
+ }
404
+ });
405
+ }
406
+
407
+ /**
408
+ * Spawn new worker process with optimizations
409
+ */
410
+ private async spawnProcess(): Promise<WorkerProcess> {
411
+ const { spawn } = await import('child_process');
412
+
413
+ const workerId = `worker_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
414
+
415
+ const env: NodeJS.ProcessEnv = {
416
+ ...process.env,
417
+ ...this.options.env,
418
+ PYTHONUNBUFFERED: '1', // Ensure immediate output
419
+ PYTHONDONTWRITEBYTECODE: '1', // Skip .pyc files for faster startup
420
+ };
421
+ if (!env.PYTHONUTF8) {
422
+ env.PYTHONUTF8 = '1';
423
+ }
424
+ if (!env.PYTHONIOENCODING) {
425
+ env.PYTHONIOENCODING = 'UTF-8';
426
+ }
427
+ if (this.options.virtualEnv) {
428
+ const venv = resolveVirtualEnv(this.options.virtualEnv, this.options.cwd);
429
+ env.VIRTUAL_ENV = venv.venvPath;
430
+ env.PATH = `${venv.binDir}${delimiter}${env.PATH ?? ''}`;
431
+ }
432
+
433
+ if (this.options.enableJsonFallback && !env.TYWRAP_CODEC_FALLBACK) {
434
+ env.TYWRAP_CODEC_FALLBACK = 'json';
435
+ }
436
+
437
+ const childProcess = spawn(this.options.pythonPath, [this.options.scriptPath], {
438
+ cwd: this.options.cwd,
439
+ stdio: ['pipe', 'pipe', 'pipe'],
440
+ env,
441
+ });
442
+
443
+ const worker: WorkerProcess = {
444
+ process: childProcess,
445
+ id: workerId,
446
+ requestCount: 0,
447
+ lastUsed: Date.now(),
448
+ busy: false,
449
+ buffer: '',
450
+ pendingRequests: new Map(),
451
+ stats: {
452
+ totalRequests: 0,
453
+ totalTime: 0,
454
+ averageTime: 0,
455
+ errorCount: 0,
456
+ },
457
+ };
458
+
459
+ // Setup process event handlers
460
+ this.setupProcessHandlers(worker);
461
+
462
+ this.processPool.push(worker);
463
+ this.stats.processSpawns++;
464
+
465
+ // Spawned Python worker process ${workerId} (pool size: ${this.processPool.length})
466
+
467
+ return worker;
468
+ }
469
+
470
+ /**
471
+ * Setup event handlers for worker process
472
+ */
473
+ private setupProcessHandlers(worker: WorkerProcess): void {
474
+ const childProcess = worker.process;
475
+
476
+ // Handle stdout data with efficient buffering
477
+ childProcess.stdout?.on('data', (chunk: Buffer) => {
478
+ worker.buffer += chunk.toString();
479
+
480
+ let idx: number;
481
+ while ((idx = worker.buffer.indexOf('\n')) !== -1) {
482
+ const line = worker.buffer.slice(0, idx).trim();
483
+ worker.buffer = worker.buffer.slice(idx + 1);
484
+
485
+ if (!line) {
486
+ continue;
487
+ }
488
+
489
+ this.handleWorkerResponse(worker, line).catch(error => {
490
+ log.error('Error handling worker response', { workerId: worker.id, error: String(error) });
491
+ });
492
+ }
493
+ });
494
+
495
+ // Handle stderr for debugging
496
+ childProcess.stderr?.on('data', (chunk: Buffer) => {
497
+ const errorText = chunk.toString().trim();
498
+ if (errorText) {
499
+ log.warn('Worker stderr', { workerId: worker.id, output: errorText });
500
+ }
501
+ });
502
+
503
+ // Handle process exit
504
+ childProcess.on('exit', code => {
505
+ log.warn('Worker exited', { workerId: worker.id, code });
506
+ this.handleWorkerExit(worker, code);
507
+ });
508
+
509
+ // Handle process errors
510
+ childProcess.on('error', error => {
511
+ log.error('Worker error', { workerId: worker.id, error: String(error) });
512
+ this.handleWorkerExit(worker, -1);
513
+ });
514
+ }
515
+
516
+ /**
517
+ * Handle response from worker process
518
+ */
519
+ private async handleWorkerResponse(worker: WorkerProcess, line: string): Promise<void> {
520
+ try {
521
+ const msg = JSON.parse(line) as RpcResponse;
522
+ if (msg.protocol !== TYWRAP_PROTOCOL) {
523
+ this.handleProtocolError(
524
+ worker,
525
+ line,
526
+ new BridgeProtocolError(
527
+ `Invalid protocol. Expected ${TYWRAP_PROTOCOL} but received ${String(msg.protocol)}`
528
+ )
529
+ );
530
+ return;
531
+ }
532
+ if (typeof msg.id !== 'number') {
533
+ this.handleProtocolError(worker, line, new BridgeProtocolError('Invalid response id'));
534
+ return;
535
+ }
536
+ const pending = worker.pendingRequests.get(msg.id);
537
+
538
+ if (!pending) {
539
+ this.handleProtocolError(
540
+ worker,
541
+ line,
542
+ new BridgeProtocolError(`Unexpected response id ${msg.id}`)
543
+ );
544
+ return;
545
+ }
546
+
547
+ worker.pendingRequests.delete(msg.id);
548
+
549
+ if (pending.timer) {
550
+ clearTimeout(pending.timer);
551
+ }
552
+
553
+ if (msg.error) {
554
+ pending.reject(this.errorFrom(msg.error));
555
+ } else {
556
+ try {
557
+ const decoded = await decodeValueAsync(msg.result);
558
+ pending.resolve(decoded);
559
+ } catch (decodeError) {
560
+ pending.reject(new BridgeProtocolError(`Failed to decode response: ${decodeError}`));
561
+ }
562
+ }
563
+ } catch (parseError) {
564
+ this.handleProtocolError(worker, line, parseError);
565
+ }
566
+ }
567
+
568
+ /**
569
+ * Handle worker process exit
570
+ */
571
+ private handleWorkerExit(worker: WorkerProcess, code: number | null): void {
572
+ // Reject all pending requests
573
+ for (const [, pending] of worker.pendingRequests) {
574
+ if (pending.timer) {
575
+ clearTimeout(pending.timer);
576
+ }
577
+ pending.reject(new Error(`Worker process exited with code ${code}`));
578
+ }
579
+
580
+ worker.pendingRequests.clear();
581
+
582
+ // Remove from pool
583
+ const index = this.processPool.indexOf(worker);
584
+ if (index >= 0) {
585
+ this.processPool.splice(index, 1);
586
+ this.stats.processDeaths++;
587
+ }
588
+
589
+ // Spawn replacement if needed and not disposing
590
+ if (!this.disposed && this.processPool.length < this.options.minProcesses) {
591
+ this.spawnProcess().catch(error => {
592
+ log.error('Failed to spawn replacement worker', { error: String(error) });
593
+ });
594
+ }
595
+ }
596
+
597
+ /**
598
+ * Warm up processes with configured commands
599
+ */
600
+ private async warmupProcesses(): Promise<void> {
601
+ const warmupPromises = this.processPool.map(async worker => {
602
+ for (const cmd of this.options.warmupCommands) {
603
+ try {
604
+ await this.sendToWorker(worker, {
605
+ method: cmd.method as 'call' | 'instantiate' | 'call_method' | 'dispose_instance',
606
+ params: cmd.params,
607
+ });
608
+ } catch (error) {
609
+ log.warn('Warmup command failed', { workerId: worker.id, error: String(error) });
610
+ }
611
+ }
612
+ });
613
+
614
+ await Promise.all(warmupPromises);
615
+ // Warmed up ${this.processPool.length} worker processes
616
+ }
617
+
618
+ /**
619
+ * Heuristic to determine if function result should be cached
620
+ */
621
+ private isPureFunctionCandidate(functionName: string, args: unknown[]): boolean {
622
+ // Simple heuristics - could be made more sophisticated
623
+ const pureFunctionPatterns = [
624
+ /^(get|fetch|read|load|find|search|query|select)_/i,
625
+ /^(compute|calculate|process|transform|convert)_/i,
626
+ /^(encode|decode|serialize|deserialize)_/i,
627
+ ];
628
+
629
+ const impureFunctionPatterns = [
630
+ /^(set|save|write|update|insert|delete|create|modify)_/i,
631
+ /^(send|post|put|patch)_/i,
632
+ /random|uuid|timestamp|now|current/i,
633
+ ];
634
+
635
+ // Don't cache if function name suggests mutation
636
+ if (impureFunctionPatterns.some(pattern => pattern.test(functionName))) {
637
+ return false;
638
+ }
639
+
640
+ // Cache if function name suggests pure computation
641
+ if (pureFunctionPatterns.some(pattern => pattern.test(functionName))) {
642
+ return true;
643
+ }
644
+
645
+ // Don't cache if args contain mutable objects (very basic check)
646
+ const hasComplexArgs = args.some(
647
+ arg => arg !== null && typeof arg === 'object' && !(arg instanceof Date)
648
+ );
649
+
650
+ return !hasComplexArgs && args.length <= 3; // Cache simple calls with few args
651
+ }
652
+
653
+ /**
654
+ * Update performance statistics
655
+ */
656
+ private updateStats(duration: number, _error: boolean = false): void {
657
+ this.stats.totalRequests++;
658
+ this.stats.totalTime += duration;
659
+
660
+ const currentMemory = process.memoryUsage().heapUsed;
661
+ if (currentMemory > this.stats.memoryPeak) {
662
+ this.stats.memoryPeak = currentMemory;
663
+ }
664
+ }
665
+
666
+ /**
667
+ * Get performance statistics
668
+ */
669
+ getStats(): OptimizedBridgeStatsSnapshot {
670
+ const avgTime =
671
+ this.stats.totalRequests > 0 ? this.stats.totalTime / this.stats.totalRequests : 0;
672
+ const hitRate =
673
+ this.stats.totalRequests > 0 ? this.stats.cacheHits / this.stats.totalRequests : 0;
674
+
675
+ return {
676
+ ...this.stats,
677
+ averageTime: avgTime,
678
+ cacheHitRate: hitRate,
679
+ poolSize: this.processPool.length,
680
+ busyWorkers: this.processPool.filter(w => w.busy).length,
681
+ memoryUsage: process.memoryUsage(),
682
+ workerStats: this.processPool.map(w => ({
683
+ id: w.id,
684
+ requestCount: w.requestCount,
685
+ averageTime: w.stats.averageTime,
686
+ errorCount: w.stats.errorCount,
687
+ busy: w.busy,
688
+ pendingRequests: w.pendingRequests.size,
689
+ })),
690
+ };
691
+ }
692
+
693
+ /**
694
+ * Cleanup idle processes
695
+ */
696
+ private async cleanup(): Promise<void> {
697
+ const now = Date.now();
698
+ const idleWorkers = this.processPool.filter(
699
+ w =>
700
+ !w.busy &&
701
+ now - w.lastUsed > this.options.maxIdleTime &&
702
+ this.processPool.length > this.options.minProcesses
703
+ );
704
+
705
+ for (const worker of idleWorkers) {
706
+ await this.terminateWorker(worker);
707
+ }
708
+
709
+ // Restart workers that have handled too many requests
710
+ const overusedWorkers = this.processPool.filter(
711
+ w => !w.busy && w.requestCount >= this.options.maxRequestsPerProcess
712
+ );
713
+
714
+ for (const worker of overusedWorkers) {
715
+ await this.terminateWorker(worker);
716
+ if (this.processPool.length < this.options.minProcesses) {
717
+ await this.spawnProcess();
718
+ }
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Gracefully terminate a worker
724
+ */
725
+ private async terminateWorker(worker: WorkerProcess): Promise<void> {
726
+ const index = this.processPool.indexOf(worker);
727
+ if (index >= 0) {
728
+ this.processPool.splice(index, 1);
729
+ }
730
+
731
+ // Reject pending requests
732
+ for (const [, pending] of worker.pendingRequests) {
733
+ if (pending.timer) {
734
+ clearTimeout(pending.timer);
735
+ }
736
+ pending.reject(new Error('Worker process terminated'));
737
+ }
738
+
739
+ // Graceful termination
740
+ try {
741
+ if (worker.process.connected) {
742
+ worker.process.kill('SIGTERM');
743
+
744
+ // Force kill if not terminated in 5 seconds
745
+ setTimeout(() => {
746
+ if (!worker.process.killed) {
747
+ worker.process.kill('SIGKILL');
748
+ }
749
+ }, 5000);
750
+ }
751
+ } catch (error) {
752
+ log.warn('Error terminating worker', { workerId: worker.id, error: String(error) });
753
+ }
754
+
755
+ // Terminated worker ${worker.id}
756
+ }
757
+
758
+ /**
759
+ * Start cleanup scheduler
760
+ */
761
+ private startCleanupScheduler(): void {
762
+ this.cleanupTimer = setInterval(async () => {
763
+ try {
764
+ await this.cleanup();
765
+ } catch (error) {
766
+ log.error('Cleanup error', { error: String(error) });
767
+ }
768
+ }, 60000); // Cleanup every minute
769
+ }
770
+
771
+ /**
772
+ * Dispose all resources
773
+ */
774
+ async dispose(): Promise<void> {
775
+ if (this.disposed) {
776
+ return;
777
+ }
778
+
779
+ this.disposed = true;
780
+
781
+ if (this.cleanupTimer) {
782
+ clearInterval(this.cleanupTimer);
783
+ this.cleanupTimer = undefined;
784
+ }
785
+
786
+ // Terminate all workers
787
+ const terminationPromises = this.processPool.map(worker => this.terminateWorker(worker));
788
+ await Promise.all(terminationPromises);
789
+
790
+ this.processPool.length = 0;
791
+ this.emitter.removeAllListeners();
792
+
793
+ // Disposed optimized Node.js bridge
794
+ }
795
+
796
+ private errorFrom(err: { type: string; message: string; traceback?: string }): Error {
797
+ const e = new BridgeExecutionError(`${err.type}: ${err.message}`);
798
+ e.traceback = err.traceback;
799
+ return e;
800
+ }
801
+
802
+ private handleProtocolError(worker: WorkerProcess, line: string, error: unknown): void {
803
+ const snippet = line.length > 500 ? `${line.slice(0, 500)}…` : line;
804
+ const detail = error instanceof Error ? error.message : String(error);
805
+ const hint =
806
+ 'Ensure your Python code does not print to stdout and that the bridge outputs only JSON lines.';
807
+ const msg = `Protocol error from Python bridge. ${detail}\n${hint}\nOffending line: ${snippet}`;
808
+ const bridgeError = new BridgeProtocolError(msg);
809
+
810
+ for (const [, pending] of worker.pendingRequests) {
811
+ if (pending.timer) {
812
+ clearTimeout(pending.timer);
813
+ }
814
+ pending.reject(bridgeError);
815
+ }
816
+ worker.pendingRequests.clear();
817
+
818
+ try {
819
+ if (worker.process.connected) {
820
+ worker.process.kill('SIGTERM');
821
+ }
822
+ } catch (killError) {
823
+ log.warn('Error terminating worker after protocol error', { workerId: worker.id, error: String(killError) });
824
+ }
825
+
826
+ const index = this.processPool.indexOf(worker);
827
+ if (index >= 0) {
828
+ this.processPool.splice(index, 1);
829
+ this.stats.processDeaths++;
830
+ }
831
+
832
+ if (!this.disposed && this.processPool.length < this.options.minProcesses) {
833
+ this.spawnProcess().catch(spawnError => {
834
+ log.error('Failed to spawn replacement worker after protocol error', { error: String(spawnError) });
835
+ });
836
+ }
837
+ }
838
+ }