|
| 1 | +// 28 — code-server (VS Code in Browser) inside an FC sandbox. |
| 2 | +// Installs code-server inside an FC microVM, binds it on 0.0.0.0:8080 |
| 3 | +// with auth disabled, exposes it through the public ingress URL, and |
| 4 | +// verifies the workbench is live by hitting GET /healthz. |
| 5 | + |
| 6 | +import type { Sandbox } from "fc-sandbox-sdk"; |
| 7 | +import { FcClient } from "fc-sandbox-sdk"; |
| 8 | + |
| 9 | +const SHAPE = "s-2vcpu-2gb"; |
| 10 | +const ROOTFS = "devbox:1"; |
| 11 | +const PORT = 8080; |
| 12 | + |
| 13 | +// exactOptionalPropertyTypes: narrow env vars before passing to FcClient. |
| 14 | +const baseUrl = process.env.FCSPAWN_URL; |
| 15 | +const apiKey = process.env.FC_API_KEY; |
| 16 | +if (!baseUrl || !apiKey) { |
| 17 | + throw new Error("set FCSPAWN_URL and FC_API_KEY (see .env.example)"); |
| 18 | +} |
| 19 | + |
| 20 | +const fc = new FcClient({ baseUrl, apiKey }); |
| 21 | + |
| 22 | +async function sh(sb: Sandbox, label: string, script: string, timeoutMs = 120_000) { |
| 23 | + const { result, exec_ms } = await sb.runCommand("bash", ["-lc", script], { timeoutMs }); |
| 24 | + if (result.exit_code !== 0) { |
| 25 | + console.log(`[${label}] exit=${result.exit_code} (${exec_ms} ms)`); |
| 26 | + if (result.stdout) console.log(" stdout:", result.stdout.slice(-2000)); |
| 27 | + if (result.stderr) console.log(" stderr:", result.stderr.slice(-2000)); |
| 28 | + throw new Error(`${label} failed (exit ${result.exit_code})`); |
| 29 | + } |
| 30 | + return result.stdout; |
| 31 | +} |
| 32 | + |
| 33 | +console.log(`[1/6] creating sandbox (shape=${SHAPE}, rootfs=${ROOTFS}, ingress on)...`); |
| 34 | +const sandbox = await fc.createSandbox({ |
| 35 | + shape: SHAPE, |
| 36 | + rootfs: ROOTFS, |
| 37 | + ingress_enabled: true, |
| 38 | +}); |
| 39 | +console.log(` sandbox: ${sandbox.id} ip: ${sandbox.ip}`); |
| 40 | + |
| 41 | +// Build the public ingress URL. Template yields https://<ulid>-<port>.<region>.<domain>. |
| 42 | +// Downgrade to http:// — TLS wildcard cert is not yet provisioned; http:// is forward-compatible. |
| 43 | +const previewUrl = sandbox.previewUrl(PORT).replace(/^https:/, "http:"); |
| 44 | +console.log(` preview URL: ${previewUrl}`); |
| 45 | + |
| 46 | +try { |
| 47 | + // Ensure curl is available (devbox:1 is Debian-based). |
| 48 | + console.log("[2/6] ensuring curl is available..."); |
| 49 | + await sh(sandbox, "curl-check", "curl --version >/dev/null || apt-get install -y curl", 60_000); |
| 50 | + |
| 51 | + // Standalone install bundles the Node runtime — predictable, no PATH conflicts. |
| 52 | + // ~120-200 MB download; 300 s budget is sufficient on the FC egress link. |
| 53 | + console.log("[3/6] installing code-server (standalone, ~100-200 MB)..."); |
| 54 | + await sh( |
| 55 | + sandbox, |
| 56 | + "install", |
| 57 | + "curl -fsSL https://code-server.dev/install.sh | sh -s -- --method=standalone", |
| 58 | + 300_000, |
| 59 | + ); |
| 60 | + |
| 61 | + // Extract the semver from `code-server --version` output (first line is the bare version). |
| 62 | + const codeServerVer = |
| 63 | + (await sh(sandbox, "version", "code-server --version 2>&1")) |
| 64 | + .split("\n") |
| 65 | + .map((l) => l.trim()) |
| 66 | + .find((l) => /^\d+\.\d+/.test(l)) ?? "unknown"; |
| 67 | + console.log(` code-server ${codeServerVer}`); |
| 68 | + |
| 69 | + // Daemonise with nohup/setsid — devbox:1 has no systemd. |
| 70 | + // `;` before nohup so the chain does not hold the /exec stdout pipe open. |
| 71 | + // --auth none: no password prompt for a short-lived demo sandbox. |
| 72 | + // --bind-addr 0.0.0.0:PORT: required for ingress (127.0.0.1 is not reachable from outside the VM). |
| 73 | + console.log(`[4/6] daemonising code-server on port ${PORT}...`); |
| 74 | + await sh( |
| 75 | + sandbox, |
| 76 | + "boot", |
| 77 | + `rm -f /tmp/code-server.log ; ` + |
| 78 | + `nohup setsid code-server --bind-addr 0.0.0.0:${PORT} --auth none ` + |
| 79 | + `>/tmp/code-server.log 2>&1 </dev/null & sleep 1; echo launched`, |
| 80 | + ); |
| 81 | + |
| 82 | + console.log(`[5/6] waiting for code-server to bind port ${PORT}...`); |
| 83 | + await sandbox.waitForPortReady(PORT, { timeoutMs: 60_000 }); |
| 84 | + console.log(" port is accepting connections"); |
| 85 | + |
| 86 | + // Poll GET /healthz through the ingress URL until code-server responds. |
| 87 | + // /healthz is an auth-exempt route that returns JSON {"status":"success","data":{"up":true}}. |
| 88 | + console.log(`[6/6] polling ${previewUrl}/healthz for a live response...`); |
| 89 | + const deadline = Date.now() + 90_000; |
| 90 | + let healthBody = ""; |
| 91 | + let healthStatus = 0; |
| 92 | + let healthy = false; |
| 93 | + while (Date.now() < deadline) { |
| 94 | + try { |
| 95 | + const res = await fetch(`${previewUrl}/healthz`, { signal: AbortSignal.timeout(10_000) }); |
| 96 | + healthStatus = res.status; |
| 97 | + healthBody = await res.text(); |
| 98 | + if (res.ok) { |
| 99 | + let json: { status?: string; data?: { up?: boolean } } = {}; |
| 100 | + try { |
| 101 | + json = JSON.parse(healthBody); |
| 102 | + } catch { |
| 103 | + // not JSON yet — keep polling |
| 104 | + } |
| 105 | + if (json.data?.up === true) { |
| 106 | + healthy = true; |
| 107 | + break; |
| 108 | + } |
| 109 | + } |
| 110 | + } catch { |
| 111 | + // ingress propagation still in flight — keep polling |
| 112 | + } |
| 113 | + await new Promise((r) => setTimeout(r, 2_000)); |
| 114 | + } |
| 115 | + |
| 116 | + if (!healthy) { |
| 117 | + // Fetch the log for diagnostics before throwing. |
| 118 | + const log = await sh(sandbox, "log", "tail -40 /tmp/code-server.log").catch( |
| 119 | + () => "(unavailable)", |
| 120 | + ); |
| 121 | + throw new Error( |
| 122 | + `GET /healthz never returned a live response (last HTTP ${healthStatus}).\n` + |
| 123 | + `Body: ${healthBody.slice(0, 300)}\ncode-server log:\n${log}`, |
| 124 | + ); |
| 125 | + } |
| 126 | + |
| 127 | + let healthJson: { status?: string; data?: { up?: boolean } } = {}; |
| 128 | + try { |
| 129 | + healthJson = JSON.parse(healthBody); |
| 130 | + } catch { |
| 131 | + // non-fatal — healthy flag already confirmed data.up === true |
| 132 | + } |
| 133 | + |
| 134 | + console.log(`\n── GET /healthz (HTTP ${healthStatus}) ────────────────────────────────`); |
| 135 | + console.log(" ", JSON.stringify(healthJson)); |
| 136 | + |
| 137 | + console.log(`\ncode-server is live at: ${previewUrl}`); |
| 138 | + console.log(`(open this URL in a browser to use VS Code in the sandbox)`); |
| 139 | + |
| 140 | + // Extract region from preview URL hostname for versions.txt output. |
| 141 | + const hostname = new URL(previewUrl).hostname; |
| 142 | + const region = hostname.split("-").slice(-1)[0]?.split(".").slice(1, -2).join(".") ?? "eu"; |
| 143 | + console.log(`\n── versions (for versions.txt) ─────────────────────────────────`); |
| 144 | + console.log(`fc control plane: ${baseUrl} (region ${region})`); |
| 145 | + console.log(`code-server: ${codeServerVer}`); |
| 146 | +} finally { |
| 147 | + console.log("\ncleanup..."); |
| 148 | + await sandbox.destroy().catch((err) => { |
| 149 | + console.error("destroy failed:", err instanceof Error ? err.message : String(err)); |
| 150 | + }); |
| 151 | + console.log(`destroyed sandbox: ${sandbox.id}`); |
| 152 | +} |
0 commit comments