tywrap 0.2.0 → 0.3.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 (163) hide show
  1. package/README.md +65 -31
  2. package/dist/cli.js +49 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/config/index.d.ts +11 -7
  5. package/dist/config/index.d.ts.map +1 -1
  6. package/dist/config/index.js +43 -7
  7. package/dist/config/index.js.map +1 -1
  8. package/dist/core/analyzer.d.ts +1 -0
  9. package/dist/core/analyzer.d.ts.map +1 -1
  10. package/dist/core/analyzer.js +47 -12
  11. package/dist/core/analyzer.js.map +1 -1
  12. package/dist/core/annotation-parser.d.ts +8 -0
  13. package/dist/core/annotation-parser.d.ts.map +1 -0
  14. package/dist/core/annotation-parser.js +409 -0
  15. package/dist/core/annotation-parser.js.map +1 -0
  16. package/dist/core/discovery.d.ts +1 -0
  17. package/dist/core/discovery.d.ts.map +1 -1
  18. package/dist/core/discovery.js +9 -9
  19. package/dist/core/discovery.js.map +1 -1
  20. package/dist/core/generator.d.ts +9 -1
  21. package/dist/core/generator.d.ts.map +1 -1
  22. package/dist/core/generator.js +738 -104
  23. package/dist/core/generator.js.map +1 -1
  24. package/dist/core/mapper.d.ts +9 -7
  25. package/dist/core/mapper.d.ts.map +1 -1
  26. package/dist/core/mapper.js +129 -44
  27. package/dist/core/mapper.js.map +1 -1
  28. package/dist/index.d.ts +23 -7
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +23 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/runtime/base.d.ts +17 -7
  33. package/dist/runtime/base.d.ts.map +1 -1
  34. package/dist/runtime/base.js +18 -1
  35. package/dist/runtime/base.js.map +1 -1
  36. package/dist/runtime/bounded-context.d.ts +252 -0
  37. package/dist/runtime/bounded-context.d.ts.map +1 -0
  38. package/dist/runtime/bounded-context.js +454 -0
  39. package/dist/runtime/bounded-context.js.map +1 -0
  40. package/dist/runtime/bridge-core.d.ts +1 -0
  41. package/dist/runtime/bridge-core.d.ts.map +1 -1
  42. package/dist/runtime/bridge-core.js +52 -17
  43. package/dist/runtime/bridge-core.js.map +1 -1
  44. package/dist/runtime/bridge-protocol.d.ts +184 -0
  45. package/dist/runtime/bridge-protocol.d.ts.map +1 -0
  46. package/dist/runtime/bridge-protocol.js +344 -0
  47. package/dist/runtime/bridge-protocol.js.map +1 -0
  48. package/dist/runtime/disposable.d.ts +40 -0
  49. package/dist/runtime/disposable.d.ts.map +1 -0
  50. package/dist/runtime/disposable.js +49 -0
  51. package/dist/runtime/disposable.js.map +1 -0
  52. package/dist/runtime/errors.d.ts +10 -0
  53. package/dist/runtime/errors.d.ts.map +1 -1
  54. package/dist/runtime/errors.js +9 -0
  55. package/dist/runtime/errors.js.map +1 -1
  56. package/dist/runtime/http-io.d.ts +91 -0
  57. package/dist/runtime/http-io.d.ts.map +1 -0
  58. package/dist/runtime/http-io.js +195 -0
  59. package/dist/runtime/http-io.js.map +1 -0
  60. package/dist/runtime/http.d.ts +48 -13
  61. package/dist/runtime/http.d.ts.map +1 -1
  62. package/dist/runtime/http.js +60 -73
  63. package/dist/runtime/http.js.map +1 -1
  64. package/dist/runtime/node.d.ts +97 -130
  65. package/dist/runtime/node.d.ts.map +1 -1
  66. package/dist/runtime/node.js +392 -521
  67. package/dist/runtime/node.js.map +1 -1
  68. package/dist/runtime/optimized-node.d.ts +1 -1
  69. package/dist/runtime/optimized-node.d.ts.map +1 -1
  70. package/dist/runtime/optimized-node.js +1 -1
  71. package/dist/runtime/optimized-node.js.map +1 -1
  72. package/dist/runtime/pooled-transport.d.ts +135 -0
  73. package/dist/runtime/pooled-transport.d.ts.map +1 -0
  74. package/dist/runtime/pooled-transport.js +177 -0
  75. package/dist/runtime/pooled-transport.js.map +1 -0
  76. package/dist/runtime/process-io.d.ts +209 -0
  77. package/dist/runtime/process-io.d.ts.map +1 -0
  78. package/dist/runtime/process-io.js +729 -0
  79. package/dist/runtime/process-io.js.map +1 -0
  80. package/dist/runtime/pyodide-io.d.ts +154 -0
  81. package/dist/runtime/pyodide-io.d.ts.map +1 -0
  82. package/dist/runtime/pyodide-io.js +459 -0
  83. package/dist/runtime/pyodide-io.js.map +1 -0
  84. package/dist/runtime/pyodide.d.ts +51 -19
  85. package/dist/runtime/pyodide.d.ts.map +1 -1
  86. package/dist/runtime/pyodide.js +57 -186
  87. package/dist/runtime/pyodide.js.map +1 -1
  88. package/dist/runtime/safe-codec.d.ts +103 -0
  89. package/dist/runtime/safe-codec.d.ts.map +1 -0
  90. package/dist/runtime/safe-codec.js +519 -0
  91. package/dist/runtime/safe-codec.js.map +1 -0
  92. package/dist/runtime/transport.d.ts +191 -0
  93. package/dist/runtime/transport.d.ts.map +1 -0
  94. package/dist/runtime/transport.js +86 -0
  95. package/dist/runtime/transport.js.map +1 -0
  96. package/dist/runtime/validators.d.ts +120 -0
  97. package/dist/runtime/validators.d.ts.map +1 -0
  98. package/dist/runtime/validators.js +229 -0
  99. package/dist/runtime/validators.js.map +1 -0
  100. package/dist/runtime/worker-pool.d.ts +208 -0
  101. package/dist/runtime/worker-pool.d.ts.map +1 -0
  102. package/dist/runtime/worker-pool.js +419 -0
  103. package/dist/runtime/worker-pool.js.map +1 -0
  104. package/dist/types/index.d.ts +51 -1
  105. package/dist/types/index.d.ts.map +1 -1
  106. package/dist/tywrap.d.ts.map +1 -1
  107. package/dist/tywrap.js +227 -328
  108. package/dist/tywrap.js.map +1 -1
  109. package/dist/utils/cache.d.ts.map +1 -1
  110. package/dist/utils/cache.js +53 -5
  111. package/dist/utils/cache.js.map +1 -1
  112. package/dist/utils/codec.d.ts.map +1 -1
  113. package/dist/utils/codec.js +114 -1
  114. package/dist/utils/codec.js.map +1 -1
  115. package/dist/utils/ir-cache.d.ts +28 -0
  116. package/dist/utils/ir-cache.d.ts.map +1 -0
  117. package/dist/utils/ir-cache.js +29 -0
  118. package/dist/utils/ir-cache.js.map +1 -0
  119. package/dist/utils/parallel-processor.d.ts +1 -1
  120. package/dist/utils/parallel-processor.d.ts.map +1 -1
  121. package/dist/utils/parallel-processor.js +111 -40
  122. package/dist/utils/parallel-processor.js.map +1 -1
  123. package/dist/utils/runtime.d.ts +5 -1
  124. package/dist/utils/runtime.d.ts.map +1 -1
  125. package/dist/utils/runtime.js +112 -18
  126. package/dist/utils/runtime.js.map +1 -1
  127. package/package.json +40 -18
  128. package/runtime/python_bridge.py +108 -15
  129. package/runtime/safe_codec.py +344 -0
  130. package/src/cli.ts +61 -2
  131. package/src/config/index.ts +63 -17
  132. package/src/core/analyzer.ts +52 -15
  133. package/src/core/annotation-parser.ts +500 -0
  134. package/src/core/discovery.ts +26 -12
  135. package/src/core/generator.ts +956 -116
  136. package/src/core/mapper.ts +158 -51
  137. package/src/index.ts +78 -6
  138. package/src/runtime/base.ts +18 -26
  139. package/src/runtime/bounded-context.ts +608 -0
  140. package/src/runtime/bridge-core.ts +58 -18
  141. package/src/runtime/bridge-protocol.ts +483 -0
  142. package/src/runtime/disposable.ts +65 -0
  143. package/src/runtime/errors.ts +14 -0
  144. package/src/runtime/http-io.ts +245 -0
  145. package/src/runtime/http.ts +76 -115
  146. package/src/runtime/node.ts +563 -676
  147. package/src/runtime/optimized-node.ts +4 -1
  148. package/src/runtime/pooled-transport.ts +263 -0
  149. package/src/runtime/process-io.ts +930 -0
  150. package/src/runtime/pyodide-io.ts +551 -0
  151. package/src/runtime/pyodide.ts +75 -215
  152. package/src/runtime/safe-codec.ts +651 -0
  153. package/src/runtime/transport.ts +278 -0
  154. package/src/runtime/validators.ts +252 -0
  155. package/src/runtime/worker-pool.ts +559 -0
  156. package/src/types/global.d.ts +11 -1
  157. package/src/types/index.ts +63 -0
  158. package/src/tywrap.ts +279 -358
  159. package/src/utils/cache.ts +59 -5
  160. package/src/utils/codec.ts +122 -1
  161. package/src/utils/ir-cache.ts +51 -0
  162. package/src/utils/parallel-processor.ts +119 -43
  163. package/src/utils/runtime.ts +129 -18
@@ -0,0 +1,559 @@
1
+ /**
2
+ * WorkerPool - Manages multiple Transport instances for concurrent request handling.
3
+ *
4
+ * Provides semaphore-based concurrency control with configurable limits per worker
5
+ * and a wait queue for callers when all workers are at capacity.
6
+ *
7
+ * @see https://github.com/bbopen/tywrap/issues/149
8
+ */
9
+
10
+ import { BoundedContext } from './bounded-context.js';
11
+ import { BridgeTimeoutError, BridgeExecutionError, BridgeProtocolError } from './errors.js';
12
+ import type { Transport } from './transport.js';
13
+
14
+ // =============================================================================
15
+ // TYPES
16
+ // =============================================================================
17
+
18
+ /**
19
+ * Configuration options for the WorkerPool.
20
+ */
21
+ export interface WorkerPoolOptions {
22
+ /** Factory function to create transports */
23
+ createTransport: () => Transport;
24
+
25
+ /** Maximum number of workers in the pool */
26
+ maxWorkers: number;
27
+
28
+ /** Minimum number of workers to pre-spawn during init. Default: 0 (lazy) */
29
+ minWorkers?: number;
30
+
31
+ /** Timeout for waiting in queue (ms). Default: 30000 */
32
+ queueTimeoutMs?: number;
33
+
34
+ /** Maximum concurrent requests per worker. Default: 1 */
35
+ maxConcurrentPerWorker?: number;
36
+
37
+ /**
38
+ * Callback invoked after each worker is created and initialized.
39
+ * Use this for per-worker warmup (e.g., importing modules, running setup).
40
+ */
41
+ onWorkerReady?: (worker: PooledWorker) => Promise<void>;
42
+
43
+ /**
44
+ * Optional callback used only for background replacement workers after a
45
+ * fatal timeout/crash. This lets callers publish a replacement only after it
46
+ * is proven ready, without charging hidden work to normal request startup.
47
+ */
48
+ onReplacementWorkerReady?: (worker: PooledWorker) => Promise<void>;
49
+ }
50
+
51
+ /**
52
+ * A pooled worker with its transport and current in-flight request count.
53
+ */
54
+ export interface PooledWorker {
55
+ /** The underlying transport instance */
56
+ transport: Transport;
57
+
58
+ /** Number of requests currently being processed by this worker */
59
+ inFlightCount: number;
60
+ }
61
+
62
+ /**
63
+ * Internal representation of a waiter in the queue.
64
+ */
65
+ interface QueuedWaiter {
66
+ /** Resolve function to fulfill the promise with a worker */
67
+ resolve: (worker: PooledWorker) => void;
68
+
69
+ /** Reject function to reject the promise with an error */
70
+ reject: (error: Error) => void;
71
+
72
+ /** Timeout timer for queue timeout */
73
+ timer: NodeJS.Timeout;
74
+ }
75
+
76
+ // =============================================================================
77
+ // WORKER POOL
78
+ // =============================================================================
79
+
80
+ /**
81
+ * Pool of Transport workers with semaphore-based concurrency control.
82
+ *
83
+ * Features:
84
+ * - Lazy worker creation (workers created on demand)
85
+ * - Configurable concurrency per worker
86
+ * - Wait queue with timeout for callers when pool is at capacity
87
+ * - Automatic cleanup of timers and workers on disposal
88
+ *
89
+ * @example
90
+ * ```typescript
91
+ * const pool = new WorkerPool({
92
+ * createTransport: () => new ProcessIO({ pythonPath: 'python3' }),
93
+ * maxWorkers: 4,
94
+ * maxConcurrentPerWorker: 2,
95
+ * queueTimeoutMs: 5000,
96
+ * });
97
+ *
98
+ * await pool.init();
99
+ *
100
+ * // Use withWorker for automatic acquire/release
101
+ * const result = await pool.withWorker(async (worker) => {
102
+ * return worker.transport.send(message, timeout);
103
+ * });
104
+ *
105
+ * await pool.dispose();
106
+ * ```
107
+ */
108
+ export class WorkerPool extends BoundedContext {
109
+ private readonly options: Omit<
110
+ Required<WorkerPoolOptions>,
111
+ 'onWorkerReady' | 'onReplacementWorkerReady'
112
+ > & {
113
+ onWorkerReady?: (worker: PooledWorker) => Promise<void>;
114
+ onReplacementWorkerReady?: (worker: PooledWorker) => Promise<void>;
115
+ };
116
+ private readonly workers: PooledWorker[] = [];
117
+ private readonly waitQueue: QueuedWaiter[] = [];
118
+ /** Tracks workers being created to prevent race condition in acquire() */
119
+ private pendingCreations = 0;
120
+
121
+ /**
122
+ * Create a new WorkerPool.
123
+ *
124
+ * @param options - Pool configuration options
125
+ */
126
+ constructor(options: WorkerPoolOptions) {
127
+ super();
128
+
129
+ // Validate required options
130
+ if (typeof options.createTransport !== 'function') {
131
+ throw new BridgeExecutionError('createTransport must be a function');
132
+ }
133
+ if (typeof options.maxWorkers !== 'number' || options.maxWorkers < 1) {
134
+ throw new BridgeExecutionError('maxWorkers must be a positive number');
135
+ }
136
+
137
+ const minWorkers = options.minWorkers ?? 0;
138
+ if (minWorkers > options.maxWorkers) {
139
+ throw new BridgeExecutionError('minWorkers cannot exceed maxWorkers');
140
+ }
141
+
142
+ this.options = {
143
+ createTransport: options.createTransport,
144
+ maxWorkers: options.maxWorkers,
145
+ minWorkers,
146
+ queueTimeoutMs: options.queueTimeoutMs ?? 30000,
147
+ maxConcurrentPerWorker: options.maxConcurrentPerWorker ?? 1,
148
+ onWorkerReady: options.onWorkerReady,
149
+ onReplacementWorkerReady: options.onReplacementWorkerReady,
150
+ };
151
+ }
152
+
153
+ // ===========================================================================
154
+ // LIFECYCLE
155
+ // ===========================================================================
156
+
157
+ /**
158
+ * Initialize the pool.
159
+ *
160
+ * If minWorkers > 0, pre-spawns workers during initialization.
161
+ * Otherwise, workers are created lazily on demand.
162
+ */
163
+ protected async doInit(): Promise<void> {
164
+ // Pre-spawn minimum workers if configured
165
+ if (this.options.minWorkers > 0) {
166
+ const spawns: Promise<PooledWorker>[] = [];
167
+ for (let i = 0; i < this.options.minWorkers; i++) {
168
+ spawns.push(this.createWorker());
169
+ }
170
+ await Promise.all(spawns);
171
+ }
172
+ }
173
+
174
+ /**
175
+ * Dispose the pool and all workers.
176
+ *
177
+ * - Rejects all waiters in the queue
178
+ * - Disposes all transport instances
179
+ * - Clears internal state
180
+ */
181
+ protected async doDispose(): Promise<void> {
182
+ // Reject all waiters in the queue
183
+ for (const waiter of this.waitQueue) {
184
+ clearTimeout(waiter.timer);
185
+ waiter.reject(new BridgeExecutionError('Pool disposed'));
186
+ }
187
+ this.waitQueue.length = 0;
188
+
189
+ // Dispose all workers
190
+ const errors: Error[] = [];
191
+ for (const worker of this.workers) {
192
+ try {
193
+ await worker.transport.dispose();
194
+ } catch (e) {
195
+ errors.push(e instanceof Error ? e : new Error(String(e)));
196
+ }
197
+ }
198
+ this.workers.length = 0;
199
+
200
+ // Report errors if any
201
+ if (errors.length === 1) {
202
+ throw errors[0];
203
+ }
204
+ if (errors.length > 1) {
205
+ throw new AggregateError(errors, 'Multiple errors during worker disposal');
206
+ }
207
+ }
208
+
209
+ // ===========================================================================
210
+ // WORKER MANAGEMENT
211
+ // ===========================================================================
212
+
213
+ /**
214
+ * Acquire a worker from the pool.
215
+ *
216
+ * This method:
217
+ * - Returns an available worker if one exists (inFlightCount < maxConcurrentPerWorker)
218
+ * - Creates a new worker if under the maxWorkers limit
219
+ * - Waits in queue if all workers are at capacity
220
+ *
221
+ * @returns Promise resolving to a pooled worker
222
+ * @throws BridgeTimeoutError if queue timeout expires
223
+ * @throws BridgeExecutionError if pool is disposed while waiting
224
+ */
225
+ async acquire(): Promise<PooledWorker> {
226
+ // Check for disposed state
227
+ if (this.isDisposed) {
228
+ throw new BridgeExecutionError('Pool has been disposed');
229
+ }
230
+
231
+ // Find an available worker (one with capacity)
232
+ const availableWorker = this.findAvailableWorker();
233
+ if (availableWorker) {
234
+ availableWorker.inFlightCount++;
235
+ return availableWorker;
236
+ }
237
+
238
+ // Create a new worker if under the limit
239
+ // Include pendingCreations to prevent race condition where multiple
240
+ // concurrent acquire() calls all pass the length check before any
241
+ // worker is actually added to the array
242
+ if (this.workers.length + this.pendingCreations < this.options.maxWorkers) {
243
+ this.pendingCreations++;
244
+ try {
245
+ const newWorker = await this.createWorker();
246
+ newWorker.inFlightCount++;
247
+ return newWorker;
248
+ } finally {
249
+ this.pendingCreations--;
250
+ }
251
+ }
252
+
253
+ // All workers at capacity - wait in queue
254
+ return this.waitForWorker();
255
+ }
256
+
257
+ /**
258
+ * Release a worker back to the pool.
259
+ *
260
+ * Decrements the worker's in-flight count and notifies any waiters
261
+ * that a worker may be available.
262
+ *
263
+ * @param worker - The worker to release
264
+ */
265
+ release(worker: PooledWorker): void {
266
+ // Validate the worker belongs to this pool
267
+ if (!this.workers.includes(worker)) {
268
+ return;
269
+ }
270
+
271
+ // Decrement in-flight count (minimum 0)
272
+ worker.inFlightCount = Math.max(0, worker.inFlightCount - 1);
273
+
274
+ // If there are waiters and this worker has capacity, fulfill the first waiter
275
+ if (this.waitQueue.length > 0 && worker.inFlightCount < this.options.maxConcurrentPerWorker) {
276
+ const waiter = this.waitQueue.shift();
277
+ if (waiter) {
278
+ clearTimeout(waiter.timer);
279
+ worker.inFlightCount++;
280
+ waiter.resolve(worker);
281
+ }
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Execute a function with an acquired worker, automatically releasing afterward.
287
+ *
288
+ * This is the recommended way to use the pool, as it ensures proper cleanup
289
+ * even if the function throws an error.
290
+ *
291
+ * @param fn - Async function to execute with the worker
292
+ * @returns Promise resolving to the function's return value
293
+ *
294
+ * @example
295
+ * ```typescript
296
+ * const result = await pool.withWorker(async (worker) => {
297
+ * return worker.transport.send(message, timeout);
298
+ * });
299
+ * ```
300
+ */
301
+ async withWorker<T>(fn: (worker: PooledWorker) => Promise<T>): Promise<T> {
302
+ const worker = await this.acquire();
303
+ let workerRemoved = false;
304
+
305
+ try {
306
+ return await fn(worker);
307
+ } catch (error) {
308
+ // If this is a fatal error indicating the worker is dead, remove it from the pool
309
+ if (this.isFatalWorkerError(error)) {
310
+ this.removeWorker(worker);
311
+ workerRemoved = true;
312
+ }
313
+ throw error;
314
+ } finally {
315
+ // Only release if worker wasn't removed due to fatal error
316
+ if (!workerRemoved) {
317
+ this.release(worker);
318
+ }
319
+ }
320
+ }
321
+
322
+ // ===========================================================================
323
+ // WORKER HEALTH
324
+ // ===========================================================================
325
+
326
+ /**
327
+ * Check if an error indicates the worker is dead and should be removed.
328
+ *
329
+ * Fatal errors include:
330
+ * - Process not running
331
+ * - Process exited unexpectedly
332
+ * - Pipe errors (EPIPE)
333
+ * - Connection reset errors (ECONNRESET)
334
+ * - Request timeouts (the worker may still be busy with an uncancellable request)
335
+ */
336
+ private isFatalWorkerError(error: unknown): boolean {
337
+ // If a request times out, the underlying transport may still be executing it.
338
+ // Quarantine this worker so subsequent requests don't get stuck behind it.
339
+ if (error instanceof BridgeTimeoutError) {
340
+ return true;
341
+ }
342
+ if (error instanceof BridgeProtocolError) {
343
+ const msg = error.message.toLowerCase();
344
+ return (
345
+ msg.includes('not running') ||
346
+ msg.includes('process exited') ||
347
+ msg.includes('epipe') ||
348
+ msg.includes('econnreset')
349
+ );
350
+ }
351
+ return false;
352
+ }
353
+
354
+ /**
355
+ * Remove a worker from the pool.
356
+ *
357
+ * This is called when a worker is detected as dead (crashed, pipe error, etc.).
358
+ * The worker's transport is disposed in the background.
359
+ */
360
+ private removeWorker(worker: PooledWorker): void {
361
+ const index = this.workers.indexOf(worker);
362
+ if (index !== -1) {
363
+ this.workers.splice(index, 1);
364
+ // Dispose transport in background - don't await to avoid blocking
365
+ worker.transport.dispose().catch(() => {
366
+ // Ignore disposal errors for dead workers
367
+ });
368
+ this.scheduleReplacementWorker();
369
+ }
370
+ }
371
+
372
+ // ===========================================================================
373
+ // POOL STATISTICS
374
+ // ===========================================================================
375
+
376
+ /**
377
+ * Current number of workers in the pool.
378
+ */
379
+ get workerCount(): number {
380
+ return this.workers.length;
381
+ }
382
+
383
+ /**
384
+ * Number of callers waiting in the queue.
385
+ */
386
+ get queueLength(): number {
387
+ return this.waitQueue.length;
388
+ }
389
+
390
+ /**
391
+ * Total number of in-flight requests across all workers.
392
+ */
393
+ get totalInFlight(): number {
394
+ return this.workers.reduce((sum, w) => sum + w.inFlightCount, 0);
395
+ }
396
+
397
+ // ===========================================================================
398
+ // PRIVATE HELPERS
399
+ // ===========================================================================
400
+
401
+ /**
402
+ * Find an available worker with capacity for another request.
403
+ */
404
+ private findAvailableWorker(): PooledWorker | undefined {
405
+ return this.workers.find(w => w.inFlightCount < this.options.maxConcurrentPerWorker);
406
+ }
407
+
408
+ /**
409
+ * Replace a removed worker in the background so the next caller does not pay
410
+ * the full worker cold-start penalty after a timeout or crash.
411
+ */
412
+ private scheduleReplacementWorker(): void {
413
+ if (this.state !== 'ready') {
414
+ return;
415
+ }
416
+ if (this.workers.length + this.pendingCreations >= this.options.maxWorkers) {
417
+ return;
418
+ }
419
+
420
+ this.pendingCreations++;
421
+ const replacementReady = this.options.onReplacementWorkerReady ?? this.options.onWorkerReady;
422
+ this.createWorker(replacementReady)
423
+ .then(worker => {
424
+ // Reuse release() to wake queued callers if one is waiting.
425
+ this.release(worker);
426
+ })
427
+ .catch(() => {
428
+ // Ignore background replacement failures. A later acquire() can retry.
429
+ })
430
+ .finally(() => {
431
+ this.pendingCreations = Math.max(0, this.pendingCreations - 1);
432
+ });
433
+ }
434
+
435
+ /**
436
+ * Create a new worker and add it to the pool.
437
+ *
438
+ * If onWorkerReady is configured, calls it after the transport is initialized.
439
+ * This is useful for per-worker warmup (importing modules, running setup).
440
+ */
441
+ private async createWorker(onWorkerReady = this.options.onWorkerReady): Promise<PooledWorker> {
442
+ const transport = this.options.createTransport();
443
+
444
+ // Initialize the transport
445
+ await transport.init();
446
+
447
+ const worker: PooledWorker = {
448
+ transport,
449
+ inFlightCount: 0,
450
+ };
451
+
452
+ try {
453
+ // Call onWorkerReady callback if provided
454
+ if (onWorkerReady) {
455
+ await onWorkerReady(worker);
456
+ }
457
+ } catch (error) {
458
+ // Ensure partially initialized workers do not leak when warmup fails.
459
+ await transport.dispose().catch(() => {
460
+ // Ignore disposal failures during warmup failure handling.
461
+ });
462
+ throw error;
463
+ }
464
+
465
+ if (this.state === 'disposing' || this.state === 'disposed') {
466
+ await transport.dispose().catch(() => {
467
+ // Ignore disposal failures if the pool was torn down mid-creation.
468
+ });
469
+ throw new BridgeExecutionError('Pool disposed during worker creation');
470
+ }
471
+
472
+ this.workers.push(worker);
473
+
474
+ return worker;
475
+ }
476
+
477
+ /**
478
+ * Wait in queue for a worker to become available.
479
+ */
480
+ private waitForWorker(): Promise<PooledWorker> {
481
+ return new Promise<PooledWorker>((resolve, reject) => {
482
+ const timer = setTimeout(() => {
483
+ // Remove this waiter from the queue
484
+ const index = this.waitQueue.findIndex(w => w.timer === timer);
485
+ if (index !== -1) {
486
+ this.waitQueue.splice(index, 1);
487
+ }
488
+ reject(
489
+ new BridgeTimeoutError(
490
+ `Timed out waiting for available worker after ${this.options.queueTimeoutMs}ms`
491
+ )
492
+ );
493
+ }, this.options.queueTimeoutMs);
494
+
495
+ // Unref the timer so it doesn't keep the Node.js process alive
496
+ if (typeof timer.unref === 'function') {
497
+ timer.unref();
498
+ }
499
+
500
+ this.waitQueue.push({ resolve, reject, timer });
501
+ });
502
+ }
503
+
504
+ // ===========================================================================
505
+ // RUNTIME EXECUTION (Not implemented - WorkerPool is just for worker management)
506
+ // ===========================================================================
507
+
508
+ /**
509
+ * Not implemented - WorkerPool does not execute Python calls directly.
510
+ * Use the BridgeProtocol layer with a pooled worker's transport.
511
+ */
512
+ async call<T = unknown>(
513
+ _module: string,
514
+ _functionName: string,
515
+ _args: unknown[],
516
+ _kwargs?: Record<string, unknown>
517
+ ): Promise<T> {
518
+ throw new BridgeExecutionError(
519
+ 'WorkerPool does not implement call() - use withWorker() to get a transport'
520
+ );
521
+ }
522
+
523
+ /**
524
+ * Not implemented - WorkerPool does not execute Python calls directly.
525
+ */
526
+ async instantiate<T = unknown>(
527
+ _module: string,
528
+ _className: string,
529
+ _args: unknown[],
530
+ _kwargs?: Record<string, unknown>
531
+ ): Promise<T> {
532
+ throw new BridgeExecutionError(
533
+ 'WorkerPool does not implement instantiate() - use withWorker() to get a transport'
534
+ );
535
+ }
536
+
537
+ /**
538
+ * Not implemented - WorkerPool does not execute Python calls directly.
539
+ */
540
+ async callMethod<T = unknown>(
541
+ _handle: string,
542
+ _methodName: string,
543
+ _args: unknown[],
544
+ _kwargs?: Record<string, unknown>
545
+ ): Promise<T> {
546
+ throw new BridgeExecutionError(
547
+ 'WorkerPool does not implement callMethod() - use withWorker() to get a transport'
548
+ );
549
+ }
550
+
551
+ /**
552
+ * Not implemented - WorkerPool does not execute Python calls directly.
553
+ */
554
+ async disposeInstance(_handle: string): Promise<void> {
555
+ throw new BridgeExecutionError(
556
+ 'WorkerPool does not implement disposeInstance() - use withWorker() to get a transport'
557
+ );
558
+ }
559
+ }
@@ -8,13 +8,20 @@ declare namespace DenoTypes {
8
8
  deno: string;
9
9
  }
10
10
 
11
+ interface CommandOptions {
12
+ args?: string[];
13
+ cwd?: string;
14
+ env?: Record<string, string>;
15
+ signal?: AbortSignal;
16
+ }
17
+
11
18
  interface DenoGlobal {
12
19
  version: Version;
13
20
  readTextFile(path: string): Promise<string>;
14
21
  writeTextFile(path: string, content: string): Promise<void>;
15
22
  Command: new (
16
23
  cmd: string,
17
- options?: { args?: string[] }
24
+ options?: CommandOptions
18
25
  ) => {
19
26
  output(): Promise<{ code: number; stdout: Uint8Array; stderr: Uint8Array }>;
20
27
  };
@@ -37,12 +44,15 @@ declare namespace BunTypes {
37
44
  options?: {
38
45
  stdout?: string;
39
46
  stderr?: string;
47
+ cwd?: string;
48
+ env?: Record<string, string>;
40
49
  }
41
50
  ): {
42
51
  stdout: ReadableStream;
43
52
  stderr: ReadableStream;
44
53
  exitCode?: number;
45
54
  exited: Promise<void>;
55
+ kill(signal?: number | string): void;
46
56
  };
47
57
  }
48
58
  }