Files
sim/scripts/setup/modes/k8s.ts
T
Theodore Li 1a4bfe4c59 fix(setup,compose): bundle Redis, fix socket reconnect, and harden the setup wizard (#5964)
* feat(compose,setup): bundle Redis, always configure it, fix lifecycle detection

Compose shipped no redis service at all — REDIS_URL was ${REDIS_URL:-} in both app and realtime, so every self-hosted stack ran without it. Storage silently falls back to PostgreSQL, but the pub/sub channels (live Chat task-status, table events) have no fallback, so live updates never arrived.

- compose (prod + local): add a redis:7-alpine service with a healthcheck, default REDIS_URL to redis://redis:6379, and make app/realtime depend on it being healthy. Not published to the host — only the containers need it, and binding 6379 would collide with a local Redis. An external REDIS_URL in root .env still overrides. Deliberately not written into root .env: doctor pings REDIS_URL from the host, and a compose-internal hostname would fail that probe the same way DATABASE_URL would.
- dev mode: configure Redis in quick too. Quick uses a new non-interactive ensureRedis (adopt whatever answers, else start the managed container, warn only if Docker is unavailable); custom keeps the ladder, with corrected copy — the old prompt claimed Redis was only for multi-replica.
- lifecycle: detect compose stacks via 'docker compose ls' instead of probing '-f <file> ps' in the working directory. Compose derives the project name from the directory it was started in, so the old probe found a stack only when run from the checkout that launched it (a globally linked sim never could) and listed the same stack once per candidate file. compose ls reports the real project and its config file, so one stack yields one install from anywhere; non-Sim projects are filtered by compose filename. Every compose op now runs in that stack's directory.
- lifecycle: distinguish 'Docker unreachable' from 'nothing installed'. With the daemon down, status reported containers as 'absent' and suggested re-running setup; it now says Docker is down and marks state unknown.

* fix(setup): don't start managed Postgres with a password the volume will ignore

POSTGRES_PASSWORD only applies when initdb runs on an empty data directory. The sim-postgres-data volume outlives its container (sim down keeps it, docker rm keeps it, and the wizard's own recreate path keeps it), and inspectManagedContainer recovers the password from the *container*, not the volume — so once the container is gone the password is unrecoverable.

Setup then generated a fresh password and ran against the initialized volume. Postgres kept its original password and rejected every connection with 'password authentication failed for user postgres', which surfaced as a misleading 'container did not become healthy'.

Detect an already-bootstrapped volume (PG_VERSION present) before choosing a password, and ask: supply the existing password, or delete the volume and start fresh (double-confirmed, since that destroys data). Refusing both fails with the exact docker volume rm command instead of looping.

* improvement(setup): default to Docker Compose and sharpen the run-mode copy

Compose was listed first but only preselected when Docker happened to be running — with Docker stopped the cursor sat on 'Local dev', steering people toward a source checkout when they wanted to run Sim. Compose mode calls ensureDocker(true), which offers to start Docker Desktop, so a stopped daemon is no reason to change the default.

Also tightens the hints to say what each mode is for: run bundled Sim (fastest way to start), work on Sim itself, test a production-style k8s deploy.

* fix(compose): point the browser socket at :3002 so it stops reconnecting

The stack publishes the app on 3000 and realtime on 3002 with no reverse proxy between them, but NEXT_PUBLIC_SOCKET_URL defaulted to empty — which tells the browser client to use the page origin. :3000/socket.io answers 308 (a Next redirect), not a Socket.IO handshake, so the client failed and retried forever. Default it to http://localhost:3002; a proxied deployment overrides it (or sets it empty to use the page origin).

Also give COPILOT_API_KEY and SIM_AGENT_API_URL empty defaults so every compose command stops printing 'variable is not set' warnings. The app already falls back to the prod copilot backend when SIM_AGENT_API_URL is blank.

* feat(setup): pass SIM_AGENT_API_URL through, and warn on a half-set mothership

Sim devs testing against a non-prod mothership export SIM_CLI_AUTH_ORIGIN so the Chat key is minted there, but nothing carried the matching backend URL into the install — the app kept defaulting to prod copilot, which rejects a staging key with 'Invalid API key'.

Persist SIM_AGENT_API_URL when it is exported, so later docker compose up / dev runs stay on that backend instead of reverting to prod once the shell is gone:

  SIM_CLI_AUTH_ORIGIN=https://www.staging.sim.ai \
  SIM_AGENT_API_URL=https://www.staging.copilot.sim.ai \
  bun run setup

Setting only the auth origin is the trap, so that combination warns. Neither set is the self-hoster default and stays silent — no prompts, no flags.

* fix(setup): survive a vanished port owner, and stop flagging our own containers

Two failures from one compose re-run:

- 'Kill it for me' crashed setup with 'kill() failed: ESRCH: No such process'. The owner list is an lsof snapshot, so the process can exit before the signal lands — which is the outcome we wanted, not an error. ESRCH now counts as freed, EPERM warns that it must be stopped by hand, and anything else warns; the loop re-probes either way instead of aborting a setup that had already written .env.

- Compose mode demanded 3000/3002 be free even when this stack was the one holding them, so re-running setup against a running install reported its own realtime container as a blocker and offered to kill Docker's listener. 'docker compose up -d' reconciles its own containers, so skip the check when the project already has some. A foreign process is still caught, and a foreign container still surfaces as a bind error from compose.

* fix(csp,setup): permit the socket origin the client actually uses; encode DSN passwords

Review round on #5964:

- The socket reconnect was a CSP bug, not a URL bug. getSocketUrl() already falls back to localhost:3002 for a localhost page, but generateRuntimeCSP gated that same fallback on isDev — and compose runs NODE_ENV=production, so connect-src omitted ws://localhost:3002 and the browser blocked the handshake. Key the fallback on the app URL being localhost instead, mirroring getSocketUrl. Revert the compose NEXT_PUBLIC_SOCKET_URL default: an explicit value suppresses the page-origin fallback that reverse-proxied self-hosts depend on, and ':-' treats empty as unset so the documented escape hatch could not work either. LOCALHOST_HOSTNAMES is duplicated locally because csp.ts is loaded by next.config.ts before @/ aliases resolve.
- Percent-encode the password when building the Postgres DSN. A user-supplied password containing @ : / # does not merely re-parse to the wrong host — it fails to parse as a URL at all, so a correct password surfaced as a connection failure.
- Tell 'Postgres rejected this password' apart from 'Postgres never started'. On the keep-the-volume path a wrong password left a healthy server and the old generic 'container did not become healthy' error, which is the confusion this change set exists to remove.

Adds a CSP regression test for the unset-socket-URL production case; verified it fails against the previous condition.

* improvement(setup): make k8s mode end somewhere usable, and show install progress

Two things made k8s mode the least satisfying path.

The services are ClusterIP, so a successful install left nothing on :3000 — 'Sim is ready' was true about the cluster and useless to the user, who had to notice and run a port-forward by hand. Compose opens a browser and dev offers to start the server; k8s now offers the forward the same way and runs it in the foreground so Ctrl-C ends it. Realtime gets its own forward (kubectl takes one resource per invocation) or the editor socket fails; it is a child in the same process group, so the terminal's Ctrl-C reaches it, and it is killed explicitly when the app forward exits.

'helm --wait' then blocked for minutes with a single static spinner, so a slow image pull looked identical to a wedged install. Run helm asynchronously and poll the cluster, so the spinner reports '3/3 pods ready · 1 starting'. CronJob-owned pods are excluded: the chart schedules a lot of them (36 on a running cluster here) and they finish as Completed, which would swamp the count and make readiness jitter for reasons unrelated to the install. Restarting pods are surfaced too — a cold cluster restarts realtime while Postgres comes up, and a silent spinner made that look like nothing was happening.

* fix(setup): identify Sim compose projects by content, not filename

Cursor (High): composeInstalls treated any project whose config basename was docker-compose.prod.yml or docker-compose.local.yml as a Sim install. Those names are common, and sim reset runs 'compose down -v' — so a stranger's stack could have had its volumes destroyed.

I introduced that reach. The previous ROOT-scoped '-f' probe was implicitly safe because it could only ever see the project in this checkout; switching to a global 'compose ls' to find stacks started elsewhere means projects must be identified by content instead. Read the config file Docker recorded and require a Sim marker (the published app image, or the app Dockerfile this repo builds), so both the prod and local variants match while an unrelated file with the same name does not. An unreadable or since-deleted file is left unmanaged rather than assumed ours.

Verified against a decoy nginx compose file using our exact filename: ignored, while both real Sim compose files still match.

* fix(setup): scope the compose port skip to published ports; print both k8s forwards

Review round on #5964:

- ensureComposePortsFree skipped conflict handling whenever the project had any container running, so leftover db/redis (which publish neither app port) waved through a foreign process on :3000 — it then surfaced as a raw compose bind error instead of the prompt. Read the host ports the project actually publishes and skip only those; the remaining ports still get the full check. Reading from the containers rather than the file matters because what counts is what is bound right now.
- The post-install note and the skip path documented only the app forward, while offerPortForward runs two. Skipping the prompt or copying the printed command left the editor's socket dead — the exact failure this change set exists to fix. Both commands now come from one forwardCommands() helper, so what is printed and what is run cannot drift.

* fix(setup): one source for the k8s forwards, and surface a dead realtime forward

Third round on the same theme, so fix it at the root rather than at another call site.

- lifecycle's k8sReachHints (used by sim start/restart) still restated an app-only forward, recreating the dead editor socket the setup path had just been fixed for. forwardCommands is now exported and consumed there, so every place that tells a user how to reach a ClusterIP release derives it from one definition.
- The realtime forward was spawned with stdio ignored and never checked, so a busy :3002 or a missing service killed it silently while the app forward kept running — indistinguishable from success until the editor won't connect. Keep its stderr, warn on an exit we did not ask for, and stay quiet on the intentional kill.

* fix(setup): pin the compose project on every lifecycle op

composeInstalls records the real project name from 'compose ls' and status and the destructive confirms print it, but every op ran 'compose -f <file>' with only cwd set — so Compose re-derived the project from that directory. The derived name is frequently not the recorded one: a directory is lowercased and stripped of dots (Sim.Demo_Test derives simdemo_test), and an explicit -p or COMPOSE_PROJECT_NAME at creation diverges outright. stop/down/reset could therefore act on a different project than the one named in the confirm, and reset runs 'down -v'.

Route every op through composeArgs(), which pins '-p <recorded project>'. cwd stays, since the file's own relative paths still resolve against it. Verified with a stack started as -p pinned-name from a directory deriving simdemo_test: the old form found 0 of its containers, the pinned form finds them.

* fix(setup): warn on both halves of a mothership mismatch

mothershipOverride warned only when SIM_CLI_AUTH_ORIGIN was set without SIM_AGENT_API_URL, while its own copy said to set both or neither. The reverse is the same failure mirrored: with only SIM_AGENT_API_URL set, the Chat key is still minted against the default prod auth origin and then validated against the override, which rejects it — silently, which is exactly what this helper exists to prevent.

Warn on either asymmetry, and read the default origin from one constant shared with the handoff so the message can't claim an origin the code no longer uses.

* fix(setup): warn about a half-set mothership before minting the key

mothershipOverride ran two steps after promptCopilotKey, so a half-set override minted a key against one environment, stored it, and only then warned that the other environment would reject it. Worse on a re-run: promptCopilotKey offers to keep an existing COPILOT_API_KEY and defaults to yes, so the bad key survives.

Move the override ahead of the key prompt in both compose and dev, so the warning arrives while it can still change the outcome — the user can abort and set the missing half before anything is minted. Nothing in the override depends on the key, so the order is free.
2026-07-25 17:48:45 -04:00

473 lines
17 KiB
TypeScript

import { spawn, spawnSync } from 'node:child_process'
import { getErrorMessage } from '@sim/utils/errors'
import type { Detection } from '../detect.ts'
import { ensureDocker } from '../docker.ts'
import { generateSecret, ROOT } from '../env-files.ts'
import { SetupError } from '../errors.ts'
import { waitFor } from '../probes.ts'
import * as p from '../prompter.ts'
import { glyph, theme } from '../theme.ts'
const APP_URL = 'http://localhost:3000'
const RELEASE = 'sim-dev'
const NAMESPACE = 'sim-dev'
const LOCAL_CONTEXT_PREFIXES = ['kind-', 'docker-desktop', 'minikube', 'orbstack']
/**
* `input` is piped on stdin rather than passed as arguments — argv is readable
* by any process on the machine, so secrets must never travel that way.
*/
function run(command: string, args: string[], failMessage: string, input?: string): string {
// `helm upgrade --install ./helm/sim` uses chart paths relative to the repo
// root, so pin cwd regardless of where the wizard was invoked from.
const result = spawnSync(command, args, { encoding: 'utf8', input, cwd: ROOT })
if (result.status !== 0) {
throw new Error(`${failMessage}: ${result.stderr.trim() || result.stdout.trim()}`)
}
return result.stdout
}
function isLocalContext(context: string): boolean {
return LOCAL_CONTEXT_PREFIXES.some((prefix) => context === prefix || context.startsWith(prefix))
}
const LOCAL_SERVER_HOSTS = new Set([
'127.0.0.1',
'localhost',
'0.0.0.0',
'::1',
'kubernetes.docker.internal',
'host.docker.internal',
])
/** True when a context's API server is a loopback/host address — i.e. a local cluster. */
export function isLocalKubeContext(context: string): boolean {
const server = contextServerHost(context)
return server !== null && LOCAL_SERVER_HOSTS.has(server)
}
/**
* Liveness probe — a kubeconfig entry can outlive a stopped or deleted cluster
* (kind clusters are Docker containers that don't restart on their own), so a
* context looking local is no guarantee its API server answers.
*/
function clusterReachable(context: string): boolean {
return (
spawnSync('kubectl', ['cluster-info', '--context', context, '--request-timeout=5s'], {
stdio: 'ignore',
}).status === 0
)
}
/** The API server host a context points at, or null if kubectl can't resolve it. */
function contextServerHost(context: string): string | null {
const result = spawnSync(
'kubectl',
[
'config',
'view',
'--minify',
'--context',
context,
'-o',
'jsonpath={.clusters[0].cluster.server}',
],
{ encoding: 'utf8' }
)
if (result.status !== 0) return null
try {
return new URL(result.stdout.trim()).hostname
} catch {
return null
}
}
/**
* POSIX-quote a value for a copyable shell hint. A kube-context passes only a
* prefix check, so it can still contain whitespace or shell metacharacters that
* would break the `--context` argument (or run embedded syntax) when copied.
* Ordinary context names stay bare; only unsafe ones get single-quoted.
*/
function shq(value: string): string {
if (/^[A-Za-z0-9._/-]+$/.test(value)) return value
return `'${value.replace(/'/g, `'\\''`)}'`
}
async function ensureLocalContext(detection: Detection): Promise<string> {
if (!detection.binaries.helm || !detection.binaries.kubectl) {
throw new SetupError('kubernetes mode needs kubectl and helm on PATH.', [
`install them: ${theme.command('brew install kubectl helm')}`,
])
}
const context = detection.kubeContext
if (context && isLocalContext(context)) {
// The name is only a hint — a remote cluster can be named like a local one
// (e.g. "kind-prod"). Verify the API server is a loopback/host address before
// defaulting to "yes", so generated secrets can't silently ship to a remote
// cluster on a blind Enter.
const server = contextServerHost(context)
if (server && LOCAL_SERVER_HOSTS.has(server)) {
if (!clusterReachable(context)) {
// The context is local but its cluster isn't answering — stopped or
// deleted. Don't offer it (helm would just fail); fall through to the
// kind path, which starts a stopped "sim" cluster or creates one.
p.log.warn(
`Context "${context}" points at a local cluster that isn't responding — it looks stopped or deleted. The wizard will start or recreate a kind cluster instead.`
)
} else {
const useIt = await p.confirm({
message: `Use current kube context "${context}"?`,
initialValue: true,
})
if (useIt) return context
}
} else {
p.log.warn(
`Context "${context}" is named like a local cluster, but its API server${server ? ` (${server})` : ''} does not look local. Continuing would deploy the generated secrets there.`
)
const useIt = await p.confirm({
message: `Deploy to "${context}" anyway?`,
initialValue: false,
})
if (useIt) return context
}
} else if (context) {
p.log.warn(
`Current context "${context}" does not look like a local cluster. Deploying to remote clusters is not supported by the wizard yet — switch to a kind/docker-desktop context, or drive helm directly (see helm/sim/examples/values-production.yaml).`
)
}
if (!detection.binaries.kind) {
throw new SetupError('no local cluster available.', [
`install kind: ${theme.command('brew install kind')} — the wizard creates the cluster for you`,
'or enable Kubernetes in Docker Desktop settings, then re-run',
])
}
await ensureDocker(true)
const clusters = run('kind', ['get', 'clusters'], 'kind get clusters failed')
.trim()
.split('\n')
.filter(Boolean)
if (clusters.includes('sim')) {
run('kind', ['export', 'kubeconfig', '--name', 'sim'], 'kind export kubeconfig failed')
if (clusterReachable('kind-sim')) {
p.log.step('Reusing existing kind cluster "sim"')
} else {
// The cluster exists in kind but isn't answering — its node containers are
// stopped (a Docker/machine restart). Start them and wait for the API.
const spin = p.spinner()
spin.start('kind cluster "sim" is stopped — starting it…')
const nodes = run('kind', ['get', 'nodes', '--name', 'sim'], 'kind get nodes failed')
.trim()
.split('\n')
.filter(Boolean)
for (const node of nodes) spawnSync('docker', ['start', node], { stdio: 'ignore' })
const up = await waitFor(() => Promise.resolve(clusterReachable('kind-sim')), 60_000, 2000)
if (!up) {
spin.stop(`${glyph.fail} kind cluster "sim" would not start`)
throw new SetupError('the kind cluster "sim" exists but will not come up.', [
`inspect it: ${theme.command('docker ps -a --filter name=sim-control-plane')}`,
`recreate it: ${theme.command('kind delete cluster --name sim')}, then re-run ${theme.command('bun run setup')}`,
])
}
spin.stop('kind cluster "sim" started')
}
} else {
const spin = p.spinner()
spin.start('Creating kind cluster "sim"…')
run('kind', ['create', 'cluster', '--name', 'sim'], 'kind create cluster failed')
spin.stop('kind cluster "sim" ready')
}
return 'kind-sim'
}
interface PodProgress {
ready: number
total: number
detail: string
}
/**
* One-line summary of what the cluster is doing, for the install spinner. Only
* long-running workloads count — the chart's CronJobs spawn short-lived pods
* that finish as Completed, and counting those makes "ready" jitter downward
* for reasons that have nothing to do with the install.
*/
function podProgress(context: string): PodProgress | null {
const result = spawnSync(
'kubectl',
[
'get',
'pods',
'--context',
context,
'-n',
NAMESPACE,
'-o',
'jsonpath={range .items[*]}{.status.phase}{"\\t"}{.metadata.ownerReferences[0].kind}{"\\t"}{range .status.containerStatuses[*]}{.ready},{.state.waiting.reason}{" "}{end}{"\\n"}{end}',
],
{ encoding: 'utf8' }
)
if (result.status !== 0) return null
const rows = result.stdout.split('\n').filter(Boolean)
if (rows.length === 0) return null
let ready = 0
let total = 0
let pulling = 0
let crashing = 0
for (const row of rows) {
const [, ownerKind = '', containers = ''] = row.split('\t')
if (ownerKind === 'Job') continue
total++
if (containers.includes('true,')) ready++
if (containers.includes('ContainerCreating') || containers.includes('PodInitializing'))
pulling++
if (containers.includes('CrashLoopBackOff') || containers.includes('ImagePullBackOff'))
crashing++
}
if (total === 0) return null
const notes: string[] = []
if (pulling > 0) notes.push(`${pulling} starting`)
// Restarts while Postgres comes up are normal on a cold cluster; say so rather
// than let a silent spinner imply nothing is happening.
if (crashing > 0) notes.push(`${crashing} restarting`)
return { ready, total, detail: notes.join(' · ') }
}
/**
* `helm --wait` blocks for minutes with no output, so a slow image pull is
* indistinguishable from a wedged install — the reason the old spinner was
* unsatisfying. Run helm asynchronously and poll the cluster so the spinner
* reports what is actually happening.
*/
async function helmInstall(
args: string[],
input: string,
context: string,
spin: ReturnType<typeof p.spinner>
): Promise<void> {
const child = spawn('helm', args, { cwd: ROOT, stdio: ['pipe', 'pipe', 'pipe'] })
child.stdin.write(input)
child.stdin.end()
let stderr = ''
let stdout = ''
child.stdout.on('data', (chunk) => {
stdout += chunk
})
child.stderr.on('data', (chunk) => {
stderr += chunk
})
const ticker = setInterval(() => {
const progress = podProgress(context)
if (!progress) return
const suffix = progress.detail ? ` · ${progress.detail}` : ''
spin.message(`${progress.ready}/${progress.total} pods ready${suffix}`)
}, 3000)
const code = await new Promise<number>((resolve) => {
child.once('close', (status) => resolve(status ?? 1))
})
clearInterval(ticker)
if (code !== 0) {
throw new Error(`helm upgrade --install failed: ${stderr.trim() || stdout.trim()}`)
}
}
function existingReleaseSecrets(context: string): Record<string, string> | null {
const scope = ['--kube-context', context, '-n', NAMESPACE]
const status = spawnSync('helm', ['status', RELEASE, ...scope], { stdio: 'ignore' })
if (status.status !== 0) return null
const values = JSON.parse(
run('helm', ['get', 'values', RELEASE, ...scope, '-o', 'json'], 'helm get values failed')
) as { app?: { env?: Record<string, string> }; postgresql?: { auth?: { password?: string } } }
const env = values.app?.env ?? {}
const password = values.postgresql?.auth?.password
if (
!env.BETTER_AUTH_SECRET ||
!env.ENCRYPTION_KEY ||
!env.INTERNAL_API_SECRET ||
!env.CRON_SECRET ||
!password
) {
return null
}
return {
BETTER_AUTH_SECRET: env.BETTER_AUTH_SECRET,
ENCRYPTION_KEY: env.ENCRYPTION_KEY,
INTERNAL_API_SECRET: env.INTERNAL_API_SECRET,
CRON_SECRET: env.CRON_SECRET,
POSTGRES_PASSWORD: password,
}
}
/**
* Values document piped to helm on stdin instead of `--set`. `JSON.stringify`
* quotes and escapes each value — JSON is a subset of YAML, so a secret
* containing `#`, `:`, or a leading `*` can neither break the document nor be
* reinterpreted as YAML syntax.
*/
function secretValues(secrets: Record<string, string>): string {
const { POSTGRES_PASSWORD, ...appEnv } = secrets
const env = Object.entries(appEnv)
.map(([key, value]) => ` ${key}: ${JSON.stringify(value)}`)
.join('\n')
return `app:\n env:\n${env}\npostgresql:\n auth:\n password: ${JSON.stringify(POSTGRES_PASSWORD)}\n`
}
export async function runK8sMode(detection: Detection): Promise<void> {
// Pin every subsequent call to the context we validated: the ambient context
// can change between detection and deploy, which would send generated
// credentials to an unintended cluster.
const context = await ensureLocalContext(detection)
const reused = existingReleaseSecrets(context)
const secrets = reused ?? {
BETTER_AUTH_SECRET: generateSecret(),
ENCRYPTION_KEY: generateSecret(),
INTERNAL_API_SECRET: generateSecret(),
CRON_SECRET: generateSecret(),
POSTGRES_PASSWORD: generateSecret().slice(0, 24),
}
if (reused) p.log.step('Reusing secrets from the existing release')
const spin = p.spinner()
spin.start('helm upgrade --install (first run pulls images — this can take several minutes)…')
try {
await helmInstall(
[
'upgrade',
'--install',
RELEASE,
'./helm/sim',
'--kube-context',
context,
'--namespace',
NAMESPACE,
'--create-namespace',
'--values',
'./helm/sim/examples/values-development.yaml',
'--values',
'-',
'--wait',
'--timeout',
'15m',
],
secretValues(secrets),
context,
spin
)
} catch (error) {
spin.stop(`${glyph.fail} helm install failed`)
throw new SetupError(getErrorMessage(error), [
`pod status: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} get pods`)}`,
`stuck pods: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} describe pod <name> | tail -20`)}`,
'ImagePullBackOff on ghcr.io/simstudioai/* usually means the chart appVersion tag was never published — check Chart.yaml against ghcr',
])
}
spin.stop('Release deployed, all pods ready')
const testSpin = p.spinner()
testSpin.start('Running helm test…')
const test = spawnSync('helm', ['test', RELEASE, '--kube-context', context, '-n', NAMESPACE], {
encoding: 'utf8',
cwd: ROOT,
})
if (test.status !== 0) {
testSpin.stop(`${glyph.fail} helm test failed`)
throw new SetupError(`helm test failed:\n${test.stdout}${test.stderr}`, [
`pod status: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} get pods`)}`,
`app logs: ${theme.command(`kubectl --context ${shq(context)} -n ${NAMESPACE} logs deploy/${RELEASE}-app --tail 50`)}`,
])
}
testSpin.stop('helm test passed')
p.note(
[
`open ${APP_URL} (needs both forwards below)`,
`pods: kubectl --context ${shq(context)} -n ${NAMESPACE} get pods`,
`app logs: kubectl --context ${shq(context)} -n ${NAMESPACE} logs deploy/${RELEASE}-app --tail 50`,
// Both, always: the app alone loads but the editor's socket has nothing to
// reach, which is the reconnect failure this change set exists to fix.
...forwardCommands(context).map(
(command, index) => `${index === 0 ? 'forward: ' : ' '} ${command}`
),
`tear down: helm uninstall ${RELEASE} --kube-context ${shq(context)} -n ${NAMESPACE}`,
].join('\n'),
'Reach your cluster'
)
await offerPortForward(context)
}
/**
* Both forwards, in the order a user should run them. Kept in one place so the
* printed instructions and what the wizard actually runs cannot drift — the app
* alone leaves the editor's socket dead.
*/
export function forwardCommands(context: string): string[] {
const scope = `kubectl --context ${shq(context)} -n ${NAMESPACE} port-forward`
return [`${scope} svc/${RELEASE}-app 3000:3000`, `${scope} svc/${RELEASE}-realtime 3002:3002`]
}
/**
* The services are ClusterIP, so a healthy release is still unreachable from the
* host — "Sim is ready" with nothing on :3000 is the least satisfying way to end
* a setup. Offer the forward the same way dev mode offers to start the server,
* and run it in the foreground so Ctrl-C ends it.
*
* Realtime needs its own forward (one resource per invocation) or the editor's
* socket fails; it runs as a child in this process group, so the terminal's
* Ctrl-C reaches it too, and it is killed explicitly once the app forward exits.
*/
async function offerPortForward(context: string): Promise<void> {
const forward = await p.confirm({
message: `Port-forward now so you can open ${APP_URL}?`,
initialValue: true,
})
if (!forward) {
p.log.info(
theme.muted(
`Skipped — run both forwards when you want to reach it (the second keeps the editor's socket alive):\n${forwardCommands(
context
)
.map((command) => ` ${command}`)
.join('\n')}`
)
)
return
}
const scope = ['--context', context, '-n', NAMESPACE]
const realtime = spawn(
'kubectl',
[...scope, 'port-forward', `svc/${RELEASE}-realtime`, '3002:3002'],
// stderr is kept so a failure can be explained; a silently dead second
// forward looks exactly like a working setup until the editor won't connect.
{ stdio: ['ignore', 'ignore', 'pipe'] }
)
let realtimeError = ''
realtime.stderr?.on('data', (chunk) => {
realtimeError += chunk
})
// Only an exit we did not ask for is a problem — the kill below also fires this.
let stopping = false
realtime.once('exit', (code) => {
if (stopping || code === 0) return
p.log.warn(
`The realtime forward (:3002) stopped — the editor's socket will not connect. ${
realtimeError.trim() || `Check that :3002 is free and svc/${RELEASE}-realtime exists.`
}`
)
})
p.log.step(`Forwarding ${APP_URL} (app) and :3002 (realtime) — Ctrl-C to stop`)
spawnSync('kubectl', [...scope, 'port-forward', `svc/${RELEASE}-app`, '3000:3000'], {
stdio: 'inherit',
})
stopping = true
realtime.kill()
}