@push.rocks/smartrust 1.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.
- package/.gitea/workflows/default_nottags.yaml +66 -0
- package/.gitea/workflows/default_tags.yaml +124 -0
- package/.vscode/launch.json +11 -0
- package/.vscode/settings.json +26 -0
- package/changelog.md +22 -0
- package/dist_ts/00_commitinfo_data.d.ts +8 -0
- package/dist_ts/00_commitinfo_data.js +9 -0
- package/dist_ts/classes.rustbinarylocator.d.ts +28 -0
- package/dist_ts/classes.rustbinarylocator.js +126 -0
- package/dist_ts/classes.rustbridge.d.ts +39 -0
- package/dist_ts/classes.rustbridge.js +231 -0
- package/dist_ts/index.d.ts +3 -0
- package/dist_ts/index.js +4 -0
- package/dist_ts/interfaces/config.d.ts +40 -0
- package/dist_ts/interfaces/config.js +2 -0
- package/dist_ts/interfaces/index.d.ts +2 -0
- package/dist_ts/interfaces/index.js +3 -0
- package/dist_ts/interfaces/ipc.d.ts +36 -0
- package/dist_ts/interfaces/ipc.js +2 -0
- package/dist_ts/paths.d.ts +1 -0
- package/dist_ts/paths.js +3 -0
- package/dist_ts/plugins.d.ts +8 -0
- package/dist_ts/plugins.js +11 -0
- package/npmextra.json +24 -0
- package/package.json +25 -0
- package/readme.md +5 -0
- package/test/helpers/mock-rust-binary.mjs +62 -0
- package/test/test.rustbinarylocator.node.ts +98 -0
- package/test/test.rustbridge.node.ts +191 -0
- package/test/test.ts +12 -0
- package/ts/00_commitinfo_data.ts +8 -0
- package/ts/classes.rustbinarylocator.ts +140 -0
- package/ts/classes.rustbridge.ts +256 -0
- package/ts/index.ts +3 -0
- package/ts/interfaces/config.ts +42 -0
- package/ts/interfaces/index.ts +2 -0
- package/ts/interfaces/ipc.ts +40 -0
- package/ts/paths.ts +5 -0
- package/ts/plugins.ts +13 -0
- package/tsconfig.json +12 -0
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
|
2
|
+
import * as path from 'path';
|
|
3
|
+
import { RustBridge } from '../ts/classes.rustbridge.js';
|
|
4
|
+
import type { ICommandDefinition } from '../ts/interfaces/index.js';
|
|
5
|
+
|
|
6
|
+
const testDir = path.resolve(path.dirname(new URL(import.meta.url).pathname));
|
|
7
|
+
const mockBinaryPath = path.join(testDir, 'helpers/mock-rust-binary.mjs');
|
|
8
|
+
|
|
9
|
+
// Define the command types for our mock binary
|
|
10
|
+
type TMockCommands = {
|
|
11
|
+
echo: { params: Record<string, any>; result: Record<string, any> };
|
|
12
|
+
error: { params: {}; result: never };
|
|
13
|
+
emitEvent: { params: { eventName: string; eventData: any }; result: null };
|
|
14
|
+
slow: { params: {}; result: { delayed: boolean } };
|
|
15
|
+
exit: { params: {}; result: null };
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
tap.test('should spawn and receive ready event', async () => {
|
|
19
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
20
|
+
binaryName: 'node',
|
|
21
|
+
binaryPath: 'node',
|
|
22
|
+
cliArgs: [mockBinaryPath],
|
|
23
|
+
readyTimeoutMs: 5000,
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
const result = await bridge.spawn();
|
|
27
|
+
expect(result).toBeTrue();
|
|
28
|
+
expect(bridge.running).toBeTrue();
|
|
29
|
+
|
|
30
|
+
bridge.kill();
|
|
31
|
+
expect(bridge.running).toBeFalse();
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
tap.test('should send command and receive response', async () => {
|
|
35
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
36
|
+
binaryName: 'node',
|
|
37
|
+
binaryPath: 'node',
|
|
38
|
+
cliArgs: [mockBinaryPath],
|
|
39
|
+
readyTimeoutMs: 5000,
|
|
40
|
+
});
|
|
41
|
+
|
|
42
|
+
await bridge.spawn();
|
|
43
|
+
|
|
44
|
+
const result = await bridge.sendCommand('echo', { hello: 'world', num: 42 });
|
|
45
|
+
expect(result).toEqual({ hello: 'world', num: 42 });
|
|
46
|
+
|
|
47
|
+
bridge.kill();
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
tap.test('should handle error responses', async () => {
|
|
51
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
52
|
+
binaryName: 'node',
|
|
53
|
+
binaryPath: 'node',
|
|
54
|
+
cliArgs: [mockBinaryPath],
|
|
55
|
+
readyTimeoutMs: 5000,
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
await bridge.spawn();
|
|
59
|
+
|
|
60
|
+
let threw = false;
|
|
61
|
+
try {
|
|
62
|
+
await bridge.sendCommand('error', {});
|
|
63
|
+
} catch (err: any) {
|
|
64
|
+
threw = true;
|
|
65
|
+
expect(err.message).toInclude('Test error message');
|
|
66
|
+
}
|
|
67
|
+
expect(threw).toBeTrue();
|
|
68
|
+
|
|
69
|
+
bridge.kill();
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
tap.test('should receive custom events from the binary', async () => {
|
|
73
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
74
|
+
binaryName: 'node',
|
|
75
|
+
binaryPath: 'node',
|
|
76
|
+
cliArgs: [mockBinaryPath],
|
|
77
|
+
readyTimeoutMs: 5000,
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
await bridge.spawn();
|
|
81
|
+
|
|
82
|
+
const eventPromise = new Promise<any>((resolve) => {
|
|
83
|
+
bridge.once('management:testEvent', (data) => {
|
|
84
|
+
resolve(data);
|
|
85
|
+
});
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
await bridge.sendCommand('emitEvent', {
|
|
89
|
+
eventName: 'testEvent',
|
|
90
|
+
eventData: { key: 'value' },
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
const eventData = await eventPromise;
|
|
94
|
+
expect(eventData).toEqual({ key: 'value' });
|
|
95
|
+
|
|
96
|
+
bridge.kill();
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
tap.test('should handle delayed responses', async () => {
|
|
100
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
101
|
+
binaryName: 'node',
|
|
102
|
+
binaryPath: 'node',
|
|
103
|
+
cliArgs: [mockBinaryPath],
|
|
104
|
+
readyTimeoutMs: 5000,
|
|
105
|
+
requestTimeoutMs: 5000,
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
await bridge.spawn();
|
|
109
|
+
|
|
110
|
+
const result = await bridge.sendCommand('slow', {});
|
|
111
|
+
expect(result).toEqual({ delayed: true });
|
|
112
|
+
|
|
113
|
+
bridge.kill();
|
|
114
|
+
});
|
|
115
|
+
|
|
116
|
+
tap.test('should handle multiple concurrent commands', async () => {
|
|
117
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
118
|
+
binaryName: 'node',
|
|
119
|
+
binaryPath: 'node',
|
|
120
|
+
cliArgs: [mockBinaryPath],
|
|
121
|
+
readyTimeoutMs: 5000,
|
|
122
|
+
});
|
|
123
|
+
|
|
124
|
+
await bridge.spawn();
|
|
125
|
+
|
|
126
|
+
const results = await Promise.all([
|
|
127
|
+
bridge.sendCommand('echo', { id: 1 }),
|
|
128
|
+
bridge.sendCommand('echo', { id: 2 }),
|
|
129
|
+
bridge.sendCommand('echo', { id: 3 }),
|
|
130
|
+
]);
|
|
131
|
+
|
|
132
|
+
expect(results[0]).toEqual({ id: 1 });
|
|
133
|
+
expect(results[1]).toEqual({ id: 2 });
|
|
134
|
+
expect(results[2]).toEqual({ id: 3 });
|
|
135
|
+
|
|
136
|
+
bridge.kill();
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
tap.test('should throw when sending command while not running', async () => {
|
|
140
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
141
|
+
binaryName: 'node',
|
|
142
|
+
binaryPath: 'node',
|
|
143
|
+
cliArgs: [mockBinaryPath],
|
|
144
|
+
});
|
|
145
|
+
|
|
146
|
+
let threw = false;
|
|
147
|
+
try {
|
|
148
|
+
await bridge.sendCommand('echo', {});
|
|
149
|
+
} catch (err: any) {
|
|
150
|
+
threw = true;
|
|
151
|
+
expect(err.message).toInclude('not running');
|
|
152
|
+
}
|
|
153
|
+
expect(threw).toBeTrue();
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
tap.test('should return false when binary not found', async () => {
|
|
157
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
158
|
+
binaryName: 'nonexistent-binary-xyz',
|
|
159
|
+
searchSystemPath: false,
|
|
160
|
+
});
|
|
161
|
+
|
|
162
|
+
const result = await bridge.spawn();
|
|
163
|
+
expect(result).toBeFalse();
|
|
164
|
+
expect(bridge.running).toBeFalse();
|
|
165
|
+
});
|
|
166
|
+
|
|
167
|
+
tap.test('should emit exit event when process exits', async () => {
|
|
168
|
+
const bridge = new RustBridge<TMockCommands>({
|
|
169
|
+
binaryName: 'node',
|
|
170
|
+
binaryPath: 'node',
|
|
171
|
+
cliArgs: [mockBinaryPath],
|
|
172
|
+
readyTimeoutMs: 5000,
|
|
173
|
+
});
|
|
174
|
+
|
|
175
|
+
await bridge.spawn();
|
|
176
|
+
|
|
177
|
+
const exitPromise = new Promise<number | null>((resolve) => {
|
|
178
|
+
bridge.once('exit', (code) => {
|
|
179
|
+
resolve(code);
|
|
180
|
+
});
|
|
181
|
+
});
|
|
182
|
+
|
|
183
|
+
// Tell mock binary to exit
|
|
184
|
+
await bridge.sendCommand('exit', {});
|
|
185
|
+
|
|
186
|
+
const exitCode = await exitPromise;
|
|
187
|
+
expect(exitCode).toEqual(0);
|
|
188
|
+
expect(bridge.running).toBeFalse();
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
export default tap.start();
|
package/test/test.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { expect, tap } from '@git.zone/tstest/tapbundle';
|
|
2
|
+
import * as smartrust from '../ts/index.js';
|
|
3
|
+
|
|
4
|
+
tap.test('should export RustBridge', async () => {
|
|
5
|
+
expect(smartrust.RustBridge).toBeTypeOf('function');
|
|
6
|
+
});
|
|
7
|
+
|
|
8
|
+
tap.test('should export RustBinaryLocator', async () => {
|
|
9
|
+
expect(smartrust.RustBinaryLocator).toBeTypeOf('function');
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
export default tap.start();
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import type { IBinaryLocatorOptions, IRustBridgeLogger } from './interfaces/index.js';
|
|
3
|
+
|
|
4
|
+
const defaultLogger: IRustBridgeLogger = {
|
|
5
|
+
log() {},
|
|
6
|
+
};
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Locates a Rust binary using a priority-ordered search strategy:
|
|
10
|
+
* 1. Explicit binaryPath override
|
|
11
|
+
* 2. Environment variable
|
|
12
|
+
* 3. Platform-specific npm package
|
|
13
|
+
* 4. Local development build paths
|
|
14
|
+
* 5. System PATH
|
|
15
|
+
*/
|
|
16
|
+
export class RustBinaryLocator {
|
|
17
|
+
private options: IBinaryLocatorOptions;
|
|
18
|
+
private logger: IRustBridgeLogger;
|
|
19
|
+
private cachedPath: string | null = null;
|
|
20
|
+
|
|
21
|
+
constructor(options: IBinaryLocatorOptions, logger?: IRustBridgeLogger) {
|
|
22
|
+
this.options = options;
|
|
23
|
+
this.logger = logger || defaultLogger;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Find the binary path.
|
|
28
|
+
* Returns null if no binary is available.
|
|
29
|
+
*/
|
|
30
|
+
public async findBinary(): Promise<string | null> {
|
|
31
|
+
if (this.cachedPath !== null) {
|
|
32
|
+
return this.cachedPath;
|
|
33
|
+
}
|
|
34
|
+
const path = await this.searchBinary();
|
|
35
|
+
this.cachedPath = path;
|
|
36
|
+
return path;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Clear the cached binary path.
|
|
41
|
+
*/
|
|
42
|
+
public clearCache(): void {
|
|
43
|
+
this.cachedPath = null;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
private async searchBinary(): Promise<string | null> {
|
|
47
|
+
const { binaryName } = this.options;
|
|
48
|
+
|
|
49
|
+
// 1. Explicit binary path override
|
|
50
|
+
if (this.options.binaryPath) {
|
|
51
|
+
if (await this.isExecutable(this.options.binaryPath)) {
|
|
52
|
+
this.logger.log('info', `Binary found via explicit path: ${this.options.binaryPath}`);
|
|
53
|
+
return this.options.binaryPath;
|
|
54
|
+
}
|
|
55
|
+
this.logger.log('warn', `Explicit binary path not executable: ${this.options.binaryPath}`);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// 2. Environment variable override
|
|
59
|
+
if (this.options.envVarName) {
|
|
60
|
+
const envPath = process.env[this.options.envVarName];
|
|
61
|
+
if (envPath) {
|
|
62
|
+
if (await this.isExecutable(envPath)) {
|
|
63
|
+
this.logger.log('info', `Binary found via ${this.options.envVarName}: ${envPath}`);
|
|
64
|
+
return envPath;
|
|
65
|
+
}
|
|
66
|
+
this.logger.log('warn', `${this.options.envVarName} set but not executable: ${envPath}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
// 3. Platform-specific npm package
|
|
71
|
+
if (this.options.platformPackagePrefix) {
|
|
72
|
+
const platformBinary = await this.findPlatformPackageBinary();
|
|
73
|
+
if (platformBinary) {
|
|
74
|
+
this.logger.log('info', `Binary found in platform package: ${platformBinary}`);
|
|
75
|
+
return platformBinary;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// 4. Local development build paths
|
|
80
|
+
const localPaths = this.options.localPaths || [
|
|
81
|
+
plugins.path.resolve(process.cwd(), `rust/target/release/${binaryName}`),
|
|
82
|
+
plugins.path.resolve(process.cwd(), `rust/target/debug/${binaryName}`),
|
|
83
|
+
];
|
|
84
|
+
for (const localPath of localPaths) {
|
|
85
|
+
if (await this.isExecutable(localPath)) {
|
|
86
|
+
this.logger.log('info', `Binary found at local path: ${localPath}`);
|
|
87
|
+
return localPath;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
// 5. System PATH
|
|
92
|
+
if (this.options.searchSystemPath !== false) {
|
|
93
|
+
const systemPath = await this.findInPath(binaryName);
|
|
94
|
+
if (systemPath) {
|
|
95
|
+
this.logger.log('info', `Binary found in system PATH: ${systemPath}`);
|
|
96
|
+
return systemPath;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
this.logger.log('error', `No binary '${binaryName}' found. Provide an explicit path, set an env var, install the platform package, or build from source.`);
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
private async findPlatformPackageBinary(): Promise<string | null> {
|
|
105
|
+
const { binaryName, platformPackagePrefix } = this.options;
|
|
106
|
+
const platform = process.platform;
|
|
107
|
+
const arch = process.arch;
|
|
108
|
+
const packageName = `${platformPackagePrefix}-${platform}-${arch}`;
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
const packagePath = require.resolve(`${packageName}/${binaryName}`);
|
|
112
|
+
if (await this.isExecutable(packagePath)) {
|
|
113
|
+
return packagePath;
|
|
114
|
+
}
|
|
115
|
+
} catch {
|
|
116
|
+
// Package not installed - expected for development
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
private async isExecutable(filePath: string): Promise<boolean> {
|
|
122
|
+
try {
|
|
123
|
+
await plugins.fs.promises.access(filePath, plugins.fs.constants.X_OK);
|
|
124
|
+
return true;
|
|
125
|
+
} catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private async findInPath(binaryName: string): Promise<string | null> {
|
|
131
|
+
const pathDirs = (process.env.PATH || '').split(plugins.path.delimiter);
|
|
132
|
+
for (const dir of pathDirs) {
|
|
133
|
+
const fullPath = plugins.path.join(dir, binaryName);
|
|
134
|
+
if (await this.isExecutable(fullPath)) {
|
|
135
|
+
return fullPath;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+
import * as plugins from './plugins.js';
|
|
2
|
+
import { RustBinaryLocator } from './classes.rustbinarylocator.js';
|
|
3
|
+
import type {
|
|
4
|
+
IRustBridgeOptions,
|
|
5
|
+
IRustBridgeLogger,
|
|
6
|
+
TCommandMap,
|
|
7
|
+
IManagementRequest,
|
|
8
|
+
IManagementResponse,
|
|
9
|
+
IManagementEvent,
|
|
10
|
+
} from './interfaces/index.js';
|
|
11
|
+
|
|
12
|
+
const defaultLogger: IRustBridgeLogger = {
|
|
13
|
+
log() {},
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Generic bridge between TypeScript and a Rust binary.
|
|
18
|
+
* Communicates via JSON-over-stdin/stdout IPC protocol.
|
|
19
|
+
*
|
|
20
|
+
* @typeParam TCommands - Map of command names to their param/result types
|
|
21
|
+
*/
|
|
22
|
+
export class RustBridge<TCommands extends TCommandMap = TCommandMap> extends plugins.events.EventEmitter {
|
|
23
|
+
private locator: RustBinaryLocator;
|
|
24
|
+
private options: Required<Pick<IRustBridgeOptions, 'cliArgs' | 'requestTimeoutMs' | 'readyTimeoutMs' | 'readyEventName'>> & IRustBridgeOptions;
|
|
25
|
+
private logger: IRustBridgeLogger;
|
|
26
|
+
private childProcess: plugins.childProcess.ChildProcess | null = null;
|
|
27
|
+
private readlineInterface: plugins.readline.Interface | null = null;
|
|
28
|
+
private pendingRequests = new Map<string, {
|
|
29
|
+
resolve: (value: any) => void;
|
|
30
|
+
reject: (error: Error) => void;
|
|
31
|
+
timer: ReturnType<typeof setTimeout>;
|
|
32
|
+
}>();
|
|
33
|
+
private requestCounter = 0;
|
|
34
|
+
private isRunning = false;
|
|
35
|
+
private binaryPath: string | null = null;
|
|
36
|
+
|
|
37
|
+
constructor(options: IRustBridgeOptions) {
|
|
38
|
+
super();
|
|
39
|
+
this.logger = options.logger || defaultLogger;
|
|
40
|
+
this.options = {
|
|
41
|
+
cliArgs: ['--management'],
|
|
42
|
+
requestTimeoutMs: 30000,
|
|
43
|
+
readyTimeoutMs: 10000,
|
|
44
|
+
readyEventName: 'ready',
|
|
45
|
+
...options,
|
|
46
|
+
};
|
|
47
|
+
this.locator = new RustBinaryLocator(options, this.logger);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Spawn the Rust binary and wait for it to signal readiness.
|
|
52
|
+
* Returns true if the binary was found and spawned successfully.
|
|
53
|
+
*/
|
|
54
|
+
public async spawn(): Promise<boolean> {
|
|
55
|
+
this.binaryPath = await this.locator.findBinary();
|
|
56
|
+
if (!this.binaryPath) {
|
|
57
|
+
return false;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
return new Promise<boolean>((resolve) => {
|
|
61
|
+
try {
|
|
62
|
+
const env = this.options.env
|
|
63
|
+
? { ...process.env, ...this.options.env }
|
|
64
|
+
: { ...process.env };
|
|
65
|
+
|
|
66
|
+
this.childProcess = plugins.childProcess.spawn(this.binaryPath!, this.options.cliArgs, {
|
|
67
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
68
|
+
env,
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
// Handle stderr
|
|
72
|
+
this.childProcess.stderr?.on('data', (data: Buffer) => {
|
|
73
|
+
const lines = data.toString().split('\n').filter((l: string) => l.trim());
|
|
74
|
+
for (const line of lines) {
|
|
75
|
+
this.logger.log('debug', `[${this.options.binaryName}] ${line}`);
|
|
76
|
+
this.emit('stderr', line);
|
|
77
|
+
}
|
|
78
|
+
});
|
|
79
|
+
|
|
80
|
+
// Handle stdout via readline for line-delimited JSON
|
|
81
|
+
this.readlineInterface = plugins.readline.createInterface({ input: this.childProcess.stdout! });
|
|
82
|
+
this.readlineInterface.on('line', (line: string) => {
|
|
83
|
+
this.handleLine(line.trim());
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
// Handle process exit
|
|
87
|
+
this.childProcess.on('exit', (code, signal) => {
|
|
88
|
+
this.logger.log('info', `Process exited (code=${code}, signal=${signal})`);
|
|
89
|
+
this.cleanup();
|
|
90
|
+
this.emit('exit', code, signal);
|
|
91
|
+
});
|
|
92
|
+
|
|
93
|
+
this.childProcess.on('error', (err) => {
|
|
94
|
+
this.logger.log('error', `Process error: ${err.message}`);
|
|
95
|
+
this.cleanup();
|
|
96
|
+
resolve(false);
|
|
97
|
+
});
|
|
98
|
+
|
|
99
|
+
// Wait for the ready event
|
|
100
|
+
const readyTimeout = setTimeout(() => {
|
|
101
|
+
this.logger.log('error', `Process did not send ready event within ${this.options.readyTimeoutMs}ms`);
|
|
102
|
+
this.kill();
|
|
103
|
+
resolve(false);
|
|
104
|
+
}, this.options.readyTimeoutMs);
|
|
105
|
+
|
|
106
|
+
this.once(`management:${this.options.readyEventName}`, () => {
|
|
107
|
+
clearTimeout(readyTimeout);
|
|
108
|
+
this.isRunning = true;
|
|
109
|
+
this.logger.log('info', `Bridge connected to ${this.options.binaryName}`);
|
|
110
|
+
this.emit('ready');
|
|
111
|
+
resolve(true);
|
|
112
|
+
});
|
|
113
|
+
} catch (err: any) {
|
|
114
|
+
this.logger.log('error', `Failed to spawn: ${err.message}`);
|
|
115
|
+
resolve(false);
|
|
116
|
+
}
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* Send a typed command to the Rust process and wait for the response.
|
|
122
|
+
*/
|
|
123
|
+
public async sendCommand<K extends string & keyof TCommands>(
|
|
124
|
+
method: K,
|
|
125
|
+
params: TCommands[K]['params'],
|
|
126
|
+
): Promise<TCommands[K]['result']> {
|
|
127
|
+
if (!this.childProcess || !this.isRunning) {
|
|
128
|
+
throw new Error(`${this.options.binaryName} bridge is not running`);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const id = `req_${++this.requestCounter}`;
|
|
132
|
+
const request: IManagementRequest = { id, method, params };
|
|
133
|
+
|
|
134
|
+
return new Promise<TCommands[K]['result']>((resolve, reject) => {
|
|
135
|
+
const timer = setTimeout(() => {
|
|
136
|
+
this.pendingRequests.delete(id);
|
|
137
|
+
reject(new Error(`Command '${method}' timed out after ${this.options.requestTimeoutMs}ms`));
|
|
138
|
+
}, this.options.requestTimeoutMs);
|
|
139
|
+
|
|
140
|
+
this.pendingRequests.set(id, { resolve, reject, timer });
|
|
141
|
+
|
|
142
|
+
const json = JSON.stringify(request) + '\n';
|
|
143
|
+
this.childProcess!.stdin!.write(json, (err) => {
|
|
144
|
+
if (err) {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
this.pendingRequests.delete(id);
|
|
147
|
+
reject(new Error(`Failed to write to stdin: ${err.message}`));
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
});
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Kill the Rust process and clean up all resources.
|
|
155
|
+
*/
|
|
156
|
+
public kill(): void {
|
|
157
|
+
if (this.childProcess) {
|
|
158
|
+
const proc = this.childProcess;
|
|
159
|
+
this.childProcess = null;
|
|
160
|
+
this.isRunning = false;
|
|
161
|
+
|
|
162
|
+
// Close readline
|
|
163
|
+
if (this.readlineInterface) {
|
|
164
|
+
this.readlineInterface.close();
|
|
165
|
+
this.readlineInterface = null;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Reject pending requests
|
|
169
|
+
for (const [, pending] of this.pendingRequests) {
|
|
170
|
+
clearTimeout(pending.timer);
|
|
171
|
+
pending.reject(new Error(`${this.options.binaryName} process killed`));
|
|
172
|
+
}
|
|
173
|
+
this.pendingRequests.clear();
|
|
174
|
+
|
|
175
|
+
// Remove all listeners
|
|
176
|
+
proc.removeAllListeners();
|
|
177
|
+
proc.stdout?.removeAllListeners();
|
|
178
|
+
proc.stderr?.removeAllListeners();
|
|
179
|
+
proc.stdin?.removeAllListeners();
|
|
180
|
+
|
|
181
|
+
// Kill the process
|
|
182
|
+
try { proc.kill('SIGTERM'); } catch { /* already dead */ }
|
|
183
|
+
|
|
184
|
+
// Destroy stdio pipes
|
|
185
|
+
try { proc.stdin?.destroy(); } catch { /* ignore */ }
|
|
186
|
+
try { proc.stdout?.destroy(); } catch { /* ignore */ }
|
|
187
|
+
try { proc.stderr?.destroy(); } catch { /* ignore */ }
|
|
188
|
+
|
|
189
|
+
// Unref so Node doesn't wait
|
|
190
|
+
try { proc.unref(); } catch { /* ignore */ }
|
|
191
|
+
|
|
192
|
+
// Force kill after 5 seconds
|
|
193
|
+
setTimeout(() => {
|
|
194
|
+
try { proc.kill('SIGKILL'); } catch { /* already dead */ }
|
|
195
|
+
}, 5000).unref();
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/**
|
|
200
|
+
* Whether the bridge is currently running.
|
|
201
|
+
*/
|
|
202
|
+
public get running(): boolean {
|
|
203
|
+
return this.isRunning;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
private handleLine(line: string): void {
|
|
207
|
+
if (!line) return;
|
|
208
|
+
|
|
209
|
+
let parsed: any;
|
|
210
|
+
try {
|
|
211
|
+
parsed = JSON.parse(line);
|
|
212
|
+
} catch {
|
|
213
|
+
this.logger.log('warn', `Non-JSON output: ${line}`);
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Check if it's an event (has 'event' field, no 'id')
|
|
218
|
+
if ('event' in parsed && !('id' in parsed)) {
|
|
219
|
+
const event = parsed as IManagementEvent;
|
|
220
|
+
this.emit(`management:${event.event}`, event.data);
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Otherwise it's a response (has 'id' field)
|
|
225
|
+
if ('id' in parsed) {
|
|
226
|
+
const response = parsed as IManagementResponse;
|
|
227
|
+
const pending = this.pendingRequests.get(response.id);
|
|
228
|
+
if (pending) {
|
|
229
|
+
clearTimeout(pending.timer);
|
|
230
|
+
this.pendingRequests.delete(response.id);
|
|
231
|
+
if (response.success) {
|
|
232
|
+
pending.resolve(response.result);
|
|
233
|
+
} else {
|
|
234
|
+
pending.reject(new Error(response.error || 'Unknown error from Rust process'));
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
private cleanup(): void {
|
|
241
|
+
this.isRunning = false;
|
|
242
|
+
this.childProcess = null;
|
|
243
|
+
|
|
244
|
+
if (this.readlineInterface) {
|
|
245
|
+
this.readlineInterface.close();
|
|
246
|
+
this.readlineInterface = null;
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
// Reject all pending requests
|
|
250
|
+
for (const [, pending] of this.pendingRequests) {
|
|
251
|
+
clearTimeout(pending.timer);
|
|
252
|
+
pending.reject(new Error(`${this.options.binaryName} process exited`));
|
|
253
|
+
}
|
|
254
|
+
this.pendingRequests.clear();
|
|
255
|
+
}
|
|
256
|
+
}
|
package/ts/index.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Minimal logger interface for the bridge.
|
|
3
|
+
*/
|
|
4
|
+
export interface IRustBridgeLogger {
|
|
5
|
+
log(level: string, message: string, data?: Record<string, any>): void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Options for locating a Rust binary.
|
|
10
|
+
*/
|
|
11
|
+
export interface IBinaryLocatorOptions {
|
|
12
|
+
/** Name of the binary (e.g., 'rustproxy') */
|
|
13
|
+
binaryName: string;
|
|
14
|
+
/** Environment variable to check for explicit binary path (e.g., 'SMARTPROXY_RUST_BINARY') */
|
|
15
|
+
envVarName?: string;
|
|
16
|
+
/** Prefix for platform-specific npm packages (e.g., '@push.rocks/smartproxy') */
|
|
17
|
+
platformPackagePrefix?: string;
|
|
18
|
+
/** Additional local paths to search (defaults to ./rust/target/release/<binaryName> and ./rust/target/debug/<binaryName>) */
|
|
19
|
+
localPaths?: string[];
|
|
20
|
+
/** Whether to search the system PATH (default: true) */
|
|
21
|
+
searchSystemPath?: boolean;
|
|
22
|
+
/** Explicit binary path override - skips all other search */
|
|
23
|
+
binaryPath?: string;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Options for the RustBridge.
|
|
28
|
+
*/
|
|
29
|
+
export interface IRustBridgeOptions extends IBinaryLocatorOptions {
|
|
30
|
+
/** CLI arguments passed to the binary (default: ['--management']) */
|
|
31
|
+
cliArgs?: string[];
|
|
32
|
+
/** Timeout for individual requests in ms (default: 30000) */
|
|
33
|
+
requestTimeoutMs?: number;
|
|
34
|
+
/** Timeout for the ready event during spawn in ms (default: 10000) */
|
|
35
|
+
readyTimeoutMs?: number;
|
|
36
|
+
/** Additional environment variables for the child process */
|
|
37
|
+
env?: Record<string, string>;
|
|
38
|
+
/** Name of the ready event emitted by the Rust binary (default: 'ready') */
|
|
39
|
+
readyEventName?: string;
|
|
40
|
+
/** Optional logger instance */
|
|
41
|
+
logger?: IRustBridgeLogger;
|
|
42
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Management request sent to the Rust binary via stdin.
|
|
3
|
+
*/
|
|
4
|
+
export interface IManagementRequest {
|
|
5
|
+
id: string;
|
|
6
|
+
method: string;
|
|
7
|
+
params: Record<string, any>;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Management response received from the Rust binary via stdout.
|
|
12
|
+
*/
|
|
13
|
+
export interface IManagementResponse {
|
|
14
|
+
id: string;
|
|
15
|
+
success: boolean;
|
|
16
|
+
result?: any;
|
|
17
|
+
error?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Management event received from the Rust binary (unsolicited, no id field).
|
|
22
|
+
*/
|
|
23
|
+
export interface IManagementEvent {
|
|
24
|
+
event: string;
|
|
25
|
+
data: any;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Definition of a single command supported by a Rust binary.
|
|
30
|
+
*/
|
|
31
|
+
export interface ICommandDefinition<TParams = any, TResult = any> {
|
|
32
|
+
params: TParams;
|
|
33
|
+
result: TResult;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Map of command names to their definitions.
|
|
38
|
+
* Used to type-safe the bridge's sendCommand method.
|
|
39
|
+
*/
|
|
40
|
+
export type TCommandMap = Record<string, ICommandDefinition>;
|