tywrap 0.7.0 → 0.9.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 +36 -11
- package/SECURITY.md +39 -0
- package/dist/config/index.d.ts.map +1 -1
- package/dist/config/index.js +8 -0
- package/dist/config/index.js.map +1 -1
- package/dist/core/annotation-parser.d.ts +2 -1
- package/dist/core/annotation-parser.d.ts.map +1 -1
- package/dist/core/annotation-parser.js +6 -3
- package/dist/core/annotation-parser.js.map +1 -1
- package/dist/core/emit-call.d.ts.map +1 -1
- package/dist/core/emit-call.js +1 -1
- package/dist/core/emit-call.js.map +1 -1
- package/dist/core/generator.d.ts +23 -4
- package/dist/core/generator.d.ts.map +1 -1
- package/dist/core/generator.js +243 -170
- package/dist/core/generator.js.map +1 -1
- package/dist/core/mapper.d.ts +3 -2
- package/dist/core/mapper.d.ts.map +1 -1
- package/dist/core/mapper.js +5 -5
- package/dist/core/mapper.js.map +1 -1
- package/dist/dev.d.ts.map +1 -1
- package/dist/dev.js +1 -3
- package/dist/dev.js.map +1 -1
- package/dist/index.d.ts +7 -5
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +6 -4
- package/dist/index.js.map +1 -1
- package/dist/runtime/base-bridge.d.ts +3 -7
- package/dist/runtime/base-bridge.d.ts.map +1 -1
- package/dist/runtime/base-bridge.js +4 -17
- package/dist/runtime/base-bridge.js.map +1 -1
- package/dist/runtime/bounded-context.d.ts +3 -22
- package/dist/runtime/bounded-context.d.ts.map +1 -1
- package/dist/runtime/bounded-context.js +13 -53
- package/dist/runtime/bounded-context.js.map +1 -1
- package/dist/runtime/bridge-codec.d.ts +1 -1
- package/dist/runtime/bridge-codec.d.ts.map +1 -1
- package/dist/runtime/bridge-codec.js +78 -55
- package/dist/runtime/bridge-codec.js.map +1 -1
- package/dist/runtime/errors.d.ts +16 -0
- package/dist/runtime/errors.d.ts.map +1 -1
- package/dist/runtime/errors.js +17 -0
- package/dist/runtime/errors.js.map +1 -1
- package/dist/runtime/frame-codec.d.ts +111 -0
- package/dist/runtime/frame-codec.d.ts.map +1 -0
- package/dist/runtime/frame-codec.js +352 -0
- package/dist/runtime/frame-codec.js.map +1 -0
- package/dist/runtime/http-transport.d.ts +1 -1
- package/dist/runtime/http-transport.d.ts.map +1 -1
- package/dist/runtime/http-transport.js +1 -1
- package/dist/runtime/http-transport.js.map +1 -1
- package/dist/runtime/index.d.ts +2 -1
- package/dist/runtime/index.d.ts.map +1 -1
- package/dist/runtime/index.js +2 -1
- package/dist/runtime/index.js.map +1 -1
- package/dist/runtime/node.d.ts +7 -23
- package/dist/runtime/node.d.ts.map +1 -1
- package/dist/runtime/node.js +5 -78
- package/dist/runtime/node.js.map +1 -1
- package/dist/runtime/pooled-transport.d.ts +120 -59
- package/dist/runtime/pooled-transport.d.ts.map +1 -1
- package/dist/runtime/pooled-transport.js +345 -78
- package/dist/runtime/pooled-transport.js.map +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.d.ts.map +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.js +1 -1
- package/dist/runtime/pyodide-bootstrap-core.generated.js.map +1 -1
- package/dist/runtime/pyodide-transport.d.ts +1 -1
- package/dist/runtime/pyodide-transport.d.ts.map +1 -1
- package/dist/runtime/pyodide-transport.js +2 -3
- package/dist/runtime/pyodide-transport.js.map +1 -1
- package/dist/runtime/rpc-client.d.ts +7 -36
- package/dist/runtime/rpc-client.d.ts.map +1 -1
- package/dist/runtime/rpc-client.js +37 -72
- package/dist/runtime/rpc-client.js.map +1 -1
- package/dist/runtime/subprocess-transport.d.ts +134 -8
- package/dist/runtime/subprocess-transport.d.ts.map +1 -1
- package/dist/runtime/subprocess-transport.js +490 -65
- package/dist/runtime/subprocess-transport.js.map +1 -1
- package/dist/runtime/timed-out-request-tracker.d.ts +2 -1
- package/dist/runtime/timed-out-request-tracker.d.ts.map +1 -1
- package/dist/runtime/transport.d.ts +90 -18
- package/dist/runtime/transport.d.ts.map +1 -1
- package/dist/runtime/transport.js +21 -1
- package/dist/runtime/transport.js.map +1 -1
- package/dist/runtime/validators.d.ts +49 -0
- package/dist/runtime/validators.d.ts.map +1 -1
- package/dist/runtime/validators.js +152 -0
- package/dist/runtime/validators.js.map +1 -1
- package/dist/types/index.d.ts +14 -15
- package/dist/types/index.d.ts.map +1 -1
- package/dist/tywrap.d.ts +3 -2
- package/dist/tywrap.d.ts.map +1 -1
- package/dist/tywrap.js +140 -21
- package/dist/tywrap.js.map +1 -1
- package/dist/utils/cache.d.ts +3 -16
- package/dist/utils/cache.d.ts.map +1 -1
- package/dist/utils/codec.d.ts +1 -0
- package/dist/utils/codec.d.ts.map +1 -1
- package/dist/utils/codec.js +165 -17
- package/dist/utils/codec.js.map +1 -1
- package/dist/utils/ir-cache.d.ts +2 -1
- package/dist/utils/ir-cache.d.ts.map +1 -1
- package/dist/utils/runtime.d.ts +0 -29
- package/dist/utils/runtime.d.ts.map +1 -1
- package/dist/utils/runtime.js +16 -107
- package/dist/utils/runtime.js.map +1 -1
- package/dist/version.js +1 -1
- package/package.json +7 -6
- package/runtime/frame_codec.py +430 -0
- package/runtime/python_bridge.py +213 -54
- package/runtime/tywrap_bridge_core.py +217 -147
- package/src/config/index.ts +11 -0
- package/src/core/annotation-parser.ts +9 -5
- package/src/core/emit-call.ts +1 -7
- package/src/core/generator.ts +315 -205
- package/src/core/mapper.ts +8 -8
- package/src/dev.ts +1 -3
- package/src/index.ts +7 -3
- package/src/runtime/base-bridge.ts +5 -30
- package/src/runtime/bounded-context.ts +12 -67
- package/src/runtime/bridge-codec.ts +94 -65
- package/src/runtime/errors.ts +21 -0
- package/src/runtime/frame-codec.ts +469 -0
- package/src/runtime/http-transport.ts +6 -1
- package/src/runtime/index.ts +7 -6
- package/src/runtime/node.ts +17 -104
- package/src/runtime/pooled-transport.ts +424 -90
- package/src/runtime/pyodide-bootstrap-core.generated.ts +1 -1
- package/src/runtime/pyodide-transport.ts +7 -3
- package/src/runtime/rpc-client.ts +58 -93
- package/src/runtime/subprocess-transport.ts +585 -80
- package/src/runtime/timed-out-request-tracker.ts +1 -1
- package/src/runtime/transport.ts +112 -22
- package/src/runtime/validators.ts +204 -0
- package/src/types/index.ts +21 -35
- package/src/tywrap.ts +157 -30
- package/src/utils/cache.ts +3 -3
- package/src/utils/codec.ts +205 -16
- package/src/utils/ir-cache.ts +1 -1
- package/src/utils/runtime.ts +17 -128
- package/src/version.ts +1 -1
- package/dist/core/discovery.d.ts +0 -103
- package/dist/core/discovery.d.ts.map +0 -1
- package/dist/core/discovery.js +0 -380
- package/dist/core/discovery.js.map +0 -1
- package/dist/core/validation.d.ts +0 -102
- package/dist/core/validation.d.ts.map +0 -1
- package/dist/core/validation.js +0 -490
- package/dist/core/validation.js.map +0 -1
- package/dist/runtime/base.d.ts +0 -22
- package/dist/runtime/base.d.ts.map +0 -1
- package/dist/runtime/base.js +0 -23
- package/dist/runtime/base.js.map +0 -1
- package/dist/runtime/transport-pool.d.ts +0 -196
- package/dist/runtime/transport-pool.d.ts.map +0 -1
- package/dist/runtime/transport-pool.js +0 -418
- package/dist/runtime/transport-pool.js.map +0 -1
- package/runtime/__pycache__/_tywrap_member_fixtures.cpython-311.pyc +0 -0
- package/runtime/__pycache__/safe_codec.cpython-311.pyc +0 -0
- package/runtime/__pycache__/tywrap_bridge_core.cpython-311.pyc +0 -0
- package/runtime/safe_codec.py +0 -352
- package/src/core/discovery.ts +0 -477
- package/src/core/validation.ts +0 -729
- package/src/runtime/base.ts +0 -24
- package/src/runtime/transport-pool.ts +0 -538
package/src/runtime/base.ts
DELETED
|
@@ -1,24 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Base runtime bridge
|
|
3
|
-
*
|
|
4
|
-
* @deprecated Use DisposableBase instead. RuntimeBridge will be removed in the next major version.
|
|
5
|
-
*/
|
|
6
|
-
|
|
7
|
-
import { DisposableBase } from './bounded-context.js';
|
|
8
|
-
|
|
9
|
-
/**
|
|
10
|
-
* @deprecated Use DisposableBase instead. RuntimeBridge will be removed in the next major version.
|
|
11
|
-
*
|
|
12
|
-
* All bridges now build on DisposableBase which provides:
|
|
13
|
-
* - Lifecycle management (init/dispose state machine)
|
|
14
|
-
* - Validation helpers
|
|
15
|
-
* - Error classification
|
|
16
|
-
* - Bounded execution (timeout, retry)
|
|
17
|
-
* - Resource ownership tracking
|
|
18
|
-
*
|
|
19
|
-
* @see DisposableBase
|
|
20
|
-
*/
|
|
21
|
-
export abstract class RuntimeBridge extends DisposableBase {}
|
|
22
|
-
|
|
23
|
-
// Re-export DisposableBase for backwards compatibility
|
|
24
|
-
export { DisposableBase };
|
|
@@ -1,538 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* TransportPool - 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 { DisposableBase } 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 TransportPool.
|
|
20
|
-
*/
|
|
21
|
-
export interface TransportPoolOptions {
|
|
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: TransportLease) => 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: TransportLease) => Promise<void>;
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/**
|
|
52
|
-
* A pooled worker with its transport and current in-flight request count.
|
|
53
|
-
*/
|
|
54
|
-
export interface TransportLease {
|
|
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: TransportLease) => 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 TransportPool({
|
|
92
|
-
* createTransport: () => new SubprocessTransport({ 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 TransportPool extends DisposableBase {
|
|
109
|
-
private readonly options: Omit<
|
|
110
|
-
Required<TransportPoolOptions>,
|
|
111
|
-
'onWorkerReady' | 'onReplacementWorkerReady'
|
|
112
|
-
> & {
|
|
113
|
-
onWorkerReady?: (worker: TransportLease) => Promise<void>;
|
|
114
|
-
onReplacementWorkerReady?: (worker: TransportLease) => Promise<void>;
|
|
115
|
-
};
|
|
116
|
-
private readonly workers: TransportLease[] = [];
|
|
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 TransportPool.
|
|
123
|
-
*
|
|
124
|
-
* @param options - Pool configuration options
|
|
125
|
-
*/
|
|
126
|
-
constructor(options: TransportPoolOptions) {
|
|
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
|
-
await this.fillToMinimumWorkers();
|
|
166
|
-
}
|
|
167
|
-
|
|
168
|
-
/**
|
|
169
|
-
* Dispose the pool and all workers.
|
|
170
|
-
*
|
|
171
|
-
* - Rejects all waiters in the queue
|
|
172
|
-
* - Disposes all transport instances
|
|
173
|
-
* - Clears internal state
|
|
174
|
-
*/
|
|
175
|
-
protected async doDispose(): Promise<void> {
|
|
176
|
-
// Reject all waiters in the queue
|
|
177
|
-
for (const waiter of this.waitQueue) {
|
|
178
|
-
clearTimeout(waiter.timer);
|
|
179
|
-
waiter.reject(new BridgeExecutionError('Pool disposed'));
|
|
180
|
-
}
|
|
181
|
-
this.waitQueue.length = 0;
|
|
182
|
-
|
|
183
|
-
// Dispose all workers
|
|
184
|
-
const errors: Error[] = [];
|
|
185
|
-
for (const worker of this.workers) {
|
|
186
|
-
try {
|
|
187
|
-
await worker.transport.dispose();
|
|
188
|
-
} catch (e) {
|
|
189
|
-
errors.push(e instanceof Error ? e : new Error(String(e)));
|
|
190
|
-
}
|
|
191
|
-
}
|
|
192
|
-
this.workers.length = 0;
|
|
193
|
-
|
|
194
|
-
// Report errors if any
|
|
195
|
-
if (errors.length === 1) {
|
|
196
|
-
throw errors[0];
|
|
197
|
-
}
|
|
198
|
-
if (errors.length > 1) {
|
|
199
|
-
throw new AggregateError(errors, 'Multiple errors during worker disposal');
|
|
200
|
-
}
|
|
201
|
-
}
|
|
202
|
-
|
|
203
|
-
// ===========================================================================
|
|
204
|
-
// WORKER MANAGEMENT
|
|
205
|
-
// ===========================================================================
|
|
206
|
-
|
|
207
|
-
/**
|
|
208
|
-
* Acquire a worker from the pool.
|
|
209
|
-
*
|
|
210
|
-
* This method:
|
|
211
|
-
* - Returns an available worker if one exists (inFlightCount < maxConcurrentPerWorker)
|
|
212
|
-
* - Creates a new worker if under the maxWorkers limit
|
|
213
|
-
* - Waits in queue if all workers are at capacity
|
|
214
|
-
*
|
|
215
|
-
* @returns Promise resolving to a pooled worker
|
|
216
|
-
* @throws BridgeTimeoutError if queue timeout expires
|
|
217
|
-
* @throws BridgeExecutionError if pool is disposed while waiting
|
|
218
|
-
*/
|
|
219
|
-
async acquire(): Promise<TransportLease> {
|
|
220
|
-
// Check for disposed state
|
|
221
|
-
if (this.isDisposed || this.state === 'disposing') {
|
|
222
|
-
throw new BridgeExecutionError('Pool has been disposed');
|
|
223
|
-
}
|
|
224
|
-
|
|
225
|
-
// Find an available worker (one with capacity)
|
|
226
|
-
const availableWorker = this.findAvailableWorker();
|
|
227
|
-
if (availableWorker) {
|
|
228
|
-
availableWorker.inFlightCount++;
|
|
229
|
-
return availableWorker;
|
|
230
|
-
}
|
|
231
|
-
|
|
232
|
-
// Create a new worker if under the limit
|
|
233
|
-
// Include pendingCreations to prevent race condition where multiple
|
|
234
|
-
// concurrent acquire() calls all pass the length check before any
|
|
235
|
-
// worker is actually added to the array
|
|
236
|
-
if (this.workers.length + this.pendingCreations < this.options.maxWorkers) {
|
|
237
|
-
this.pendingCreations++;
|
|
238
|
-
try {
|
|
239
|
-
const newWorker = await this.createWorker();
|
|
240
|
-
if (this.isShuttingDown()) {
|
|
241
|
-
this.removeWorker(newWorker);
|
|
242
|
-
throw new BridgeExecutionError('Pool has been disposed');
|
|
243
|
-
}
|
|
244
|
-
newWorker.inFlightCount++;
|
|
245
|
-
this.publishAvailableWorker(newWorker);
|
|
246
|
-
return newWorker;
|
|
247
|
-
} finally {
|
|
248
|
-
this.pendingCreations--;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// All workers at capacity - wait in queue
|
|
253
|
-
return this.waitForWorker();
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
/**
|
|
257
|
-
* Release a worker back to the pool.
|
|
258
|
-
*
|
|
259
|
-
* Decrements the worker's in-flight count and notifies any waiters
|
|
260
|
-
* that a worker may be available.
|
|
261
|
-
*
|
|
262
|
-
* @param worker - The worker to release
|
|
263
|
-
*/
|
|
264
|
-
release(worker: TransportLease): void {
|
|
265
|
-
// Validate the worker belongs to this pool
|
|
266
|
-
if (!this.workers.includes(worker)) {
|
|
267
|
-
return;
|
|
268
|
-
}
|
|
269
|
-
|
|
270
|
-
// Decrement in-flight count (minimum 0)
|
|
271
|
-
worker.inFlightCount = Math.max(0, worker.inFlightCount - 1);
|
|
272
|
-
this.publishAvailableWorker(worker);
|
|
273
|
-
}
|
|
274
|
-
|
|
275
|
-
/**
|
|
276
|
-
* Execute a function with an acquired worker, automatically releasing afterward.
|
|
277
|
-
*
|
|
278
|
-
* This is the recommended way to use the pool, as it ensures proper cleanup
|
|
279
|
-
* even if the function throws an error.
|
|
280
|
-
*
|
|
281
|
-
* @param fn - Async function to execute with the worker
|
|
282
|
-
* @returns Promise resolving to the function's return value
|
|
283
|
-
*
|
|
284
|
-
* @example
|
|
285
|
-
* ```typescript
|
|
286
|
-
* const result = await pool.withWorker(async (worker) => {
|
|
287
|
-
* return worker.transport.send(message, timeout);
|
|
288
|
-
* });
|
|
289
|
-
* ```
|
|
290
|
-
*/
|
|
291
|
-
async withWorker<T>(fn: (worker: TransportLease) => Promise<T>): Promise<T> {
|
|
292
|
-
const worker = await this.acquire();
|
|
293
|
-
let workerRemoved = false;
|
|
294
|
-
|
|
295
|
-
try {
|
|
296
|
-
return await fn(worker);
|
|
297
|
-
} catch (error) {
|
|
298
|
-
// If this is a fatal error indicating the worker is dead, remove it from the pool
|
|
299
|
-
if (this.isFatalWorkerError(error)) {
|
|
300
|
-
this.removeWorker(worker);
|
|
301
|
-
workerRemoved = true;
|
|
302
|
-
}
|
|
303
|
-
throw error;
|
|
304
|
-
} finally {
|
|
305
|
-
// Only release if worker wasn't removed due to fatal error
|
|
306
|
-
if (!workerRemoved) {
|
|
307
|
-
this.release(worker);
|
|
308
|
-
}
|
|
309
|
-
}
|
|
310
|
-
}
|
|
311
|
-
|
|
312
|
-
// ===========================================================================
|
|
313
|
-
// WORKER HEALTH
|
|
314
|
-
// ===========================================================================
|
|
315
|
-
|
|
316
|
-
/**
|
|
317
|
-
* Check if an error indicates the worker is dead and should be removed.
|
|
318
|
-
*
|
|
319
|
-
* Fatal errors include:
|
|
320
|
-
* - Process not running
|
|
321
|
-
* - Process exited unexpectedly
|
|
322
|
-
* - Pipe errors (EPIPE)
|
|
323
|
-
* - Connection reset errors (ECONNRESET)
|
|
324
|
-
*/
|
|
325
|
-
private isFatalWorkerError(error: unknown): boolean {
|
|
326
|
-
if (error instanceof BridgeProtocolError) {
|
|
327
|
-
const msg = error.message.toLowerCase();
|
|
328
|
-
return (
|
|
329
|
-
msg.includes('not running') ||
|
|
330
|
-
msg.includes('process exited') ||
|
|
331
|
-
msg.includes('epipe') ||
|
|
332
|
-
msg.includes('econnreset')
|
|
333
|
-
);
|
|
334
|
-
}
|
|
335
|
-
return false;
|
|
336
|
-
}
|
|
337
|
-
|
|
338
|
-
/**
|
|
339
|
-
* Remove a worker from the pool.
|
|
340
|
-
*
|
|
341
|
-
* This is called when a worker is detected as dead (crashed, pipe error, etc.).
|
|
342
|
-
* The worker's transport is disposed in the background.
|
|
343
|
-
*/
|
|
344
|
-
private removeWorker(worker: TransportLease): void {
|
|
345
|
-
const index = this.workers.indexOf(worker);
|
|
346
|
-
if (index !== -1) {
|
|
347
|
-
this.workers.splice(index, 1);
|
|
348
|
-
// Dispose transport in background - don't await to avoid blocking
|
|
349
|
-
worker.transport.dispose().catch(() => {
|
|
350
|
-
// Ignore disposal errors for dead workers
|
|
351
|
-
});
|
|
352
|
-
if (this.state === 'ready') {
|
|
353
|
-
this.scheduleReplacementWorker();
|
|
354
|
-
}
|
|
355
|
-
}
|
|
356
|
-
}
|
|
357
|
-
|
|
358
|
-
// ===========================================================================
|
|
359
|
-
// POOL STATISTICS
|
|
360
|
-
// ===========================================================================
|
|
361
|
-
|
|
362
|
-
/**
|
|
363
|
-
* Current number of workers in the pool.
|
|
364
|
-
*/
|
|
365
|
-
get workerCount(): number {
|
|
366
|
-
return this.workers.length;
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
/**
|
|
370
|
-
* Number of callers waiting in the queue.
|
|
371
|
-
*/
|
|
372
|
-
get queueLength(): number {
|
|
373
|
-
return this.waitQueue.length;
|
|
374
|
-
}
|
|
375
|
-
|
|
376
|
-
/**
|
|
377
|
-
* Total number of in-flight requests across all workers.
|
|
378
|
-
*/
|
|
379
|
-
get totalInFlight(): number {
|
|
380
|
-
return this.workers.reduce((sum, w) => sum + w.inFlightCount, 0);
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
// ===========================================================================
|
|
384
|
-
// PRIVATE HELPERS
|
|
385
|
-
// ===========================================================================
|
|
386
|
-
|
|
387
|
-
/**
|
|
388
|
-
* Find an available worker with capacity for another request.
|
|
389
|
-
*/
|
|
390
|
-
private findAvailableWorker(): TransportLease | undefined {
|
|
391
|
-
return this.workers.find(w => w.inFlightCount < this.options.maxConcurrentPerWorker);
|
|
392
|
-
}
|
|
393
|
-
|
|
394
|
-
private getMinimumWorkerDeficit(): number {
|
|
395
|
-
return Math.max(0, this.options.minWorkers - (this.workers.length + this.pendingCreations));
|
|
396
|
-
}
|
|
397
|
-
|
|
398
|
-
private isShuttingDown(): boolean {
|
|
399
|
-
return this.isDisposed || this.state === 'disposing';
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
private async fillToMinimumWorkers(): Promise<void> {
|
|
403
|
-
await this.spawnWorkers(this.getMinimumWorkerDeficit());
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
private async spawnWorkers(count: number): Promise<void> {
|
|
407
|
-
if (count === 0) {
|
|
408
|
-
return;
|
|
409
|
-
}
|
|
410
|
-
this.pendingCreations += count;
|
|
411
|
-
try {
|
|
412
|
-
await Promise.all(Array.from({ length: count }, () => this.spawnWorkerToPool()));
|
|
413
|
-
} finally {
|
|
414
|
-
this.pendingCreations = Math.max(0, this.pendingCreations - count);
|
|
415
|
-
}
|
|
416
|
-
}
|
|
417
|
-
|
|
418
|
-
/**
|
|
419
|
-
* Replace a removed worker in the background so the next caller does not pay
|
|
420
|
-
* the full worker cold-start penalty after a timeout or crash.
|
|
421
|
-
*/
|
|
422
|
-
private scheduleReplacementWorker(): void {
|
|
423
|
-
if (this.state !== 'ready') {
|
|
424
|
-
return;
|
|
425
|
-
}
|
|
426
|
-
if (this.workers.length + this.pendingCreations >= this.options.maxWorkers) {
|
|
427
|
-
return;
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
this.pendingCreations++;
|
|
431
|
-
const replacementReady = this.options.onReplacementWorkerReady ?? this.options.onWorkerReady;
|
|
432
|
-
this.spawnWorkerToPool(replacementReady)
|
|
433
|
-
.catch(() => {
|
|
434
|
-
// Ignore background replacement failures. A later acquire() can retry.
|
|
435
|
-
})
|
|
436
|
-
.finally(() => {
|
|
437
|
-
this.pendingCreations = Math.max(0, this.pendingCreations - 1);
|
|
438
|
-
});
|
|
439
|
-
}
|
|
440
|
-
|
|
441
|
-
private async spawnWorkerToPool(onWorkerReady = this.options.onWorkerReady): Promise<void> {
|
|
442
|
-
if (this.isShuttingDown()) {
|
|
443
|
-
return;
|
|
444
|
-
}
|
|
445
|
-
|
|
446
|
-
const worker = await this.createWorker(onWorkerReady);
|
|
447
|
-
if (this.isShuttingDown()) {
|
|
448
|
-
this.removeWorker(worker);
|
|
449
|
-
return;
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
this.publishAvailableWorker(worker);
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
private publishAvailableWorker(worker: TransportLease): void {
|
|
456
|
-
while (
|
|
457
|
-
this.waitQueue.length > 0 &&
|
|
458
|
-
worker.inFlightCount < this.options.maxConcurrentPerWorker
|
|
459
|
-
) {
|
|
460
|
-
const waiter = this.waitQueue.shift();
|
|
461
|
-
if (!waiter) {
|
|
462
|
-
return;
|
|
463
|
-
}
|
|
464
|
-
clearTimeout(waiter.timer);
|
|
465
|
-
worker.inFlightCount++;
|
|
466
|
-
waiter.resolve(worker);
|
|
467
|
-
}
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
/**
|
|
471
|
-
* Create a new worker and add it to the pool.
|
|
472
|
-
*
|
|
473
|
-
* If onWorkerReady is configured, calls it after the transport is initialized.
|
|
474
|
-
* This is useful for per-worker warmup (importing modules, running setup).
|
|
475
|
-
*/
|
|
476
|
-
private async createWorker(onWorkerReady = this.options.onWorkerReady): Promise<TransportLease> {
|
|
477
|
-
const transport = this.options.createTransport();
|
|
478
|
-
|
|
479
|
-
// Initialize the transport
|
|
480
|
-
await transport.init();
|
|
481
|
-
|
|
482
|
-
const worker: TransportLease = {
|
|
483
|
-
transport,
|
|
484
|
-
inFlightCount: 0,
|
|
485
|
-
};
|
|
486
|
-
|
|
487
|
-
try {
|
|
488
|
-
// Call onWorkerReady callback if provided
|
|
489
|
-
if (onWorkerReady) {
|
|
490
|
-
await onWorkerReady(worker);
|
|
491
|
-
}
|
|
492
|
-
} catch (error) {
|
|
493
|
-
// Ensure partially initialized workers do not leak when warmup fails.
|
|
494
|
-
await transport.dispose().catch(() => {
|
|
495
|
-
// Ignore disposal failures during warmup failure handling.
|
|
496
|
-
});
|
|
497
|
-
throw error;
|
|
498
|
-
}
|
|
499
|
-
|
|
500
|
-
if (this.state === 'disposing' || this.state === 'disposed') {
|
|
501
|
-
await transport.dispose().catch(() => {
|
|
502
|
-
// Ignore disposal failures if the pool was torn down mid-creation.
|
|
503
|
-
});
|
|
504
|
-
throw new BridgeExecutionError('Pool disposed during worker creation');
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
this.workers.push(worker);
|
|
508
|
-
|
|
509
|
-
return worker;
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
/**
|
|
513
|
-
* Wait in queue for a worker to become available.
|
|
514
|
-
*/
|
|
515
|
-
private waitForWorker(): Promise<TransportLease> {
|
|
516
|
-
return new Promise<TransportLease>((resolve, reject) => {
|
|
517
|
-
const timer = setTimeout(() => {
|
|
518
|
-
// Remove this waiter from the queue
|
|
519
|
-
const index = this.waitQueue.findIndex(w => w.timer === timer);
|
|
520
|
-
if (index !== -1) {
|
|
521
|
-
this.waitQueue.splice(index, 1);
|
|
522
|
-
}
|
|
523
|
-
reject(
|
|
524
|
-
new BridgeTimeoutError(
|
|
525
|
-
`Timed out waiting for available worker after ${this.options.queueTimeoutMs}ms`
|
|
526
|
-
)
|
|
527
|
-
);
|
|
528
|
-
}, this.options.queueTimeoutMs);
|
|
529
|
-
|
|
530
|
-
// Unref the timer so it doesn't keep the Node.js process alive
|
|
531
|
-
if (typeof timer.unref === 'function') {
|
|
532
|
-
timer.unref();
|
|
533
|
-
}
|
|
534
|
-
|
|
535
|
-
this.waitQueue.push({ resolve, reject, timer });
|
|
536
|
-
});
|
|
537
|
-
}
|
|
538
|
-
}
|