134 lines
9.5 KiB
JavaScript
134 lines
9.5 KiB
JavaScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
|
|
function localUrl(value) {
|
|
const url = new URL(value);
|
|
if (url.protocol !== 'http:' || url.hostname !== '127.0.0.1' || url.username || url.password || url.search || url.hash) throw new Error('Upgrade only accepts the local Workbench address.');
|
|
return url.origin;
|
|
}
|
|
|
|
async function within(promise, milliseconds, label) {
|
|
let timer;
|
|
try { return await Promise.race([promise, new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(label + ' timed out.')), milliseconds); })]); }
|
|
finally { clearTimeout(timer); }
|
|
}
|
|
|
|
class Protocol {
|
|
constructor(socket) {
|
|
this.socket = socket; this.nextId = 1; this.pending = new Map(); this.listeners = new Map();
|
|
socket.addEventListener('message', event => {
|
|
const message = JSON.parse(String(event.data));
|
|
if (message.id) {
|
|
const pending = this.pending.get(message.id); if (!pending) return;
|
|
this.pending.delete(message.id);
|
|
if (message.error) pending.reject(new Error(message.error.message)); else pending.resolve(message.result);
|
|
} else for (const listener of this.listeners.get(message.method) ?? []) listener(message.params);
|
|
});
|
|
socket.addEventListener('close', () => { for (const pending of this.pending.values()) pending.reject(new Error('Inspector connection closed.')); this.pending.clear(); });
|
|
}
|
|
on(method, listener) { this.listeners.set(method, [...(this.listeners.get(method) ?? []), listener]); }
|
|
send(method, params = {}) {
|
|
return within(new Promise((resolve, reject) => {
|
|
const id = this.nextId++; this.pending.set(id, { resolve, reject }); this.socket.send(JSON.stringify({ id, method, params }));
|
|
}), 10000, method);
|
|
}
|
|
}
|
|
|
|
function sameFile(url, file) {
|
|
try { return path.resolve(fileURLToPath(url)).toLowerCase() === path.resolve(file).toLowerCase(); } catch { return false; }
|
|
}
|
|
function sameTarget(target, file) {
|
|
if (sameFile(target.url, file)) return true;
|
|
const displayName = path.resolve(file).replaceAll('\\', '_').replaceAll('/', '_');
|
|
return target.title === displayName && target.url === 'file://' + displayName;
|
|
}
|
|
|
|
export async function upgradeRunning({ url, pid, currentRoot, newRoot, handlerRoot }) {
|
|
const origin = localUrl(url), original = fs.realpathSync.native(currentRoot), next = fs.realpathSync.native(newRoot);
|
|
const originalScript = path.join(original, 'dist-server', 'server.mjs');
|
|
const upgradeScript = path.join(next, 'dist-server', 'hot-upgrade.mjs');
|
|
if (!fs.existsSync(originalScript) || !fs.existsSync(upgradeScript) || !fs.existsSync(path.join(next, 'dist-client', 'index.html'))) throw new Error('Upgrade bundles are incomplete.');
|
|
if (!Number.isInteger(pid) || pid < 1 || pid === process.pid) throw new Error('Invalid target process.');
|
|
const before = await (await fetch(origin + '/api/bootstrap', { signal: AbortSignal.timeout(5000) })).json();
|
|
if (!before.token || !['0.1.0', '1.0.0', '1.1.0'].includes(before.version)) throw new Error('This migration accepts a supported existing Workbench.');
|
|
if (before.sessions.some(session => ['running', 'awaiting_approval', 'stopping'].includes(session.status))) throw new Error('Wait for existing tasks and approvals before upgrading.');
|
|
let protocol, socket, enabledHere = false, paused = false;
|
|
const breakpoints = [];
|
|
try {
|
|
let targets;
|
|
try { targets = await (await fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) })).json(); } catch {}
|
|
if (targets && !targets.some(target => sameTarget(target, originalScript))) throw new Error('The local inspector port belongs to another process.');
|
|
if (!targets) {
|
|
process._debugProcess(pid); enabledHere = true;
|
|
for (let attempt = 0; attempt < 40 && !targets; attempt++) {
|
|
await delay(100);
|
|
try { targets = await (await fetch('http://127.0.0.1:9229/json/list', { signal: AbortSignal.timeout(500) })).json(); } catch {}
|
|
}
|
|
}
|
|
const target = targets?.find(item => sameTarget(item, originalScript));
|
|
if (!target || !target.webSocketDebuggerUrl?.startsWith('ws://127.0.0.1:9229/')) throw new Error('The expected Workbench inspector was not found.');
|
|
socket = new WebSocket(target.webSocketDebuggerUrl);
|
|
await within(new Promise((resolve, reject) => { socket.addEventListener('open', resolve, { once: true }); socket.addEventListener('error', reject, { once: true }); }), 10000, 'Inspector connection');
|
|
protocol = new Protocol(socket);
|
|
const scripts = [];
|
|
protocol.on('Debugger.scriptParsed', script => scripts.push(script));
|
|
let pausedResolve;
|
|
const pausedEvent = new Promise(resolve => { pausedResolve = resolve; });
|
|
protocol.on('Debugger.paused', event => { paused = true; pausedResolve(event); });
|
|
await protocol.send('Runtime.enable');
|
|
const identity = await protocol.send('Runtime.evaluate', { expression: 'process.pid', returnByValue: true });
|
|
if (identity.result.value !== pid) throw new Error('The inspector belongs to a different process.');
|
|
await protocol.send('Debugger.enable');
|
|
const previousRoot = handlerRoot || before.runtimeRoot;
|
|
const expectedScripts = [originalScript, ...(previousRoot ? [path.join(fs.realpathSync.native(previousRoot), 'dist-server', 'hot-upgrade.mjs')] : [])];
|
|
const candidates = scripts.filter(item => expectedScripts.some(file => sameFile(item.url, file)));
|
|
if (!candidates.length) throw new Error('The existing server module is missing from inspector metadata.');
|
|
for (const script of candidates) {
|
|
const { scriptSource } = await protocol.send('Debugger.getScriptSource', { scriptId: script.scriptId });
|
|
const locations = scriptSource.split('\n').flatMap((line, index) => line.includes('const url = new URL(request.url') ? [index] : []);
|
|
if (locations.length !== 1) throw new Error('The existing request handler could not be identified uniquely.');
|
|
breakpoints.push((await protocol.send('Debugger.setBreakpoint', { location: { scriptId: script.scriptId, lineNumber: locations[0] } })).breakpointId);
|
|
}
|
|
const probe = fetch(origin + '/api/health', { signal: AbortSignal.timeout(15000) });
|
|
probe.catch(() => {});
|
|
const event = await within(pausedEvent, 10000, 'Workbench request observation');
|
|
const captured = await protocol.send('Debugger.evaluateOnCallFrame', { callFrameId: event.callFrames[0].callFrameId,
|
|
expression: "globalThis.__awUpgradeContext = { server, store, provider, runtime, token, clients, started, exampleProject, shutdown }; 'context-ready'", returnByValue: true });
|
|
if (captured.exceptionDetails || captured.result.value !== 'context-ready') throw new Error('Could not retain the existing runtime objects.');
|
|
for (const breakpointId of breakpoints.splice(0)) await protocol.send('Debugger.removeBreakpoint', { breakpointId });
|
|
await protocol.send('Debugger.resume'); paused = false; await probe;
|
|
const expression = '(() => { try { const module = process.getBuiltinModule("module").createRequire(' + JSON.stringify(upgradeScript) + ')(' + JSON.stringify(upgradeScript) + '); return module.installUpgrade(globalThis.__awUpgradeContext, { appDirectory: ' + JSON.stringify(next) + ' }); } finally { delete globalThis.__awUpgradeContext; } })()';
|
|
const upgraded = await protocol.send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true });
|
|
if (upgraded.exceptionDetails) throw new Error('Runtime upgrade failed: ' + (upgraded.exceptionDetails.exception?.description ?? upgraded.exceptionDetails.text));
|
|
const result = upgraded.result.value;
|
|
const after = await (await fetch(origin + '/api/bootstrap', { signal: AbortSignal.timeout(5000) })).json();
|
|
const health = await (await fetch(origin + '/api/health', { signal: AbortSignal.timeout(5000) })).json();
|
|
if (health.pid !== pid || result.pid !== pid || after.version !== result.version || after.config.hasKey !== before.config.hasKey
|
|
|| after.config.model !== before.config.model || after.config.baseUrl !== before.config.baseUrl
|
|
|| JSON.stringify(after.projects) !== JSON.stringify(before.projects)
|
|
|| JSON.stringify(after.sessions) !== JSON.stringify(before.sessions)) throw new Error('The upgraded runtime did not preserve the existing state.');
|
|
return { ...result, verified: true, connectionPreserved: true, url: origin };
|
|
} finally {
|
|
if (protocol) {
|
|
for (const breakpointId of breakpoints) { try { await protocol.send('Debugger.removeBreakpoint', { breakpointId }); } catch {} }
|
|
try { if (paused) await protocol.send('Debugger.resume'); } catch {}
|
|
try { await protocol.send('Runtime.evaluate', { expression: 'delete globalThis.__awUpgradeContext; true', returnByValue: true }); } catch {}
|
|
if (enabledHere) {
|
|
try { await protocol.send('Runtime.evaluate', { expression: "setTimeout(() => process.getBuiltinModule('inspector').close(), 25); true", returnByValue: true }); } catch {}
|
|
}
|
|
}
|
|
socket?.close();
|
|
if (enabledHere) await delay(150);
|
|
}
|
|
}
|
|
|
|
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
const args = Object.fromEntries(process.argv.slice(2).reduce((items, value, index, all) => {
|
|
if (value.startsWith('--')) items.push([value.slice(2), all[index + 1]]); return items;
|
|
}, []));
|
|
const result = await upgradeRunning({ url: args.url || 'http://127.0.0.1:4318', pid: Number(args.pid), currentRoot: args['current-root'], newRoot: args['new-root'], handlerRoot: args['handler-root'] });
|
|
console.log(JSON.stringify(result, null, 2));
|
|
}
|