@braedonsaunders/appkit-desk 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.
Files changed (46) hide show
  1. package/README.md +126 -1
  2. package/backend.d.ts +32 -7
  3. package/backend.d.ts.map +1 -1
  4. package/backend.js +107 -524
  5. package/backend.js.map +1 -1
  6. package/host.d.ts +27 -1
  7. package/host.d.ts.map +1 -1
  8. package/host.js +47 -19
  9. package/host.js.map +1 -1
  10. package/index.d.ts +2 -0
  11. package/index.d.ts.map +1 -1
  12. package/index.js +2 -0
  13. package/index.js.map +1 -1
  14. package/machine.d.ts +154 -0
  15. package/machine.d.ts.map +1 -0
  16. package/machine.js +573 -0
  17. package/machine.js.map +1 -0
  18. package/package.json +2 -2
  19. package/plan.d.ts +192 -31
  20. package/plan.d.ts.map +1 -1
  21. package/plan.js +298 -12
  22. package/plan.js.map +1 -1
  23. package/port-relay.d.ts +13 -0
  24. package/port-relay.d.ts.map +1 -0
  25. package/port-relay.js +56 -0
  26. package/port-relay.js.map +1 -0
  27. package/virtualization.d.ts +16 -0
  28. package/virtualization.d.ts.map +1 -0
  29. package/virtualization.js +156 -0
  30. package/virtualization.js.map +1 -0
  31. package/vz/Package.swift +23 -0
  32. package/vz/Sources/DeskNet/Addresses.swift +106 -0
  33. package/vz/Sources/DeskNet/DHCP.swift +111 -0
  34. package/vz/Sources/DeskNet/Fence.swift +57 -0
  35. package/vz/Sources/DeskNet/NetworkStack.swift +547 -0
  36. package/vz/Sources/DeskNet/Packets.swift +355 -0
  37. package/vz/Sources/DeskNet/Plumbing.swift +312 -0
  38. package/vz/Sources/DeskNet/Sockets.swift +221 -0
  39. package/vz/Sources/DeskNet/TCPFlow.swift +448 -0
  40. package/vz/Sources/appkit-desk-vz/Control.swift +152 -0
  41. package/vz/Sources/appkit-desk-vz/Helper.swift +550 -0
  42. package/vz/Sources/appkit-desk-vz/main.swift +38 -0
  43. package/vz/Tests/DeskNetTests/DeskNetTests.swift +426 -0
  44. package/vz/appkit-desk-vz.entitlements +8 -0
  45. package/vz/build.sh +23 -0
  46. package/vz/check/extract-boot.py +221 -0
package/machine.js ADDED
@@ -0,0 +1,573 @@
1
+ /**
2
+ * The guest channel every backend shares: the hybrid-vsock handshake, the
3
+ * proof that a guest is really behind it, the reconnecting machine, and the
4
+ * child-process plumbing around a VMM. Cloud Hypervisor and the
5
+ * Virtualization.framework helper both expose the guest agent through a host
6
+ * Unix socket with the same `CONNECT <port>` preamble, so everything from the
7
+ * socket inwards is one implementation. Internal to the package.
8
+ */
9
+ import { spawn } from 'node:child_process';
10
+ import { readFile, writeFile } from 'node:fs/promises';
11
+ import { createConnection } from 'node:net';
12
+ import { join } from 'node:path';
13
+ import { Buffer } from 'node:buffer';
14
+ import { DeskRequestFateUnknownError } from './backend.js';
15
+ import { DeskError } from './plan.js';
16
+ import { encodeFrame, FrameDecoder, parseHostBoundMessage, } from './protocol.js';
17
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
18
+ export const DEFAULT_CONNECT_TIMEOUT_MS = 20_000;
19
+ export const DEFAULT_CONNECT_RETRY_DELAY_MS = 100;
20
+ export const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000;
21
+ export const DEFAULT_RECONNECT_WINDOW_MS = 30_000;
22
+ export const DEFAULT_RECONNECT_RETRY_DELAY_MS = 250;
23
+ /**
24
+ * How far the reconnect delay is allowed to double. A guest agent that systemd
25
+ * is restarting is not helped by being hammered four times a second for the
26
+ * whole window, and an unbounded doubling would spend most of the window
27
+ * asleep after two failures.
28
+ */
29
+ export const RECONNECT_BACKOFF_CEILING = 8;
30
+ export const DEFAULT_KILL_GRACE_MS = 2_000;
31
+ const HANDSHAKE_LINE_LIMIT = 128;
32
+ /**
33
+ * The machine, and the small state machine that keeps it connected.
34
+ *
35
+ * A vsock channel is not a fact the host learns once at boot — the transport
36
+ * can lie about being connected, and it can go away mid-lease for reasons that
37
+ * have nothing to do with the desk being unusable: the guest agent restarts,
38
+ * the socat bridge drops, a transient vsock error, the guest wedges for a
39
+ * moment. Treating any of those as terminal stranded the desk for the rest of
40
+ * its lease with a perfectly healthy guest behind it, answering every call
41
+ * with "no longer connected". So a live connection is something this machine
42
+ * RE-ESTABLISHES:
43
+ *
44
+ * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live
45
+ * │ │
46
+ * │ └──window exhausted / VMM exited──▶ closed
47
+ * └──shutdown(), VMM already exited, protocol violation───────────▶ closed
48
+ *
49
+ * `closed` is terminal. Nothing reconnects out of it, which is what makes
50
+ * `shutdown()` and a dead VMM final rather than the start of a retry loop.
51
+ *
52
+ * What differs between hypervisors is only how the VM stops, parks, and
53
+ * reaches guest ports, and those arrive as functions.
54
+ */
55
+ export function createGuestMachine(options) {
56
+ const { deskId, exit, now, idFactory, requestTimeoutMs, reconnectWindowMs } = options;
57
+ const pending = new Map();
58
+ // Listeners live on the machine rather than on the socket, so a reconnect
59
+ // re-points the data path at the new stream and every subscriber keeps
60
+ // working without re-registering.
61
+ const listeners = new Set();
62
+ const watchers = new Set();
63
+ let stream = options.stream;
64
+ let state = 'live';
65
+ let reconnects = 0;
66
+ let reconnecting = null;
67
+ function failAll(error) {
68
+ for (const entry of pending.values()) {
69
+ clearTimeout(entry.timer);
70
+ entry.reject(error);
71
+ }
72
+ pending.clear();
73
+ }
74
+ function announce(change) {
75
+ for (const watcher of [...watchers])
76
+ watcher(change);
77
+ }
78
+ function close(error, intentional) {
79
+ if (state === 'closed')
80
+ return;
81
+ state = 'closed';
82
+ failAll(error);
83
+ stream.destroy();
84
+ // A desk the consumer asked to stop is not news; one that stopped on its
85
+ // own is the thing an operator needs to be told about.
86
+ if (!intentional)
87
+ announce({ state: 'lost', deskId, reason: error.message });
88
+ }
89
+ function attach(next) {
90
+ stream = next;
91
+ // Each connection decodes with its OWN decoder: a frame the drop cut in
92
+ // half must never be completed by the first bytes of its replacement.
93
+ const decoder = new FrameDecoder();
94
+ const current = () => stream === next && state !== 'closed';
95
+ const onData = (chunk) => {
96
+ if (!current())
97
+ return;
98
+ let values;
99
+ try {
100
+ values = decoder.push(chunk);
101
+ }
102
+ catch (error) {
103
+ close(new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`), false);
104
+ return;
105
+ }
106
+ for (const value of values) {
107
+ let message;
108
+ try {
109
+ message = parseHostBoundMessage(value);
110
+ }
111
+ catch (error) {
112
+ close(new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`), false);
113
+ return;
114
+ }
115
+ if ('id' in message) {
116
+ const entry = pending.get(message.id);
117
+ if (!entry)
118
+ continue;
119
+ pending.delete(message.id);
120
+ clearTimeout(entry.timer);
121
+ if (message.ok)
122
+ entry.resolve(message.result);
123
+ else
124
+ entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`));
125
+ }
126
+ else {
127
+ for (const listener of [...listeners])
128
+ listener(message);
129
+ }
130
+ }
131
+ };
132
+ next.on('data', onData);
133
+ next.once('close', () => {
134
+ drop(next, `the guest agent connection closed on desk ${deskId}`);
135
+ });
136
+ next.once('error', (error) => {
137
+ drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`);
138
+ });
139
+ }
140
+ function drop(from, reason) {
141
+ if (state !== 'live' || from !== stream)
142
+ return;
143
+ from.destroy();
144
+ if (exit.done) {
145
+ // A dead VMM is not a connection problem. There is no guest to get back
146
+ // to, and retrying against it forever only delays the fresh boot the
147
+ // desk actually needs.
148
+ close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false);
149
+ return;
150
+ }
151
+ state = 'reconnecting';
152
+ const lostAt = now();
153
+ // In-flight requests CANNOT be silently retried. Each of their frames
154
+ // already reached the guest, and whether the guest ran it before the
155
+ // channel went away is not knowable from here: an `exec` may have sent
156
+ // mail, a `click` may have landed. Replaying a side-effecting operation to
157
+ // paper over a blip is the wrong kind of resilience, so every one of them
158
+ // is told its fate is unknown and the caller decides.
159
+ failAll(new DeskRequestFateUnknownError(`Desk ${deskId} lost its guest agent connection while this request was in flight `
160
+ + `(${reason}); the guest may or may not have run it.`));
161
+ reconnecting = restore(reason, lostAt);
162
+ }
163
+ /** Always resolves: callers await it to learn the outcome, not to be thrown at. */
164
+ async function restore(reason, lostAt) {
165
+ let next;
166
+ try {
167
+ next = await options.reconnect(() => state !== 'reconnecting');
168
+ }
169
+ catch (error) {
170
+ close(new DeskError(`Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`), false);
171
+ return;
172
+ }
173
+ if (state !== 'reconnecting') {
174
+ // shutdown() won the race while the replacement socket was coming up.
175
+ next.destroy();
176
+ return;
177
+ }
178
+ attach(next);
179
+ state = 'live';
180
+ reconnects += 1;
181
+ announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects });
182
+ }
183
+ attach(options.stream);
184
+ const machine = {
185
+ deskId,
186
+ async request(command, requestOptions = {}) {
187
+ // A call that lands mid-reconnect waits for it rather than failing on
188
+ // the spot: the guest is usually back within seconds, and telling a
189
+ // caller a desk is gone when it is about to be fine is the bug this
190
+ // machine exists to end. The wait is bounded by the same window the
191
+ // reconnect itself is.
192
+ const waitUntil = now() + reconnectWindowMs;
193
+ while (state === 'reconnecting') {
194
+ const attempt = reconnecting;
195
+ if (!attempt || now() >= waitUntil)
196
+ break;
197
+ await attempt;
198
+ }
199
+ if (state !== 'live') {
200
+ // This one never left the host, so — unlike a request that was in
201
+ // flight when the channel dropped — repeating it is safe.
202
+ throw new DeskError(`Desk ${deskId} is no longer connected.`);
203
+ }
204
+ const id = idFactory();
205
+ const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs;
206
+ const target = stream;
207
+ return await new Promise((resolvePromise, rejectPromise) => {
208
+ const timer = setTimeout(() => {
209
+ pending.delete(id);
210
+ rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`));
211
+ }, timeoutMs);
212
+ timer.unref();
213
+ pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer });
214
+ target.write(encodeFrame({ ...command, id }));
215
+ });
216
+ },
217
+ subscribe(listener) {
218
+ listeners.add(listener);
219
+ return () => {
220
+ listeners.delete(listener);
221
+ };
222
+ },
223
+ onConnectionChange(listener) {
224
+ watchers.add(listener);
225
+ return () => {
226
+ watchers.delete(listener);
227
+ };
228
+ },
229
+ async shutdown() {
230
+ // Terminal by construction: `closed` is the state the reconnect loop
231
+ // checks, so an explicit shutdown can never be followed by a reconnect.
232
+ close(new DeskError(`Desk ${deskId} is shutting down.`), true);
233
+ await options.stop();
234
+ },
235
+ };
236
+ if (options.park) {
237
+ const park = options.park;
238
+ machine.park = async (snapshotDir) => {
239
+ // Close the guest channel FIRST. Pausing a VM strands whatever was in
240
+ // flight on the vsock, and a reconnect attempt against a paused guest
241
+ // would burn the whole reconnect window before giving up — so the channel
242
+ // is made terminal before the VM stops answering, exactly as shutdown
243
+ // does it.
244
+ close(new DeskError(`Desk ${deskId} is being parked.`), true);
245
+ await park(snapshotDir);
246
+ };
247
+ }
248
+ if (options.connect) {
249
+ const connect = options.connect;
250
+ machine.connect = async (port) => {
251
+ if (state === 'closed')
252
+ throw new DeskError(`Desk ${deskId} is no longer connected.`);
253
+ return await connect(port);
254
+ };
255
+ }
256
+ return machine;
257
+ }
258
+ /**
259
+ * Read a child's output and keep only the last few kilobytes.
260
+ *
261
+ * This is not for logging — it is load-bearing. A child spawned with its
262
+ * streams as PIPES blocks once a pipe nobody reads fills, after about 64KB.
263
+ * Cloud Hypervisor logs while it runs, so an unread pipe freezes the guest
264
+ * partway through boot: the process is alive, the disk is untouched, and the
265
+ * guest agent never reaches vsock. Every symptom points at the image and none
266
+ * of them are its fault.
267
+ *
268
+ * Draining costs nothing and buys the tail of what the process said, which is
269
+ * the difference between "the VMM exited" and knowing why. `streams` names the
270
+ * pipes to drain: a helper that speaks a protocol on stdout drains only stderr.
271
+ */
272
+ export function drainOutput(child, limit = 8 * 1024, streams = ['stdout', 'stderr']) {
273
+ let buffered = '';
274
+ const absorb = (chunk) => {
275
+ buffered += String(chunk);
276
+ if (buffered.length > limit)
277
+ buffered = buffered.slice(buffered.length - limit);
278
+ };
279
+ for (const name of streams) {
280
+ const pipe = child[name];
281
+ pipe?.on('data', absorb);
282
+ // A pipe that errors must not take the process down with it.
283
+ pipe?.on('error', () => undefined);
284
+ }
285
+ return { tail: () => buffered.trim() };
286
+ }
287
+ export function watchExit(child) {
288
+ const watcher = { done: false, promise: Promise.resolve() };
289
+ watcher.promise = new Promise((resolvePromise) => {
290
+ const settle = () => {
291
+ watcher.done = true;
292
+ resolvePromise();
293
+ };
294
+ child.once('exit', settle);
295
+ child.once('error', settle);
296
+ });
297
+ return watcher;
298
+ }
299
+ export async function terminate(child, exit, killGraceMs) {
300
+ if (exit.done)
301
+ return;
302
+ child.kill('SIGTERM');
303
+ const forceKill = setTimeout(() => {
304
+ if (!exit.done)
305
+ child.kill('SIGKILL');
306
+ }, killGraceMs);
307
+ forceKill.unref();
308
+ await exit.promise;
309
+ clearTimeout(forceKill);
310
+ }
311
+ export function runToCompletion(child, label) {
312
+ return new Promise((resolvePromise, rejectPromise) => {
313
+ let stderr = '';
314
+ child.stderr?.on('data', (chunk) => {
315
+ stderr += String(chunk);
316
+ });
317
+ child.once('error', (error) => {
318
+ rejectPromise(new DeskError(`${label} failed to start: ${error.message}`));
319
+ });
320
+ child.once('exit', (code, signal) => {
321
+ if (code === 0) {
322
+ resolvePromise();
323
+ return;
324
+ }
325
+ const detail = stderr.trim();
326
+ rejectPromise(new DeskError(`${label} exited with code ${code ?? 'unknown'}`
327
+ + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`));
328
+ });
329
+ });
330
+ }
331
+ /**
332
+ * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with
333
+ * a line-oriented preamble: the client writes `CONNECT <port>\n` and the VMM
334
+ * answers `OK <assigned>\n` before the byte stream becomes the guest
335
+ * connection. The VMM creates the socket during boot, so connection attempts
336
+ * retry until the deadline. The Virtualization.framework helper speaks the
337
+ * same preamble on its own socket.
338
+ *
339
+ * The same loop serves the first connection and every later reconnect, so a
340
+ * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the
341
+ * banner would re-adopt exactly the hollow stream the boot path learned not to.
342
+ */
343
+ export async function connectWithRetry(options) {
344
+ const deadline = options.now() + options.timeoutMs;
345
+ let lastFailure = 'the guest agent never answered';
346
+ let retryDelayMs = options.retryDelayMs;
347
+ while (options.now() <= deadline) {
348
+ if (options.exited.done) {
349
+ throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.');
350
+ }
351
+ if (options.abandoned?.() === true) {
352
+ throw new DeskError('the connection attempt was abandoned.');
353
+ }
354
+ try {
355
+ const stream = await attemptHandshake(options.connect, options.socketPath, options.port, options.attemptTimeoutMs);
356
+ try {
357
+ await confirmGuest(stream, options.attemptTimeoutMs);
358
+ }
359
+ catch (error) {
360
+ stream.destroy();
361
+ throw error;
362
+ }
363
+ return stream;
364
+ }
365
+ catch (error) {
366
+ lastFailure = errorMessage(error);
367
+ }
368
+ await delay(retryDelayMs);
369
+ if (options.maxRetryDelayMs !== undefined) {
370
+ retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs);
371
+ }
372
+ }
373
+ throw new DeskError(`Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`);
374
+ }
375
+ /**
376
+ * Prove a guest is behind the handshake by asking it something.
377
+ *
378
+ * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything
379
+ * in the guest is listening on that port, and only closes the socket a moment
380
+ * later when it finds nobody there. A caller that trusts the banner therefore
381
+ * "connects" to a guest that is still booting, gets a closed stream seconds
382
+ * later, and — because a closed machine is not retried — leaves the desk dead
383
+ * for as long as it is leased, with a healthy guest sitting behind it. So the
384
+ * handshake is not the test; a reply is.
385
+ */
386
+ async function confirmGuest(stream, timeoutMs) {
387
+ const decoder = new FrameDecoder();
388
+ await new Promise((resolvePromise, rejectPromise) => {
389
+ let settled = false;
390
+ const finish = (error) => {
391
+ if (settled)
392
+ return;
393
+ settled = true;
394
+ clearTimeout(timer);
395
+ stream.off('data', onData);
396
+ stream.off('close', onClose);
397
+ stream.off('error', finish);
398
+ if (error)
399
+ rejectPromise(error);
400
+ else
401
+ resolvePromise();
402
+ };
403
+ const timer = setTimeout(() => finish(new DeskError('the guest agent did not answer the first request.')), timeoutMs);
404
+ timer.unref?.();
405
+ const onClose = () => finish(new DeskError('the connection closed before the guest agent answered.'));
406
+ const onData = (chunk) => {
407
+ let values;
408
+ try {
409
+ values = decoder.push(chunk);
410
+ }
411
+ catch (error) {
412
+ finish(error instanceof Error ? error : new Error(String(error)));
413
+ return;
414
+ }
415
+ for (const value of values) {
416
+ // Anything at all proves a guest is there; the reply is parsed for
417
+ // real by the machine once it owns the stream.
418
+ if (value && typeof value === 'object') {
419
+ finish();
420
+ return;
421
+ }
422
+ }
423
+ };
424
+ stream.on('data', onData);
425
+ stream.once('close', onClose);
426
+ stream.once('error', finish);
427
+ stream.write(encodeFrame({ id: 'hello', op: 'ping' }));
428
+ });
429
+ }
430
+ /**
431
+ * One handshake attempt, which MUST settle.
432
+ *
433
+ * Cloud Hypervisor accepts a connection on the vsock socket whether or not
434
+ * anything in the guest is listening on the port, and when nothing is it may
435
+ * answer nothing at all: no reply, no error, no close. Without a deadline of
436
+ * its own this promise then never settles — and because the caller awaits it
437
+ * inside the retry loop, the loop stops iterating, the overall deadline is
438
+ * never re-checked, and the boot hangs forever rather than failing. That is
439
+ * indistinguishable from a wedged host and it is why every attempt is bounded
440
+ * here as well as in aggregate.
441
+ *
442
+ * A close before the reply line is a refusal: that is how a port with nothing
443
+ * listening presents through Cloud Hypervisor, and the Virtualization.framework
444
+ * helper presents a refused vsock or TCP port the same way.
445
+ */
446
+ export function attemptHandshake(connect, socketPath, port, attemptTimeoutMs) {
447
+ return new Promise((resolvePromise, rejectPromise) => {
448
+ let stream;
449
+ try {
450
+ stream = connect(socketPath);
451
+ }
452
+ catch (error) {
453
+ rejectPromise(error instanceof Error ? error : new Error(String(error)));
454
+ return;
455
+ }
456
+ let banner = '';
457
+ let settled = false;
458
+ const timer = setTimeout(() => {
459
+ fail(new DeskError('vsock handshake went unanswered.'));
460
+ }, attemptTimeoutMs);
461
+ // An unref'd timer must not hold the process open on its own.
462
+ timer.unref?.();
463
+ const fail = (error) => {
464
+ if (settled)
465
+ return;
466
+ settled = true;
467
+ clearTimeout(timer);
468
+ stream.destroy();
469
+ rejectPromise(error);
470
+ };
471
+ const onData = (chunk) => {
472
+ banner += chunk.toString('latin1');
473
+ const newline = banner.indexOf('\n');
474
+ if (newline === -1) {
475
+ if (banner.length > HANDSHAKE_LINE_LIMIT) {
476
+ fail(new DeskError('vsock handshake reply exceeded the line limit.'));
477
+ }
478
+ return;
479
+ }
480
+ const line = banner.slice(0, newline);
481
+ const rest = banner.slice(newline + 1);
482
+ stream.off('data', onData);
483
+ stream.off('error', fail);
484
+ if (!line.startsWith('OK ')) {
485
+ fail(new DeskError(`vsock handshake was refused: ${line}`));
486
+ return;
487
+ }
488
+ settled = true;
489
+ clearTimeout(timer);
490
+ if (rest.length > 0)
491
+ stream.unshift(Buffer.from(rest, 'latin1'));
492
+ resolvePromise(stream);
493
+ };
494
+ stream.on('data', onData);
495
+ stream.once('error', fail);
496
+ // A close before the banner is a refusal, not a hang.
497
+ stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')));
498
+ stream.write(`CONNECT ${port}\n`);
499
+ });
500
+ }
501
+ /**
502
+ * The shares a snapshot was taken with, kept beside it.
503
+ *
504
+ * A snapshot holds the machine's devices, shares among them, so it can only
505
+ * come back with the shares it was parked with: Cloud Hypervisor would resume
506
+ * without a share that was added since, and Virtualization.framework refuses a
507
+ * changed device list. The host restores with this list rather than the one it
508
+ * was given, and a backend refuses a plan that disagrees with it.
509
+ */
510
+ const SHARE_MANIFEST = 'shares.json';
511
+ export async function writeShareManifest(snapshotDir, shares) {
512
+ await writeFile(join(snapshotDir, SHARE_MANIFEST), `${shareManifest(shares)}\n`, { mode: 0o600 });
513
+ }
514
+ /**
515
+ * The shares recorded beside a snapshot. A snapshot with no record predates
516
+ * shares, so it was taken with none. Paths are returned as recorded; whether
517
+ * they still exist is the launch plan's to check.
518
+ */
519
+ export async function readShareManifest(snapshotDir) {
520
+ let text;
521
+ try {
522
+ text = await readFile(join(snapshotDir, SHARE_MANIFEST), 'utf8');
523
+ }
524
+ catch (error) {
525
+ if (error.code === 'ENOENT')
526
+ return [];
527
+ throw error;
528
+ }
529
+ let value;
530
+ try {
531
+ value = JSON.parse(text);
532
+ }
533
+ catch {
534
+ throw new DeskError(`${join(snapshotDir, SHARE_MANIFEST)} is not valid JSON.`);
535
+ }
536
+ const valid = Array.isArray(value) && value.every((entry) => typeof entry === 'object' && entry !== null
537
+ && typeof entry.tag === 'string'
538
+ && typeof entry.path === 'string'
539
+ && typeof entry.readOnly === 'boolean');
540
+ if (!valid)
541
+ throw new DeskError(`${join(snapshotDir, SHARE_MANIFEST)} is not a list of shares.`);
542
+ return value.map(({ tag, path, readOnly }) => ({ tag, path, readOnly }));
543
+ }
544
+ /** Throws unless the snapshot was parked with exactly `shares`, in order. */
545
+ export async function assertShareManifest(snapshotDir, shares) {
546
+ const saved = shareManifest(await readShareManifest(snapshotDir));
547
+ const wanted = shareManifest(shares);
548
+ if (saved !== wanted)
549
+ throw new DeskError(`the snapshot was taken with shares ${saved}, not ${wanted}`);
550
+ }
551
+ function shareManifest(shares) {
552
+ return JSON.stringify(shares.map(({ tag, path, readOnly }) => ({ tag, path, readOnly })));
553
+ }
554
+ export function defaultLauncher(command, args, options) {
555
+ return spawn(command, [...args], {
556
+ stdio: ['ignore', 'pipe', 'pipe'],
557
+ uid: options.identity?.uid,
558
+ gid: options.identity?.gid,
559
+ });
560
+ }
561
+ export function defaultConnect(socketPath) {
562
+ return createConnection(socketPath);
563
+ }
564
+ export function delay(ms) {
565
+ return new Promise((resolvePromise) => {
566
+ const timer = setTimeout(resolvePromise, ms);
567
+ timer.unref();
568
+ });
569
+ }
570
+ export function errorMessage(error) {
571
+ return error instanceof Error ? error.message : String(error);
572
+ }
573
+ //# sourceMappingURL=machine.js.map
package/machine.js.map ADDED
@@ -0,0 +1 @@
1
+ {"version":3,"file":"machine.js","sourceRoot":"","sources":["../src/machine.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AACH,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,kBAAkB,CAAA;AACtD,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AAChC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AAEpC,OAAO,EAAE,2BAA2B,EAA+C,MAAM,WAAW,CAAA;AACpG,OAAO,EAAE,SAAS,EAA6C,MAAM,QAAQ,CAAA;AAC7E,OAAO,EACL,WAAW,EACX,YAAY,EACZ,qBAAqB,GAGtB,MAAM,YAAY,CAAA;AAEnB,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AAChD,MAAM,CAAC,MAAM,0BAA0B,GAAG,MAAM,CAAA;AAChD,MAAM,CAAC,MAAM,8BAA8B,GAAG,GAAG,CAAA;AACjD,MAAM,CAAC,MAAM,4BAA4B,GAAG,KAAK,CAAA;AACjD,MAAM,CAAC,MAAM,2BAA2B,GAAG,MAAM,CAAA;AACjD,MAAM,CAAC,MAAM,gCAAgC,GAAG,GAAG,CAAA;AACnD;;;;;GAKG;AACH,MAAM,CAAC,MAAM,yBAAyB,GAAG,CAAC,CAAA;AAC1C,MAAM,CAAC,MAAM,qBAAqB,GAAG,KAAK,CAAA;AAC1C,MAAM,oBAAoB,GAAG,GAAG,CAAA;AAEhC;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAmBlC;IACC,MAAM,EAAE,MAAM,EAAE,IAAI,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AAA;AAC/D,CAAC","sourcesContent":["/**\n * The guest channel every backend shares: the hybrid-vsock handshake, the\n * proof that a guest is really behind it, the reconnecting machine, and the\n * child-process plumbing around a VMM. Cloud Hypervisor and the\n * Virtualization.framework helper both expose the guest agent through a host\n * Unix socket with the same `CONNECT <port>` preamble, so everything from the\n * socket inwards is one implementation. Internal to the package.\n */\nimport { spawn, type ChildProcess } from 'node:child_process'\nimport { readFile, writeFile } from 'node:fs/promises'\nimport { createConnection } from 'node:net'\nimport { join } from 'node:path'\nimport { Buffer } from 'node:buffer'\nimport type { Duplex } from 'node:stream'\nimport { DeskRequestFateUnknownError, type DeskConnectionChange, type DeskMachine } from './backend'\nimport { DeskError, type DeskLauncherIdentity, type DeskShare } from './plan'\nimport {\n encodeFrame,\n FrameDecoder,\n parseHostBoundMessage,\n type GuestEventMessage,\n type HostBoundMessage,\n} from './protocol'\n\nexport const DEFAULT_REQUEST_TIMEOUT_MS = 30_000\nexport const DEFAULT_CONNECT_TIMEOUT_MS = 20_000\nexport const DEFAULT_CONNECT_RETRY_DELAY_MS = 100\nexport const DEFAULT_HANDSHAKE_TIMEOUT_MS = 5_000\nexport const DEFAULT_RECONNECT_WINDOW_MS = 30_000\nexport const DEFAULT_RECONNECT_RETRY_DELAY_MS = 250\n/**\n * How far the reconnect delay is allowed to double. A guest agent that systemd\n * is restarting is not helped by being hammered four times a second for the\n * whole window, and an unbounded doubling would spend most of the window\n * asleep after two failures.\n */\nexport const RECONNECT_BACKOFF_CEILING = 8\nexport const DEFAULT_KILL_GRACE_MS = 2_000\nconst HANDSHAKE_LINE_LIMIT = 128\n\n/**\n * The machine, and the small state machine that keeps it connected.\n *\n * A vsock channel is not a fact the host learns once at boot — the transport\n * can lie about being connected, and it can go away mid-lease for reasons that\n * have nothing to do with the desk being unusable: the guest agent restarts,\n * the socat bridge drops, a transient vsock error, the guest wedges for a\n * moment. Treating any of those as terminal stranded the desk for the rest of\n * its lease with a perfectly healthy guest behind it, answering every call\n * with \"no longer connected\". So a live connection is something this machine\n * RE-ESTABLISHES:\n *\n * live ──unexpected drop──▶ reconnecting ──confirmed guest──▶ live\n * │ │\n * │ └──window exhausted / VMM exited──▶ closed\n * └──shutdown(), VMM already exited, protocol violation───────────▶ closed\n *\n * `closed` is terminal. Nothing reconnects out of it, which is what makes\n * `shutdown()` and a dead VMM final rather than the start of a retry loop.\n *\n * What differs between hypervisors is only how the VM stops, parks, and\n * reaches guest ports, and those arrive as functions.\n */\nexport function createGuestMachine(options: {\n deskId: string\n exit: ExitWatcher\n stream: Duplex\n /** Re-establishes the channel; resolves only once a guest has answered. */\n reconnect: (abandoned: () => boolean) => Promise<Duplex>\n reconnectWindowMs: number\n now: () => number\n idFactory: () => string\n requestTimeoutMs: number\n /** Stop the VMM; resolves once its process has exited. */\n stop: () => Promise<void>\n /**\n * Pause, snapshot into `snapshotDir`, and stop the VMM. Called after the\n * guest channel has been closed. Must leave the VMM stopped on failure too.\n */\n park?: (snapshotDir: string) => Promise<void>\n /** Open a host-to-guest TCP stream, for backends with no routable guest. */\n connect?: (port: number) => Promise<Duplex>\n}): DeskMachine {\n const { deskId, exit, now, idFactory, requestTimeoutMs, reconnectWindowMs } = options\n const pending = new Map<\n string,\n { resolve: (result: unknown) => void; reject: (error: Error) => void; timer: NodeJS.Timeout }\n >()\n // Listeners live on the machine rather than on the socket, so a reconnect\n // re-points the data path at the new stream and every subscriber keeps\n // working without re-registering.\n const listeners = new Set<(event: GuestEventMessage) => void>()\n const watchers = new Set<(change: DeskConnectionChange) => void>()\n let stream = options.stream\n let state: 'live' | 'reconnecting' | 'closed' = 'live'\n let reconnects = 0\n let reconnecting: Promise<void> | null = null\n\n function failAll(error: Error): void {\n for (const entry of pending.values()) {\n clearTimeout(entry.timer)\n entry.reject(error)\n }\n pending.clear()\n }\n\n function announce(change: DeskConnectionChange): void {\n for (const watcher of [...watchers]) watcher(change)\n }\n\n function close(error: DeskError, intentional: boolean): void {\n if (state === 'closed') return\n state = 'closed'\n failAll(error)\n stream.destroy()\n // A desk the consumer asked to stop is not news; one that stopped on its\n // own is the thing an operator needs to be told about.\n if (!intentional) announce({ state: 'lost', deskId, reason: error.message })\n }\n\n function attach(next: Duplex): void {\n stream = next\n // Each connection decodes with its OWN decoder: a frame the drop cut in\n // half must never be completed by the first bytes of its replacement.\n const decoder = new FrameDecoder()\n const current = () => stream === next && state !== 'closed'\n const onData = (chunk: Buffer): void => {\n if (!current()) return\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n close(\n new DeskError(`Guest agent protocol violation on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n for (const value of values) {\n let message: HostBoundMessage\n try {\n message = parseHostBoundMessage(value)\n } catch (error) {\n close(\n new DeskError(`Guest agent sent a malformed message on desk ${deskId}: ${errorMessage(error)}`),\n false,\n )\n return\n }\n if ('id' in message) {\n const entry = pending.get(message.id)\n if (!entry) continue\n pending.delete(message.id)\n clearTimeout(entry.timer)\n if (message.ok) entry.resolve(message.result)\n else entry.reject(new DeskError(`Guest agent error on desk ${deskId}: ${message.error}`))\n } else {\n for (const listener of [...listeners]) listener(message)\n }\n }\n }\n next.on('data', onData)\n next.once('close', () => {\n drop(next, `the guest agent connection closed on desk ${deskId}`)\n })\n next.once('error', (error: Error) => {\n drop(next, `the guest agent connection failed on desk ${deskId}: ${error.message}`)\n })\n }\n\n function drop(from: Duplex, reason: string): void {\n if (state !== 'live' || from !== stream) return\n from.destroy()\n if (exit.done) {\n // A dead VMM is not a connection problem. There is no guest to get back\n // to, and retrying against it forever only delays the fresh boot the\n // desk actually needs.\n close(new DeskError(`Desk ${deskId} is no longer connected: the VMM exited (${reason}).`), false)\n return\n }\n state = 'reconnecting'\n const lostAt = now()\n // In-flight requests CANNOT be silently retried. Each of their frames\n // already reached the guest, and whether the guest ran it before the\n // channel went away is not knowable from here: an `exec` may have sent\n // mail, a `click` may have landed. Replaying a side-effecting operation to\n // paper over a blip is the wrong kind of resilience, so every one of them\n // is told its fate is unknown and the caller decides.\n failAll(\n new DeskRequestFateUnknownError(\n `Desk ${deskId} lost its guest agent connection while this request was in flight `\n + `(${reason}); the guest may or may not have run it.`,\n ),\n )\n reconnecting = restore(reason, lostAt)\n }\n\n /** Always resolves: callers await it to learn the outcome, not to be thrown at. */\n async function restore(reason: string, lostAt: number): Promise<void> {\n let next: Duplex\n try {\n next = await options.reconnect(() => state !== 'reconnecting')\n } catch (error) {\n close(\n new DeskError(\n `Desk ${deskId} lost its guest agent connection and could not get it back: ${errorMessage(error)}`,\n ),\n false,\n )\n return\n }\n if (state !== 'reconnecting') {\n // shutdown() won the race while the replacement socket was coming up.\n next.destroy()\n return\n }\n attach(next)\n state = 'live'\n reconnects += 1\n announce({ state: 'reconnected', deskId, reason, downtimeMs: now() - lostAt, reconnects })\n }\n\n attach(options.stream)\n\n const machine: DeskMachine = {\n deskId,\n async request(command, requestOptions = {}) {\n // A call that lands mid-reconnect waits for it rather than failing on\n // the spot: the guest is usually back within seconds, and telling a\n // caller a desk is gone when it is about to be fine is the bug this\n // machine exists to end. The wait is bounded by the same window the\n // reconnect itself is.\n const waitUntil = now() + reconnectWindowMs\n while (state === 'reconnecting') {\n const attempt = reconnecting\n if (!attempt || now() >= waitUntil) break\n await attempt\n }\n if (state !== 'live') {\n // This one never left the host, so — unlike a request that was in\n // flight when the channel dropped — repeating it is safe.\n throw new DeskError(`Desk ${deskId} is no longer connected.`)\n }\n const id = idFactory()\n const timeoutMs = requestOptions.timeoutMs ?? requestTimeoutMs\n const target = stream\n return await new Promise<unknown>((resolvePromise, rejectPromise) => {\n const timer = setTimeout(() => {\n pending.delete(id)\n rejectPromise(new DeskError(`Guest request ${command.op} timed out on desk ${deskId}.`))\n }, timeoutMs)\n timer.unref()\n pending.set(id, { resolve: resolvePromise, reject: rejectPromise, timer })\n target.write(encodeFrame({ ...command, id }))\n })\n },\n subscribe(listener) {\n listeners.add(listener)\n return () => {\n listeners.delete(listener)\n }\n },\n onConnectionChange(listener) {\n watchers.add(listener)\n return () => {\n watchers.delete(listener)\n }\n },\n async shutdown() {\n // Terminal by construction: `closed` is the state the reconnect loop\n // checks, so an explicit shutdown can never be followed by a reconnect.\n close(new DeskError(`Desk ${deskId} is shutting down.`), true)\n await options.stop()\n },\n }\n if (options.park) {\n const park = options.park\n machine.park = async (snapshotDir: string) => {\n // Close the guest channel FIRST. Pausing a VM strands whatever was in\n // flight on the vsock, and a reconnect attempt against a paused guest\n // would burn the whole reconnect window before giving up — so the channel\n // is made terminal before the VM stops answering, exactly as shutdown\n // does it.\n close(new DeskError(`Desk ${deskId} is being parked.`), true)\n await park(snapshotDir)\n }\n }\n if (options.connect) {\n const connect = options.connect\n machine.connect = async (port: number) => {\n if (state === 'closed') throw new DeskError(`Desk ${deskId} is no longer connected.`)\n return await connect(port)\n }\n }\n return machine\n}\n\nexport interface ExitWatcher {\n done: boolean\n promise: Promise<void>\n}\n\n/**\n * Read a child's output and keep only the last few kilobytes.\n *\n * This is not for logging — it is load-bearing. A child spawned with its\n * streams as PIPES blocks once a pipe nobody reads fills, after about 64KB.\n * Cloud Hypervisor logs while it runs, so an unread pipe freezes the guest\n * partway through boot: the process is alive, the disk is untouched, and the\n * guest agent never reaches vsock. Every symptom points at the image and none\n * of them are its fault.\n *\n * Draining costs nothing and buys the tail of what the process said, which is\n * the difference between \"the VMM exited\" and knowing why. `streams` names the\n * pipes to drain: a helper that speaks a protocol on stdout drains only stderr.\n */\nexport function drainOutput(\n child: ChildProcess,\n limit = 8 * 1024,\n streams: readonly ('stdout' | 'stderr')[] = ['stdout', 'stderr'],\n): { tail: () => string } {\n let buffered = ''\n const absorb = (chunk: unknown) => {\n buffered += String(chunk)\n if (buffered.length > limit) buffered = buffered.slice(buffered.length - limit)\n }\n for (const name of streams) {\n const pipe = child[name]\n pipe?.on('data', absorb)\n // A pipe that errors must not take the process down with it.\n pipe?.on('error', () => undefined)\n }\n return { tail: () => buffered.trim() }\n}\n\nexport function watchExit(child: ChildProcess): ExitWatcher {\n const watcher: ExitWatcher = { done: false, promise: Promise.resolve() }\n watcher.promise = new Promise<void>((resolvePromise) => {\n const settle = () => {\n watcher.done = true\n resolvePromise()\n }\n child.once('exit', settle)\n child.once('error', settle)\n })\n return watcher\n}\n\nexport async function terminate(child: ChildProcess, exit: ExitWatcher, killGraceMs: number): Promise<void> {\n if (exit.done) return\n child.kill('SIGTERM')\n const forceKill = setTimeout(() => {\n if (!exit.done) child.kill('SIGKILL')\n }, killGraceMs)\n forceKill.unref()\n await exit.promise\n clearTimeout(forceKill)\n}\n\nexport function runToCompletion(child: ChildProcess, label: string): Promise<void> {\n return new Promise<void>((resolvePromise, rejectPromise) => {\n let stderr = ''\n child.stderr?.on('data', (chunk) => {\n stderr += String(chunk)\n })\n child.once('error', (error) => {\n rejectPromise(new DeskError(`${label} failed to start: ${error.message}`))\n })\n child.once('exit', (code, signal) => {\n if (code === 0) {\n resolvePromise()\n return\n }\n const detail = stderr.trim()\n rejectPromise(\n new DeskError(\n `${label} exited with code ${code ?? 'unknown'}`\n + `${signal ? ` (${signal})` : ''}${detail ? `: ${detail}` : '.'}`,\n ),\n )\n })\n })\n}\n\n/**\n * Cloud Hypervisor exposes guest vsock ports through a host Unix socket with\n * a line-oriented preamble: the client writes `CONNECT <port>\\n` and the VMM\n * answers `OK <assigned>\\n` before the byte stream becomes the guest\n * connection. The VMM creates the socket during boot, so connection attempts\n * retry until the deadline. The Virtualization.framework helper speaks the\n * same preamble on its own socket.\n *\n * The same loop serves the first connection and every later reconnect, so a\n * reconnect gets `confirmGuest` too — a mid-lease reconnect that trusted the\n * banner would re-adopt exactly the hollow stream the boot path learned not to.\n */\nexport async function connectWithRetry(options: {\n connect: (socketPath: string) => Duplex\n now: () => number\n socketPath: string\n port: number\n timeoutMs: number\n retryDelayMs: number\n /** Ceiling the delay doubles toward; omitted keeps the delay constant. */\n maxRetryDelayMs?: number\n attemptTimeoutMs: number\n exited: ExitWatcher\n /** A dead VMM means something different at boot than it does mid-lease. */\n exitedMessage?: string\n /** Stops the loop early when the caller no longer wants the connection. */\n abandoned?: () => boolean\n}): Promise<Duplex> {\n const deadline = options.now() + options.timeoutMs\n let lastFailure = 'the guest agent never answered'\n let retryDelayMs = options.retryDelayMs\n while (options.now() <= deadline) {\n if (options.exited.done) {\n throw new DeskError(options.exitedMessage ?? 'The VMM exited before the guest agent came up.')\n }\n if (options.abandoned?.() === true) {\n throw new DeskError('the connection attempt was abandoned.')\n }\n try {\n const stream = await attemptHandshake(\n options.connect,\n options.socketPath,\n options.port,\n options.attemptTimeoutMs,\n )\n try {\n await confirmGuest(stream, options.attemptTimeoutMs)\n } catch (error) {\n stream.destroy()\n throw error\n }\n return stream\n } catch (error) {\n lastFailure = errorMessage(error)\n }\n await delay(retryDelayMs)\n if (options.maxRetryDelayMs !== undefined) {\n retryDelayMs = Math.min(retryDelayMs * 2, options.maxRetryDelayMs)\n }\n }\n throw new DeskError(\n `Timed out connecting to the guest agent at ${options.socketPath}: ${lastFailure}`,\n )\n}\n\n/**\n * Prove a guest is behind the handshake by asking it something.\n *\n * Cloud Hypervisor answers `CONNECT <port>` with `OK` whether or not anything\n * in the guest is listening on that port, and only closes the socket a moment\n * later when it finds nobody there. A caller that trusts the banner therefore\n * \"connects\" to a guest that is still booting, gets a closed stream seconds\n * later, and — because a closed machine is not retried — leaves the desk dead\n * for as long as it is leased, with a healthy guest sitting behind it. So the\n * handshake is not the test; a reply is.\n */\nasync function confirmGuest(stream: Duplex, timeoutMs: number): Promise<void> {\n const decoder = new FrameDecoder()\n await new Promise<void>((resolvePromise, rejectPromise) => {\n let settled = false\n const finish = (error?: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.off('data', onData)\n stream.off('close', onClose)\n stream.off('error', finish)\n if (error) rejectPromise(error)\n else resolvePromise()\n }\n const timer = setTimeout(\n () => finish(new DeskError('the guest agent did not answer the first request.')),\n timeoutMs,\n )\n timer.unref?.()\n const onClose = () =>\n finish(new DeskError('the connection closed before the guest agent answered.'))\n const onData = (chunk: Buffer) => {\n let values: unknown[]\n try {\n values = decoder.push(chunk)\n } catch (error) {\n finish(error instanceof Error ? error : new Error(String(error)))\n return\n }\n for (const value of values) {\n // Anything at all proves a guest is there; the reply is parsed for\n // real by the machine once it owns the stream.\n if (value && typeof value === 'object') {\n finish()\n return\n }\n }\n }\n stream.on('data', onData)\n stream.once('close', onClose)\n stream.once('error', finish)\n stream.write(encodeFrame({ id: 'hello', op: 'ping' }))\n })\n}\n\n/**\n * One handshake attempt, which MUST settle.\n *\n * Cloud Hypervisor accepts a connection on the vsock socket whether or not\n * anything in the guest is listening on the port, and when nothing is it may\n * answer nothing at all: no reply, no error, no close. Without a deadline of\n * its own this promise then never settles — and because the caller awaits it\n * inside the retry loop, the loop stops iterating, the overall deadline is\n * never re-checked, and the boot hangs forever rather than failing. That is\n * indistinguishable from a wedged host and it is why every attempt is bounded\n * here as well as in aggregate.\n *\n * A close before the reply line is a refusal: that is how a port with nothing\n * listening presents through Cloud Hypervisor, and the Virtualization.framework\n * helper presents a refused vsock or TCP port the same way.\n */\nexport function attemptHandshake(\n connect: (socketPath: string) => Duplex,\n socketPath: string,\n port: number,\n attemptTimeoutMs: number,\n): Promise<Duplex> {\n return new Promise<Duplex>((resolvePromise, rejectPromise) => {\n let stream: Duplex\n try {\n stream = connect(socketPath)\n } catch (error) {\n rejectPromise(error instanceof Error ? error : new Error(String(error)))\n return\n }\n let banner = ''\n let settled = false\n const timer = setTimeout(() => {\n fail(new DeskError('vsock handshake went unanswered.'))\n }, attemptTimeoutMs)\n // An unref'd timer must not hold the process open on its own.\n timer.unref?.()\n const fail = (error: Error) => {\n if (settled) return\n settled = true\n clearTimeout(timer)\n stream.destroy()\n rejectPromise(error)\n }\n const onData = (chunk: Buffer) => {\n banner += chunk.toString('latin1')\n const newline = banner.indexOf('\\n')\n if (newline === -1) {\n if (banner.length > HANDSHAKE_LINE_LIMIT) {\n fail(new DeskError('vsock handshake reply exceeded the line limit.'))\n }\n return\n }\n const line = banner.slice(0, newline)\n const rest = banner.slice(newline + 1)\n stream.off('data', onData)\n stream.off('error', fail)\n if (!line.startsWith('OK ')) {\n fail(new DeskError(`vsock handshake was refused: ${line}`))\n return\n }\n settled = true\n clearTimeout(timer)\n if (rest.length > 0) stream.unshift(Buffer.from(rest, 'latin1'))\n resolvePromise(stream)\n }\n stream.on('data', onData)\n stream.once('error', fail)\n // A close before the banner is a refusal, not a hang.\n stream.once('close', () => fail(new DeskError('vsock handshake closed before a reply.')))\n stream.write(`CONNECT ${port}\\n`)\n })\n}\n\n/**\n * The shares a snapshot was taken with, kept beside it.\n *\n * A snapshot holds the machine's devices, shares among them, so it can only\n * come back with the shares it was parked with: Cloud Hypervisor would resume\n * without a share that was added since, and Virtualization.framework refuses a\n * changed device list. The host restores with this list rather than the one it\n * was given, and a backend refuses a plan that disagrees with it.\n */\nconst SHARE_MANIFEST = 'shares.json'\n\nexport async function writeShareManifest(snapshotDir: string, shares: readonly DeskShare[]): Promise<void> {\n await writeFile(join(snapshotDir, SHARE_MANIFEST), `${shareManifest(shares)}\\n`, { mode: 0o600 })\n}\n\n/**\n * The shares recorded beside a snapshot. A snapshot with no record predates\n * shares, so it was taken with none. Paths are returned as recorded; whether\n * they still exist is the launch plan's to check.\n */\nexport async function readShareManifest(snapshotDir: string): Promise<DeskShare[]> {\n let text: string\n try {\n text = await readFile(join(snapshotDir, SHARE_MANIFEST), 'utf8')\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return []\n throw error\n }\n let value: unknown\n try {\n value = JSON.parse(text)\n } catch {\n throw new DeskError(`${join(snapshotDir, SHARE_MANIFEST)} is not valid JSON.`)\n }\n const valid = Array.isArray(value) && value.every((entry: unknown) =>\n typeof entry === 'object' && entry !== null\n && typeof (entry as DeskShare).tag === 'string'\n && typeof (entry as DeskShare).path === 'string'\n && typeof (entry as DeskShare).readOnly === 'boolean')\n if (!valid) throw new DeskError(`${join(snapshotDir, SHARE_MANIFEST)} is not a list of shares.`)\n return (value as DeskShare[]).map(({ tag, path, readOnly }) => ({ tag, path, readOnly }))\n}\n\n/** Throws unless the snapshot was parked with exactly `shares`, in order. */\nexport async function assertShareManifest(snapshotDir: string, shares: readonly DeskShare[]): Promise<void> {\n const saved = shareManifest(await readShareManifest(snapshotDir))\n const wanted = shareManifest(shares)\n if (saved !== wanted) throw new DeskError(`the snapshot was taken with shares ${saved}, not ${wanted}`)\n}\n\nfunction shareManifest(shares: readonly DeskShare[]): string {\n return JSON.stringify(shares.map(({ tag, path, readOnly }) => ({ tag, path, readOnly })))\n}\n\nexport function defaultLauncher(\n command: string,\n args: readonly string[],\n options: { identity?: DeskLauncherIdentity },\n): ChildProcess {\n return spawn(command, [...args], {\n stdio: ['ignore', 'pipe', 'pipe'],\n uid: options.identity?.uid,\n gid: options.identity?.gid,\n })\n}\n\nexport function defaultConnect(socketPath: string): Duplex {\n return createConnection(socketPath)\n}\n\nexport function delay(ms: number): Promise<void> {\n return new Promise<void>((resolvePromise) => {\n const timer = setTimeout(resolvePromise, ms)\n timer.unref()\n })\n}\n\nexport function errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n"]}