Detect actual service and Runner readiness, restore LAN access after network changes, protect production web builds with rollback, honor cancellation during executor startup, and show truthful cached-data and credential states.
114 lines
4.1 KiB
JavaScript
114 lines
4.1 KiB
JavaScript
import { spawnSync } from 'node:child_process';
|
|
import { createConnection } from 'node:net';
|
|
import { mkdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
import { randomUUID } from 'node:crypto';
|
|
import path from 'node:path';
|
|
|
|
export function portOccupied(host, port, timeoutMs = 1000) {
|
|
return new Promise((resolve, reject) => {
|
|
const socket = createConnection({ host, port });
|
|
const finish = (error, occupied) => {
|
|
socket.destroy();
|
|
error ? reject(error) : resolve(occupied);
|
|
};
|
|
socket.once('connect', () => finish(undefined, true));
|
|
socket.once('error', error =>
|
|
['ECONNREFUSED', 'EHOSTUNREACH', 'ENETUNREACH', 'EAFNOSUPPORT'].includes(error.code)
|
|
? finish(undefined, false)
|
|
: finish(new Error('Cannot establish whether the local web listener is stopped')),
|
|
);
|
|
socket.setTimeout(timeoutMs, () => finish(new Error('Timed out checking the local web listener; build refused')));
|
|
});
|
|
}
|
|
|
|
export async function assertWebOffline(port, host = '0.0.0.0') {
|
|
if (!Number.isInteger(port) || port < 1 || port > 65535) throw new Error('Invalid local web port');
|
|
if (process.platform === 'darwin') {
|
|
const registered = spawnSync(
|
|
'/bin/launchctl',
|
|
['print', `gui/${process.getuid()}/cc.d-robotics.wishforge.local-poc`],
|
|
{ encoding: 'utf8', timeout: 3000 },
|
|
);
|
|
if (registered.error) throw new Error('Cannot determine LaunchAgent state; build refused');
|
|
if (registered.status === 0)
|
|
throw new Error('Stop the local POC LaunchAgent before rebuilding the web application');
|
|
}
|
|
const addresses = [
|
|
...new Set(['127.0.0.1', '::1', ...(!['0.0.0.0', '::', 'localhost'].includes(host) ? [host] : [])]),
|
|
];
|
|
if ((await Promise.all(addresses.map(address => portOccupied(address, port)))).some(Boolean))
|
|
throw new Error(`Port ${port} is still in use; stop the web process before rebuilding`);
|
|
}
|
|
|
|
export async function buildWithRollback(
|
|
root,
|
|
build,
|
|
{ port = 3000, host = '0.0.0.0', offline = assertWebOffline } = {},
|
|
) {
|
|
await offline(port, host);
|
|
const state = path.join(root, '.wishforge/local-poc');
|
|
await mkdir(state, { recursive: true, mode: 0o700 });
|
|
const lock = path.join(state, 'web-build.lock');
|
|
try {
|
|
await mkdir(lock, { mode: 0o700 });
|
|
} catch (error) {
|
|
if (error.code === 'EEXIST') throw new Error('Another protected web build is in progress');
|
|
throw error;
|
|
}
|
|
const current = path.join(root, 'apps/web/.next');
|
|
const archive = path.join(state, 'web-builds');
|
|
const id = randomUUID();
|
|
const previous = path.join(archive, `previous-${id}`);
|
|
const failed = path.join(archive, `failed-${id}`);
|
|
let saved = false,
|
|
started = false;
|
|
try {
|
|
await writeFile(
|
|
path.join(lock, 'owner.json'),
|
|
JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }),
|
|
{ mode: 0o600 },
|
|
);
|
|
await offline(port, host);
|
|
await mkdir(archive, { recursive: true, mode: 0o700 });
|
|
if (
|
|
await stat(current).then(
|
|
() => true,
|
|
error => {
|
|
if (error.code === 'ENOENT') return false;
|
|
throw error;
|
|
},
|
|
)
|
|
) {
|
|
await rename(current, previous);
|
|
saved = true;
|
|
}
|
|
started = true;
|
|
await build();
|
|
const buildId = (await readFile(path.join(current, 'BUILD_ID'), 'utf8')).trim();
|
|
if (!buildId || !(await stat(path.join(current, 'server'))).isDirectory())
|
|
throw new Error('Next did not produce a complete production web build');
|
|
const receipt = {
|
|
buildId: buildId.slice(0, 200),
|
|
completedAt: new Date().toISOString(),
|
|
previousBuild: saved ? previous : null,
|
|
currentBuild: current,
|
|
};
|
|
await writeFile(path.join(state, 'last-web-build.json'), `${JSON.stringify(receipt, null, 2)}\n`, { mode: 0o600 });
|
|
return receipt;
|
|
} catch (error) {
|
|
if (started) {
|
|
if (
|
|
await stat(current).then(
|
|
() => true,
|
|
() => false,
|
|
)
|
|
)
|
|
await rename(current, failed);
|
|
if (saved) await rename(previous, current);
|
|
}
|
|
throw error;
|
|
} finally {
|
|
await rm(lock, { recursive: true, force: true });
|
|
}
|
|
}
|