An open-source, faster Devin alternative
TypeScript
wire: wake a parked computer on a 530, back off when it stays asleep (#1080)
opencomputer-app[bot]9804dc50e1b3
diff --git a/docs/reference/api-schema.mdx b/docs/reference/api-schema.mdxindex 71cea3d9..35033a61 100644--- a/docs/reference/api-schema.mdx+++ b/docs/reference/api-schema.mdx@@ -216,5 +216,6 @@ Other limits are in [Limits and defaults](/reference/limits#api).| `4029` | More than 50 connections for one member || `4400` | The `opc.v1` subprotocol was not offered || `4503` | The relay has no signing key from the host yet. The reason is `{"retryAfterMs":2000}` |+| `4503` | The computer is not connected. The reason is `{"reason":"waking","retryAfterMs":5000}` when it is starting, `{"reason":"asleep","retryAfterMs":60000}` when it is parked and billing refuses to wake it, `{"retryAfterMs":1000}` otherwise |{/* Sources: computer/schema/computer-api.v1.json (x-methods, x-eventTypes, $defs); computer/src/api/schema-methods.ts; computer/src/api/read-methods.ts (events.list default limit, idempotency 24 h); computer/src/wire/limits.ts; computer/src/wire/rpc.ts; computer/src/wire/relay.ts; computer/src/wire/files.ts; computer/src/wire/attachment.ts (detach reasons); computer/src/host/session-writer.ts and computer/src/runner/api/api.ts (QUEUE_MAX); computer/src/host/terminal.ts; computer/src/host/workspace-files.ts; opc/src/cli.rs (schema subcommand) */}diff --git a/services/managed-agents/src/computer/durable-object.ts b/services/managed-agents/src/computer/durable-object.tsindex 96b0b43a..64f0957a 100644--- a/services/managed-agents/src/computer/durable-object.ts+++ b/services/managed-agents/src/computer/durable-object.ts@@ -1779,6 +1779,24 @@ export class ComputerDurableObject extends DurableObject<ComputerEdgeEnv> {return "waking";}+ /**+ * The wire found the tunnel down (530) under a key's connection: wake a+ * parked computer as an API call would, unless billing refuses it (a free+ * trial over), when it stays asleep and the client is told to back off.+ */+ async wireWake(): Promise<"waking" | "asleep" | "gone"> {+ if (!this.previewOrganization()) return "gone";+ const state = this.lifecycle.row()?.state;+ if (state === "provisioning" || state === "waking" || state === "resizing" || state === "ready") return "waking";+ if (state !== "parked" && state !== "parking") return "gone";+ if (!(await this.admitForApi().catch(() => false))) return "asleep";+ console.log(JSON.stringify({ level: "info", event: "computer.wire_wake", accountId: this.setting("accountId") }));+ // lifecycle.wake answers false when a wake is already in flight: still on its way up.+ await this.wakeComputer();+ this.noteActivity();+ return "waking";+ }+/** A preview served a visitor (at most every 30 s per name and isolate): the computer is in use, so it does not park. */notePreviewHit(): void {if (this.previewOrganization() && this.lifecycle.row()?.state === "ready") this.noteActivity();diff --git a/services/managed-agents/src/wire/worker.ts b/services/managed-agents/src/wire/worker.tsindex 2119d332..36014934 100644--- a/services/managed-agents/src/wire/worker.ts+++ b/services/managed-agents/src/wire/worker.ts@@ -8,7 +8,9 @@// /v1/sessions/<cs_…>/workspace/(archive|file|files)// key only → /files/<cs_…>/<op> on the tunnel, both bodies streamed//-// No DO, no D1: one KV read (two for a ticket), WebCrypto, one fetch. The key+// No D1, and no DO on the way in: one KV read (two for a ticket), WebCrypto,+// one fetch. Only a tunnel that is not connected (530) asks the organization's+// computer (COMPUTERS) to wake, and how long the client should wait. The key// and the ticket never leave this Worker. A refused upgrade is still accepted// and closed at once with the code, because a browser sees only 1006 for a// failed one.@@ -25,6 +27,14 @@ export const DEFAULT_TUNNEL_DOMAIN = "w.opencomputer.dev";/** A ticket connection is closed by the relay this long after it opened. */export const TICKET_CONNECTION_TTL_MS = 3600_000;export const RETRY_AFTER_MS = 1_000;+/** A parked computer was woken: it boots in seconds, not one. */+export const WAKING_RETRY_AFTER_MS = 5_000;+/** A computer that stays asleep (billing refuses it) or is gone: no use dialing every second. */+export const ASLEEP_RETRY_AFTER_MS = 60_000;+/** How long one organization's answer is reused, so a client's burst asks its computer once. */+const WAKE_TTL_MS = 10_000;++export type WireComputerState = "waking" | "asleep" | "gone";export const CLOSE = {unauthenticated: 4001,@@ -43,6 +53,8 @@ export interface WireEnv {PREVIEW_PLATFORM_KEY?: string;/** Where the tunnels' wire hostnames live; `w.opencomputer.dev` unless set. */WIRE_TUNNEL_DOMAIN?: string;+ /** The organizations' computers (managed-agents' ComputerDurableObject): asked only on a 530. */+ COMPUTERS?: { getByName(organizationId: string): { wireWake(): Promise<WireComputerState> } };/** Telemetry (work 084): both set turns on one `wireworker.request` per request; the gateway's append token. */TINYBIRD_API_URL?: string;TINYBIRD_APPEND_TOKEN?: string;@@ -174,6 +186,23 @@ export function createWireHandler(options: WireHandlerOptions = {}) {const now = options.now ?? Date.now;const computerKeys = new Map<string, Promise<string>>();+ const wakes = new Map<string, { value: Promise<WireComputerState | null>; until: number }>();++ /** Single-flight per organization: what its computer says to a 530 (null: not asked, or it failed). */+ function computerState(env: WireEnv, org: string): Promise<WireComputerState | null> {+ const cached = wakes.get(org);+ if (cached && cached.until > now()) return cached.value;+ const value = env.COMPUTERS+ ? env.COMPUTERS.getByName(org).wireWake().catch((error: unknown) => {+ log("wire.wake_failed", { org, error: String(error) });+ return null;+ })+ : Promise.resolve(null);+ wakes.set(org, { value, until: now() + WAKE_TTL_MS });+ if (wakes.size > 5_000) wakes.delete(wakes.keys().next().value as string);+ return value;+ }+function keyFor(env: WireEnv, tunnelId: string): Promise<string> {let key = computerKeys.get(tunnelId);if (!key) {@@ -311,7 +340,15 @@ export function createWireHandler(options: WireHandlerOptions = {}) {await response.body?.cancel().catch(() => undefined);log("wire.tunnel_refused", { org: record!.org, status: response.status });f.reason = "tunnel_refused";- if (response.status === 530 || response.status === 502 || response.status === 503 || response.status === 504) {+ if (response.status === 530) {+ f.result = "unavailable";+ f.code = CLOSE.unavailable;+ const state = await computerState(env, record!.org);+ if (state === "waking") return closedSocket(CLOSE.unavailable, { reason: state, retryAfterMs: WAKING_RETRY_AFTER_MS });+ if (state) return closedSocket(CLOSE.unavailable, { reason: state, retryAfterMs: ASLEEP_RETRY_AFTER_MS });+ return closedSocket(CLOSE.unavailable, { retryAfterMs: RETRY_AFTER_MS });+ }+ if (response.status === 502 || response.status === 503 || response.status === 504) {f.result = "unavailable";f.code = CLOSE.unavailable;return closedSocket(CLOSE.unavailable, { retryAfterMs: RETRY_AFTER_MS });diff --git a/services/managed-agents/test/computer-routes.test.ts b/services/managed-agents/test/computer-routes.test.tsindex 46684195..3aca1d3b 100644--- a/services/managed-agents/test/computer-routes.test.ts+++ b/services/managed-agents/test/computer-routes.test.ts@@ -324,6 +324,36 @@ describe("computer routes", () => {expect((await row())?.state).toBe("parked");});+ it("wakes a parked computer for the wire's 530, unless billing refuses it", async () => {+ const ORG = "org_wire_wake";+ const org = () => computers().getByName(ORG);+ const inside = <T,>(fn: (instance: any, state: DurableObjectState) => T) => runInDurableObject(org(), fn as never) as Promise<T>;+ const row = () => inside((instance) => instance.lifecycle.row() as { state: string } | undefined);++ expect(await org().wireWake()).toBe("gone");+ expect(await slackInstall(ORG, "join:T0WIREWAKE:U0INSTALLER")).toMatchObject({ status: 302 });+ for (let i = 0; i < 30 && (await row())?.state !== "ready"; i += 1) {+ await inside((_instance, state) => state.storage.sql.exec("UPDATE alarms SET at = 0"));+ await runDurableObjectAlarm(org());+ }+ expect((await row())?.state).toBe("ready");+ expect(await inside((instance) => instance.lifecycle.park() as Promise<boolean>)).toBe(true);+ for (let i = 0; i < 5; i += 1) {+ await inside((_instance, state) => state.storage.sql.exec("UPDATE alarms SET at = 0"));+ await runDurableObjectAlarm(org());+ }+ expect((await row())?.state).toBe("parked");++ // A free trial over: it stays asleep.+ await inside((instance) => void (instance.admitForApi = async () => false));+ expect(await org().wireWake()).toBe("asleep");+ expect((await row())?.state).toBe("parked");++ await inside((instance) => void (instance.admitForApi = async () => true));+ expect(await org().wireWake()).toBe("waking");+ expect((await row())?.state).toBe("waking");+ });+it("unpaid (work 086): retries a DM that failed, parks despite preview traffic, counts the VM gone only once it is", async () => {const ORG = "org_unpaid";const org = () => computers().getByName(ORG);diff --git a/services/managed-agents/test/wire-worker.test.ts b/services/managed-agents/test/wire-worker.test.tsindex 2e68113b..287740a2 100644--- a/services/managed-agents/test/wire-worker.test.ts+++ b/services/managed-agents/test/wire-worker.test.ts@@ -51,7 +51,7 @@ beforeAll(async () => {type Call = { url: string; init: RequestInit; headers: Headers };-function harness(answer: (call: Call) => Response | Promise<Response> = () => upgraded()) {+function harness(answer: (call: Call) => Response | Promise<Response> = () => upgraded(), computers?: WireEnv["COMPUTERS"]) {const calls: Call[] = [];const handle = createWireHandler({now: () => NOW,@@ -61,7 +61,7 @@ function harness(answer: (call: Call) => Response | Promise<Response> = () => upreturn answer(call);}) as typeof fetch,});- return { calls, handle: (request: Request) => handle(request, wireEnv) };+ return { calls, handle: (request: Request) => handle(request, computers ? { ...wireEnv, COMPUTERS: computers } : wireEnv) };}/** What the relay answers: an accepted socket selecting opc.v1. */@@ -198,6 +198,38 @@ describe("the wire Worker's upgrade", () => {expect(await closeOf(await handle(dial({ "x-api-key": KEYS.full.key })))).toEqual({ code: 4503, reason: { retryAfterMs: 1000 } });}});++ it("on a 530 asks the computer once per burst: waking waits 5 s, asleep or gone a minute, a failed ask 1 s", async () => {+ for (const [state, reason] of [+ ["waking", { reason: "waking", retryAfterMs: 5000 }],+ ["asleep", { reason: "asleep", retryAfterMs: 60_000 }],+ ["gone", { reason: "gone", retryAfterMs: 60_000 }],+ [null, { retryAfterMs: 1000 }],+ ] as const) {+ const asked: string[] = [];+ const computers = {+ getByName: (org: string) => ({+ wireWake: async () => {+ asked.push(org);+ if (!state) throw new Error("no computer object");+ return state;+ },+ }),+ };+ const { handle } = harness(() => new Response("tunnel down", { status: 530 }), computers);+ expect(await closeOf(await handle(dial({ "x-api-key": KEYS.full.key })))).toEqual({ code: 4503, reason });+ expect(await closeOf(await handle(dial({ "x-api-key": KEYS.full.key })))).toEqual({ code: 4503, reason });+ expect(asked).toEqual(["org_wire"]);+ }+ });++ it("does not ask the computer on a 502", async () => {+ const asked: string[] = [];+ const computers = { getByName: (org: string) => ({ wireWake: async () => (asked.push(org), "waking" as const) }) };+ const { handle } = harness(() => new Response("bad gateway", { status: 502 }), computers);+ expect(await closeOf(await handle(dial({ "x-api-key": KEYS.full.key })))).toEqual({ code: 4503, reason: { retryAfterMs: 1000 } });+ expect(asked).toEqual([]);+ });});describe("the wire Worker's workspace files", () => {diff --git a/services/managed-agents/wrangler.wire.jsonc b/services/managed-agents/wrangler.wire.jsoncindex 62b8a02f..1cb89765 100644--- a/services/managed-agents/wrangler.wire.jsonc+++ b/services/managed-agents/wrangler.wire.jsonc@@ -3,8 +3,10 @@// Work 084: the wire's front door, `wire.example.com`. Checks the// credential on the WebSocket upgrade (`/v1`) and the workspace file routes,// signs for the computer's relay (X-Wire-*) and hands the organization's- // tunnel (`<tunnelId>.w.example.com`) the request. No DO, no D1: the- // key records in WIRE_KEYS are written by `managed-agents`.+ // tunnel (`<tunnelId>.w.example.com`) the request. No D1: the key records+ // in WIRE_KEYS are written by `managed-agents`, and COMPUTERS (its+ // ComputerDurableObject) is asked only when a tunnel answers 530, to wake+ // a parked computer.//// Secrets (wrangler secret put --config wrangler.wire.jsonc):// WIRE_TICKET_KEY verifies tickets; the same value as in `managed-agents`@@ -26,6 +28,11 @@"kv_namespaces": [{ "binding": "WIRE_KEYS", "id": "00000000000000000000000000000084" }],+ "durable_objects": {+ "bindings": [+ { "name": "COMPUTERS", "class_name": "ComputerDurableObject", "script_name": "managed-agents" }+ ]+ },"version_metadata": { "binding": "CF_VERSION_METADATA" },// Logs to Axiom through cloudflare-workers/log-tail."tail_consumers": [{ "service": "opencomputer-log-tail-prod" }],