import { DurableObject } from "cloudflare:workers"; import { containerLimits } from "./container-config"; import { closeContainerSession, openContainerSession } from "./container-meter"; const MINUTE_MS = 60 * 1000; const CHECK_MS = MINUTE_MS; const READY_ATTEMPTS = 60; const READY_DELAY_MS = 500; const ACTIVITY_WRITE_MS = 30 * 1000; const MAX_SYNC_FILES = 300; const DEFAULT_COLS = 120; const DEFAULT_ROWS = 32; const MAX_TERMINALS = 8; const WORKSPACE = "/workspace"; type Meta = { accountId: string; repoId: string; branch: string; repoDir: string; sessionId: string; startedAt: number; lastActivity: number; }; export type ContainerStart = { accountId: string; repoId: string; branch: string; repoName: string; cloneUrl: string; publicRemote: string; author: { name: string; email: string }; }; export type ContainerState = { state: "stopped" | "running"; startedAt: number | null; lastActivity: number | null; repoDir: string | null; }; const encoder = new TextEncoder(); function safeRelative(path: string): string { const parts = path.split("/"); if (path.startsWith("/") || parts.some((part) => part === ".." || part === "" || part === ".git")) { throw new Error(`Refusing to write ${path}`); } return path; } /** * One container per (account, repo, branch) for the editor's opt-in "Run in container" mode. It checks * out the branch read-only (commits still go through the forge, so protections apply), serves PTY * terminals over WebSockets, proxies previews of container ports, sleeps after the idle window and is * hard-stopped at the session cap. Each start/stop is metered in editor_container_sessions. */ export class EditorContainer extends DurableObject { private lastActivityWrite = 0; private terminals = 0; private async meta(): Promise { return (await this.ctx.storage.get("meta")) ?? null; } private get container(): Container { const container = this.ctx.container; if (!container) throw new Error("EditorContainer has no container binding"); return container; } async status(): Promise { const meta = await this.meta(); if (!meta || !this.ctx.container?.running) return { state: "stopped", startedAt: null, lastActivity: null, repoDir: null }; return { state: "running", startedAt: meta.startedAt, lastActivity: meta.lastActivity, repoDir: meta.repoDir }; } /** Boots (or reuses) the container and checks out the branch. The caller has authorized and checked quota. */ async start(input: ContainerStart): Promise { const existing = await this.meta(); if (existing && this.container.running) { await this.touch(true); return this.status(); } if (existing) await this.finish(existing, "restarted"); const container = this.container; if (!container.running) container.start({ enableInternet: true }); const limits = containerLimits(); await container.setInactivityTimeout(limits.capHours * 60 * MINUTE_MS); await this.waitReady(); const repoDir = `${WORKSPACE}/${input.repoName.replace(/[^\w.-]/g, "_")}`; const clone = await container.exec( [ "sh", "-c", 'rm -rf "$1" && git clone --quiet --depth 50 --branch "$2" "$3" "$1" && cd "$1" && git remote set-url origin "$4" && git config user.name "$5" && git config user.email "$6"', "sh", repoDir, input.branch, input.cloneUrl, input.publicRemote, input.author.name, input.author.email, ], { stdout: "ignore", stderr: "pipe", env: { GIT_TERMINAL_PROMPT: "0" } }, ); const [code, stderr] = await Promise.all([clone.exitCode, clone.stderr ? new Response(clone.stderr).text() : ""]); if (code !== 0) { await container.destroy().catch(() => undefined); throw new Error(`Checkout failed: ${stderr.replaceAll(input.cloneUrl, "").slice(0, 300)}`); } const now = Date.now(); const sessionId = await openContainerSession(input.accountId, input.repoId, input.branch); await this.ctx.storage.put("meta", { accountId: input.accountId, repoId: input.repoId, branch: input.branch, repoDir, sessionId, startedAt: now, lastActivity: now, } satisfies Meta); await this.ctx.storage.setAlarm(now + CHECK_MS); return this.status(); } async stop(reason = "stopped"): Promise { const meta = await this.meta(); return meta ? this.finish(meta, reason) : 0; } /** Writes the room's pending edits into the checkout so terminals and tasks see what the editor shows. */ async sync(changes: Array<{ path: string; content: string | null }>): Promise { const meta = await this.meta(); if (!meta || !this.container.running) throw new Error("The container isn't running"); let written = 0; for (const change of changes.slice(0, MAX_SYNC_FILES)) { const target = `${meta.repoDir}/${safeRelative(change.path)}`; const command = change.content === null ? ["rm", "-f", target] : ["sh", "-c", 'mkdir -p "$(dirname "$1")" && cat > "$1"', "sh", target]; const bytes = change.content === null ? null : encoder.encode(change.content); const process = await this.container.exec(command, { stdin: bytes ? new ReadableStream({ start(controller) { controller.enqueue(bytes); controller.close(); }, }) : undefined, stdout: "ignore", stderr: "ignore", }); if ((await process.exitCode) === 0) written++; } await this.touch(true); return written; } /** Forwards an HTTP request to a port inside the container (port previews). */ async proxy(port: number, request: Request): Promise { if (!(await this.meta()) || !this.container.running) return new Response("Container not running\n", { status: 503 }); await this.touch(false); return this.container.getTcpPort(port).fetch(request); } /** PTY terminal over a WebSocket: binary frames carry I/O, JSON text frames carry resize and exit. */ async fetch(request: Request): Promise { if (request.headers.get("upgrade") !== "websocket") return new Response("Expected websocket", { status: 426 }); const meta = await this.meta(); if (!meta || !this.container.running) return new Response("Container not running", { status: 409 }); if (this.terminals >= MAX_TERMINALS) return new Response("Too many terminals", { status: 429 }); const url = new URL(request.url); const command = url.searchParams.get("command"); const cols = Number(url.searchParams.get("cols")) || DEFAULT_COLS; const rows = Number(url.searchParams.get("rows")) || DEFAULT_ROWS; const pair = new WebSocketPair(); const socket = pair[1]; socket.accept(); void this.runTerminal(socket, meta, command, cols, rows); return new Response(null, { status: 101, webSocket: pair[0], headers: { "sec-websocket-protocol": request.headers.get("x-editor-protocol") ?? "" }, }); } private async runTerminal(socket: WebSocket, meta: Meta, command: string | null, cols: number, rows: number) { this.terminals++; try { const process = await this.container.exec(command ? ["bash", "-lc", command] : ["bash", "-l"], { cwd: meta.repoDir, env: { TERM: "xterm-256color", HOME: "/root", GITFOR_BRANCH: meta.branch }, pty: { cols, rows }, stdin: "pipe", stdout: "pipe", stderr: "combined", }); const writer = process.stdin?.getWriter() ?? null; socket.addEventListener("message", (event) => { void this.touch(false); if (typeof event.data === "string") { try { const message = JSON.parse(event.data) as { type?: string; cols?: number; rows?: number }; if (message.type === "resize" && message.cols && message.rows) process.resize(message.cols, message.rows); } catch { return; } return; } void writer?.write(new Uint8Array(event.data as ArrayBuffer)).catch(() => undefined); }); socket.addEventListener("close", () => { process.kill(); }); const reader = process.stdout?.getReader(); if (reader) { for (;;) { const { done, value } = await reader.read(); if (done) break; void this.touch(false); socket.send(value); } } const code = await process.exitCode; socket.send(JSON.stringify({ type: "exit", code })); socket.close(1000, "exited"); } catch (error) { try { socket.send(JSON.stringify({ type: "error", message: error instanceof Error ? error.message : "Terminal failed" })); socket.close(1011, "terminal failed"); } catch { // socket already closed } } finally { this.terminals--; } } async alarm(): Promise { const meta = await this.meta(); if (!meta) return; const limits = containerLimits(); const now = Date.now(); if (!this.container.running) { await this.finish(meta, "exited"); } else if (now - meta.startedAt >= limits.capHours * 60 * MINUTE_MS) { await this.finish(meta, "cap"); } else if (now - meta.lastActivity >= limits.idleMinutes * MINUTE_MS) { await this.finish(meta, "idle"); } else { await this.ctx.storage.setAlarm(now + CHECK_MS); } } private async touch(force: boolean): Promise { const now = Date.now(); if (!force && now - this.lastActivityWrite < ACTIVITY_WRITE_MS) return; this.lastActivityWrite = now; const meta = await this.meta(); if (meta) await this.ctx.storage.put("meta", { ...meta, lastActivity: now } satisfies Meta); } private async finish(meta: Meta, reason: string): Promise { await this.ctx.storage.delete("meta"); await this.ctx.storage.deleteAlarm(); if (this.ctx.container?.running) await this.ctx.container.destroy(reason).catch(() => undefined); return closeContainerSession(meta.sessionId, reason); } private async waitReady(): Promise { for (let attempt = 0; attempt < READY_ATTEMPTS; attempt++) { try { const probe = await this.container.exec(["true"], { stdout: "ignore", stderr: "ignore" }); if ((await probe.exitCode) === 0) return; } catch { // still booting } await new Promise((resolve) => setTimeout(resolve, READY_DELAY_MS)); } throw new Error("The container didn't start in time"); } }