返回源码地图

packages/env/src/connection.ts

v1.3.0 · 71023aec1546 · 21:连接、帧请求、取消与session归属

完整原文供逐行核对;页面收录不代表每行都经过人工语义审核。MIT 许可见 许可证。

1import { type ChildProcessWithoutNullStreams, spawn } from "node:child_process";
2import { randomBytes } from "node:crypto";
3
4/** Frame types (docs/protocol.md). */
5const REQUEST = 1;
6const RESULT = 2;
7const ERROR = 3;
8const EVENT = 4;
9const CANCEL = 5;
10const PING = 6;
11
12const MAX_FRAME = 16 * 1024 * 1024;
13const PING_INTERVAL_MS = 5000;
14/** The daemon pings every five seconds; this much silence means the connection is gone. */
15const SILENCE_LIMIT_MS = 30_000;
16/** How long starting the daemon and its `hello` may take. */
17const START_TIMEOUT_MS = 60_000;
18
19export type Json = Record<string, unknown>;
20
21/** A failure reported by the daemon, with its Node-style code. */
22export class RemoteError extends Error {
23 readonly code: string;
24 readonly path?: string;
25 readonly fields: Json;
26
27 constructor(fields: Json) {
28 super(typeof fields.message === "string" ? fields.message : "Remote operation failed");
29 this.name = "RemoteError";
30 this.code = typeof fields.code === "string" ? fields.code : "unknown";
31 if (typeof fields.path === "string") this.path = fields.path;
32 this.fields = fields;
33 }
34}
35
36/** What `hello` reports about the remote machine. */
37export interface RemoteInfo {
38 protocol: number;
39 version: string;
40 os: string;
41 arch: string;
42 home: string;
43 tmpdir: string;
44 /** Path separator: `/`, or `\\` on Windows. */
45 separator: string;
46 /** The daemon's working directory, where Node's `path.resolve` would fall back to `process.cwd()`. */
47 cwd: string;
48 /** Windows: per-drive working directories (`C:` → `C:\\work`) of the `=C:` variables. */
49 driveCwds: Record<string, string>;
50 pid: number;
51 /** Operations added to protocol 1 that this daemon supports, such as `listFiles`; absent from older daemons. */
52 features?: string[];
53}
54
55/**
56 * Node's names for the daemon's system and architecture, which `hello` reports in Rust's spelling: `windows` is
57 * `win32`, `macos` is `darwin`, `x86_64` is `x64`, `aarch64` is `arm64`, so they compare with `process.platform` and
58 * `process.arch`. Other names are kept.
59 */
60export function nodePlatform(info: Pick<RemoteInfo, "os" | "arch">): { platform: string; arch: string } {
61 const platforms: Record<string, string> = { windows: "win32", macos: "darwin" };
62 const archs: Record<string, string> = { x86_64: "x64", aarch64: "arm64", x86: "ia32" };
63 return { platform: platforms[info.os] ?? info.os, arch: archs[info.arch] ?? info.arch };
64}
65
66export interface ConnectionOptions {
67 /**
68 * Command that starts the daemon, before its `serve --token <hex>` arguments, e.g. `["ssh", "-T", "--", "host",
69 * "~/.pi/mobile/tools/pi-env"]`. A function computes it at each start (detecting and deploying first, for example);
70 * its failure fails that start, and the next request tries again.
71 */
72 command: readonly string[] | (() => Promise<readonly string[]>);
73 /** Receives the daemon's and the transport's diagnostic output. */
74 onLog?: (text: string) => void;
75}
76
77export interface Reply {
78 json: Json;
79 payload: Uint8Array;
80 /** The daemon session that answered; handles from it are only valid while it lives. */
81 session: number;
82}
83
84type Pending = {
85 resolve: (value: Reply) => void;
86 reject: (error: Error) => void;
87 onEvent?: (json: Json, payload: Uint8Array) => void;
88};
89
90export interface RequestOptions {
91 payload?: Uint8Array;
92 /** Aborting sends `cancel`; the request still settles with the daemon's result or error. */
93 signal?: AbortSignal;
94 /** Progress events of the request, such as `exec` output. */
95 onEvent?: (json: Json, payload: Uint8Array) => void;
96 /** The request's id and session, for `kill`. */
97 onStart?: (id: number, session: number) => void;
98 /**
99 * Only run in this daemon session, for requests on handles it opened. After the connection was lost and started
100 * again, such requests fail instead of reaching a daemon that never opened the handle.
101 */
102 session?: number;
103}
104
105/** Lone surrogates become U+FFFD, as Node encodes strings for system calls. */
106function wellFormed(_key: string, value: unknown): unknown {
107 return typeof value === "string" ? value.toWellFormed() : value;
108}
109
110function frame(type: number, id: number, json: Json, payload: Uint8Array = new Uint8Array(0)): Buffer {
111 const body = Buffer.from(JSON.stringify(json, wellFormed), "utf8");
112 const header = Buffer.alloc(13);
113 header.writeUInt32BE(9 + body.length + payload.length, 0);
114 header.writeUInt8(type, 4);
115 header.writeUInt32BE(id, 5);
116 header.writeUInt32BE(body.length, 9);
117 return Buffer.concat([header, body, payload]);
118}
119
120/** The connection failed or ended; a request may succeed once it is started again. */
121function lost(message: string): RemoteError {
122 return new RemoteError({ code: "unknown", message, lost: true });
123}
124
125/** Whether an error means the connection was lost, not that the daemon refused the request. */
126export function isConnectionLost(error: unknown): boolean {
127 return error instanceof RemoteError && error.fields.lost === true;
128}
129
130function closed(): RemoteError {
131 return new RemoteError({ code: "unknown", message: "Connection closed" });
132}
133
134/** One running daemon. */
135class Session {
136 readonly id: number;
137 readonly child: ChildProcessWithoutNullStreams;
138 readonly token: string;
139 readonly pending = new Map<number, Pending>();
140 /** Received bytes not yet parsed, without concatenating on every chunk. */
141 chunks: Buffer[] = [];
142 buffered = 0;
143 synced = false;
144 lastSeen = Date.now();
145 timer: ReturnType<typeof setInterval> | undefined;
146 live = true;
147
148 constructor(id: number, child: ChildProcessWithoutNullStreams, token: string) {
149 this.id = id;
150 this.child = child;
151 this.token = token;
152 }
153
154 /** The first `length` buffered bytes as one buffer, without consuming them. */
155 peek(length: number): Buffer {
156 if (this.chunks[0]!.length < length) {
157 this.chunks = [Buffer.concat(this.chunks)];
158 }
159 return this.chunks[0]!.subarray(0, length);
160 }
161
162 consume(length: number): void {
163 this.buffered -= length;
164 while (length > 0) {
165 const first = this.chunks[0]!;
166 if (first.length <= length) {
167 this.chunks.shift();
168 length -= first.length;
169 } else {
170 this.chunks[0] = first.subarray(length);
171 length = 0;
172 }
173 }
174 }
175}
176
177/**
178 * One connection to a pi-env daemon: started lazily on the first request and started again after it is lost. Requests
179 * in flight when it is lost fail with code `unknown`; for mutations their outcome is then unknown.
180 */
181export class Connection {
182 readonly #options: ConnectionOptions;
183 #session: Session | undefined;
184 #ready: Promise<{ info: RemoteInfo; session: Session }> | undefined;
185 #sessions = 0;
186 #nextId = 1;
187 #closed = false;
188
189 constructor(options: ConnectionOptions) {
190 this.#options = options;
191 }
192
193 /** Connect if needed and return what the daemon reported about its machine. */
194 async info(): Promise<RemoteInfo> {
195 return (await this.#connect()).info;
196 }
197
198 /** Connect if needed and return the live session's id. */
199 async session(): Promise<number> {
200 return (await this.#connect()).session.id;
201 }
202
203 async request(op: string, json: Json, options: RequestOptions = {}): Promise<Reply> {
204 if (options.session !== undefined) {
205 const current = this.#session;
206 if (current === undefined || current.id !== options.session || !current.live) {
207 throw lost("pi-env connection lost");
208 }
209 return this.#send(current, op, json, options);
210 }
211 const { session } = await this.#connect();
212 return this.#send(session, op, json, options);
213 }
214
215 /** Stop the daemon; it kills everything it started. */
216 close(): void {
217 this.#closed = true;
218 if (this.#session) this.#teardown(this.#session, closed());
219 }
220
221 /** Kill one `exec` without aborting it. */
222 kill(id: number, session: number): void {
223 const current = this.#session;
224 if (current?.id === session && current.live) this.#write(current, frame(CANCEL, id, { mode: "kill" }));
225 }
226
227 #connect(): Promise<{ info: RemoteInfo; session: Session }> {
228 if (this.#closed) return Promise.reject(closed());
229 if (this.#ready === undefined) {
230 const ready = this.#start();
231 this.#ready = ready;
232 // A failed start is not remembered: the next request tries again.
233 ready.catch(() => {
234 if (this.#ready === ready) this.#ready = undefined;
235 });
236 }
237 return this.#ready;
238 }
239
240 #send(session: Session, op: string, json: Json, options: RequestOptions): Promise<Reply> {
241 if (!session.live) return Promise.reject(lost("pi-env connection lost"));
242 const id = this.#nextId++;
243 return new Promise((resolve, reject) => {
244 const onAbort = () => this.#write(session, frame(CANCEL, id, {}));
245 const done = () => options.signal?.removeEventListener("abort", onAbort);
246 session.pending.set(id, {
247 resolve: (value) => {
248 done();
249 resolve(value);
250 },
251 reject: (error) => {
252 done();
253 reject(error);
254 },
255 ...(options.onEvent ? { onEvent: options.onEvent } : {}),
256 });
257 options.signal?.addEventListener("abort", onAbort, { once: true });
258 options.onStart?.(id, session.id);
259 this.#write(session, frame(REQUEST, id, { ...json, op }, options.payload));
260 if (options.signal?.aborted) onAbort();
261 });
262 }
263
264 #write(session: Session, data: Buffer): void {
265 if (session.live) session.child.stdin.write(data);
266 }
267
268 async #start(): Promise<{ info: RemoteInfo; session: Session }> {
269 let command: readonly string[];
270 try {
271 const option = this.#options.command;
272 command = typeof option === "function" ? await option() : option;
273 } catch (error) {
274 const message = error instanceof Error ? error.message : String(error);
275 throw new RemoteError({ code: "spawn_error", message, lost: true });
276 }
277 if (this.#closed) throw closed();
278 const [program, ...args] = command;
279 if (program === undefined) throw new RemoteError({ code: "spawn_error", message: "No daemon command" });
280 const token = randomBytes(16).toString("hex");
281 const child = spawn(program, [...args, "serve", "--token", token], { stdio: ["pipe", "pipe", "pipe"] });
282 const session = new Session(++this.#sessions, child, token);
283 this.#session = session;
284 let startTimer: ReturnType<typeof setTimeout> | undefined;
285 const failed = new Promise<never>((_resolve, reject) => {
286 startTimer = setTimeout(
287 () => reject(lost(`pi-env did not answer within ${START_TIMEOUT_MS / 1000} s`)),
288 START_TIMEOUT_MS,
289 );
290 child.once("error", (error) =>
291 reject(new RemoteError({ code: "spawn_error", message: error.message, lost: true })),
292 );
293 child.once("exit", (code) => reject(lost(`pi-env exited with code ${code} before it was ready`)));
294 });
295 failed.catch(() => {});
296 child.stdout.on("data", (chunk: Buffer) => this.#onData(session, chunk));
297 child.stderr.on("data", (chunk: Buffer) => this.#options.onLog?.(chunk.toString("utf8")));
298 child.on("error", () => this.#teardown(session, lost("pi-env connection lost")));
299 child.on("exit", () => this.#teardown(session, lost("pi-env connection lost")));
300 child.stdin.on("error", () => {});
301 session.timer = setInterval(() => {
302 this.#write(session, frame(PING, 0, {}));
303 if (Date.now() - session.lastSeen > SILENCE_LIMIT_MS) {
304 this.#teardown(session, lost("pi-env connection timed out"));
305 }
306 }, PING_INTERVAL_MS);
307 session.timer.unref();
308 try {
309 const { json } = await Promise.race([this.#send(session, "hello", { protocol: 1 }, {}), failed]);
310 if (json.protocol !== 1) throw lost(`Unsupported protocol ${json.protocol}`);
311 return { info: json as unknown as RemoteInfo, session };
312 } catch (error) {
313 this.#teardown(session, error instanceof Error ? error : lost(String(error)));
314 throw error;
315 } finally {
316 clearTimeout(startTimer);
317 }
318 }
319
320 #teardown(session: Session, error: Error): void {
321 if (!session.live) return;
322 session.live = false;
323 clearInterval(session.timer);
324 if (this.#session === session) {
325 this.#session = undefined;
326 this.#ready = undefined;
327 }
328 session.child.stdin.end();
329 session.child.kill();
330 const pending = [...session.pending.values()];
331 session.pending.clear();
332 for (const request of pending) request.reject(error);
333 }
334
335 #onData(session: Session, chunk: Buffer): void {
336 if (!session.live) return;
337 session.lastSeen = Date.now();
338 session.chunks.push(chunk);
339 session.buffered += chunk.length;
340 if (!session.synced) {
341 // Shell startup files may print before the daemon runs; skip everything before its sync line.
342 const marker = Buffer.from(`PI-ENV ${session.token}\n`, "utf8");
343 const all = session.peek(session.buffered);
344 const index = all.indexOf(marker);
345 if (index === -1) {
346 if (session.buffered > 1024 * 1024) {
347 session.consume(session.buffered - marker.length);
348 }
349 return;
350 }
351 const noise = all.subarray(0, index).toString("utf8").trim();
352 if (noise !== "") this.#options.onLog?.(noise);
353 session.consume(index + marker.length);
354 session.synced = true;
355 }
356 while (session.live && session.buffered >= 4) {
357 const length = session.peek(4).readUInt32BE(0);
358 if (length < 9 || length > MAX_FRAME) {
359 this.#teardown(session, lost("Corrupt frame from pi-env"));
360 return;
361 }
362 if (session.buffered < 4 + length) return;
363 const body = session.peek(4 + length).subarray(4);
364 const type = body.readUInt8(0);
365 const id = body.readUInt32BE(1);
366 const jsonLength = body.readUInt32BE(5);
367 let json: Json;
368 try {
369 if (9 + jsonLength > length) throw new Error("JSON length out of range");
370 const parsed: unknown = JSON.parse(body.subarray(9, 9 + jsonLength).toString("utf8"));
371 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed))
372 throw new Error("not an object");
373 json = parsed as Json;
374 } catch {
375 this.#teardown(session, lost("Corrupt frame from pi-env"));
376 return;
377 }
378 // A plain Uint8Array copy, like `NodeExecutionEnv`'s reader results, not a view of the receive buffer.
379 const payload = new Uint8Array(body.subarray(9 + jsonLength));
380 session.consume(4 + length);
381 this.#dispatch(session, type, id, json, payload);
382 }
383 }
384
385 #dispatch(session: Session, type: number, id: number, json: Json, payload: Uint8Array): void {
386 const pending = session.pending.get(id);
387 if (type === EVENT) {
388 pending?.onEvent?.(json, payload);
389 return;
390 }
391 if (type !== RESULT && type !== ERROR) return;
392 if (pending === undefined) return;
393 session.pending.delete(id);
394 if (type === RESULT) pending.resolve({ json, payload, session: session.id });
395 else pending.reject(new RemoteError(json));
396 }
397}