@celljs/ta-exec 4.6.1 → 4.8.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.en.md +43 -0
- package/README.md +5 -1
- package/esm/node/exec-client.d.ts +28 -11
- package/esm/node/exec-client.js +89 -33
- package/esm/node/exec-client.js.map +1 -1
- package/esm/node/exec-peer.d.ts +40 -0
- package/esm/node/exec-peer.js +167 -0
- package/esm/node/exec-peer.js.map +1 -0
- package/esm/node/exec-protocol.d.ts +19 -1
- package/esm/node/exec-remote-source.d.ts +5 -0
- package/esm/node/exec-remote-source.js +9 -0
- package/esm/node/exec-remote-source.js.map +1 -0
- package/esm/node/exec-rpc.d.ts +21 -3
- package/esm/node/exec-rpc.js +14 -3
- package/esm/node/exec-rpc.js.map +1 -1
- package/esm/node/exec-server.d.ts +2 -26
- package/esm/node/exec-server.js +3 -132
- package/esm/node/exec-server.js.map +1 -1
- package/esm/node/exec-stdio.d.ts +27 -0
- package/esm/node/exec-stdio.js +60 -0
- package/esm/node/exec-stdio.js.map +1 -0
- package/esm/node/index.d.ts +8 -0
- package/esm/node/index.js +8 -0
- package/esm/node/index.js.map +1 -1
- package/esm/node/local-exec-environment.d.ts +2 -2
- package/esm/node/local-exec-environment.js +11 -11
- package/esm/node/local-exec-environment.js.map +1 -1
- package/esm/node/remote-exec-environment.d.ts +3 -2
- package/esm/node/remote-exec-environment.js +41 -2
- package/esm/node/remote-exec-environment.js.map +1 -1
- package/esm/node/ssh/node-dist.d.ts +20 -0
- package/esm/node/ssh/node-dist.js +77 -0
- package/esm/node/ssh/node-dist.js.map +1 -0
- package/esm/node/ssh/ssh-askpass.d.ts +24 -0
- package/esm/node/ssh/ssh-askpass.js +112 -0
- package/esm/node/ssh/ssh-askpass.js.map +1 -0
- package/esm/node/ssh/ssh-config.d.ts +20 -0
- package/esm/node/ssh/ssh-config.js +127 -0
- package/esm/node/ssh/ssh-config.js.map +1 -0
- package/esm/node/ssh/ssh-host.d.ts +73 -0
- package/esm/node/ssh/ssh-host.js +258 -0
- package/esm/node/ssh/ssh-host.js.map +1 -0
- package/esm/node/ssh/ssh-util.d.ts +45 -0
- package/esm/node/ssh/ssh-util.js +110 -0
- package/esm/node/ssh/ssh-util.js.map +1 -0
- package/lib/node/exec-client.d.ts +28 -11
- package/lib/node/exec-client.d.ts.map +1 -1
- package/lib/node/exec-client.js +89 -33
- package/lib/node/exec-client.js.map +1 -1
- package/lib/node/exec-peer.d.ts +41 -0
- package/lib/node/exec-peer.d.ts.map +1 -0
- package/lib/node/exec-peer.js +171 -0
- package/lib/node/exec-peer.js.map +1 -0
- package/lib/node/exec-protocol.d.ts +19 -1
- package/lib/node/exec-protocol.d.ts.map +1 -1
- package/lib/node/exec-remote-source.d.ts +6 -0
- package/lib/node/exec-remote-source.d.ts.map +1 -0
- package/lib/node/exec-remote-source.js +10 -0
- package/lib/node/exec-remote-source.js.map +1 -0
- package/lib/node/exec-rpc.d.ts +21 -3
- package/lib/node/exec-rpc.d.ts.map +1 -1
- package/lib/node/exec-rpc.js +14 -3
- package/lib/node/exec-rpc.js.map +1 -1
- package/lib/node/exec-server.d.ts +2 -26
- package/lib/node/exec-server.d.ts.map +1 -1
- package/lib/node/exec-server.js +4 -134
- package/lib/node/exec-server.js.map +1 -1
- package/lib/node/exec-server.spec.js +4 -1
- package/lib/node/exec-server.spec.js.map +1 -1
- package/lib/node/exec-stdio.d.ts +28 -0
- package/lib/node/exec-stdio.d.ts.map +1 -0
- package/lib/node/exec-stdio.js +64 -0
- package/lib/node/exec-stdio.js.map +1 -0
- package/lib/node/exec-stdio.spec.d.ts +2 -0
- package/lib/node/exec-stdio.spec.d.ts.map +1 -0
- package/lib/node/exec-stdio.spec.js +106 -0
- package/lib/node/exec-stdio.spec.js.map +1 -0
- package/lib/node/index.d.ts +8 -0
- package/lib/node/index.d.ts.map +1 -1
- package/lib/node/index.js +8 -0
- package/lib/node/index.js.map +1 -1
- package/lib/node/local-exec-environment.d.ts +2 -2
- package/lib/node/local-exec-environment.d.ts.map +1 -1
- package/lib/node/local-exec-environment.js +10 -10
- package/lib/node/local-exec-environment.js.map +1 -1
- package/lib/node/local-exec-environment.spec.js +2 -0
- package/lib/node/local-exec-environment.spec.js.map +1 -1
- package/lib/node/remote-exec-environment.d.ts +3 -2
- package/lib/node/remote-exec-environment.d.ts.map +1 -1
- package/lib/node/remote-exec-environment.js +41 -2
- package/lib/node/remote-exec-environment.js.map +1 -1
- package/lib/node/ssh/node-dist.d.ts +21 -0
- package/lib/node/ssh/node-dist.d.ts.map +1 -0
- package/lib/node/ssh/node-dist.js +80 -0
- package/lib/node/ssh/node-dist.js.map +1 -0
- package/lib/node/ssh/ssh-askpass.d.ts +25 -0
- package/lib/node/ssh/ssh-askpass.d.ts.map +1 -0
- package/lib/node/ssh/ssh-askpass.js +114 -0
- package/lib/node/ssh/ssh-askpass.js.map +1 -0
- package/lib/node/ssh/ssh-config.d.ts +21 -0
- package/lib/node/ssh/ssh-config.d.ts.map +1 -0
- package/lib/node/ssh/ssh-config.js +130 -0
- package/lib/node/ssh/ssh-config.js.map +1 -0
- package/lib/node/ssh/ssh-host.d.ts +74 -0
- package/lib/node/ssh/ssh-host.d.ts.map +1 -0
- package/lib/node/ssh/ssh-host.js +262 -0
- package/lib/node/ssh/ssh-host.js.map +1 -0
- package/lib/node/ssh/ssh-host.spec.d.ts +2 -0
- package/lib/node/ssh/ssh-host.spec.d.ts.map +1 -0
- package/lib/node/ssh/ssh-host.spec.js +182 -0
- package/lib/node/ssh/ssh-host.spec.js.map +1 -0
- package/lib/node/ssh/ssh-util.d.ts +46 -0
- package/lib/node/ssh/ssh-util.d.ts.map +1 -0
- package/lib/node/ssh/ssh-util.js +113 -0
- package/lib/node/ssh/ssh-util.js.map +1 -0
- package/lib/node/ssh/ssh-util.spec.d.ts +2 -0
- package/lib/node/ssh/ssh-util.spec.d.ts.map +1 -0
- package/lib/node/ssh/ssh-util.spec.js +87 -0
- package/lib/node/ssh/ssh-util.spec.js.map +1 -0
- package/package.json +3 -3
- package/src/node/exec-client.ts +108 -39
- package/src/node/exec-peer.ts +186 -0
- package/src/node/exec-protocol.ts +21 -1
- package/src/node/exec-remote-source.ts +7 -0
- package/src/node/exec-rpc.ts +23 -3
- package/src/node/exec-server.spec.ts +4 -1
- package/src/node/exec-server.ts +4 -140
- package/src/node/exec-stdio.spec.ts +108 -0
- package/src/node/exec-stdio.ts +75 -0
- package/src/node/index.ts +8 -0
- package/src/node/local-exec-environment.spec.ts +2 -0
- package/src/node/local-exec-environment.ts +11 -10
- package/src/node/remote-exec-environment.ts +41 -3
- package/src/node/ssh/node-dist.ts +83 -0
- package/src/node/ssh/ssh-askpass.ts +117 -0
- package/src/node/ssh/ssh-config.ts +128 -0
- package/src/node/ssh/ssh-host.spec.ts +189 -0
- package/src/node/ssh/ssh-host.ts +300 -0
- package/src/node/ssh/ssh-util.spec.ts +97 -0
- package/src/node/ssh/ssh-util.ts +127 -0
package/src/node/exec-client.ts
CHANGED
|
@@ -1,11 +1,21 @@
|
|
|
1
1
|
import { ExecRpc } from './exec-rpc';
|
|
2
2
|
|
|
3
|
+
/** One connection to `ta exec-server`, whatever carries it: a WebSocket, or ssh (SshHost). */
|
|
4
|
+
export interface ExecConnection {
|
|
5
|
+
send(text: string): void;
|
|
6
|
+
close(): void;
|
|
7
|
+
onMessage(listener: (text: string) => void): void;
|
|
8
|
+
/** Once, with what went wrong when it was not closed on purpose. */
|
|
9
|
+
onClose(listener: (reason?: string) => void): void;
|
|
10
|
+
}
|
|
11
|
+
|
|
3
12
|
export interface ExecClientOptions {
|
|
4
|
-
/**
|
|
5
|
-
|
|
6
|
-
token: string;
|
|
13
|
+
/** Opens a connection; rejects with an ExecError when it cannot. See {@link ExecClient.webSocket}. */
|
|
14
|
+
connect(): Promise<ExecConnection>;
|
|
7
15
|
/** Larger than the epoch of any host that ran these sessions before; see {@link ExecRpc.InitializeParams}. */
|
|
8
16
|
epoch: number;
|
|
17
|
+
/** Pings this often (milliseconds) while connected, for a server that ends without them (over stdio). */
|
|
18
|
+
pingMs?: number;
|
|
9
19
|
}
|
|
10
20
|
|
|
11
21
|
/** A failed call to `ta exec-server`. */
|
|
@@ -32,20 +42,49 @@ interface PendingCall {
|
|
|
32
42
|
* host with a newer epoch it refuses every call: this host must stop running sessions there.
|
|
33
43
|
*/
|
|
34
44
|
export class ExecClient {
|
|
35
|
-
protected
|
|
36
|
-
protected current?:
|
|
45
|
+
protected connection?: Promise<ExecConnection>;
|
|
46
|
+
protected current?: ExecConnection;
|
|
37
47
|
protected nextCall = 0;
|
|
38
48
|
protected nextProcess = 0;
|
|
39
49
|
protected fenced = false;
|
|
50
|
+
protected pinger?: ReturnType<typeof setInterval>;
|
|
40
51
|
protected initialized?: ExecRpc.InitializeResult;
|
|
41
52
|
protected readonly pending = new Map<number, PendingCall>();
|
|
42
53
|
protected readonly listeners = new Map<number, NotificationListener>();
|
|
54
|
+
protected readonly stateListeners = new Set<(connected: boolean, error?: string) => void>();
|
|
43
55
|
|
|
44
56
|
constructor(protected readonly options: ExecClientOptions) {}
|
|
45
57
|
|
|
58
|
+
/** Connects to a `ta exec-server` listening on a WebSocket. */
|
|
59
|
+
static webSocket(url: string, token: string): () => Promise<ExecConnection> {
|
|
60
|
+
return async () => {
|
|
61
|
+
const address = new URL(url);
|
|
62
|
+
address.searchParams.set('token', token);
|
|
63
|
+
const socket = new WebSocket(address);
|
|
64
|
+
await new Promise<void>((resolve, reject) => {
|
|
65
|
+
socket.onopen = () => resolve();
|
|
66
|
+
socket.onerror = () => reject(new ExecError(`Cannot connect to ${url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
67
|
+
});
|
|
68
|
+
return {
|
|
69
|
+
send: text => socket.send(text),
|
|
70
|
+
close: () => socket.close(),
|
|
71
|
+
onMessage: listener => {
|
|
72
|
+
socket.onmessage = message => listener(String(message.data));
|
|
73
|
+
},
|
|
74
|
+
onClose: listener => {
|
|
75
|
+
socket.onclose = () => listener();
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
get connected(): boolean {
|
|
82
|
+
return this.current !== undefined;
|
|
83
|
+
}
|
|
84
|
+
|
|
46
85
|
async call<T>(method: string, params: object): Promise<T> {
|
|
47
|
-
const
|
|
48
|
-
return this.send<T>(
|
|
86
|
+
const connection = await this.connect();
|
|
87
|
+
return this.send<T>(connection, method, params);
|
|
49
88
|
}
|
|
50
89
|
|
|
51
90
|
/** What the server said when this client connected. */
|
|
@@ -54,7 +93,7 @@ export class ExecClient {
|
|
|
54
93
|
return this.initialized as ExecRpc.InitializeResult;
|
|
55
94
|
}
|
|
56
95
|
|
|
57
|
-
/** An id for a process, which its notifications carry. */
|
|
96
|
+
/** An id for a process or a TCP connection, which its notifications carry. */
|
|
58
97
|
processId(): number {
|
|
59
98
|
return ++this.nextProcess;
|
|
60
99
|
}
|
|
@@ -64,59 +103,82 @@ export class ExecClient {
|
|
|
64
103
|
return () => this.listeners.delete(id);
|
|
65
104
|
}
|
|
66
105
|
|
|
106
|
+
/** Runs when a connection opens (true), is lost or closed (false), or cannot be opened (false, with why). */
|
|
107
|
+
onState(listener: (connected: boolean, error?: string) => void): () => void {
|
|
108
|
+
this.stateListeners.add(listener);
|
|
109
|
+
return () => this.stateListeners.delete(listener);
|
|
110
|
+
}
|
|
111
|
+
|
|
67
112
|
close(): void {
|
|
68
|
-
this.current
|
|
69
|
-
this.
|
|
70
|
-
|
|
113
|
+
const current = this.current;
|
|
114
|
+
this.connection = undefined;
|
|
115
|
+
current?.close();
|
|
116
|
+
if (current) {
|
|
117
|
+
this.lost(current);
|
|
118
|
+
}
|
|
71
119
|
}
|
|
72
120
|
|
|
73
|
-
protected connect(): Promise<
|
|
121
|
+
protected connect(): Promise<ExecConnection> {
|
|
74
122
|
if (this.fenced) {
|
|
75
123
|
return Promise.reject(new ExecError('A host with a newer epoch took over the execution environment.', ExecRpc.ErrorCode.STALE_EPOCH));
|
|
76
124
|
}
|
|
77
|
-
this.
|
|
78
|
-
this.
|
|
125
|
+
this.connection ??= this.open().catch(error => {
|
|
126
|
+
this.connection = undefined;
|
|
127
|
+
for (const listener of this.stateListeners) {
|
|
128
|
+
listener(false, error instanceof Error ? error.message : String(error));
|
|
129
|
+
}
|
|
79
130
|
throw error;
|
|
80
131
|
});
|
|
81
|
-
return this.
|
|
132
|
+
return this.connection;
|
|
82
133
|
}
|
|
83
134
|
|
|
84
|
-
protected async open(): Promise<
|
|
85
|
-
const
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
socket.onopen = () => resolve();
|
|
90
|
-
socket.onerror = () => reject(new ExecError(`Cannot connect to ${this.options.url}.`, ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
91
|
-
});
|
|
92
|
-
socket.onmessage = message => this.receive(String(message.data));
|
|
93
|
-
this.current = socket;
|
|
94
|
-
socket.onclose = () => this.lost(socket);
|
|
135
|
+
protected async open(): Promise<ExecConnection> {
|
|
136
|
+
const connection = await this.options.connect();
|
|
137
|
+
connection.onMessage(text => this.receive(text));
|
|
138
|
+
connection.onClose(reason => this.lost(connection, reason));
|
|
139
|
+
this.current = connection;
|
|
95
140
|
try {
|
|
96
|
-
this.initialized = await this.send(
|
|
141
|
+
this.initialized = await this.send(connection, ExecRpc.Method.INITIALIZE, { epoch: this.options.epoch } satisfies ExecRpc.InitializeParams);
|
|
97
142
|
} catch (error) {
|
|
98
143
|
if ((error as ExecError).code === ExecRpc.ErrorCode.STALE_EPOCH) {
|
|
99
144
|
this.fenced = true;
|
|
100
145
|
}
|
|
101
|
-
|
|
146
|
+
connection.close();
|
|
102
147
|
throw error;
|
|
103
148
|
}
|
|
104
|
-
|
|
149
|
+
if (this.options.pingMs) {
|
|
150
|
+
clearInterval(this.pinger);
|
|
151
|
+
this.pinger = setInterval(() => connection.send(JSON.stringify({ jsonrpc: '2.0', method: ExecRpc.PING })), this.options.pingMs);
|
|
152
|
+
this.pinger.unref?.();
|
|
153
|
+
}
|
|
154
|
+
for (const listener of this.stateListeners) {
|
|
155
|
+
listener(true);
|
|
156
|
+
}
|
|
157
|
+
return connection;
|
|
105
158
|
}
|
|
106
159
|
|
|
107
|
-
protected send<T>(
|
|
108
|
-
if (
|
|
160
|
+
protected send<T>(connection: ExecConnection, method: string, params: object): Promise<T> {
|
|
161
|
+
if (this.current !== connection) {
|
|
109
162
|
return Promise.reject(new ExecError('The connection to the execution environment was lost.', ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
110
163
|
}
|
|
111
164
|
const id = ++this.nextCall;
|
|
112
165
|
return new Promise<T>((resolve, reject) => {
|
|
113
166
|
this.pending.set(id, { resolve: resolve as (result: unknown) => void, reject });
|
|
114
|
-
|
|
167
|
+
connection.send(JSON.stringify({ jsonrpc: '2.0', id, method, params } satisfies ExecRpc.Message));
|
|
115
168
|
});
|
|
116
169
|
}
|
|
117
170
|
|
|
171
|
+
/** Anything but JSON-RPC is left alone: a shell of the other machine may have printed it first. */
|
|
118
172
|
protected receive(text: string): void {
|
|
119
|
-
|
|
173
|
+
let message: ExecRpc.Message;
|
|
174
|
+
try {
|
|
175
|
+
message = JSON.parse(text);
|
|
176
|
+
} catch {
|
|
177
|
+
return;
|
|
178
|
+
}
|
|
179
|
+
if (message?.jsonrpc !== '2.0') {
|
|
180
|
+
return;
|
|
181
|
+
}
|
|
120
182
|
if (message.method) {
|
|
121
183
|
this.listeners.get(message.params?.id)?.(message.method, message.params);
|
|
122
184
|
return;
|
|
@@ -134,19 +196,26 @@ export class ExecClient {
|
|
|
134
196
|
}
|
|
135
197
|
}
|
|
136
198
|
|
|
137
|
-
/** Calls fail, and processes are gone: the server ended them with the connection. */
|
|
138
|
-
protected lost(
|
|
139
|
-
if (this.current
|
|
140
|
-
|
|
141
|
-
this.socket = undefined;
|
|
199
|
+
/** Calls fail, and processes are gone: the server ended them with the connection. `reason`: it was not closed on purpose. */
|
|
200
|
+
protected lost(connection: ExecConnection, reason?: string): void {
|
|
201
|
+
if (this.current !== connection) {
|
|
202
|
+
return;
|
|
142
203
|
}
|
|
204
|
+
this.current = undefined;
|
|
205
|
+
this.connection = undefined;
|
|
206
|
+
clearInterval(this.pinger);
|
|
207
|
+
this.pinger = undefined;
|
|
208
|
+
const message = reason ?? 'The connection to the execution environment was lost.';
|
|
143
209
|
for (const call of this.pending.values()) {
|
|
144
|
-
call.reject(new ExecError(
|
|
210
|
+
call.reject(new ExecError(message, ExecRpc.ErrorCode.CONNECTION_LOST));
|
|
145
211
|
}
|
|
146
212
|
this.pending.clear();
|
|
147
213
|
for (const listener of [...this.listeners.values()]) {
|
|
148
214
|
listener(ExecRpc.Notification.EXIT, { exitCode: null });
|
|
149
215
|
}
|
|
150
216
|
this.listeners.clear();
|
|
217
|
+
for (const listener of this.stateListeners) {
|
|
218
|
+
listener(false, reason);
|
|
219
|
+
}
|
|
151
220
|
}
|
|
152
221
|
}
|
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { connect, type Socket } from 'node:net';
|
|
2
|
+
import type { ExecProcess } from './exec-protocol';
|
|
3
|
+
import { ExecRpc } from './exec-rpc';
|
|
4
|
+
import { LocalExecEnvironment } from './local-exec-environment';
|
|
5
|
+
|
|
6
|
+
type Method = (typeof ExecRpc.Method)[keyof typeof ExecRpc.Method];
|
|
7
|
+
|
|
8
|
+
/** What a peer needs of its server: the default directory, and which host may run things now. */
|
|
9
|
+
export interface ExecPeerServer {
|
|
10
|
+
readonly cwd: string;
|
|
11
|
+
/** False when a newer host has taken over. */
|
|
12
|
+
admit(peer: ExecPeer, epoch: number): boolean;
|
|
13
|
+
isCurrent(epoch: number | undefined): boolean;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** How a peer answers its host: a WebSocket, or the standard output. */
|
|
17
|
+
export interface ExecPeerChannel {
|
|
18
|
+
send(text: string): void;
|
|
19
|
+
close(code: number, reason: string): void;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** One host connection: its calls, and the processes and TCP connections it started. */
|
|
23
|
+
export class ExecPeer {
|
|
24
|
+
epoch?: number;
|
|
25
|
+
protected readonly running = new Map<number, AbortController>();
|
|
26
|
+
protected readonly spawned = new Map<number, ExecProcess>();
|
|
27
|
+
protected readonly sockets = new Map<number, Socket>();
|
|
28
|
+
|
|
29
|
+
constructor(
|
|
30
|
+
protected readonly server: ExecPeerServer,
|
|
31
|
+
protected readonly channel: ExecPeerChannel,
|
|
32
|
+
) {}
|
|
33
|
+
|
|
34
|
+
close(code: number, reason: string): void {
|
|
35
|
+
this.dispose();
|
|
36
|
+
this.channel.close(code, reason);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Ends what this host started. */
|
|
40
|
+
dispose(): void {
|
|
41
|
+
for (const controller of this.running.values()) {
|
|
42
|
+
controller.abort();
|
|
43
|
+
}
|
|
44
|
+
for (const child of this.spawned.values()) {
|
|
45
|
+
child.kill();
|
|
46
|
+
}
|
|
47
|
+
for (const socket of this.sockets.values()) {
|
|
48
|
+
socket.destroy();
|
|
49
|
+
}
|
|
50
|
+
this.running.clear();
|
|
51
|
+
this.spawned.clear();
|
|
52
|
+
this.sockets.clear();
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async receive(text: string): Promise<void> {
|
|
56
|
+
let message: ExecRpc.Message;
|
|
57
|
+
try {
|
|
58
|
+
message = JSON.parse(text);
|
|
59
|
+
} catch {
|
|
60
|
+
this.close(1007, 'Not JSON.');
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
const { id, method, params } = message;
|
|
64
|
+
if (method === ExecRpc.PING) {
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
let reply: ExecRpc.Message;
|
|
68
|
+
if (method === ExecRpc.Method.INITIALIZE) {
|
|
69
|
+
reply = this.initialize(id, params);
|
|
70
|
+
} else if (this.epoch === undefined) {
|
|
71
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.NOT_INITIALIZED, 'Call initialize first.');
|
|
72
|
+
} else if (!this.server.isCurrent(this.epoch)) {
|
|
73
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch took over.');
|
|
74
|
+
} else {
|
|
75
|
+
try {
|
|
76
|
+
reply = { jsonrpc: '2.0', id, result: (await this.call(method as Method, params)) ?? null };
|
|
77
|
+
} catch (error) {
|
|
78
|
+
reply = ExecRpc.error(id, ExecRpc.ErrorCode.FAILED, error instanceof Error ? error.message : String(error));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
if (id !== undefined) {
|
|
82
|
+
this.send(reply);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
protected initialize(id: number | undefined, params: ExecRpc.InitializeParams): ExecRpc.Message {
|
|
87
|
+
if (typeof params?.epoch !== 'number' || !this.server.admit(this, params.epoch)) {
|
|
88
|
+
return ExecRpc.error(id, ExecRpc.ErrorCode.STALE_EPOCH, 'A host with a newer epoch is connected.');
|
|
89
|
+
}
|
|
90
|
+
this.epoch = params.epoch;
|
|
91
|
+
const result: ExecRpc.InitializeResult = { platform: process.platform, cwd: this.server.cwd };
|
|
92
|
+
return { jsonrpc: '2.0', id, result };
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
protected async call(method: Method, params: any): Promise<unknown> {
|
|
96
|
+
const environment = new LocalExecEnvironment(params.root ?? this.server.cwd);
|
|
97
|
+
switch (method) {
|
|
98
|
+
case ExecRpc.Method.EXEC:
|
|
99
|
+
return this.exec(environment, params);
|
|
100
|
+
case ExecRpc.Method.SPAWN:
|
|
101
|
+
return this.spawn(environment, params);
|
|
102
|
+
case ExecRpc.Method.WRITE:
|
|
103
|
+
this.spawned.get(params.id)?.write(ExecRpc.fromBase64(params.data));
|
|
104
|
+
return;
|
|
105
|
+
case ExecRpc.Method.KILL:
|
|
106
|
+
this.running.get(params.id)?.abort();
|
|
107
|
+
this.spawned.get(params.id)?.kill();
|
|
108
|
+
return;
|
|
109
|
+
case ExecRpc.Method.READ_FILE:
|
|
110
|
+
return ExecRpc.toBase64(await environment.readFile(params.path));
|
|
111
|
+
case ExecRpc.Method.WRITE_FILE:
|
|
112
|
+
return environment.writeFile(params.path, ExecRpc.fromBase64(params.data), { append: params.append === true });
|
|
113
|
+
case ExecRpc.Method.STAT:
|
|
114
|
+
return environment.stat(params.path);
|
|
115
|
+
case ExecRpc.Method.READDIR:
|
|
116
|
+
return environment.readdir(params.path);
|
|
117
|
+
case ExecRpc.Method.MKDIR:
|
|
118
|
+
return environment.mkdir(params.path);
|
|
119
|
+
case ExecRpc.Method.REMOVE:
|
|
120
|
+
return environment.remove(params.path, { recursive: params.recursive });
|
|
121
|
+
case ExecRpc.Method.NET_CONNECT:
|
|
122
|
+
return this.connect(params);
|
|
123
|
+
case ExecRpc.Method.NET_WRITE:
|
|
124
|
+
this.sockets.get(params.id)?.write(ExecRpc.fromBase64(params.data));
|
|
125
|
+
return;
|
|
126
|
+
case ExecRpc.Method.NET_CLOSE:
|
|
127
|
+
this.sockets.get(params.id)?.end();
|
|
128
|
+
return;
|
|
129
|
+
default:
|
|
130
|
+
throw new Error(`No method ${method}.`);
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
protected async exec(environment: LocalExecEnvironment, params: ExecRpc.ExecParams): Promise<unknown> {
|
|
135
|
+
const controller = new AbortController();
|
|
136
|
+
this.running.set(params.id, controller);
|
|
137
|
+
try {
|
|
138
|
+
return await environment.exec(params.command, {
|
|
139
|
+
cwd: params.cwd,
|
|
140
|
+
env: { ...process.env, ...params.env },
|
|
141
|
+
timeout: params.timeout,
|
|
142
|
+
signal: controller.signal,
|
|
143
|
+
onData: data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }),
|
|
144
|
+
});
|
|
145
|
+
} finally {
|
|
146
|
+
this.running.delete(params.id);
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
protected spawn(environment: LocalExecEnvironment, params: ExecRpc.SpawnParams): void {
|
|
151
|
+
const child = environment.spawn(params.command, params.args, { cwd: params.cwd, env: { ...process.env, ...params.env } });
|
|
152
|
+
this.spawned.set(params.id, child);
|
|
153
|
+
child.onStdout(data => this.notify(ExecRpc.Notification.OUTPUT, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
154
|
+
child.onStderr(data => this.notify(ExecRpc.Notification.STDERR, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
155
|
+
child.onExit(exitCode => {
|
|
156
|
+
this.spawned.delete(params.id);
|
|
157
|
+
this.notify(ExecRpc.Notification.EXIT, { id: params.id, exitCode });
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** Resolves once connected; the data comes as notifications, the end as NET_CLOSED. */
|
|
162
|
+
protected connect(params: ExecRpc.ConnectParams): Promise<void> {
|
|
163
|
+
return new Promise((resolve, reject) => {
|
|
164
|
+
const socket = connect({ port: params.port, host: params.host ?? '127.0.0.1' });
|
|
165
|
+
socket.once('connect', () => {
|
|
166
|
+
this.sockets.set(params.id, socket);
|
|
167
|
+
resolve();
|
|
168
|
+
});
|
|
169
|
+
socket.on('data', data => this.notify(ExecRpc.Notification.NET_DATA, { id: params.id, data: ExecRpc.toBase64(data) }));
|
|
170
|
+
socket.once('error', reject);
|
|
171
|
+
socket.once('close', () => {
|
|
172
|
+
if (this.sockets.delete(params.id)) {
|
|
173
|
+
this.notify(ExecRpc.Notification.NET_CLOSED, { id: params.id });
|
|
174
|
+
}
|
|
175
|
+
});
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
protected notify(method: string, params: unknown): void {
|
|
180
|
+
this.send({ jsonrpc: '2.0', method, params });
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
protected send(message: ExecRpc.Message): void {
|
|
184
|
+
this.channel.send(JSON.stringify(message));
|
|
185
|
+
}
|
|
186
|
+
}
|
|
@@ -30,6 +30,20 @@ export interface ExecProcess {
|
|
|
30
30
|
kill(): void;
|
|
31
31
|
}
|
|
32
32
|
|
|
33
|
+
/** A TCP connection made from inside an environment. */
|
|
34
|
+
export interface ExecSocket {
|
|
35
|
+
write(data: Uint8Array): void;
|
|
36
|
+
/** Ends the connection; `onClose` follows. */
|
|
37
|
+
end(): void;
|
|
38
|
+
onData(listener: (data: Uint8Array) => void): void;
|
|
39
|
+
/** Once, when either side ended it or the environment was lost. */
|
|
40
|
+
onClose(listener: () => void): void;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface WriteFileOptions {
|
|
44
|
+
append?: boolean;
|
|
45
|
+
}
|
|
46
|
+
|
|
33
47
|
export interface FileStat {
|
|
34
48
|
isDirectory: boolean;
|
|
35
49
|
size: number;
|
|
@@ -53,12 +67,18 @@ export interface ExecEnvironment {
|
|
|
53
67
|
exec(command: string, options?: ExecOptions): Promise<ExecResult>;
|
|
54
68
|
spawn(command: string, args: string[], options?: SpawnOptions): ExecProcess;
|
|
55
69
|
readFile(path: string): Promise<Uint8Array>;
|
|
56
|
-
|
|
70
|
+
/** With `append`, the data goes after what the file holds (made when missing), as for a file sent in parts. */
|
|
71
|
+
writeFile(path: string, data: Uint8Array | string, options?: WriteFileOptions): Promise<void>;
|
|
57
72
|
/** undefined when nothing is there. */
|
|
58
73
|
stat(path: string): Promise<FileStat | undefined>;
|
|
59
74
|
readdir(path: string): Promise<DirEntry[]>;
|
|
60
75
|
mkdir(path: string): Promise<void>;
|
|
61
76
|
remove(path: string, options?: { recursive?: boolean }): Promise<void>;
|
|
77
|
+
/**
|
|
78
|
+
* A TCP connection to a port of the environment's machine (default host 127.0.0.1), for one only
|
|
79
|
+
* reachable there; only environments on another machine have it. Rejects when nothing listens.
|
|
80
|
+
*/
|
|
81
|
+
connect?(port: number, host?: string): Promise<ExecSocket>;
|
|
62
82
|
}
|
|
63
83
|
|
|
64
84
|
/** Bind another implementation with `rebind: true` to run sessions elsewhere. */
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Generated by scripts/remote-server.ts from scripts/remote-main.ts: do not edit.
|
|
2
|
+
|
|
3
|
+
/** `ta exec-server` on stdio in one script for Node.js 18, and the hash that names its version. */
|
|
4
|
+
export const EXEC_REMOTE_SOURCE = {
|
|
5
|
+
hash: "9c733cfd94c14c82",
|
|
6
|
+
script: "var b=require(\"node:net\");var H;((Y)=>{Y.PATH=\"/exec\",Y.Method={INITIALIZE:\"initialize\",EXEC:\"process/exec\",SPAWN:\"process/spawn\",WRITE:\"process/write\",KILL:\"process/kill\",READ_FILE:\"fs/readFile\",WRITE_FILE:\"fs/writeFile\",STAT:\"fs/stat\",READDIR:\"fs/readdir\",MKDIR:\"fs/mkdir\",REMOVE:\"fs/remove\",NET_CONNECT:\"net/connect\",NET_WRITE:\"net/write\",NET_CLOSE:\"net/close\"},Y.PING=\"ping\",Y.Notification={OUTPUT:\"process/output\",STDERR:\"process/stderr\",EXIT:\"process/exit\",NET_DATA:\"net/data\",NET_CLOSED:\"net/closed\"},Y.ErrorCode={STALE_EPOCH:\"CELL_TA_EXEC_STALE_EPOCH\",NOT_INITIALIZED:\"CELL_TA_EXEC_NOT_INITIALIZED\",FAILED:\"CELL_TA_EXEC_FAILED\",CONNECTION_LOST:\"CELL_TA_EXEC_CONNECTION_LOST\"},Y.ERROR=-32060;function Q(U,q,B){return{jsonrpc:\"2.0\",id:U,error:{code:-32060,message:B,data:{code:q}}}}Y.error=Q;function $(U){return Buffer.from(U).toString(\"base64\")}Y.toBase64=$;function Z(U){return Buffer.from(U,\"base64\")}Y.fromBase64=Z})(H||={});var O=require(\"node:child_process\"),V=require(\"node:fs/promises\"),I=require(\"node:path\");class P{cwd;local=!0;constructor(A){this.cwd=A}exec(A,z={}){let[G,...J]=process.platform===\"win32\"?[\"cmd.exe\",\"/d\",\"/s\",\"/c\"]:[\"/bin/sh\",\"-c\"],K=O.spawn(G,[...J,A],{cwd:I.resolve(this.cwd,z.cwd??\".\"),env:z.env??process.env,stdio:[\"ignore\",\"pipe\",\"pipe\"],detached:process.platform!==\"win32\"});return new Promise((X)=>{let Q=()=>this.killGroup(K),$=z.timeout?setTimeout(Q,z.timeout):void 0;if(z.signal?.addEventListener(\"abort\",Q,{once:!0}),z.signal?.aborted)Q();K.stdout?.on(\"data\",(U)=>z.onData?.(U)),K.stderr?.on(\"data\",(U)=>z.onData?.(U));let Z=(U)=>{clearTimeout($),z.signal?.removeEventListener(\"abort\",Q),X({exitCode:U})};K.once(\"error\",()=>Z(null)),K.once(\"close\",Z)})}spawn(A,z,G={}){let J=O.spawn(A,z,{cwd:I.resolve(this.cwd,G.cwd??\".\"),env:G.env??process.env,stdio:[\"pipe\",\"pipe\",\"pipe\"]});return J.stdin.on(\"error\",()=>{return}),{write:(K)=>J.stdin.write(K),onStdout:(K)=>J.stdout.on(\"data\",K),onStderr:(K)=>J.stderr.on(\"data\",K),onExit:(K)=>{J.once(\"error\",()=>K(null)),J.once(\"close\",K)},kill:()=>J.kill()}}readFile(A){return V.readFile(this.resolve(A))}writeFile(A,z,G={}){return G.append?V.appendFile(this.resolve(A),z):V.writeFile(this.resolve(A),z)}async stat(A){try{let z=await V.stat(this.resolve(A));return{isDirectory:z.isDirectory(),size:z.size,mtimeMs:z.mtimeMs}}catch(z){if(z.code===\"ENOENT\")return;throw z}}async readdir(A){return(await V.readdir(this.resolve(A),{withFileTypes:!0})).map((G)=>({name:G.name,isDirectory:G.isDirectory()}))}async mkdir(A){await V.mkdir(this.resolve(A),{recursive:!0})}remove(A,z={}){return V.rm(this.resolve(A),{recursive:z.recursive,force:!0})}resolve(A){return I.resolve(this.cwd,A)}killGroup(A){if(A.pid===void 0)return;if(process.platform!==\"win32\")try{process.kill(-A.pid,\"SIGKILL\");return}catch{}A.kill(\"SIGKILL\")}}class W{server;channel;epoch;running=new Map;spawned=new Map;sockets=new Map;constructor(A,z){this.server=A;this.channel=z}close(A,z){this.dispose(),this.channel.close(A,z)}dispose(){for(let A of this.running.values())A.abort();for(let A of this.spawned.values())A.kill();for(let A of this.sockets.values())A.destroy();this.running.clear(),this.spawned.clear(),this.sockets.clear()}async receive(A){let z;try{z=JSON.parse(A)}catch{this.close(1007,\"Not JSON.\");return}let{id:G,method:J,params:K}=z;if(J===H.PING)return;let X;if(J===H.Method.INITIALIZE)X=this.initialize(G,K);else if(this.epoch===void 0)X=H.error(G,H.ErrorCode.NOT_INITIALIZED,\"Call initialize first.\");else if(!this.server.isCurrent(this.epoch))X=H.error(G,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch took over.\");else try{X={jsonrpc:\"2.0\",id:G,result:await this.call(J,K)??null}}catch(Q){X=H.error(G,H.ErrorCode.FAILED,Q instanceof Error?Q.message:String(Q))}if(G!==void 0)this.send(X)}initialize(A,z){if(typeof z?.epoch!==\"number\"||!this.server.admit(this,z.epoch))return H.error(A,H.ErrorCode.STALE_EPOCH,\"A host with a newer epoch is connected.\");this.epoch=z.epoch;let G={platform:process.platform,cwd:this.server.cwd};return{jsonrpc:\"2.0\",id:A,result:G}}async call(A,z){let G=new P(z.root??this.server.cwd);switch(A){case H.Method.EXEC:return this.exec(G,z);case H.Method.SPAWN:return this.spawn(G,z);case H.Method.WRITE:this.spawned.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.KILL:this.running.get(z.id)?.abort(),this.spawned.get(z.id)?.kill();return;case H.Method.READ_FILE:return H.toBase64(await G.readFile(z.path));case H.Method.WRITE_FILE:return G.writeFile(z.path,H.fromBase64(z.data),{append:z.append===!0});case H.Method.STAT:return G.stat(z.path);case H.Method.READDIR:return G.readdir(z.path);case H.Method.MKDIR:return G.mkdir(z.path);case H.Method.REMOVE:return G.remove(z.path,{recursive:z.recursive});case H.Method.NET_CONNECT:return this.connect(z);case H.Method.NET_WRITE:this.sockets.get(z.id)?.write(H.fromBase64(z.data));return;case H.Method.NET_CLOSE:this.sockets.get(z.id)?.end();return;default:throw Error(`No method ${A}.`)}}async exec(A,z){let G=new AbortController;this.running.set(z.id,G);try{return await A.exec(z.command,{cwd:z.cwd,env:{...process.env,...z.env},timeout:z.timeout,signal:G.signal,onData:(J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})})}finally{this.running.delete(z.id)}}spawn(A,z){let G=A.spawn(z.command,z.args,{cwd:z.cwd,env:{...process.env,...z.env}});this.spawned.set(z.id,G),G.onStdout((J)=>this.notify(H.Notification.OUTPUT,{id:z.id,data:H.toBase64(J)})),G.onStderr((J)=>this.notify(H.Notification.STDERR,{id:z.id,data:H.toBase64(J)})),G.onExit((J)=>{this.spawned.delete(z.id),this.notify(H.Notification.EXIT,{id:z.id,exitCode:J})})}connect(A){return new Promise((z,G)=>{let J=b.connect({port:A.port,host:A.host??\"127.0.0.1\"});J.once(\"connect\",()=>{this.sockets.set(A.id,J),z()}),J.on(\"data\",(K)=>this.notify(H.Notification.NET_DATA,{id:A.id,data:H.toBase64(K)})),J.once(\"error\",G),J.once(\"close\",()=>{if(this.sockets.delete(A.id))this.notify(H.Notification.NET_CLOSED,{id:A.id})})})}notify(A,z){this.send({jsonrpc:\"2.0\",method:A,params:z})}send(A){this.channel.send(JSON.stringify(A))}}class N{options;cwd;epoch;constructor(A){this.options=A;this.cwd=A.cwd??process.cwd()}serve(){let{input:A,output:z,idleMs:G}=this.options;return new Promise((J)=>{let K,X=\"\",Q=()=>{clearTimeout(K),A.removeListener(\"data\",U),$.dispose(),J()},$=new W(this,{send:(q)=>z.write(`${q}\n`),close:Q}),Z=()=>{if(G)clearTimeout(K),K=setTimeout(Q,G)},U=(q)=>{Z();let B=(X+q.toString()).split(`\n`);X=B.pop()??\"\";for(let T of B)if(T.trim())$.receive(T)};A.on(\"data\",U),A.once(\"end\",Q),A.once(\"error\",Q),Z()})}admit(A,z){if(this.epoch!==void 0&&z<this.epoch)return!1;return this.epoch=z,!0}isCurrent(A){return A===this.epoch}}var j=60000;new N({input:process.stdin,output:process.stdout,idleMs:j}).serve().then(()=>process.exit(0));\n",
|
|
7
|
+
};
|
package/src/node/exec-rpc.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* The protocol of `ta exec-server`: JSON-RPC 2.0
|
|
3
|
-
*
|
|
4
|
-
*
|
|
2
|
+
* The protocol of `ta exec-server`: JSON-RPC 2.0, as Codex's exec-server does it, over a WebSocket (one
|
|
3
|
+
* text message each) or over the standard input and output of the server (one line each), which is how
|
|
4
|
+
* it runs at the other end of ssh. The host calls methods; the server sends the output of processes
|
|
5
|
+
* and the data of connections as notifications. Bytes travel as base64.
|
|
5
6
|
*/
|
|
6
7
|
export namespace ExecRpc {
|
|
7
8
|
/** Path of the WebSocket endpoint. */
|
|
@@ -19,14 +20,25 @@ export namespace ExecRpc {
|
|
|
19
20
|
READDIR: 'fs/readdir',
|
|
20
21
|
MKDIR: 'fs/mkdir',
|
|
21
22
|
REMOVE: 'fs/remove',
|
|
23
|
+
/** A TCP connection from the server's machine, for a port only reachable there. */
|
|
24
|
+
NET_CONNECT: 'net/connect',
|
|
25
|
+
NET_WRITE: 'net/write',
|
|
26
|
+
NET_CLOSE: 'net/close',
|
|
22
27
|
} as const;
|
|
23
28
|
|
|
29
|
+
/** Sent by the host, without an id, to say it is still there; over stdio the server ends without it. */
|
|
30
|
+
export const PING = 'ping';
|
|
31
|
+
|
|
24
32
|
export const Notification = {
|
|
25
33
|
/** Output of `process/exec` (stdout and stderr together) and stdout of `process/spawn`. */
|
|
26
34
|
OUTPUT: 'process/output',
|
|
27
35
|
STDERR: 'process/stderr',
|
|
28
36
|
/** A spawned process ended. */
|
|
29
37
|
EXIT: 'process/exit',
|
|
38
|
+
/** Data a connection of `net/connect` received. */
|
|
39
|
+
NET_DATA: 'net/data',
|
|
40
|
+
/** A connection of `net/connect` ended. */
|
|
41
|
+
NET_CLOSED: 'net/closed',
|
|
30
42
|
} as const;
|
|
31
43
|
|
|
32
44
|
/** `error.data.code` of failed calls. */
|
|
@@ -74,6 +86,14 @@ export namespace ExecRpc {
|
|
|
74
86
|
args: string[];
|
|
75
87
|
}
|
|
76
88
|
|
|
89
|
+
export interface ConnectParams {
|
|
90
|
+
/** Chosen by the host, unique per connection, as the id of a process: the notifications carry it. */
|
|
91
|
+
id: number;
|
|
92
|
+
port: number;
|
|
93
|
+
/** Default 127.0.0.1. */
|
|
94
|
+
host?: string;
|
|
95
|
+
}
|
|
96
|
+
|
|
77
97
|
export interface PathParams {
|
|
78
98
|
root: string;
|
|
79
99
|
path: string;
|
|
@@ -24,7 +24,7 @@ describe('ta exec-server', () => {
|
|
|
24
24
|
let url: string;
|
|
25
25
|
|
|
26
26
|
const environment = (epoch = 1, token = TOKEN) => {
|
|
27
|
-
const client = new ExecClient({ url, token, epoch });
|
|
27
|
+
const client = new ExecClient({ connect: ExecClient.webSocket(url, token), epoch });
|
|
28
28
|
clients.push(client);
|
|
29
29
|
return new RemoteExecEnvironment(client, root);
|
|
30
30
|
};
|
|
@@ -70,6 +70,9 @@ describe('ta exec-server', () => {
|
|
|
70
70
|
await env.mkdir('dir/sub');
|
|
71
71
|
await env.writeFile('dir/sub/a.txt', 'hello');
|
|
72
72
|
expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello');
|
|
73
|
+
await env.writeFile('dir/sub/a.txt', ' world', { append: true });
|
|
74
|
+
expect(readFileSync(join(root, 'dir/sub/a.txt'), 'utf8')).toBe('hello world');
|
|
75
|
+
await env.writeFile('dir/sub/a.txt', 'hello');
|
|
73
76
|
expect(Buffer.from(await env.readFile('dir/sub/a.txt')).toString()).toBe('hello');
|
|
74
77
|
expect(await env.stat('dir')).toMatchObject({ isDirectory: true });
|
|
75
78
|
expect(await env.stat('nothing')).toBeUndefined();
|