opencode/packages/server/script/workerd-machine-link.worker.ts
Kit Langton 44d32f6ce0
Some checks are pending
bot-nix-hashes / hash (blacksmith-4vcpu-ubuntu-2404, x86_64-linux) (push) Waiting to run
bot-nix-hashes / hash (blacksmith-4vcpu-ubuntu-2404-arm, aarch64-linux) (push) Waiting to run
bot-nix-hashes / hash (blacksmith-6vcpu-macos-latest, aarch64-darwin) (push) Waiting to run
bot-nix-hashes / compute (push) Blocked by required conditions
bot-nix-hashes / publish (push) Blocked by required conditions
check-cli-rs / check (push) Waiting to run
check-nix / nix-eval (push) Waiting to run
check / typecheck (push) Waiting to run
deploy-files / files-build (push) Waiting to run
deploy-files / files-deploy (push) Blocked by required conditions
deploy-site / site-build (push) Waiting to run
deploy-site / site-deploy (push) Blocked by required conditions
deploy / legacy-build (push) Waiting to run
deploy / legacy-deploy (push) Blocked by required conditions
deploy / data-build (push) Waiting to run
deploy / data-deploy (push) Blocked by required conditions
feat(server): support WebSocketPair upgrade for /api/experimental/machine/link on ServerWorkerd (#66954)
2026-11-28 10:58:56 -08:00

41 lines
1.5 KiB
TypeScript

// The Durable Object script/workerd-machine-link.ts runs in Miniflare: `ServerWorkerd` behind a password, with machines
// on unless the request asks `?machines=off`, each in a Durable Object of its own.
import { Effect, Scope } from "effect"
import type { DurableObjectStorage } from "@opencode/core/database/sqlite.workerd"
import { ServerWorkerd } from "../src/workerd"
interface State {
readonly storage: DurableObjectStorage
}
interface Namespace {
idFromName(name: string): unknown
get(id: unknown): { fetch(request: Request): Promise<Response> }
}
export class Home {
private handler: Promise<ServerWorkerd.Handler> | undefined
constructor(private readonly state: State) {}
fetch(request: Request) {
const machines = request.headers.get("x-machines") === "on"
this.handler ??= Effect.runPromise(
ServerWorkerd.create({
storage: this.state.storage,
app: { version: "workerd-machine-link" },
password: "secret",
config: { content: JSON.stringify({ experimental: { machines } }) },
}).pipe(Scope.provide(Scope.makeUnsafe())),
)
return this.handler.then((handler) => handler(request))
}
}
export default {
fetch(request: Request, env: { readonly HOME: Namespace }) {
const machines = new URL(request.url).searchParams.get("machines") ?? "on"
const forwarded = new Request(request, { headers: new Headers(request.headers) })
forwarded.headers.set("x-machines", machines)
return env.HOME.get(env.HOME.idFromName(machines)).fetch(forwarded)
},
}