#!/usr/bin/env bun /** * Live check for #261 (replace deploys) on Hetzner Cloud, through Floating IPs. * * HCLOUD_TOKEN=... bun --no-env-file scripts/livecheck/hetzner.ts --run --dir [--location fsn1] * * `all` deploys a scratch app with a replace strategy and checks, in order: * the first deploy runs in place and creates the Floating IPs; a dry run plans * the replace; a failing warm-up leaves the old server serving with nothing * left behind; a replace deploy serves every request during the switch and * carries the moved volume's data; rollback within the window is an address * switch; after the window the old server is deleted; `cloud destroy` removes * the servers and the Floating IPs. Then it sweeps. * * `sweep` deletes every server, Floating IP, volume, firewall, network and * SSH key whose name starts with the run's project slug or that is labelled * with it, and reports what it found. The slug is `tscloud-lc-`, so * nothing outside the run can match. Evidence goes to `/evidence.md`. */ import { appendFileSync, mkdirSync, writeFileSync } from 'node:fs' import { join, resolve } from 'node:path' const ROOT = resolve(import.meta.dir, '../..') const CLI = join(ROOT, 'packages/ts-cloud/bin/cli.ts') const API = 'https://api.hetzner.cloud/v1' const args = process.argv.slice(2) const option = (name: string, fallback?: string): string | undefined => { const at = args.indexOf(name); return at >= 0 ? args[at + 1] : fallback } const phase = args[0] const runId = option('--run') const dir = option('--dir') const location = option('--location', 'fsn1')! const token = process.env.HCLOUD_TOKEN if (!phase || !runId || !dir || !/^[a-z0-9]{4,12}$/.test(runId) || !token) { console.error('usage: HCLOUD_TOKEN=... bun --no-env-file scripts/livecheck/hetzner.ts --run --dir ') process.exit(2) } const slug = `tscloud-lc-${runId}` const env = 'production' const SITE_PORT = 3000 const projectDir = join(resolve(dir), `project-${runId}`) mkdirSync(projectDir, { recursive: true }) const evidencePath = join(resolve(dir), 'evidence.md') const failures: string[] = [] function evidence(line: string): void { console.log(line) appendFileSync(evidencePath, `${line}\n`) } function check(name: string, ok: boolean, detail: string): void { evidence(`${ok ? 'PASS' : 'FAIL'} ${name}: ${detail}`) if (!ok) failures.push(name) } const sleep = (ms: number) => new Promise(r => setTimeout(r, ms)) async function api(method: string, path: string, body?: unknown): Promise { const response = await fetch(`${API}${path}`, { method, headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, body: body === undefined ? undefined : JSON.stringify(body) }) const text = await response.text() if (!response.ok) throw new Error(`${method} ${path} ${response.status}: ${text.slice(0, 300)}`) return (text ? JSON.parse(text) : {}) as T } async function list(kind: string): Promise { const out: any[] = [] for (let page = 1; ; page++) { const data = await api('GET', `/${kind}?per_page=50&page=${page}`) out.push(...data[kind]) if (!data.meta?.pagination?.next_page) return out } } const ours = (resource: any) => String(resource.name ?? '').startsWith(slug) || resource.labels?.['ts-cloud/project'] === slug const role = (server: any) => server.labels?.['ts-cloud/role'] function servers(): Promise { return list('servers').then(all => all.filter(ours)) } function floatingIps(): Promise { return list('floating_ips').then(all => all.filter(ours)) } function fipv4(): Promise { return floatingIps().then(ips => ips.find(ip => ip.type === 'ipv4')) } function volume(key: string): Promise { return list('volumes').then(all => all.filter(ours).find(v => v.labels?.['ts-cloud/volume'] === key)) } let address = '' function probe(): string { return probeDetail().code } function probeDetail(): { code: string, curlExit: number } { const r = Bun.spawnSync(['curl', '-s', '-o', '/dev/null', '-w', '%{http_code}', '--max-time', '5', `http://${address}:${SITE_PORT}/health`]) return { code: r.stdout.toString().trim() || '000', curlExit: r.exitCode ?? -1 } } function body(): string { return Bun.spawnSync(['curl', '-s', '--max-time', '5', `http://${address}:${SITE_PORT}/`]).stdout.toString().trim() } function ssh(ip: string, command: string): string { const r = Bun.spawnSync(['ssh', '-o', 'StrictHostKeyChecking=no', '-o', 'UserKnownHostsFile=/dev/null', '-o', 'LogLevel=ERROR', '-o', 'ConnectTimeout=10', `root@${ip}`, command]) if (r.exitCode !== 0) throw new Error(`ssh ${ip}: ${r.stderr.toString().slice(0, 300)}`) return r.stdout.toString().trim() } function writeProject(release: string, strategy: Record): void { mkdirSync(join(projectDir, 'app'), { recursive: true }) writeFileSync(join(projectDir, 'app/server.ts'), [ 'const release = await Bun.file(new URL(\'./release.txt\', import.meta.url)).text()', `Bun.serve({ port: ${SITE_PORT}, reusePort: true, fetch: req => new URL(req.url).pathname === '/health' ? new Response('ok') : new Response(release) })`, '', ].join('\n')) writeFileSync(join(projectDir, 'app/release.txt'), release) const config = { project: { name: slug, slug, region: location }, environments: { production: { type: 'production' } }, cloud: { provider: 'hetzner' }, hetzner: { location }, sites: { web: { domain: `${slug}.invalid`, root: 'app', start: 'bun server.ts', port: SITE_PORT } }, infrastructure: { compute: { mode: 'server', size: 'small', volumes: { archive: { size: 10, mountPath: '/data/archive', deleteProtection: false } }, deployStrategy: strategy, }, }, } writeFileSync(join(projectDir, 'cloud.config.ts'), `export default ${JSON.stringify(config, null, 2)}\n`) } async function cloud(cliArgs: string[], label: string): Promise<{ code: number, output: string }> { evidence(`$ cloud ${cliArgs.join(' ')} (${label})`) const child = Bun.spawn(['bun', CLI, ...cliArgs], { cwd: projectDir, env: { ...process.env, CI: 'true' }, stdout: 'pipe', stderr: 'pipe' }) const [code, out, err] = await Promise.all([child.exited, new Response(child.stdout).text(), new Response(child.stderr).text()]) const log = join(projectDir, `${label}.log`) writeFileSync(log, `${out}${err}`) evidence(` exit ${code}; log ${log}`) return { code, output: `${out}${err}` } } const deployArgs = ['deploy', '--env', env, '--yes', '--skip-dns-verification'] const strategy = (warmUp: Record, retainOldForMinutes: number) => ({ type: 'replace', warmUp, timeoutSeconds: 900, retainOldForMinutes, volumes: { archive: 'move' } }) const healthy = { command: 'true', healthCheck: { path: '/health', port: SITE_PORT } } async function until(what: string, timeoutMs: number, everyMs: number, probeFn: () => Promise | T | undefined): Promise { const deadline = Date.now() + timeoutMs while (Date.now() < deadline) { try { const value = await probeFn(); if (value !== undefined && value !== false) return value } catch {} await sleep(everyMs) } throw new Error(`timed out waiting for ${what}`) } async function all(): Promise { evidence(`\n## Hetzner replace deploys, run ${runId} (${slug}, ${location}), ${new Date().toISOString()}`) // 1. First deploy with replace configured: in place, Floating IPs created and assigned. writeProject('v1', strategy(healthy, 15)) const first = await cloud(deployArgs, 'deploy-1-in-place') const ips = await floatingIps() const v4 = ips.find(ip => ip.type === 'ipv4') const original = (await servers()).find(s => role(s) === 'app') if (!v4 || !original) throw new Error('the first deploy left no Floating IP or app server; see its log') address = v4.ip const serving = await until('the app on the Floating IP', 5 * 60_000, 5_000, () => (/^[23]/.test(probe()) ? probe() : undefined)).catch(() => probe()) check('first deploy runs in place and serves from the Floating IPs', first.code === 0 && ips.length === 2 && ips.every(ip => ip.server === original.id) && /^[23]/.test(serving) && body() === 'v1', `exit ${first.code}; Floating IPs ${ips.map(ip => `${ip.type} ${ip.ip} on ${ip.server}`).join(', ')}; app server ${original.id} (${original.public_net.ipv4.ip}); /health ${serving}; / = ${JSON.stringify(body())}`) const sha = ssh(original.public_net.ipv4.ip, `head -c 1048576 /dev/urandom > /data/archive/lc.bin && sync && sha256sum /data/archive/lc.bin | cut -d' ' -f1`) evidence(`wrote /data/archive/lc.bin on ${original.id}, sha256 ${sha}`) // 2. Dry run plans the replace. writeProject('v2', strategy(healthy, 15)) const dry = await cloud([...deployArgs, '--dry-run'], 'replace-dry-run') check('dry run plans the replace', dry.output.includes('would launch and provision a replacement'), dry.output.split('\n').filter(l => l.includes('would ')).slice(0, 8).join(' / ')) // 3. Failing warm-up. writeProject('v2-broken', strategy({ command: 'echo failing on purpose; exit 1' }, 15)) const failing = await cloud(deployArgs, 'replace-failing-warmup') const afterFail = await servers() const archiveAfterFail = await volume('archive') check('failing warm-up leaves the old server serving', failing.code !== 0 && failing.output.includes('keeps serving') && afterFail.length === 1 && afterFail[0].id === original.id && role(afterFail[0]) === 'app' && (await fipv4())?.server === original.id && archiveAfterFail?.server === original.id && /^[23]/.test(probe()) && body() === 'v1', `exit ${failing.code}; servers ${afterFail.map(s => `${s.id}:${role(s)}`).join(',')}; Floating IP on ${(await fipv4())?.server}; archive on ${archiveAfterFail?.server}; / = ${JSON.stringify(body())}`) // 4. Zero-failure switch while polling once a second. writeProject('v2', strategy(healthy, 15)) const polls: string[] = [] const failedAt: string[] = [] let polling = true const poller = (async () => { while (polling) { const started = new Date().toISOString() const { code, curlExit } = probeDetail() polls.push(code) if (!/^[23]/.test(code)) failedAt.push(`${started} code ${code} curl exit ${curlExit}`) await sleep(1000) } })() const good = await cloud(deployArgs, 'replace-good') await sleep(10_000) polling = false await poller const bad = polls.filter(code => !/^[23]/.test(code)) const afterGood = await servers() const replacement = afterGood.find(s => role(s) === 'app') const standby = afterGood.find(s => role(s) === 'app-standby') if (failedAt.length) { const v4 = await fipv4() const actions = v4 ? (await api('GET', `/floating_ips/${v4.id}/actions?sort=id:desc`)).actions : [] evidence(`failed polls: ${failedAt.join('; ')}`) evidence(`Floating IP actions: ${actions.map((a: any) => `${a.command} ${a.started} -> ${a.finished}`).join('; ')}`) } const movedSha = replacement ? ssh(replacement.public_net.ipv4.ip, 'sha256sum /data/archive/lc.bin | cut -d" " -f1') : '' check('replace deploy serves every request during the switch', good.code === 0 && bad.length === 0 && !!replacement && replacement.id !== original.id && replacement.name === original.name && standby?.id === original.id && (await floatingIps()).every(ip => ip.server === replacement.id) && body() === 'v2' && movedSha === sha, `${polls.length} polls, ${bad.length} failures (${[...new Set(bad)].join(',') || 'none'}); serving ${replacement?.id} "${replacement?.name}", standby ${standby?.id} "${standby?.name}"; moved file sha ${movedSha === sha ? 'matches' : `differs (${movedSha})`}; / = ${JSON.stringify(body())}`) // 5. Rollback within the window: address switch only. const rollback = await cloud(['deploy:rollback', '--env', env], 'replace-rollback') const afterRollback = await servers() check('rollback within the window is an address switch', rollback.code === 0 && rollback.output.includes('Rolled back the replace deploy') && afterRollback.length === 1 && afterRollback[0].id === original.id && role(afterRollback[0]) === 'app' && (await fipv4())?.server === original.id && (await volume('archive'))?.server === original.id && body() === 'v1', `exit ${rollback.code}; servers ${afterRollback.map(s => `${s.id}:${role(s)}:${s.name}`).join(',')}; / = ${JSON.stringify(body())} (the old release, so nothing was redeployed)`) // 6. After the window: one-minute window, wait, finalize. writeProject('v3', strategy(healthy, 1)) const third = await cloud(deployArgs, 'replace-short-window') await sleep(75_000) const { createCloudDriver } = await import('../../packages/ts-cloud/src/drivers') const { finalizeComputeReplace, supportsReplaceDeploy } = await import('../../packages/ts-cloud/src/deploy/replace-compute') const configModule = await import(`${join(projectDir, 'cloud.config.ts')}?t=${Date.now()}`) const previousCwd = process.cwd() process.chdir(projectDir) try { const driver = createCloudDriver({ config: configModule.default }) if (!supportsReplaceDeploy(driver)) throw new Error('driver cannot replace') const finalState = await finalizeComputeReplace(driver, configModule.default, env) evidence(`finalize: ${finalState?.phase}`) } finally { process.chdir(previousCwd) } const afterWindow = await until('the old server to be deleted', 5 * 60_000, 10_000, async () => { const s = await servers(); return s.length === 1 ? s : undefined }).catch(() => servers()) check('old server deleted after the window, nothing orphaned', third.code === 0 && afterWindow.length === 1 && afterWindow[0].id !== original.id && role(afterWindow[0]) === 'app' && body() === 'v3', `exit ${third.code}; servers ${afterWindow.map(s => `${s.id}:${role(s)}`).join(',')}; / = ${JSON.stringify(body())}`) // 7. Teardown through ts-cloud. const destroy = await cloud(['destroy', '--env', env, '--force'], 'destroy') const left = { servers: await servers(), ips: await floatingIps() } check('cloud destroy removes the servers and the Floating IPs', destroy.code === 0 && left.servers.length === 0 && left.ips.length === 0, `exit ${destroy.code}; servers left ${left.servers.length}; Floating IPs left ${left.ips.length}`) } async function sweep(): Promise { const report: string[] = [] for (const s of await servers()) { await api('DELETE', `/servers/${s.id}`); report.push(`server ${s.id} ${s.name}`) } if (report.length) await sleep(20_000) for (const ip of await floatingIps()) { await api('DELETE', `/floating_ips/${ip.id}`); report.push(`floating ip ${ip.ip}`) } for (const v of (await list('volumes')).filter(ours)) { // A volume is locked while its deleted server releases it; wait that out. if (v.server) await until(`volume ${v.id} to detach`, 3 * 60_000, 10_000, async () => { const now = (await api('GET', `/volumes/${v.id}`)).volume; if (!now.server) return true; await api('POST', `/volumes/${v.id}/actions/detach`).catch(() => undefined); return undefined }) if (v.protection?.delete) await api('POST', `/volumes/${v.id}/actions/change_protection`, { delete: false }) await api('DELETE', `/volumes/${v.id}`); report.push(`volume ${v.id} ${v.name}`) } for (const kind of ['firewalls', 'networks', 'ssh_keys']) { for (const r of (await list(kind)).filter(ours)) { await api('DELETE', `/${kind}/${r.id}`); report.push(`${kind} ${r.id} ${r.name}`) } } evidence(`sweep (${slug}): ${report.length ? `deleted ${report.join('; ')}` : 'nothing left'}`) } try { if (phase === 'all') await all() else if (phase !== 'sweep') throw new Error(`unknown phase ${phase}`) } catch (error) { failures.push(String(error)) evidence(`ERROR ${String(error)}`) } finally { await sweep().catch(error => evidence(`ERROR sweep: ${String(error)}`)) } evidence(failures.length ? `\n${failures.length} failed: ${failures.join(' | ')}` : '\nall checks passed') process.exit(failures.length ? 1 : 0)