import { DomainAPI } from "../../control-plane/domain-api.ts"; import * as Effect from "effect/Effect"; import { isDomainFailure } from "../../control-plane/domain-errors.ts"; import { InstallationRegistry as NativeRegistry } from "../../control-plane/installation-registry.ts"; export { AuthVault } from "./oauth-worker.ts"; export { InstallationWorkflow } from "../../control-plane/installation-workflow.ts"; interface Env { INSTALLATIONS: DurableObjectNamespace; } export class InstallationRegistry extends NativeRegistry { fixturePut(id: string, value: unknown) { return this.ctx.storage.put(`installation:${id}`, value); } } const domainId = "d".repeat(40); let attached = false; let losePutReply = false; let existing: "none" | "foreign-worker" | "dns" = "none"; const trace: Array<{ path: string; method: string; body: unknown }> = []; const ok = (result: unknown, result_info?: unknown) => Response.json({ success: true, result, ...(result_info ? { result_info } : {}), }); function installation(id: string, ownerSubject: string) { const release = { version: "1.0.0", sourceRevision: "1".repeat(40), artifactDigest: "2".repeat(64), }; return { schemaVersion: 1, installationId: id, ownerSubject, accountId: "a".repeat(32), createdAt: 1, updatedAt: 2, revision: 7, resources: { workerName: `flarebot-${id}`, sandboxApplicationName: `flarebot-shell-${id}`, personalAgentNamespaceId: "3".repeat(32), sandboxNamespaceId: "4".repeat(32), sandboxApplicationId: "5".repeat(32), runtimeOrigin: `https://flarebot-${id}.fixture.workers.dev`, }, desiredRelease: release, installedRelease: { ...release, installedAt: 2 }, status: "ready", progress: "complete", errorCode: null, operationId: "6".repeat(32), }; } function registry(env: Env, subject: string) { return env.INSTALLATIONS.getByName( `owner:${subject}`, ) as unknown as DurableObjectStub; } export default { async fetch(request: Request, env: Env) { const url = new URL(request.url); const body = request.method === "POST" ? ((await request.json()) as any) : {}; if (url.pathname === "/registry") { const stub = registry(env, body.owner); if (body.action === "seed") return Response.json( await stub .fixturePut( body.id, body.value ?? installation(body.id, body.owner), ) .then(() => ({ ok: true })), ); if (body.action === "get") return Response.json( await stub.get(body.subject ?? body.owner, body.id), ); if (body.action === "getDomain") return Response.json( await stub.getDomain(body.subject ?? body.owner, body.id), ); if (body.action === "start") return Response.json( await stub.startDomain( body.owner, body.id, body.requestId, body.intent, ), ); if (body.action === "update") return Response.json( await stub.updateDomain( body.owner, body.id, body.operationId, body.revision, body.changes, ), ); } if (url.pathname === "/api/reset") { attached = false; losePutReply = !!body.losePutReply; existing = body.existing ?? "none"; trace.length = 0; return Response.json({ ok: true }); } if (url.pathname === "/api/run") { const id = body.installationId ?? "b".repeat(32); const record = installation(id, "owner"); const domain = { revision: 1, origin: "https://bot.example.com", hostname: "bot.example.com", zoneId: "c".repeat(32), domainId: body.savedDomainId ?? null, operationId: "e".repeat(32), status: "connecting", action: "attach", errorCode: null, writeIntent: body.writeIntent ?? true, }; const network = async (input: RequestInfo | URL, init?: RequestInit) => { const outgoing = new Request(input, init); const path = new URL(outgoing.url).pathname + new URL(outgoing.url).search; const requestBody = outgoing.body ? await outgoing.clone().json() : null; trace.push({ path, method: outgoing.method, body: requestBody }); if (path === `/client/v4/zones/${domain.zoneId}`) return ok({ id: domain.zoneId, name: "example.com", account: { id: record.accountId }, status: "active", }); if (path.includes("/dns_records")) return ok(existing === "dns" ? [{ id: "x" }] : []); if (path.includes("/workers/domains?")) { if (!attached && existing !== "foreign-worker") return ok([], { total_pages: 1 }); return ok( [ { id: domainId, hostname: domain.hostname, zone_id: domain.zoneId, service: existing === "foreign-worker" ? "somebody-else" : record.resources.workerName, environment: "production", }, ], { total_pages: 1 }, ); } if (path.endsWith("/domains/records") && outgoing.method === "PUT") { attached = true; if (losePutReply) { losePutReply = false; throw new Error("lost reply"); } return ok({}); } if ( path.endsWith(`/workers/domains/${domainId}`) && outgoing.method === "DELETE" ) { attached = false; return ok({}); } throw new Error(`unexpected request ${outgoing.method} ${path}`); }; try { const api = new DomainAPI( "token", record as any, network as typeof fetch, ); const value = body.operation === "preflight" ? await Effect.runPromise(api.preflight(domain as any)) : body.operation === "remove" ? await Effect.runPromise(api.remove(domain as any)) : body.operation === "find" ? await Effect.runPromise(api.find(domain as any)) : await Effect.runPromise(api.attach(domain as any)); return Response.json({ ok: true, value, trace }); } catch (error) { return Response.json({ ok: false, error: isDomainFailure(error) ? error.code : "unexpected", trace, }); } } return new Response(null, { status: 404 }); }, } satisfies ExportedHandler;