|
| 1 | +// Example Worker + Durable Object whose container can run scripts on |
| 2 | +// the host. |
| 3 | +// |
| 4 | +// The Durable Object owns one Workspace backed by one container, the |
| 5 | +// same shape as examples/container. The one addition is the `codemode` |
| 6 | +// option on the container backend: with it, a command inside the |
| 7 | +// container can run `codemode < script.js`, and the script runs here, |
| 8 | +// in a dynamic worker, with the notes connector in scope. |
| 9 | +// |
| 10 | +// client ─► Worker POST /c/<name>/exec ─► DO ─► container |
| 11 | +// │ codemode |
| 12 | +// ws://computer.internal/codemode |
| 13 | +// ▼ |
| 14 | +// DO: codemode runtime ─► dynamic worker |
| 15 | + |
| 16 | +import { DurableObject } from "cloudflare:workers"; |
| 17 | + |
| 18 | +import { CodemodeRuntime } from "@cloudflare/codemode"; |
| 19 | +import { |
| 20 | + type DurableObjectStorageLike, |
| 21 | + getWorkspace, |
| 22 | + type WorkspaceOptions, |
| 23 | + WorkspaceProxy, |
| 24 | + withWorkspace, |
| 25 | +} from "@cloudflare/computer"; |
| 26 | +import { |
| 27 | + CloudflareContainerBackend, |
| 28 | + withWorkspaceContainer, |
| 29 | +} from "@cloudflare/computer/backends/container"; |
| 30 | + |
| 31 | +import { NotesConnector } from "./notes-connector.js"; |
| 32 | + |
| 33 | +interface Env { |
| 34 | + LOADER: WorkerLoader; |
| 35 | + CodemodeExample: DurableObjectNamespace<CodemodeExample>; |
| 36 | +} |
| 37 | + |
| 38 | +// WorkspaceProxy is how the container reaches this Durable Object; the |
| 39 | +// codemode runtime keeps its executions in a facet it looks up on |
| 40 | +// ctx.exports under the name CodemodeRuntime. Both must be exported |
| 41 | +// from the Worker entry. |
| 42 | +export { CodemodeRuntime, WorkspaceProxy }; |
| 43 | + |
| 44 | +class ContainerBase extends withWorkspaceContainer(class extends DurableObject<Env> {}) { |
| 45 | + readonly backend = new CloudflareContainerBackend({ |
| 46 | + container: () => this, |
| 47 | + workspace: { binding: "CodemodeExample", id: this.ctx.id.toString() }, |
| 48 | + egress: { mode: "direct" }, |
| 49 | + codemode: { |
| 50 | + ctx: this.ctx, |
| 51 | + loader: this.env.LOADER, |
| 52 | + connectors: () => [new NotesConnector(this.ctx, this.env)], |
| 53 | + }, |
| 54 | + }); |
| 55 | +} |
| 56 | + |
| 57 | +function workspaceOptions(self: InstanceType<typeof ContainerBase>): WorkspaceOptions { |
| 58 | + const { ctx } = self as unknown as { ctx: DurableObjectState }; |
| 59 | + return { |
| 60 | + storage: ctx.storage as unknown as DurableObjectStorageLike, |
| 61 | + backends: [self.backend], |
| 62 | + }; |
| 63 | +} |
| 64 | + |
| 65 | +export class CodemodeExample extends withWorkspace(ContainerBase, workspaceOptions) { |
| 66 | + // Both computerd's /api upgrade and a codemode session's /codemode |
| 67 | + // upgrade arrive here through WorkspaceProxy. |
| 68 | + override async fetch(request: Request): Promise<Response> { |
| 69 | + return this.backend.handleFetch(request); |
| 70 | + } |
| 71 | +} |
| 72 | + |
| 73 | +interface ExecRequest { |
| 74 | + command?: string; |
| 75 | + cwd?: string; |
| 76 | +} |
| 77 | + |
| 78 | +export default { |
| 79 | + async fetch(request: Request, env: Env): Promise<Response> { |
| 80 | + const url = new URL(request.url); |
| 81 | + |
| 82 | + const execMatch = url.pathname.match(/^\/c\/([^/]+)\/exec\/?$/); |
| 83 | + if (execMatch) return handleExec(request, env, execMatch[1]); |
| 84 | + |
| 85 | + if (url.pathname === "/") { |
| 86 | + return new Response( |
| 87 | + [ |
| 88 | + "codemode example", |
| 89 | + "", |
| 90 | + " POST /c/<name>/exec run a command in the container (JSON result)", |
| 91 | + "", |
| 92 | + 'Try: {"command":"codemode types"}', |
| 93 | + "", |
| 94 | + ].join("\n"), |
| 95 | + { headers: { "content-type": "text/plain" } }, |
| 96 | + ); |
| 97 | + } |
| 98 | + |
| 99 | + return new Response("not found", { status: 404 }); |
| 100 | + }, |
| 101 | +} satisfies ExportedHandler<Env>; |
| 102 | + |
| 103 | +async function handleExec(request: Request, env: Env, name: string): Promise<Response> { |
| 104 | + if (request.method !== "POST") { |
| 105 | + return new Response("method not allowed", { status: 405, headers: { allow: "POST" } }); |
| 106 | + } |
| 107 | + let body: ExecRequest; |
| 108 | + try { |
| 109 | + body = (await request.json()) as ExecRequest; |
| 110 | + } catch { |
| 111 | + return errorJSON(new Error("invalid JSON body"), 400); |
| 112 | + } |
| 113 | + if (typeof body.command !== "string" || body.command.length === 0) { |
| 114 | + return errorJSON(new Error("must provide command"), 400); |
| 115 | + } |
| 116 | + |
| 117 | + const stub = env.CodemodeExample.get(env.CodemodeExample.idFromName(name)); |
| 118 | + const ws = await getWorkspace(stub as unknown as Parameters<typeof getWorkspace>[0]); |
| 119 | + try { |
| 120 | + const handle = await ws.runtime.exec(body.command, { cwd: body.cwd, encoding: "utf8" }); |
| 121 | + const result = await handle.result(); |
| 122 | + return new Response(JSON.stringify(result), { |
| 123 | + status: 200, |
| 124 | + headers: { "content-type": "application/json" }, |
| 125 | + }); |
| 126 | + } catch (error) { |
| 127 | + return errorJSON(error, 500); |
| 128 | + } |
| 129 | +} |
| 130 | + |
| 131 | +function errorJSON(error: unknown, status: number): Response { |
| 132 | + const message = error instanceof Error ? error.message : String(error); |
| 133 | + return new Response(JSON.stringify({ error: message }), { |
| 134 | + status, |
| 135 | + headers: { "content-type": "application/json" }, |
| 136 | + }); |
| 137 | +} |
0 commit comments