@commonlyai/cli 0.1.395 → 0.1.396
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/package.json
CHANGED
|
@@ -137,7 +137,13 @@ export const startMcpBridge = async ({
|
|
|
137
137
|
return;
|
|
138
138
|
}
|
|
139
139
|
children.add(child);
|
|
140
|
-
|
|
140
|
+
// A spawn that fails (a missing command) emits 'error' with no pid and
|
|
141
|
+
// never 'exit', so it frees its session slot here. A running child that
|
|
142
|
+
// errors keeps its slot until it exits.
|
|
143
|
+
child.on('error', () => {
|
|
144
|
+
if (child.pid === undefined) children.delete(child);
|
|
145
|
+
socket.destroy();
|
|
146
|
+
});
|
|
141
147
|
child.on('exit', () => { children.delete(child); socket.end(); });
|
|
142
148
|
child.stdin.on('error', () => {});
|
|
143
149
|
if (rest.length) child.stdin.write(rest);
|
|
@@ -31,7 +31,7 @@ import { createHash, randomBytes } from 'crypto';
|
|
|
31
31
|
import { spawnSync } from 'child_process';
|
|
32
32
|
import { existsSync, readFileSync, writeFileSync } from 'fs';
|
|
33
33
|
import {
|
|
34
|
-
chmod, mkdir, mkdtemp, readdir, rename, rm, stat, writeFile,
|
|
34
|
+
chmod, mkdir, mkdtemp, readFile, readdir, rename, rm, stat, writeFile,
|
|
35
35
|
} from 'fs/promises';
|
|
36
36
|
import { homedir, tmpdir } from 'os';
|
|
37
37
|
import { join } from 'path';
|
|
@@ -201,11 +201,14 @@ const defaultExtract = (archive, dir, env = process.env) => spawnSync(
|
|
|
201
201
|
* first time. A hash mismatch, a failed download or an archive without msb.exe
|
|
202
202
|
* refuses and leaves nothing runnable behind.
|
|
203
203
|
*/
|
|
204
|
+
export const MSB_DOWNLOAD_TIMEOUT_MS = 5 * 60 * 1000;
|
|
205
|
+
|
|
204
206
|
export const ensureMsb = async ({
|
|
205
207
|
root = microsandboxRoot(),
|
|
206
208
|
asset = msbAsset(),
|
|
207
209
|
fetchImpl = globalThis.fetch,
|
|
208
210
|
extract = defaultExtract,
|
|
211
|
+
timeoutMs = MSB_DOWNLOAD_TIMEOUT_MS,
|
|
209
212
|
} = {}) => {
|
|
210
213
|
const binary = join(root, 'msb.exe');
|
|
211
214
|
const marker = join(root, '.verified');
|
|
@@ -221,9 +224,19 @@ export const ensureMsb = async ({
|
|
|
221
224
|
const archive = join(root, `.download-${tag}.zip`);
|
|
222
225
|
const staging = join(root, `.staging-${tag}`);
|
|
223
226
|
try {
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
+
// One deadline for the request and the body, so a stalled connection
|
|
228
|
+
// can't hold the install lock indefinitely.
|
|
229
|
+
let bytes;
|
|
230
|
+
try {
|
|
231
|
+
const response = await fetchImpl(msbReleaseUrl(asset), { redirect: 'follow', signal: AbortSignal.timeout(timeoutMs) });
|
|
232
|
+
if (!response?.ok) throw new Error(`downloading microsandbox ${MSB_PIN.version} failed (HTTP ${response?.status})`);
|
|
233
|
+
bytes = Buffer.from(await response.arrayBuffer());
|
|
234
|
+
} catch (error) {
|
|
235
|
+
if (error?.name === 'TimeoutError' || error?.name === 'AbortError') {
|
|
236
|
+
throw new Error(`downloading microsandbox ${MSB_PIN.version} took longer than ${Math.round(timeoutMs / 1000)} s; try again`);
|
|
237
|
+
}
|
|
238
|
+
throw error;
|
|
239
|
+
}
|
|
227
240
|
const actual = sha256(bytes);
|
|
228
241
|
if (actual !== asset.sha256) {
|
|
229
242
|
throw new Error(`microsandbox ${asset.name} has SHA-256 ${actual}, not the pinned ${asset.sha256}; refusing to run it`);
|
|
@@ -430,29 +443,111 @@ export const startMicrovmTurn = async ({
|
|
|
430
443
|
};
|
|
431
444
|
|
|
432
445
|
const INSTALL_LOCK_STALE_MS = 15 * 60 * 1000;
|
|
446
|
+
// Longer than the slowest install can run (a 5-minute download, the volume
|
|
447
|
+
// probe and a 10-minute npm install), so a lock older than this was leaked by
|
|
448
|
+
// its holder, or names a pid since reused, and is taken over even though that
|
|
449
|
+
// pid is alive.
|
|
450
|
+
const INSTALL_LOCK_MAX_MS = 60 * 60 * 1000;
|
|
451
|
+
|
|
452
|
+
const defaultPidAlive = (pid) => {
|
|
453
|
+
try {
|
|
454
|
+
process.kill(pid, 0);
|
|
455
|
+
return true;
|
|
456
|
+
} catch (error) {
|
|
457
|
+
// EPERM: the process exists, owned by someone else.
|
|
458
|
+
return error?.code === 'EPERM';
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
|
|
462
|
+
/**
|
|
463
|
+
* Whether a lock whose file reads `content` can be taken over. The lock lives
|
|
464
|
+
* in this user's %LOCALAPPDATA%, so its holder ran on this machine: it is
|
|
465
|
+
* abandoned once that process is gone, and a slow install is not cut in on
|
|
466
|
+
* while it runs. Past INSTALL_LOCK_MAX_MS it is abandoned whatever the pid, so
|
|
467
|
+
* a lock a live process leaked, or one naming a reused pid, can't wedge every
|
|
468
|
+
* later install. A lock that names no process falls back to the shorter age.
|
|
469
|
+
*/
|
|
470
|
+
const lockAbandoned = (content, mtimeMs, { now, pidAlive }) => {
|
|
471
|
+
const age = now() - mtimeMs;
|
|
472
|
+
const pid = Number.parseInt(String(content).split(/\s+/)[0], 10);
|
|
473
|
+
if (Number.isInteger(pid) && pid > 0) return age > INSTALL_LOCK_MAX_MS || !pidAlive(pid);
|
|
474
|
+
return age > INSTALL_LOCK_STALE_MS;
|
|
475
|
+
};
|
|
476
|
+
|
|
477
|
+
// The guard is held only for a read and an unlink, so one older than this was
|
|
478
|
+
// left by a process that died inside that window.
|
|
479
|
+
const INSTALL_LOCK_GUARD_STALE_MS = 30 * 1000;
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* Runs `fn` holding `guard`, a short-lived lock that serialises every removal
|
|
483
|
+
* of the install lock (a takeover or a release), so no removal can act on a
|
|
484
|
+
* lock that changed after it was read.
|
|
485
|
+
*/
|
|
486
|
+
const withLockGuard = async (guard, fn, { now }) => {
|
|
487
|
+
for (;;) {
|
|
488
|
+
try {
|
|
489
|
+
// eslint-disable-next-line no-await-in-loop
|
|
490
|
+
await writeFile(guard, `${process.pid}\n`, { flag: 'wx' });
|
|
491
|
+
break;
|
|
492
|
+
} catch (error) {
|
|
493
|
+
if (error?.code !== 'EEXIST') throw error;
|
|
494
|
+
// eslint-disable-next-line no-await-in-loop
|
|
495
|
+
const held = await stat(guard).catch(() => null);
|
|
496
|
+
if (held && now() - held.mtimeMs > INSTALL_LOCK_GUARD_STALE_MS) {
|
|
497
|
+
// eslint-disable-next-line no-await-in-loop
|
|
498
|
+
await rm(guard, { force: true });
|
|
499
|
+
} else {
|
|
500
|
+
// eslint-disable-next-line no-await-in-loop
|
|
501
|
+
await new Promise((resolve) => { setTimeout(resolve, 20); });
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
try {
|
|
506
|
+
return await fn();
|
|
507
|
+
} finally {
|
|
508
|
+
await rm(guard, { force: true }).catch(() => {});
|
|
509
|
+
}
|
|
510
|
+
};
|
|
433
511
|
|
|
434
512
|
/**
|
|
435
513
|
* Runs `fn` holding this version's install lock, so two first turns never
|
|
436
514
|
* unpack msb or install into the volume (mounted writable then) at once.
|
|
515
|
+
*
|
|
516
|
+
* The lock names its holder (`<pid> <token>`, the token unique to each take).
|
|
517
|
+
* Only an exclusive create takes it. A waiter takes over a lock whose process
|
|
518
|
+
* has exited, or one past INSTALL_LOCK_MAX_MS, by deleting it and trying the
|
|
519
|
+
* create again. Every deletion, a takeover or the holder's release, runs under
|
|
520
|
+
* a guard lock and re-reads the lock first, deleting only the exact lock it
|
|
521
|
+
* judged (same token). So a takeover can never delete a lock another waiter
|
|
522
|
+
* took after the judgement, and the lock's path is never free while a live
|
|
523
|
+
* holder's lock is displaced. The holder also removes a lock it can't read at
|
|
524
|
+
* all, so an unreadable lock is never left behind.
|
|
437
525
|
*/
|
|
438
526
|
export const withInstallLock = async (root, fn, {
|
|
439
|
-
waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now,
|
|
527
|
+
waitMs = INSTALL_LOCK_STALE_MS, pollMs = 500, now = Date.now, pidAlive = defaultPidAlive,
|
|
440
528
|
} = {}) => {
|
|
441
529
|
await mkdir(root, { recursive: true });
|
|
442
530
|
const lock = join(root, '.install.lock');
|
|
531
|
+
const guard = join(root, '.install.lock.guard');
|
|
532
|
+
const mine = `${process.pid} ${randomBytes(8).toString('hex')}\n`;
|
|
443
533
|
const deadline = now() + waitMs;
|
|
444
534
|
for (;;) {
|
|
445
535
|
try {
|
|
446
536
|
// eslint-disable-next-line no-await-in-loop
|
|
447
|
-
await writeFile(lock,
|
|
537
|
+
await writeFile(lock, mine, { flag: 'wx' });
|
|
448
538
|
break;
|
|
449
539
|
} catch (error) {
|
|
450
540
|
if (error?.code !== 'EEXIST') throw error;
|
|
451
541
|
// eslint-disable-next-line no-await-in-loop
|
|
452
542
|
const held = await stat(lock).catch(() => null);
|
|
453
|
-
|
|
543
|
+
// eslint-disable-next-line no-await-in-loop
|
|
544
|
+
const judged = held ? await readFile(lock, 'utf8').catch(() => null) : null;
|
|
545
|
+
if (held && judged !== null && lockAbandoned(judged, held.mtimeMs, { now, pidAlive })) {
|
|
454
546
|
// eslint-disable-next-line no-await-in-loop
|
|
455
|
-
await
|
|
547
|
+
await withLockGuard(guard, async () => {
|
|
548
|
+
const current = await readFile(lock, 'utf8').catch(() => null);
|
|
549
|
+
if (current === judged) await rm(lock, { force: true });
|
|
550
|
+
}, { now });
|
|
456
551
|
} else if (now() > deadline) {
|
|
457
552
|
throw new Error(`another turn is still installing the microVM sandbox (${lock}); try again shortly`);
|
|
458
553
|
} else {
|
|
@@ -464,7 +559,12 @@ export const withInstallLock = async (root, fn, {
|
|
|
464
559
|
try {
|
|
465
560
|
return await fn();
|
|
466
561
|
} finally {
|
|
467
|
-
await
|
|
562
|
+
await withLockGuard(guard, async () => {
|
|
563
|
+
const current = await readFile(lock, 'utf8').then((text) => text, (error) => error);
|
|
564
|
+
// Not `instanceof Error`: fs errors can come from another realm (a test VM).
|
|
565
|
+
const unreadable = typeof current !== 'string' && current?.code !== 'ENOENT';
|
|
566
|
+
if (current === mine || unreadable) await rm(lock, { recursive: true, force: true });
|
|
567
|
+
}, { now }).catch(() => {});
|
|
468
568
|
}
|
|
469
569
|
};
|
|
470
570
|
|