wishforge-ide/apps/ide/provisioner/workspace-lifecycle.mjs
eust-w 0ef99b1e6d style: add Prettier and EditorConfig, format the codebase
Adds prettier 3.9.8 (exact) with a shared config (single quotes,
120 columns, trailing commas), .prettierignore, .editorconfig and the
`format` / `format:check` scripts, then formats all TypeScript,
JavaScript, CSS, JSON and YAML sources.

Purely mechanical: no behaviour change. Typecheck passes, the vitest
suite and the 74 IDE node tests produce the same results as before
(socket-binding tests still cannot run inside this sandbox).
Previously the longest source line was ~3000 characters; reviewing the
following semantic changes now produces readable diffs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-19 13:32:43 +08:00

133 lines
5.4 KiB
JavaScript

import { createHash } from 'node:crypto';
import { spawn } from 'node:child_process';
const id = /^[a-zA-Z0-9_-]{1,128}$/;
const revisionKey = 'wishforge.io/lifecycle-revision';
const desiredKey = 'wishforge.io/lifecycle-desired';
function scope(config, input) {
if (
!input ||
input.tenantId !== config.tenantId ||
!id.test(input.projectId ?? '') ||
!id.test(input.workspaceId ?? '')
)
throw new Error('INVALID_WORKSPACE_SCOPE');
return `wf-ide-${createHash('sha256').update(`${input.tenantId}/${input.workspaceId}`).digest('hex').slice(0, 24)}`;
}
function assertOwned(config, name, value) {
if (
value?.metadata?.name !== name ||
value.metadata.namespace !== config.namespace ||
value.metadata.labels?.['app.kubernetes.io/managed-by'] !== 'wishforge-provisioner' ||
value.metadata.labels?.['wishforge.io/component'] !== 'ide' ||
value.metadata.labels?.['wishforge.io/workspace'] !== name
)
throw new Error('WORKSPACE_OWNERSHIP_MISMATCH');
}
export function kubectlJson(config, args) {
return new Promise((resolve, reject) => {
const child = spawn('kubectl', ['--context', config.context, '--namespace', config.namespace, ...args], {
stdio: ['ignore', 'pipe', 'pipe'],
});
let output = '';
let settled = false;
const fail = () => {
if (!settled) {
settled = true;
reject(new Error('KUBERNETES_LIFECYCLE_UNKNOWN'));
}
};
const timeout = setTimeout(() => {
child.kill('SIGTERM');
fail();
}, 10000);
child.stdout.on('data', part => {
output += part;
if (output.length > 2 * 1024 * 1024) {
child.kill('SIGTERM');
fail();
}
});
child.stderr.resume();
child.on('error', fail);
child.on('close', code => {
clearTimeout(timeout);
if (settled) return;
try {
if (code !== 0) throw Error();
const value = JSON.parse(output);
settled = true;
resolve(value);
} catch {
fail();
}
});
});
}
export async function observeWorkspaceLifecycle(config, input, options = {}) {
const name = scope(config, input);
const execute = options.execute ?? kubectlJson;
const deployment = await execute(config, ['get', 'deployment', name, '-o', 'json']);
assertOwned(config, name, deployment);
const revision = Number(deployment.metadata.annotations?.[revisionKey] ?? 0);
const desired = deployment.metadata.annotations?.[desiredKey] ?? 'running';
if (!Number.isSafeInteger(revision) || revision < 0 || !['running', 'paused'].includes(desired))
throw new Error('INVALID_WORKSPACE_LIFECYCLE_STATE');
let status = 'pending';
const observed = deployment.status?.observedGeneration >= deployment.metadata.generation;
if (
desired === 'running' &&
deployment.spec?.replicas === 1 &&
observed &&
deployment.status.availableReplicas === 1 &&
deployment.status.updatedReplicas === 1
)
status = 'ready';
if (desired === 'paused' && deployment.spec?.replicas === 0 && observed && (deployment.status.replicas ?? 0) === 0) {
const selector = `wishforge.io/workspace=${name},wishforge.io/component=ide,app.kubernetes.io/managed-by=wishforge-provisioner`;
const pods = await execute(config, ['get', 'pods', '--selector', selector, '-o', 'json']);
if (!Array.isArray(pods.items)) throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');
if (pods.items.every(p => ['Succeeded', 'Failed'].includes(p.status?.phase))) status = 'paused';
}
return {
workspaceId: input.workspaceId,
revision,
desired,
status,
deploymentUid: deployment.metadata.uid,
resourceVersion: deployment.metadata.resourceVersion,
};
}
export async function reconcileWorkspaceLifecycle(config, input, options = {}) {
if (
!['running', 'paused'].includes(input?.desired) ||
!Number.isSafeInteger(input.revision) ||
input.revision < 1 ||
Object.keys(input).some(k => !['tenantId', 'projectId', 'workspaceId', 'revision', 'desired'].includes(k))
)
throw new Error('INVALID_WORKSPACE_LIFECYCLE_REQUEST');
const execute = options.execute ?? kubectlJson;
const name = scope(config, input);
const deployment = await execute(config, ['get', 'deployment', name, '-o', 'json']);
assertOwned(config, name, deployment);
const previous = Number(deployment.metadata.annotations?.[revisionKey] ?? 0);
if (!Number.isSafeInteger(previous) || previous > input.revision) throw new Error('STALE_WORKSPACE_REVISION');
if (previous === input.revision) {
if (deployment.metadata.annotations?.[desiredKey] !== input.desired) throw new Error('WORKSPACE_REVISION_CONFLICT');
return observeWorkspaceLifecycle(config, input, { execute });
}
if (!deployment.metadata.resourceVersion || !deployment.metadata.uid) throw new Error('KUBERNETES_LIFECYCLE_UNKNOWN');
const annotations = {
...deployment.metadata.annotations,
[revisionKey]: String(input.revision),
[desiredKey]: input.desired,
};
const patch = [
{ op: 'test', path: '/metadata/resourceVersion', value: deployment.metadata.resourceVersion },
{ op: 'test', path: '/metadata/uid', value: deployment.metadata.uid },
{ op: 'add', path: '/metadata/annotations', value: annotations },
{ op: 'replace', path: '/spec/replicas', value: input.desired === 'paused' ? 0 : 1 },
];
await execute(config, ['patch', 'deployment', name, '--type=json', '-p', JSON.stringify(patch), '-o', 'json']);
return observeWorkspaceLifecycle(config, input, { execute });
}