tywrap 0.1.2 → 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 CHANGED
@@ -1,12 +1,13 @@
1
1
  # tywrap
2
2
 
3
3
  [![npm version](https://img.shields.io/npm/v/tywrap.svg)](https://www.npmjs.com/package/tywrap)
4
+ [![PyPI version](https://img.shields.io/pypi/v/tywrap-ir.svg)](https://pypi.org/project/tywrap-ir/)
4
5
  [![CI](https://github.com/bbopen/tywrap/actions/workflows/ci.yml/badge.svg)](https://github.com/bbopen/tywrap/actions/workflows/ci.yml)
5
6
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
6
7
 
7
8
  TypeScript wrapper for Python libraries with full type safety.
8
9
 
9
- > **⚠️ Experimental Software (v0.1.2)** - APIs may change between versions. Not recommended for production use until v1.0.0.
10
+ > **⚠️ Experimental Software (v0.2.0)** - APIs may change between versions. Not recommended for production use until v1.0.0.
10
11
 
11
12
  ## Features
12
13
 
@@ -18,14 +19,19 @@ TypeScript wrapper for Python libraries with full type safety.
18
19
  ## Requirements
19
20
 
20
21
  - Node.js 20+ (or Bun 1.1+ / Deno 1.46+)
21
- - Python 3.10+
22
+ - Python 3.10+ with `tywrap-ir`:
23
+
24
+ ```bash
25
+ pip install tywrap-ir
26
+ ```
22
27
 
23
28
  ## Quick Start
24
29
 
25
30
  ```bash
26
31
  npm install tywrap
27
- npx tywrap init # Create config (and package.json scripts if present)
28
- npx tywrap generate # Generate wrappers
32
+ pip install tywrap-ir # Python component for code generation
33
+ npx tywrap init # Create config (and package.json scripts if present)
34
+ npx tywrap generate # Generate wrappers
29
35
  ```
30
36
 
31
37
  For CI (or to verify a dependency upgrade didn’t change the generated surface):
@@ -149,4 +155,5 @@ MIT © [tywrap contributors](LICENSE)
149
155
 
150
156
  - [GitHub](https://github.com/bbopen/tywrap)
151
157
  - [npm](https://www.npmjs.com/package/tywrap)
158
+ - [PyPI](https://pypi.org/project/tywrap-ir/)
152
159
  - [Issues](https://github.com/bbopen/tywrap/issues)
package/dist/index.d.ts CHANGED
@@ -18,7 +18,7 @@ export { tywrap } from './tywrap.js';
18
18
  export { generate } from './tywrap.js';
19
19
  export { detectRuntime, isNodejs, isDeno, isBun, isBrowser } from './utils/runtime.js';
20
20
  export { decodeValue, decodeValueAsync, autoRegisterArrowDecoder, registerArrowDecoder, clearArrowDecoder, } from './utils/codec.js';
21
- export declare const VERSION = "0.1.2";
21
+ export declare const VERSION = "0.2.0";
22
22
  /**
23
23
  * Quick setup function for getting started
24
24
  */
package/dist/index.js CHANGED
@@ -20,7 +20,7 @@ export { generate } from './tywrap.js';
20
20
  export { detectRuntime, isNodejs, isDeno, isBun, isBrowser } from './utils/runtime.js';
21
21
  export { decodeValue, decodeValueAsync, autoRegisterArrowDecoder, registerArrowDecoder, clearArrowDecoder, } from './utils/codec.js';
22
22
  // Version info
23
- export const VERSION = '0.1.2';
23
+ export const VERSION = '0.2.0';
24
24
  /**
25
25
  * Quick setup function for getting started
26
26
  */
@@ -1,35 +1,115 @@
1
1
  /**
2
- * Node.js runtime bridge (minimal MVP)
2
+ * Node.js Runtime Bridge with Optional Connection Pooling
3
+ *
4
+ * NodeBridge is the unified Node.js runtime bridge that supports both single-process
5
+ * (correctness-first) and multi-process (pooled) configurations. By default, it runs
6
+ * in single-process mode for maximum compatibility with the original NodeBridge behavior.
7
+ *
8
+ * For high-throughput workloads, configure pooling via minProcesses/maxProcesses options.
3
9
  */
4
10
  import type { BridgeInfo } from '../types/index.js';
5
11
  import { RuntimeBridge } from './base.js';
12
+ /**
13
+ * Configuration options for NodeBridge.
14
+ *
15
+ * By default, NodeBridge runs in single-process mode (minProcesses=1, maxProcesses=1).
16
+ * For high-throughput workloads, increase these values to enable process pooling.
17
+ */
6
18
  export interface NodeBridgeOptions {
19
+ /** Minimum number of Python processes to keep alive. Default: 1 */
20
+ minProcesses?: number;
21
+ /** Maximum number of Python processes to spawn. Default: 1 (single-process mode) */
22
+ maxProcesses?: number;
23
+ /** Time in ms to keep idle processes alive before termination. Default: 300000 (5 min) */
24
+ maxIdleTime?: number;
25
+ /** Restart process after this many requests. Default: 1000 */
26
+ maxRequestsPerProcess?: number;
27
+ /** Path to Python executable. Auto-detected if not specified. */
7
28
  pythonPath?: string;
29
+ /** Path to python_bridge.py script. Auto-detected if not specified. */
8
30
  scriptPath?: string;
31
+ /** Path to Python virtual environment. */
9
32
  virtualEnv?: string;
33
+ /** Working directory for Python process. Default: process.cwd() */
10
34
  cwd?: string;
35
+ /** Timeout in ms for Python calls. Default: 30000 */
11
36
  timeoutMs?: number;
37
+ /** Maximum line length for JSONL protocol. */
12
38
  maxLineLength?: number;
39
+ /** Inherit all environment variables from parent process. Default: false */
13
40
  inheritProcessEnv?: boolean;
14
41
  /**
15
42
  * When true, sets TYWRAP_CODEC_FALLBACK=json for the Python process to prefer JSON encoding
16
43
  * for rich types (ndarray/dataframe/series). Default: false for fast-fail on Arrow path issues.
17
44
  */
18
45
  enableJsonFallback?: boolean;
19
- /**
20
- * Optional extra environment variables to pass to the Python subprocess.
21
- */
46
+ /** Enable result caching for pure functions. Default: false */
47
+ enableCache?: boolean;
48
+ /** Optional extra environment variables to pass to the Python subprocess. */
22
49
  env?: Record<string, string | undefined>;
50
+ /** Commands to run on each process at startup for warming up. */
51
+ warmupCommands?: Array<{
52
+ method: string;
53
+ params: unknown;
54
+ }>;
55
+ }
56
+ interface BridgeStats {
57
+ totalRequests: number;
58
+ totalTime: number;
59
+ cacheHits: number;
60
+ poolHits: number;
61
+ poolMisses: number;
62
+ processSpawns: number;
63
+ processDeaths: number;
64
+ memoryPeak: number;
65
+ averageTime: number;
66
+ cacheHitRate: number;
67
+ }
68
+ interface BridgeStatsSnapshot extends BridgeStats {
69
+ poolSize: number;
70
+ busyWorkers: number;
71
+ memoryUsage: NodeJS.MemoryUsage;
72
+ workerStats: Array<{
73
+ id: string;
74
+ requestCount: number;
75
+ averageTime: number;
76
+ errorCount: number;
77
+ busy: boolean;
78
+ pendingRequests: number;
79
+ }>;
23
80
  }
81
+ /**
82
+ * Node.js runtime bridge for executing Python code.
83
+ *
84
+ * By default, runs in single-process mode for correctness-first behavior.
85
+ * Configure minProcesses/maxProcesses for process pooling in high-throughput scenarios.
86
+ *
87
+ * @example
88
+ * ```typescript
89
+ * // Single-process mode (default)
90
+ * const bridge = new NodeBridge();
91
+ *
92
+ * // Multi-process pooling for high throughput
93
+ * const pooledBridge = new NodeBridge({
94
+ * minProcesses: 2,
95
+ * maxProcesses: 8,
96
+ * enableCache: true,
97
+ * });
98
+ * ```
99
+ */
24
100
  export declare class NodeBridge extends RuntimeBridge {
25
- private child?;
26
- private core?;
27
- private readonly options;
101
+ private processPool;
102
+ private roundRobinIndex;
103
+ private cleanupTimer?;
104
+ private options;
105
+ private emitter;
28
106
  private disposed;
29
- private initPromise?;
30
107
  private bridgeInfo?;
108
+ private initPromise?;
109
+ private stats;
31
110
  constructor(options?: NodeBridgeOptions);
32
111
  init(): Promise<void>;
112
+ private doInit;
33
113
  getBridgeInfo(options?: {
34
114
  refresh?: boolean;
35
115
  }): Promise<BridgeInfo>;
@@ -37,11 +117,78 @@ export declare class NodeBridge extends RuntimeBridge {
37
117
  instantiate<T = unknown>(module: string, className: string, args: unknown[], kwargs?: Record<string, unknown>): Promise<T>;
38
118
  callMethod<T = unknown>(handle: string, methodName: string, args: unknown[], kwargs?: Record<string, unknown>): Promise<T>;
39
119
  disposeInstance(handle: string): Promise<void>;
120
+ /**
121
+ * Execute request with intelligent process selection
122
+ */
123
+ private executeRequest;
124
+ /**
125
+ * Select optimal worker based on load and performance
126
+ */
127
+ private selectOptimalWorker;
128
+ /**
129
+ * Wait for any worker to become available
130
+ */
131
+ private waitForAvailableWorker;
132
+ /**
133
+ * Send request to specific worker
134
+ */
135
+ private sendToWorker;
136
+ private quarantineWorker;
137
+ /**
138
+ * Spawn new worker process with optimizations
139
+ */
140
+ private spawnProcess;
141
+ /**
142
+ * Setup event handlers for worker process
143
+ */
144
+ private setupProcessHandlers;
145
+ /**
146
+ * Handle worker process exit
147
+ */
148
+ private handleWorkerExit;
149
+ /**
150
+ * Warm up processes with configured commands
151
+ */
152
+ private warmupProcesses;
153
+ private safeCacheKey;
154
+ /**
155
+ * Heuristic to determine if function result should be cached
156
+ */
157
+ private isPureFunctionCandidate;
158
+ /**
159
+ * Update performance statistics
160
+ */
161
+ private updateStats;
162
+ /**
163
+ * Get performance statistics
164
+ */
165
+ getStats(): BridgeStatsSnapshot;
166
+ /**
167
+ * Cleanup idle processes
168
+ */
169
+ private cleanup;
170
+ /**
171
+ * Gracefully terminate a worker
172
+ */
173
+ private terminateWorker;
174
+ /**
175
+ * Start cleanup scheduler
176
+ */
177
+ private startCleanupScheduler;
178
+ /**
179
+ * Dispose all resources
180
+ */
40
181
  dispose(): Promise<void>;
41
- private send;
42
- private startProcess;
43
182
  private buildEnv;
44
- private resetProcess;
45
183
  private refreshBridgeInfo;
46
184
  }
185
+ /**
186
+ * @deprecated Use NodeBridge with minProcesses/maxProcesses options instead.
187
+ * This alias is provided for backward compatibility.
188
+ */
189
+ export { NodeBridge as OptimizedNodeBridge };
190
+ /**
191
+ * @deprecated Use NodeBridgeOptions instead.
192
+ */
193
+ export type { NodeBridgeOptions as ProcessPoolOptions };
47
194
  //# sourceMappingURL=node.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"node.d.ts","sourceRoot":"","sources":["../../src/runtime/node.ts"],"names":[],"mappings":"AAAA;;GAEG;AAUH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAEpD,OAAO,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AAa1C,MAAM,WAAW,iBAAiB;IAChC,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,SAAS,CA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