Skip to content

An open-source, faster Devin alternative

TypeScript

api-edge: remove the sandbox API, cell proxy, edge pool and VM-DO paths

Mohamed Habib via Computerd946445ff64f
diff --git a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
index 7cc39717..ad9a464b 100644
--- a/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
+++ b/cloudflare-workers/api-edge/src/agent_runtime_usage.test.ts
@@ -22,7 +22,6 @@ function env(overrides: Partial<AutumnEnv> = {}): AutumnEnv {
AUTUMN_WEBHOOK_SECRET: "whsec_test",
EVENT_SECRET: "event-secret",
AGENT_RUNTIME_USAGE_HMAC_SECRET: "agent-runtime-secret",
- CF_ADMIN_SECRET: "admin-secret",
OPENCOMPUTER_DB: {} as D1Database,
...overrides,
};
@@ -97,7 +96,7 @@ describe("managed-agent runtime usage billing", () => {
expect(response.status).toBe(200);
expect(fetchMock.mock.calls.filter(([url]) => String(url).includes("/customers/org_1"))).toHaveLength(2);
- expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);
+ expect(writes.some((sql) => sql.includes("billing_warning = ?7"))).toBe(true);
});
it("replaces a trial_days warning once the minutes are the nearer limit", async () => {
@@ -112,7 +111,7 @@ describe("managed-agent runtime usage billing", () => {
await post({ quantity_seconds: 1_200, close_reason: "turn_settled", idempotency_key: "crt_1:5" }, { OPENCOMPUTER_DB: db });
- expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);
+ expect(writes.some((sql) => sql.includes("billing_warning = ?7"))).toBe(true);
});
it("does not re-project when the stored warning still stands", async () => {
@@ -126,7 +125,7 @@ describe("managed-agent runtime usage billing", () => {
await post({ close_reason: "turn_settled", idempotency_key: "crt_1:6" }, { OPENCOMPUTER_DB: db });
expect(fetchMock.mock.calls.filter(([url]) => String(url).includes("/customers/org_1"))).toHaveLength(1);
- expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(false);
+ expect(writes.some((sql) => sql.includes("billing_warning = ?7"))).toBe(false);
});
it("bills an org on a work-minute plan in work minutes", async () => {
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
index 70d68676..68ace444 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.test.ts
@@ -331,7 +331,6 @@ describe("billing funnel events from Autumn", () => {
function fakeDb(usagePlan: string, pastDueAt: number | null = null) {
const org: Record<string, unknown> = {
is_halted: 0,
- autumn_concurrency_override: null,
usage_plan: usagePlan,
payment_past_due_at: pastDueAt,
};
@@ -342,7 +341,7 @@ describe("billing funnel events from Autumn", () => {
return {
bind(...args: unknown[]) {
return {
- first: async () => (sql.includes("FROM sandboxes_index") ? null : { ...org }),
+ first: async () => ({ ...org }),
run: async () => {
if (sql.includes("INSERT OR IGNORE INTO autumn_webhook_deliveries")) {
if (deliveries.has(args[0] as string)) return { meta: { changes: 0 } };
@@ -356,8 +355,8 @@ describe("billing funnel events from Autumn", () => {
} else if (sql.includes("SET is_halted")) {
org.is_halted = args[0];
org.halted_at = args[1];
- org.usage_plan = args[3];
- org.billing_warning = args[7];
+ org.usage_plan = args[2];
+ org.billing_warning = args[6];
}
return { meta: { changes: 1 } };
},
diff --git a/cloudflare-workers/api-edge/src/autumn_webhook.ts b/cloudflare-workers/api-edge/src/autumn_webhook.ts
index 6384a0c2..1a68978a 100644
--- a/cloudflare-workers/api-edge/src/autumn_webhook.ts
+++ b/cloudflare-workers/api-edge/src/autumn_webhook.ts
@@ -5,11 +5,11 @@
// "re-check, not payload" design: the ONLY field we read from the body is
// data.customer_id (= our org id). We then GET the customer from Autumn and
// project the *authoritative* balance + plans into D1:
-// - orgs.is_halted / halted_at (credits balance <= 0)
-// - orgs.max_concurrent_sandboxes (highest active concurrency plan,
-// unless autumn_concurrency_override is set)
-// On a halt/resume transition we dispatch /admin/halt-org or /admin/resume-org
-// to the cells running the org's sandboxes (same HMAC scheme the DO used).
+// - orgs.is_halted / halted_at / halt_reason
+// - orgs.usage_plan / billing_warning
+// The projection is all there is: the edge gates (the managed-agents credit
+// gate among them) read D1. Halts are no longer dispatched to sandbox cells,
+// and orgs.max_concurrent_sandboxes is no longer written (097 step 7.2).
//
// Event catalog (Svix): billing.updated, billing.auto_topup_succeeded,
// billing.auto_topup_failed, balances.limit_reached, balances.usage_alert_triggered.
@@ -35,9 +35,8 @@ export interface AutumnSyncEnv extends AutumnApiEnv, BillingEventsEnv, LoopsEnv
OPENCOMPUTER_DB: D1Database;
}
-// AutumnEnv adds the secrets needed to dispatch halt to cells + verify webhooks.
+// AutumnEnv adds the secrets needed to verify webhooks and internal triggers.
export interface AutumnEnv extends AutumnSyncEnv {
- CF_ADMIN_SECRET: string;
EVENT_SECRET: string;
AUTUMN_WEBHOOK_SECRET: string;
BROWSER_USAGE_HMAC_SECRET?: string;
@@ -58,15 +57,6 @@ const TURN_CLOSE_REASON = "turn_settled";
const LEASE_CLOSE_REASONS = new Set(["suspended", "terminated", "session_ended", "heartbeat_expired"]);
const SVIX_TOLERANCE_SEC = 300;
-// Mirror of internal/billing/autumn.ConcurrencyByPlan — keep in sync.
-const CONCURRENCY_BY_PLAN: Record<string, number> = {
- base: 50,
- concurrency_pro: 100,
- concurrency_pro_plus: 600,
- concurrency_pro_plus_plus: 1000,
-};
-const DEFAULT_CONCURRENCY = 50;
-
export type UsagePlan = "base" | "pro" | "max";
const USAGE_PLAN_RANK: Record<string, number> = { base: 0, pro: 1, max: 2 };
@@ -368,11 +358,10 @@ export function planChangeKind(from: UsagePlan, to: UsagePlan, lapsed: boolean):
return USAGE_PLAN_RANK[to] > USAGE_PLAN_RANK[from] ? "upgrade" : "downgrade";
}
-// autumnProjectInternal is the cell/reconciler-facing trigger for the SAME
-// re-check+project logic, behind the in-house EVENT_SECRET HMAC ({ts}.{body}).
-// The cell's inline halt (off track()) and the Go reconciler POST this so they
-// can drive the D1 projection without owning Autumn reads or D1 writes —
-// keeping all of that at the edge, exactly as the Svix path does.
+// autumnProjectInternal is the internal trigger for the SAME re-check+project
+// logic, behind the in-house EVENT_SECRET HMAC ({ts}.{body}). The Go reconciler
+// POSTs this so it can drive the D1 projection without owning Autumn reads or
+// D1 writes — keeping all of that at the edge, exactly as the Svix path does.
export async function autumnProjectInternal(req: Request, env: AutumnEnv): Promise<Response> {
const rawBody = await req.text();
const ts = req.headers.get("X-Timestamp") ?? "";
@@ -382,7 +371,7 @@ export async function autumnProjectInternal(req: Request, env: AutumnEnv): Promi
if (!Number.isFinite(tsNum) || Math.abs(Date.now() / 1000 - tsNum) > SVIX_TOLERANCE_SEC) {
return json({ error: "timestamp out of window" }, 401);
}
- // POST signs {ts}.{path}{query}.{body} — matches edgeclient.sign + templates.ts.
+ // POST signs {ts}.{path}{query}.{body} — matches edgeclient.sign.
const url = new URL(req.url);
const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}.${rawBody}`);
if (!timingSafeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
@@ -804,13 +793,12 @@ export async function refreshWarning(env: AutumnEnv, orgID: string, customer?: A
export const TRIAL_WARN_AFTER_SEC = (TRIAL_DAYS - TRIAL_WARN_DAYS_LEFT) * DAY_SEC;
// syncAutumnToD1 reads Autumn's authoritative balance/plans and writes the D1
-// projection (is_halted / usage_plan / max_concurrent) WITHOUT any cell dispatch. Returns the
-// halt transition so callers can decide whether to actively hibernate. Reusable
-// by the dashboard (checkout-return) since it needs no dispatch secrets.
+// projection (is_halted / halt_reason / usage_plan / billing_warning). Returns
+// the halt transition. Reusable by the dashboard (checkout-return) since it
+// needs no secrets beyond the Autumn key.
export interface AutumnSyncResult {
customer: AutumnCustomer;
creditsRemaining: number; // dollars
- maxConcurrent: number;
halted: boolean;
haltReason: HaltReason | null;
warning: BillingWarning | null;
@@ -827,17 +815,15 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
const creditsRemaining = cust.balances?.[CREDITS_FEATURE_ID]?.remaining ?? 0;
const usagePlan = activeUsagePlan(cust);
- const projectedMaxConcurrent = maxConcurrency(cust.subscriptions ?? []);
const nowSec = Math.floor(Date.now() / 1000);
const prevRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted, halted_at, autumn_concurrency_override, usage_plan, payment_past_due_at, trial_started_at, billing_warning FROM orgs WHERE id = ?1",
+ "SELECT is_halted, halted_at, usage_plan, payment_past_due_at, trial_started_at, billing_warning FROM orgs WHERE id = ?1",
)
.bind(orgID)
.first<{
is_halted: number;
halted_at: number | null;
- autumn_concurrency_override: number | null;
usage_plan: UsagePlan;
payment_past_due_at: number | null;
trial_started_at: number | null;
@@ -851,7 +837,6 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
// Since when the org has been halted, for any reason: kept across projections
// while it stays halted (blue parks an unpaid computer 7 days in, 086).
const haltedAt = halted ? (wasHalted && prevRow?.halted_at ? prevRow.halted_at : nowSec) : null;
- const maxConcurrent = prevRow?.autumn_concurrency_override ?? projectedMaxConcurrent;
// Compare-and-set the plan first: the webhook, checkout-return and the cron can
// project the same change concurrently, and only the writer that moves it emits.
@@ -874,12 +859,12 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
// billing_warning_at marks when the org started being warned and holds while
// any warning stands, so a surface can tell each reason once per episode.
await env.OPENCOMPUTER_DB.prepare(
- `UPDATE orgs SET is_halted = ?1, halted_at = ?2, max_concurrent_sandboxes = ?3, usage_plan = ?4, updated_at = ?5,
- halt_reason = ?7, billing_warning = ?8,
- billing_warning_at = CASE WHEN ?8 IS NULL THEN NULL ELSE COALESCE(billing_warning_at, ?5) END
- WHERE id = ?6`,
+ `UPDATE orgs SET is_halted = ?1, halted_at = ?2, usage_plan = ?3, updated_at = ?4,
+ halt_reason = ?6, billing_warning = ?7,
+ billing_warning_at = CASE WHEN ?7 IS NULL THEN NULL ELSE COALESCE(billing_warning_at, ?4) END
+ WHERE id = ?5`,
)
- .bind(halted ? 1 : 0, haltedAt, maxConcurrent, usagePlan, nowSec, orgID, reason, warning)
+ .bind(halted ? 1 : 0, haltedAt, usagePlan, nowSec, orgID, reason, warning)
.run();
// After the writes, so the event's send time never widens the window in which
@@ -903,12 +888,12 @@ export async function syncAutumnToD1(env: AutumnSyncEnv, orgID: string): Promise
}
if (planChange) await syncLoopsPlan(env, orgID, usagePlan);
- return { customer: cust, creditsRemaining, maxConcurrent, halted, haltReason: reason, warning, wasHalted, usagePlan };
+ return { customer: cust, creditsRemaining, halted, haltReason: reason, warning, wasHalted, usagePlan };
}
// autumnSetProviderInternal flips D1 orgs.billing_provider for one org (the
// migrate tool's D1 half; cell-PG is flipped by the Go cmd). EVENT_SECRET HMAC.
-// On →autumn it also projects (is_halted/max_concurrent from Autumn) so the
+// On →autumn it also projects (is_halted etc. from Autumn) so the
// edge gates are correct the instant the flag flips. Body: {org_id, provider}.
export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): Promise<Response> {
const rawBody = await req.text();
@@ -944,47 +929,13 @@ export async function autumnSetProviderInternal(req: Request, env: AutumnEnv): P
return json({ ok: true, org_id: p.org_id, provider: p.provider });
}
-// projectOrg = syncAutumnToD1 + actively hibernate on a fresh halt.
-//
-// On halt we dispatch /admin/halt-org to hibernate running boxes. On RESUME we
-// do NOT dispatch — D1.is_halted is already cleared, which unblocks the gates;
-// hibernated boxes wake lazily on the next request. This is the locked "no
-// auto-wake for prepaid" decision: a top-up unblocks but never force-wakes.
+// projectOrg re-checks Autumn and writes the D1 projection. It used to also
+// dispatch /admin/halt-org to the sandbox cells on a fresh halt; the cells are
+// retired (097 step 7.2), so the projection is the whole job. The edge gates,
+// the managed-agents credit gate among them, read is_halted from D1, so a halt
+// still takes effect the moment it is projected, and a top-up clears it.
export async function projectOrg(env: AutumnEnv, orgID: string): Promise<void> {
- const r = await syncAutumnToD1(env, orgID);
- if (!r || !r.halted) return;
- // Dispatch halt on the fresh transition, OR whenever a halted org STILL has
- // running sandboxes — so a halt is eventually complete even if a single
- // hibernation flaked on the first dispatch. The autumn-meter cron + the
- // webhook both call projectOrg, so this is the straggler safety net (a halted
- // org with a leftover running box gets re-dispatched on the next sight).
- if (!r.wasHalted || (await hasRunningSandboxes(env, orgID))) {
- // The cells stamp and resume by "credits_exhausted" whatever the cause; the
- // reason a surface shows lives in orgs.halt_reason.
- await dispatchToCells(env, orgID, "/admin/halt-org", { org_id: orgID, reason: "credits_exhausted" });
- }
-}
-
-// hasRunningSandboxes — does this org have any sandbox still running (across all
-// cells)? Cheap indexed lookup; gates the straggler re-dispatch so a fully
-// hibernated halted org costs no dispatch.
-async function hasRunningSandboxes(env: AutumnSyncEnv, orgID: string): Promise<boolean> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT 1 AS one FROM sandboxes_index WHERE org_id = ?1 AND status = 'running' LIMIT 1",
- )
- .bind(orgID)
- .first<{ one: number }>();
- return row != null;
-}
-
-function maxConcurrency(subs: AutumnSubscription[]): number {
- let limit = DEFAULT_CONCURRENCY;
- for (const s of subs) {
- if (s.status && s.status !== "active") continue;
- const v = CONCURRENCY_BY_PLAN[s.plan_id];
- if (v !== undefined && v > limit) limit = v;
- }
- return limit;
+ await syncAutumnToD1(env, orgID);
}
// createAutumnCustomer provisions an Autumn customer (id = our org UUID) →
@@ -1348,53 +1299,6 @@ export async function autumnSetAutoTopup(
if (!resp.ok) throw new Error(`autumn set auto-topup ${resp.status}: ${await resp.text()}`);
}
-// ── cell dispatch (mirrors the DO's halt/resume fan-out) ───────────────────
-
-interface CellRow {
- cell_id: string;
- base_url: string;
-}
-const DISPATCH_BACKOFFS_MS = [200, 1000, 3000];
-
-async function dispatchToCells(env: AutumnEnv, orgID: string, path: string, payload: unknown): Promise<void> {
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT DISTINCT c.cell_id, c.base_url
- FROM sandboxes_index s
- JOIN cells c ON s.cell_id = c.cell_id
- WHERE s.org_id = ?1 AND s.status IN ('running', 'hibernated', 'migrating')`,
- )
- .bind(orgID)
- .all<CellRow>();
- const cells = results ?? [];
- if (cells.length === 0) return;
-
- const body = JSON.stringify(payload);
- await Promise.all(cells.map((c) => postWithRetry(env, c, path, body)));
-}
-
-async function postWithRetry(env: AutumnEnv, cell: CellRow, path: string, body: string): Promise<void> {
- const ts = Math.floor(Date.now() / 1000).toString();
- const sig = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${body}`);
- const url = cell.base_url.replace(/\/$/, "") + path;
-
- for (let attempt = 0; attempt <= DISPATCH_BACKOFFS_MS.length; attempt++) {
- try {
- const resp = await fetch(url, {
- method: "POST",
- headers: { "content-type": "application/json", "X-Timestamp": ts, "X-Signature": sig },
- body,
- });
- if (resp.status >= 200 && resp.status < 300) return;
- console.error(`autumn-webhook: dispatch ${path} → ${cell.cell_id} status=${resp.status} attempt=${attempt}`);
- } catch (err) {
- console.error(`autumn-webhook: dispatch ${path} → ${cell.cell_id} error=${(err as Error).message}`);
- }
- if (attempt < DISPATCH_BACKOFFS_MS.length) {
- await new Promise((r) => setTimeout(r, DISPATCH_BACKOFFS_MS[attempt]));
- }
- }
-}
-
// ── crypto ─────────────────────────────────────────────────────────────────
// Svix signature: base64( HMAC_SHA256( "{id}.{ts}.{body}", base64decode(secret) ) ),
diff --git a/cloudflare-workers/api-edge/src/billing_onramp.test.ts b/cloudflare-workers/api-edge/src/billing_onramp.test.ts
index 2e8915a6..46b936ab 100644
--- a/cloudflare-workers/api-edge/src/billing_onramp.test.ts
+++ b/cloudflare-workers/api-edge/src/billing_onramp.test.ts
@@ -19,7 +19,6 @@ vi.mock("./autumn_webhook", async (importOriginal) => ({
syncAutumnToD1: vi.fn(async () => ({
customer: { subscriptions: [] },
creditsRemaining: 10,
- maxConcurrent: 1,
halted: false,
haltReason: null,
wasHalted: false,
diff --git a/cloudflare-workers/api-edge/src/browser_usage.test.ts b/cloudflare-workers/api-edge/src/browser_usage.test.ts
index 8a390668..a342d616 100644
--- a/cloudflare-workers/api-edge/src/browser_usage.test.ts
+++ b/cloudflare-workers/api-edge/src/browser_usage.test.ts
@@ -26,7 +26,6 @@ function env(db: D1Database = {} as D1Database): AutumnEnv {
AUTUMN_WEBHOOK_SECRET: "whsec_test",
EVENT_SECRET: "event-secret",
BROWSER_USAGE_HMAC_SECRET: "browser-usage-secret",
- CF_ADMIN_SECRET: "admin-secret",
OPENCOMPUTER_DB: db,
};
}
@@ -73,7 +72,7 @@ describe("browser usage billing", () => {
.mockResolvedValue(new Response(null, { status: 200 }));
expect((await postUsage(env(db))).status).toBe(200);
- expect(writes.some((sql) => sql.includes("billing_warning = ?8"))).toBe(true);
+ expect(writes.some((sql) => sql.includes("billing_warning = ?7"))).toBe(true);
});
it("tracks browser runtime into Autumn with the signed usage payload", async () => {
diff --git a/cloudflare-workers/api-edge/src/cli_auth.test.ts b/cloudflare-workers/api-edge/src/cli_auth.test.ts
index 9e4c9c13..b8190117 100644
--- a/cloudflare-workers/api-edge/src/cli_auth.test.ts
+++ b/cloudflare-workers/api-edge/src/cli_auth.test.ts
@@ -74,14 +74,6 @@ class FakeStatement {
if (this.sql.includes("JOIN org_memberships")) {
return { results: this.db.memberships as T[] };
}
- if (this.sql.includes("FROM cells") && this.sql.includes("accepts_new_orgs = 1")) {
- return {
- results: [{
- cell_id: "azure-us-east-2-a",
- region: "us-east-2",
- } as T],
- };
- }
return { results: [] };
}
@@ -100,6 +92,9 @@ class FakeStatement {
class FakeDB {
executed: CapturedStatement[] = [];
+ // Every SQL string prepared, read or write, so a test can prove a table was
+ // never touched.
+ prepared: string[] = [];
memberships: FakeMembership[];
pendingInvitations: { id: string; org_id: string; role: string }[] = [];
user: { id: string; email: string; name: string } | null;
@@ -125,6 +120,7 @@ class FakeDB {
}
prepare(sql: string): FakeStatement {
+ this.prepared.push(sql);
return new FakeStatement(this, sql);
}
@@ -660,10 +656,11 @@ describe("CLI device authorization edge contract", () => {
expect(userInsert?.sql).toContain("durable_sessions_enabled");
expect(userInsert?.sql).toContain("infrastructure_enabled");
expect(userInsert?.sql).toMatch(/VALUES\s*\(\?1, \?2, \?3, \?4, \?5, 0, 0\)/);
- expect(orgInsert?.args[3]).toBe("azure-us-east-2-a");
+ // No home cell: the legacy NOT NULL home_cell column gets '' (097 step 7.2).
+ expect(orgInsert?.sql).toMatch(/VALUES\s*\(\?1, \?2, \?3, 'free', '', 1,/);
// Legacy billing (no Autumn customer) has no trial.
expect(orgInsert?.sql).toContain("trial_started_at");
- expect(orgInsert?.args[8]).toBeNull();
+ expect(orgInsert?.args[6]).toBeNull();
expect(membershipInsert?.args[0]).toBe(body.org.id);
expect(membershipInsert?.args[1]).toBe(body.user.id);
expect(keyInsert?.args[1]).toBe(body.org.id);
@@ -685,9 +682,35 @@ describe("CLI device authorization edge contract", () => {
expect(fetchMock.mock.calls.some(([url]) => String(url).endsWith("/customers"))).toBe(true);
const orgInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO orgs"));
- expect(orgInsert?.args[6]).toBe("autumn");
- expect(orgInsert?.args[8]).toBe(orgInsert?.args[5]);
- expect(typeof orgInsert?.args[8]).toBe("number");
+ expect(orgInsert?.args[5]).toBe("autumn");
+ expect(orgInsert?.args[6]).toBe(orgInsert?.args[4]);
+ expect(typeof orgInsert?.args[6]).toBe("number");
+ });
+
+ it("signs up a first-login user without picking or reading a cell", async () => {
+ const db = new FakeDB([], null);
+ vi.stubGlobal("fetch", vi.fn(async () => Response.json({
+ user: { id: "new-workos-user", email: "[email protected]", first_name: "New" },
+ })));
+ const resp = await worker.fetch(request("/auth/cli/device/exchange", {
+ method: "POST",
+ headers: { "content-type": "application/json", "cf-ipcountry": "DE" },
+ body: JSON.stringify({ device_code: "opaque", credential_name: "oc CLI" }),
+ }), testEnv(db), ctx);
+ expect(resp.status).toBe(200);
+ const body = await resp.json<{ org: { id: string }; credential: { key: string } }>();
+ expect(body.credential.key).toMatch(/^osb_[0-9a-f]{64}$/);
+
+ // The cells table is never queried, and the org row carries no cell and
+ // no sandbox concurrency (the column keeps its schema default).
+ expect(db.prepared.some((sql) => /\bcells\b/.test(sql))).toBe(false);
+ const orgInsert = db.executed.find((entry) => entry.sql.includes("INSERT INTO orgs"));
+ expect(orgInsert?.args[0]).toBe(body.org.id);
+ expect(orgInsert?.sql).toContain("'', 1,");
+ expect(orgInsert?.sql).not.toContain("max_concurrent_sandboxes");
+ expect(orgInsert?.args).not.toContain("azure-us-east-2-a");
+ expect(db.executed.some((entry) => entry.sql.includes("INSERT INTO org_memberships"))).toBe(true);
+ expect(db.executed.some((entry) => entry.sql.includes("INSERT INTO api_keys"))).toBe(true);
});
it("sends the welcome event to Loops off the login path", async () => {
diff --git a/cloudflare-workers/api-edge/src/create_context_cache.ts b/cloudflare-workers/api-edge/src/create_context_cache.ts
deleted file mode 100644
index a5e58544..00000000
--- a/cloudflare-workers/api-edge/src/create_context_cache.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-// The create hot path's three D1 reads — org policy, running-sandbox count,
-// active-cells list — and the colo-cache entries that keep them off D1.
-//
-// This module exists so those entries have exactly ONE definition. They are
-// written from two places now: the create path itself (index.ts, on a miss) and
-// the PoolStock alarm (pool_stock.ts, proactively). A second copy of the shapes
-// or the TTLs in the DO would drift silently — the reader would just stop
-// finding hits and quietly go back to paying D1, which is invisible in every
-// signal except latency.
-//
-// Why anything writes them proactively: the colo tier only helps if something
-// touched that colo recently. A burst-100 arrives on ~100 isolates at once,
-// they all miss together, and single-flight cannot collapse across isolates —
-// so a cold burst pays the full read on every request (measured: `ctx` 376ms
-// median across all 100 on prod, where the D1 primary is in WNAM and creates
-// run in IAD).
-//
-// Two writers, and the difference between them is which colo they can reach:
-//
-// - keepCreateContextWarm, from the request path. Runs in the colo that will
-// serve the next request, so it is always the right one. Needs traffic.
-// - warmCreateContextColo, from the PoolStock alarm. Needs no traffic, but a
-// DO can only write the cache of the colo IT runs in — which is not
-// reliably the request's colo (measured on dev: shards in IAD/MIA, requests
-// served in SJC). Useful where a shard and the traffic do share a colo;
-// never something to rely on alone.
-//
-// Neither covers a genuinely cold colo — the first request after a long silence
-// still pays the read. Only moving the data closer (D1 read replication in
-// ENAM) removes that floor.
-
-import { coloGet, coloPut } from "./colo_cache";
-
-export interface CellRow {
- cell_id: string;
- cloud: string;
- region: string;
- base_url: string;
- status: string;
- available_workers: number;
- capacity_updated_at: number | null;
-}
-
-export interface OrgPolicy {
- home_cell: string;
- plan: string;
- is_halted: number;
- max_concurrent_sandboxes: number;
- max_disk_mb: number;
- billing_provider: string;
- // Which sandbox runtime this org's creates belong on. NULL/"" is the QEMU
- // fleet — so every org that predates this column keeps its current runtime
- // and opting one in is a single-row change.
- runtime: string | null;
-}
-
-// Freshness windows. The TTL is how long a value is used outright; the STALE
-// window is how long it may still gate a create while a refresh runs behind it.
-// 60s, not 5s. These three TTLs expire together, and D1.batch() is ONE round
-// trip — so the moment the shortest of them lapses, the create pays the full
-// read no matter how fresh the other two are. Measured under a burst-100 on
-// dev: ctxd1 245ms for a 3-statement batch against ctxcolo 14ms, i.e. the tier
-// that was supposed to absorb this was fast and EMPTY.
-//
-// Bounding is_halted staleness is still the job, and the stale-while-revalidate
-// window below (60s) has always been the real bound on that — this only changes
-// how long a value is used before a refresh is kicked off behind the response.
-//
-// WHY 60s AND NOT 15s. The three reads are single-flighted per isolate, so when
-// the context has expired ONE request runs the D1 batch and every other request
-// in the burst waits on it. That turns a single slow read into a fixed tax on
-// the whole burst: measured on dev at `ctx` 496ms on 18 of 20 requests with
-// `ctxn` = 3 on exactly one of them. It is what made burst-20 bimodal — 527ms
-// when the context was cached, 1.28s when it had just expired, with a spread of
-// only ~110ms INSIDE each run either way.
-//
-// The stale windows below (5 min) are what actually bound freshness; these
-// values only decide when a background refresh starts.
-export const ORG_POLICY_TTL_MS = 60_000;
-// 5 min, a DELIBERATE trade made 2026-08-26. This window is the bound on halt
-// latency: a stale-but-not-halted policy keeps gating creates while the refresh
-// runs behind it, so an org halted mid-window can keep creating for up to this
-// long. That was raised from 60s knowingly, in exchange for bursts never
-// blocking on the org read. Shorten it if halt enforcement ever needs to be
-// prompt again — it costs latency, not correctness.
-export const ORG_STALE_MAX_MS = 300_000;
-// 1.5s was deliberately shorter than a create→exec→destroy cycle, which meant
-// it expired BETWEEN benchmark-shaped creates by construction — every sequential
-// create dropped to the colo tier (or D1) for a number that had barely moved.
-// 5s matches ORG_POLICY_TTL_MS, is still a small fraction of the 30s stale
-// window the optimistic gate already relies on, and does not change the gate's
-// semantics: this is how long a count is used OUTRIGHT, and the cap has always
-// been approximate to ±CONCURRENCY_STALE_HEADROOM regardless.
-export const CONCURRENCY_COUNT_TTL_MS = 60_000;
-// Also 5 min, same trade. The cap has always been approximate to
-// ±CONCURRENCY_STALE_HEADROOM; this widens the window in which a fast creator
-// can overshoot it before the background refresh catches up.
-export const CONCURRENCY_STALE_MAX_MS = 300_000;
-export const CELL_TTL_MS = 60_000;
-// See the isHealthy() interaction noted at the cells stale-serve branch in
-// index.ts: reading capacity_updated_at from a ≤30s-stale snapshot stretches
-// the effective 120s freshness window to ~150s, still ~5× the CP's ~30s
-// capacity cadence.
-export const CELL_STALE_MAX_MS = 300_000;
-
-export const ORG_POLICY_SQL =
- "SELECT home_cell, plan, is_halted, max_concurrent_sandboxes, max_disk_mb, billing_provider, runtime FROM orgs WHERE id = ?1";
-export const RUNNING_COUNT_SQL =
- "SELECT COUNT(*) AS n FROM sandboxes_index WHERE org_id = ?1 AND status = 'running'";
-export const ACTIVE_CELLS_SQL =
- "SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at FROM cells WHERE status = 'active'";
-
-// How many recently-serving orgs one warm pass refreshes. The point is to cover
-// whoever is actually creating through this shard, not the whole customer base:
-// each org costs two statements in the batch, and an unbounded list would turn a
-// 10s alarm into a scan of every org that ever touched this shard.
-export const WARM_ORG_LIMIT = 4;
-
-// Refresh threshold for the request-driven keep-warm below: act once an entry
-// is past half its stale window, so it is replaced well before it can lapse
-// rather than exactly as it does.
-const REFRESH_AT_MS = CELL_STALE_MAX_MS / 2;
-
-// One in-flight refresh per org per isolate. The whole point is to fire on
-// ordinary traffic, and ordinary traffic is concurrent — without this a burst
-// would kick one background batch per request.
-const keepWarmInflight = new Map<string, Promise<void>>();
-
-// keepCreateContextWarm refreshes this COLO's create-context entries off the
-// back of any authenticated request for that org.
-//
-// This is the colo-correct half of the warming story, and it is why it does not
-// live in the PoolStock alarm. A Durable Object can only write the Cache API of
-// the colo IT runs in, which is not reliably the colo serving the request — dev
-// shards sit in IAD/MIA while requests land in SJC, so a shard-driven warm is
-// invisible to them. A request handler, by construction, runs in exactly the
-// colo whose cache the next request will read.
-//
-// Every authenticated call counts, not just creates: exec, delete, and list all
-// keep the create path warm for the same org, which is what carries an org
-// through the gap between its last request and its next burst.
-export function keepCreateContextWarm(
- db: D1Database | undefined,
- ctx: ExecutionContext | undefined,
- orgID: string,
-): void {
- if (!db || !ctx || !orgID) return;
- if (keepWarmInflight.has(orgID)) return;
- const p = (async () => {
- try {
- const [org, count, cells] = await Promise.all([
- coloGet<{ cachedAtMs: number }>("org", orgID),
- coloGet<{ cachedAtMs: number }>("count", orgID),
- coloGet<{ cachedAtMs: number }>("cells", "active"),
- ]);
- const now = Date.now();
- const aging = (e: { cachedAtMs: number } | null) => e === null || now - e.cachedAtMs > REFRESH_AT_MS;
- if (!aging(org) && !aging(count) && !aging(cells)) return;
- await warmCreateContextColo(db, [orgID]);
- } catch {
- /* best-effort */
- } finally {
- keepWarmInflight.delete(orgID);
- }
- })();
- keepWarmInflight.set(orgID, p);
- ctx.waitUntil(p);
-}
-
-// warmCreateContextColo refreshes the colo entries the create path reads.
-//
-// Best-effort by construction: it runs off every hot path, and a failure just
-// means the next create pays the read it would have paid anyway. It must never
-// throw into the alarm, or a D1 blip would stop the stock top-up as collateral.
-export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): Promise<void> {
- try {
- const orgs = orgIDs.slice(0, WARM_ORG_LIMIT);
- const stmts: D1PreparedStatement[] = [db.prepare(ACTIVE_CELLS_SQL)];
- for (const id of orgs) {
- stmts.push(db.prepare(ORG_POLICY_SQL).bind(id));
- stmts.push(db.prepare(RUNNING_COUNT_SQL).bind(id));
- }
- // One round trip for everything: the whole reason this is worth doing from
- // a 10s alarm rather than N separate reads.
- const res = await db.batch(stmts);
- const at = Date.now();
- const puts: Promise<void>[] = [];
-
- const cells = (res[0]?.results as CellRow[] | undefined) ?? [];
- // Never publish an empty cells list. A blip that cached one would 503 every
- // create in this colo until it aged out — strictly worse than the stale
- // read this is meant to replace.
- if (cells.length > 0) {
- puts.push(coloPut("cells", "active", { cells, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000));
- }
-
- for (let i = 0; i < orgs.length; i++) {
- const policy = (res[1 + i * 2]?.results?.[0] as OrgPolicy | undefined) ?? null;
- const n = (res[2 + i * 2]?.results?.[0] as { n: number } | undefined)?.n ?? 0;
- // A null policy is a real answer (org deleted), but publishing it from a
- // background pass would hand the create path a "no such org" it did not
- // ask for. Let the create path establish that itself.
- if (policy) {
- puts.push(coloPut("org", orgs[i], { policy, cachedAtMs: at }, ORG_STALE_MAX_MS / 1000));
- }
- puts.push(coloPut("count", orgs[i], { count: n, cachedAtMs: at }, CONCURRENCY_STALE_MAX_MS / 1000));
- }
- await Promise.all(puts);
- } catch {
- /* best-effort: the next create pays the read, exactly as it does today */
- }
-}
diff --git a/cloudflare-workers/api-edge/src/dashboard.ts b/cloudflare-workers/api-edge/src/dashboard.ts
index 73a68785..c493a113 100644
--- a/cloudflare-workers/api-edge/src/dashboard.ts
+++ b/cloudflare-workers/api-edge/src/dashboard.ts
@@ -1,21 +1,15 @@
// dashboard.ts — edge-native dashboard backend.
//
-// The new architecture (see docs/dev-cutover-runbook.md + the dev-cutover diagram)
-// makes the CF edge authoritative for identity, billing, sandbox routing index,
-// and audit log. The dashboard accordingly lives here: D1 is the source of
-// truth for org/user/api-key/checkpoint data, and only sandbox-RUNTIME ops
-// (exec, PTY, logs) proxy to the cell where the sandbox actually runs.
+// The CF edge is authoritative for identity and billing, and the dashboard
+// backend lives here: D1 is the source of truth for org/user/api-key data.
//
// Auth: session JWT cookie `oc_session` minted by /auth/callback. Browser
// hits /api/dashboard/...; we validate the cookie and execute the handler.
//
-// Proxy pattern for sandbox-runtime ops:
-// 1. Look up the sandbox's cell_id in D1 sandboxes_index (or org.home_cell
-// for non-sandbox-scoped proxies like /agents).
-// 2. Mint a short-lived capability JWT for that cell with claims.OrgID +
-// claims.Plan (the same cap-token shape /api/sandboxes POST uses).
-// 3. Fetch the cell's /internal/dashboard/{path} with Authorization: Bearer.
-// 4. Stream the response (or WebSocket pair) back to the browser.
+// The sandbox-runtime proxy to the cells (/internal/dashboard/* for sessions,
+// PTY, agents, sandbox create, previews and snapshot deletes) was removed in
+// 097 step 7.2. The D1-only sandbox reads (sessions, checkpoints, images) stay
+// until the sandbox tables themselves are retired.
import {
autumnPurchase,
@@ -150,24 +144,6 @@ function setSessionCookie(jwt: string): string {
return `${SESSION_COOKIE}=${jwt}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${SESSION_TTL_SEC}`;
}
-// Same shape as the cap-token /api/sandboxes mints for /internal/sandboxes/create.
-// Cells' capTokenMiddleware validates this same format on /internal/dashboard/*.
-async function mintCellCapToken(secret: string, orgID: string, cellID: string, plan: string, userID: string | null): Promise<string> {
- const now = Math.floor(Date.now() / 1000);
- const header = { alg: "HS256", typ: "JWT" };
- const payload: Record<string, unknown> = {
- sub: orgID, iss: "opensandbox-edge", iat: now, exp: now + 120,
- org_id: orgID, cell_id: cellID, plan,
- };
- if (userID) payload.user_id = userID;
- const enc = new TextEncoder();
- const signingInput =
- b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
- const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
- const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
- return signingInput + "." + b64url(sig);
-}
-
function b64url(buf: ArrayBuffer | Uint8Array): string {
const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
let s = "";
@@ -197,8 +173,8 @@ function epochToISORequired(s: number | null | undefined): string {
return new Date(((s ?? 0) || 0) * 1000).toISOString();
}
-// Cell ID → region. Reverse of api-edge's pickCell convention:
-// cells follow {cloud}-{region-with-hyphens}-{slot}, e.g.
+// Cell ID → region, for the sandbox rows still listed from D1. Cell ids
+// follow {cloud}-{region-with-hyphens}-{slot}, e.g.
// "azure-us-west-2-b" → region "us-west-2".
function cellToRegion(cellID: string): string {
// Strip first segment (cloud) and last segment (slot).
@@ -249,103 +225,6 @@ function shapeOrg(r: OrgRow): Record<string, unknown> {
};
}
-// ── cell lookup helpers ──────────────────────────────────────────────────
-
-interface CellRow {
- cell_id: string;
- base_url: string;
-}
-
-async function homeCell(env: DashboardEnv, orgID: string): Promise<CellRow | null> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT c.cell_id, c.base_url FROM orgs o JOIN cells c ON c.cell_id = o.home_cell WHERE o.id = ?1`,
- ).bind(orgID).first<CellRow>();
- return row ?? null;
-}
-
-async function sandboxCell(env: DashboardEnv, sandboxID: string): Promise<{ cell_id: string; base_url: string; org_id: string } | null> {
- return env.OPENCOMPUTER_DB.prepare(
- `SELECT s.cell_id, s.org_id, c.base_url FROM sandboxes_index s JOIN cells c ON c.cell_id = s.cell_id WHERE s.id = ?1`,
- ).bind(sandboxID).first<{ cell_id: string; base_url: string; org_id: string }>();
-}
-
-// proxyToCell handles non-WebSocket dashboard requests. Looks up the
-// destination URL (caller-supplied), mints a cap-token for that cell, and
-// streams the response back. Pass-through for status, body, content-type.
-async function proxyToCell(
- req: Request,
- env: DashboardEnv,
- caller: Caller,
- cell: CellRow,
- path: string,
-): Promise<Response> {
- const url = new URL(req.url);
- const target = cell.base_url.replace(/\/$/, "") + path + url.search;
- const token = await mintCellCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.plan, caller.userID);
-
- // Forward only the headers the cell actually needs. CF Workers forbids
- // some headers (Host, Connection, Content-Length) and stripping cookies
- // avoids sending the browser's session JWT to the cell. The Authorization
- // header is the auth signal the cell needs; content-type matters for body
- // parsing on POST/PUT.
- const headers = new Headers();
- headers.set("authorization", "Bearer " + token);
- const ct = req.headers.get("content-type");
- if (ct) headers.set("content-type", ct);
- const accept = req.headers.get("accept");
- if (accept) headers.set("accept", accept);
- const ua = req.headers.get("user-agent");
- if (ua) headers.set("user-agent", ua);
-
- const init: RequestInit = { method: req.method, headers };
- if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;
- return fetch(target, init);
-}
-
-// ── WebSocket proxy (PTY) ────────────────────────────────────────────────
-
-async function proxyWebSocket(
- req: Request,
- env: DashboardEnv,
- caller: Caller,
- cell: CellRow,
- cellPath: string,
-): Promise<Response> {
- if (req.headers.get("upgrade")?.toLowerCase() !== "websocket") {
- return json({ error: "expected websocket upgrade" }, 400);
- }
-
- // Mint the cell-bound cap-token the cell-CP expects in Authorization,
- // then transparently forward the upgrade to the cell-CP. With the
- // OPENSANDBOX_WS_BROKER=1 cell-CP path active, the cell-CP's
- // wsgateway terminates the browser's WS and brokers it against the
- // worker — redial on upstream close, keepalive, exec-exit suppression,
- // multi-session per sandbox, etc. live in Go, not here.
- //
- // Previously this function did an edge-side WebSocketPair + manual
- // Blob-aware bridge. That made the cell-CP see the EDGE as the client,
- // which short-circuited the broker's redial/keepalive — a worker
- // restart killed the browser's terminal. Replacing the bridge with
- // a transparent forward puts the broker actually in the middle.
- let token: string;
- try {
- token = await mintCellCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, caller.plan, caller.userID);
- } catch (e) {
- console.error("proxyWebSocket: mint failed:", e);
- return new Response("token mint failed", { status: 500 });
- }
- const upstreamURL = cell.base_url.replace(/\/$/, "") + cellPath;
- console.log(`proxyWebSocket: forwarding upgrade to ${upstreamURL}`);
-
- const fwd = new Request(upstreamURL, req);
- fwd.headers.set("authorization", "Bearer " + token);
- // Strip browser cookies — cell-CP authenticates the cap-token, not
- // dashboard session cookies, and the cookies would only bloat the
- // upstream request.
- fwd.headers.delete("cookie");
- return await fetch(fwd);
-}
-
// ── identity (/me, /orgs, /org, /org/switch) ─────────────────────────────
async function handleMe(req: Request, env: DashboardEnv, caller: Caller): Promise<Response> {
@@ -1010,8 +889,8 @@ export async function handleDashboard(
if (sub === "/managed-agents" || sub.startsWith("/managed-agents/")) {
if (sub === "/managed-agents/sessions" && method === "POST") {
try {
- // Dispatch-free re-check (DashboardEnv has no cell secrets): a fresh
- // halt is still hibernated by the webhook/reconciler.
+ // Re-check Autumn and re-project D1 (the same projection projectOrg
+ // writes; it no longer dispatches anywhere since 097 step 7.2).
const billing = await enableManagedBilling(
env,
caller.orgID,
@@ -1115,25 +994,8 @@ export async function handleDashboard(
if (m && method === "PATCH") return handleRenameAPIKey(req, env, caller, m[1]);
}
- // ── sessions: cross-cell list, then per-cell proxy ─────────────────────
+ // ── sessions: list from D1 sandboxes_index ─────────────────────────────
if (sub === "/sessions" && method === "GET") return handleListSessions(req, env, caller);
- {
- const m = sub.match(/^\/sessions\/([^/]+)(\/.*)?$/);
- if (m) {
- const sandboxID = m[1];
- const rest = m[2] ?? ""; // "" means /sessions/:id only
- const target = await sandboxCell(env, sandboxID);
- if (!target) return json({ error: "sandbox not found" }, 404);
- if (target.org_id !== caller.orgID) return json({ error: "sandbox not in your org" }, 403);
- const cell = { cell_id: target.cell_id, base_url: target.base_url };
- const cellPath = `/internal/dashboard/sessions/${sandboxID}${rest}`;
- // WebSocket on PTY GET — anything else is a regular HTTP proxy.
- if (req.headers.get("upgrade")?.toLowerCase() === "websocket" && /^\/pty\/[^/]+$/.test(rest)) {
- return proxyWebSocket(req, env, caller, cell, cellPath);
- }
- return proxyToCell(req, env, caller, cell, cellPath);
- }
- }
// ── checkpoints ───────────────────────────────────────────────────────
if (sub === "/checkpoints" && method === "GET") return handleListCheckpoints(req, env, caller);
@@ -1142,64 +1004,11 @@ export async function handleDashboard(
if (m && method === "DELETE") return handleDeleteCheckpoint(req, env, caller, m[1]);
}
- // ── images: cross-cell list from D1 images_index ───────────────────────
- // CP emits image_cache_ready / image_cache_deleted events; events-ingest
- // upserts/deletes this table. The dashboard's Images page used to proxy
- // to the user's home_cell, which broke cross-cell visibility — building
- // a snapshot on cell A wouldn't show in the dashboard if the user later
- // moved to cell B. D1 is now authoritative.
- //
- // Mutations (DELETE) still need to land on the owning cell — only that
- // cell has the underlying bytes/checkpoint to clean up — so DELETE is
- // routed to the cell that owns the row.
+ // ── images: list from D1 images_index ──────────────────────────────────
if (sub === "/images" && method === "GET") {
return handleListImages(env, caller);
}
- {
- const m = sub.match(/^\/images\/([^/]+)$/);
- if (m && method === "DELETE") {
- return handleDeleteImage(req, env, caller, m[1]);
- }
- }
- {
- const m = sub.match(/^\/snapshots\/([^/]+)$/);
- if (m && method === "DELETE") {
- return handleDeleteSnapshot(req, env, caller, decodeURIComponent(m[1]));
- }
- }
- // ── agents: proxy to home cell (cell-side hits external agents service) ─
- if (sub === "/agents" || sub.startsWith("/agents/")) {
- if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);
- const cell = await homeCell(env, caller.orgID);
- if (!cell) return json({ error: "home cell unavailable" }, 503);
- return proxyToCell(req, env, caller, cell, `/internal/dashboard${sub}`);
- }
-
- // ── sandboxes: one-click create from the dashboard → the org's home cell.
- // Reuses the cap-token /internal/sandboxes/create path (same token shape the
- // /api/sandboxes create mints); the cell stamps ownership from the token's org.
- if (sub === "/sandboxes" && method === "POST") {
- const cell = await homeCell(env, caller.orgID);
- if (!cell) return json({ error: "home cell unavailable" }, 503);
- return proxyToCell(req, env, caller, cell, "/internal/sandboxes/create");
- }
-
- // ── sandbox preview URLs: expose/list/unexpose a port on a running sandbox.
- // Proxies to the public /api/sandboxes/:id/preview, which accepts this same
- // edge cap-token (PGAPIKeyMiddleware validates it and sets the org), so no
- // cell-side handler is needed. POST create, GET list, DELETE /:port unexpose.
- {
- const pv = sub.match(/^\/sandboxes\/([^/]+)\/preview(?:\/(\d+))?$/);
- if (pv) {
- const cell = await homeCell(env, caller.orgID);
- if (!cell) return json({ error: "home cell unavailable" }, 503);
- const cellPath = pv[2]
- ? `/api/sandboxes/${pv[1]}/preview/${pv[2]}`
- : `/api/sandboxes/${pv[1]}/preview`;
- return proxyToCell(req, env, caller, cell, cellPath);
- }
- }
if (sub === "/billing/agent-subscriptions" && method === "GET") return handleListAgentSubscriptions(req, env, caller);
// /billing — basic billing read used by the dashboard billing page.
@@ -1370,55 +1179,6 @@ async function handleListImages(env: DashboardEnv, caller: Caller): Promise<Resp
return json(out);
}
-async function handleDeleteImage(req: Request, env: DashboardEnv, caller: Caller, imageID: string): Promise<Response> {
- // Look up owning cell to forward the DELETE to (bytes + checkpoint live there).
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT owner_cell_id, name FROM images_index WHERE id = ?1 AND org_id = ?2`,
- )
- .bind(imageID, caller.orgID)
- .first<{ owner_cell_id: string; name: string | null }>();
- if (!row) return json({ error: "image not found" }, 404);
- if (!row.name) return json({ error: "auto-cached images are managed by the cell — only named snapshots can be deleted via dashboard" }, 400);
-
- return deleteSnapshotOnCell(req, env, caller, row.owner_cell_id, row.name);
-}
-
-async function handleDeleteSnapshot(req: Request, env: DashboardEnv, caller: Caller, name: string): Promise<Response> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT owner_cell_id FROM images_index WHERE name = ?1 AND org_id = ?2`,
- )
- .bind(name, caller.orgID)
- .first<{ owner_cell_id: string }>();
- if (!row) return json({ error: "snapshot not found" }, 404);
-
- return deleteSnapshotOnCell(req, env, caller, row.owner_cell_id, name);
-}
-
-async function deleteSnapshotOnCell(
- req: Request,
- env: DashboardEnv,
- caller: Caller,
- ownerCellID: string,
- name: string,
-): Promise<Response> {
- // Find the cell's base_url and forward via tunnel.
- const cell = await env.OPENCOMPUTER_DB.prepare(
- `SELECT base_url FROM cells WHERE cell_id = ?1`,
- )
- .bind(ownerCellID)
- .first<{ base_url: string }>();
- if (!cell) return json({ error: "owning cell not registered" }, 503);
-
- // Reuse proxyToCell so the cap-token / cookie auth chain handles auth.
- return proxyToCell(
- req,
- env,
- caller,
- { cell_id: ownerCellID, base_url: cell.base_url },
- `/internal/dashboard/snapshots/${encodeURIComponent(name)}`,
- );
-}
-
// ── Stripe helpers ─────────────────────────────────────────────────────
// stripeApi POSTs form-urlencoded to Stripe's REST API. GET is supported via
@@ -1629,8 +1389,9 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { o
const creditBreakdown = summarizeAutumnCreditBalance(r.customer, usagePlan);
const plan = summarizeWorkMinutePlan(r.customer);
const billingState = await env.OPENCOMPUTER_DB.prepare(
- "SELECT halt_reason, payment_past_due_at, trial_started_at FROM orgs WHERE id = ?1",
+ "SELECT halt_reason, payment_past_due_at, trial_started_at, max_concurrent_sandboxes FROM orgs WHERE id = ?1",
).bind(caller.orgID).first<{
+ max_concurrent_sandboxes: number | null;
halt_reason: string | null;
payment_past_due_at: number | null;
trial_started_at: number | null;
@@ -1683,7 +1444,7 @@ async function handleAutumnBilling(_req: Request, env: DashboardEnv, caller: { o
? null
: new Date(creditBreakdown.planResetsAt).toISOString(),
},
- maxConcurrentSandboxes: r.maxConcurrent,
+ maxConcurrentSandboxes: billingState?.max_concurrent_sandboxes ?? 0,
concurrencyPlan,
usagePlan: plan.usagePlan,
isHalted: r.halted,
diff --git a/cloudflare-workers/api-edge/src/exec_shape.test.ts b/cloudflare-workers/api-edge/src/exec_shape.test.ts
deleted file mode 100644
index 8668d653..00000000
--- a/cloudflare-workers/api-edge/src/exec_shape.test.ts
+++ /dev/null
@@ -1,50 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { buildAgentExecRequest } from "./index";
-
-// Regression cover for a bug that produced no error signal at all: the
-// microvm-direct exec path read only `cmd` and dropped `args`, so the SDK's
-// {cmd:"sh", args:["-c", ...]} became `/bin/sh -lc sh` — a shell with no script,
-// which exits 0 having printed nothing. Every SDK exec on a MicroVM box returned
-// {exitCode: 0, stdout: ""} and looked like a command that produced no output.
-describe("buildAgentExecRequest", () => {
- it("runs the argv form verbatim (the shape the SDK sends)", () => {
- const req = buildAgentExecRequest({ cmd: "sh", args: ["-c", "echo hi"] }, "sh");
- expect(req.command).toBe("/bin/sh");
- expect(req.args).toEqual(["-c", "echo hi"]);
- // The bug: the script was replaced by the program name.
- expect(req.args).not.toEqual(["-lc", "sh"]);
- });
-
- it("treats the string form as a shell line", () => {
- const req = buildAgentExecRequest({ cmd: "echo hi" }, "echo hi");
- expect(req.command).toBe("/bin/sh");
- expect(req.args).toEqual(["-lc", "echo hi"]);
- });
-
- it("keeps a non-shell program as the program", () => {
- const req = buildAgentExecRequest({ cmd: "node", args: ["-e", "console.log(1)"] }, "node");
- expect(req.command).toBe("node");
- expect(req.args).toEqual(["-e", "console.log(1)"]);
- });
-
- it("ignores a non-string entry rather than shipping it to the guest", () => {
- const req = buildAgentExecRequest({ cmd: "sh", args: ["-c", 42, "echo hi"] as unknown[] }, "sh");
- expect(req.args).toEqual(["-c", "echo hi"]);
- });
-
- it("falls back to the shell line when args is present but empty", () => {
- const req = buildAgentExecRequest({ cmd: "echo hi", args: [] }, "echo hi");
- expect(req.args).toEqual(["-lc", "echo hi"]);
- });
-
- it("passes cwd, env and timeout through, omitting what was not sent", () => {
- const req = buildAgentExecRequest(
- { cmd: "sh", args: ["-c", "pwd"], cwd: "/tmp", env: { A: "1" }, timeoutSeconds: 5 },
- "sh",
- );
- expect(req.cwd).toBe("/tmp");
- expect(req.env).toEqual({ A: "1" });
- expect(req.timeoutSeconds).toBe(5);
- expect(buildAgentExecRequest({ cmd: "x" }, "x").cwd).toBeUndefined();
- });
-});
diff --git a/cloudflare-workers/api-edge/src/index.test.ts b/cloudflare-workers/api-edge/src/index.test.ts
index c4cd711a..dbf422d9 100644
--- a/cloudflare-workers/api-edge/src/index.test.ts
+++ b/cloudflare-workers/api-edge/src/index.test.ts
@@ -3,17 +3,11 @@ import worker, { type Env, safeReturnTo } from "./index";
const orgID = "org-1";
const userID = "user-1";
-const cellID = "azure-us-east-2-a";
-
-const sandboxIndexInserts: unknown[][] = [];
class FakeStatement {
constructor(private sql: string) {}
- private args: unknown[] = [];
-
- bind(...args: unknown[]) {
- this.args = args;
+ bind(..._args: unknown[]) {
return this;
}
@@ -21,70 +15,23 @@ class FakeStatement {
if (this.sql.includes("FROM api_keys")) {
return { org_id: orgID, created_by: userID, expires_at: null } as T;
}
- if (this.sql.includes("FROM sandboxes_index") && this.sql.includes("SELECT cell_id, org_id")) {
- return { cell_id: cellID, org_id: orgID } as T;
- }
- if (this.sql.includes("FROM cells WHERE cell_id")) {
- return {
- cell_id: cellID,
- cloud: "azure",
- region: "us-east-2",
- base_url: "https://cp-us-east-2.opencomputer.dev",
- status: "active",
- available_workers: 1,
- capacity_updated_at: Math.floor(Date.now() / 1000),
- } as T;
- }
if (this.sql.includes("SELECT plan FROM orgs")) {
return { plan: "pro" } as T;
}
- if (this.sql.includes("SELECT home_cell, plan, is_halted")) {
- return {
- home_cell: cellID,
- plan: "pro",
- is_halted: 0,
- max_concurrent_sandboxes: 10,
- max_disk_mb: 262144,
- } as T;
- }
- if (this.sql.includes("COUNT(*) AS n FROM sandboxes_index")) {
- return { n: 0 } as T;
- }
return null;
}
async all<T>() {
- if (this.sql.includes("FROM cells WHERE status = 'active'")) {
- return {
- results: [
- {
- cell_id: cellID,
- cloud: "azure",
- region: "us-east-2",
- base_url: "https://cp-us-east-2.opencomputer.dev",
- status: "active",
- available_workers: 1,
- capacity_updated_at: Math.floor(Date.now() / 1000),
- },
- ],
- } as { results: T[] };
- }
return { results: [] as T[] };
}
async run() {
- if (this.sql.includes("INSERT INTO sandboxes_index") && this.sql.includes("ON CONFLICT(id)")) {
- sandboxIndexInserts.push(this.args);
- }
return {};
}
// Mirrors D1's batch() per-statement result shape ({ results: [...] }):
- // list queries use all(); single-row queries wrap first() in an array.
+ // single-row queries wrap first() in an array.
async batchResult<T>(): Promise<{ results: T[] }> {
- if (this.sql.includes("WHERE status = 'active'")) {
- return (await this.all<T>()) as { results: T[] };
- }
const row = await this.first<T>();
return { results: row ? [row] : [] };
}
@@ -117,169 +64,62 @@ const ctx = {
passThroughOnException: vi.fn(),
} as unknown as ExecutionContext;
-describe("api-edge WebSocket auth", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- sandboxIndexInserts.length = 0;
- });
-
- it("accepts api_key query auth for sandbox WebSocket proxy requests", async () => {
- const fetchSpy = vi.fn(async (_req: Request) => new Response("proxied", { status: 200 }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const resp = await worker.fetch(
- new Request(
- "https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-123?api_key=osb_test&stream=1",
- {
- headers: {
- Upgrade: "websocket",
- },
- },
- ),
- env,
- ctx,
- );
-
- expect(resp.status).toBe(200);
- expect(fetchSpy).toHaveBeenCalledTimes(1);
-
- const forwarded = fetchSpy.mock.calls[0][0] as Request;
- const forwardedURL = new URL(forwarded.url);
- expect(forwardedURL.origin).toBe("https://cp-us-east-2.opencomputer.dev");
- expect(forwardedURL.pathname).toBe("/api/sandboxes/sb-123/exec/es-123");
- expect(forwardedURL.searchParams.get("stream")).toBe("1");
- expect(forwardedURL.searchParams.has("api_key")).toBe(false);
- expect(forwarded.headers.get("authorization")).toMatch(/^Bearer /);
- expect(forwarded.headers.get("x-api-key")).toBeNull();
- });
+// The sandbox API, preview URLs and cell routing were removed in 097 step 7.2.
+// What used to reach a cell is now an authenticated 404, and nothing is ever
+// forwarded.
+describe("api-edge after the sandbox strip", () => {
+ afterEach(() => vi.unstubAllGlobals());
- it("does not accept api_key query auth for non-WebSocket HTTP requests", async () => {
- const fetchSpy = vi.fn(async (_req: Request) => new Response("proxied", { status: 200 }));
+ const call = (path: string, init: RequestInit = {}) => {
+ const fetchSpy = vi.fn(async () => new Response("proxied", { status: 200 }));
vi.stubGlobal("fetch", fetchSpy);
+ return { fetchSpy, resp: worker.fetch(new Request(`https://app.opencomputer.dev${path}`, init), env, ctx) };
+ };
- const resp = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-123?api_key=osb_test"),
- env,
- ctx,
- );
-
- expect(resp.status).toBe(401);
- expect(await resp.json()).toEqual({ error: "missing or invalid API key" });
+ it("answers 401 for a sandbox path without an API key, forwarding nothing", async () => {
+ const { fetchSpy, resp } = call("/api/sandboxes/sb-123/exec/es-123?api_key=osb_test");
+ expect((await resp).status).toBe(401);
+ expect(await (await resp).json()).toEqual({ error: "missing or invalid API key" });
expect(fetchSpy).not.toHaveBeenCalled();
});
- it("strips api_key query params from proxied HTTP requests authenticated by header", async () => {
- const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => new Response("proxied", { status: 200 }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const resp = await worker.fetch(
- new Request(
- "https://app.opencomputer.dev/api/sandboxes/sb-123/exec?api_key=osb_query&stream=1",
- {
- headers: {
- "X-API-Key": "osb_header",
- },
- },
- ),
- env,
- ctx,
- );
-
- expect(resp.status).toBe(200);
- expect(fetchSpy).toHaveBeenCalledTimes(1);
-
- const forwardedURL = new URL(fetchSpy.mock.calls[0][0] as string);
- expect(forwardedURL.origin).toBe("https://cp-us-east-2.opencomputer.dev");
- expect(forwardedURL.pathname).toBe("/api/sandboxes/sb-123/exec");
- expect(forwardedURL.searchParams.get("stream")).toBe("1");
- expect(forwardedURL.searchParams.has("api_key")).toBe(false);
-
- const forwardedHeaders = new Headers(fetchSpy.mock.calls[0][1]?.headers);
- expect(forwardedHeaders.get("authorization")).toMatch(/^Bearer /);
- expect(forwardedHeaders.get("x-api-key")).toBeNull();
- });
-
- it("rejects WebSocket proxy requests without header or query auth", async () => {
- const fetchSpy = vi.fn(async (_req: Request) => new Response("proxied", { status: 200 }));
- vi.stubGlobal("fetch", fetchSpy);
-
- const resp = await worker.fetch(
- new Request(
- "https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-123",
- {
- headers: {
- Upgrade: "websocket",
- },
- },
- ),
- env,
- ctx,
- );
-
- expect(resp.status).toBe(401);
- expect(await resp.json()).toEqual({ error: "missing or invalid API key" });
+ it("answers 401 for a sandbox WebSocket without an API key", async () => {
+ const { fetchSpy, resp } = call("/api/sandboxes/sb-123/exec/es-123", { headers: { Upgrade: "websocket" } });
+ expect((await resp).status).toBe(401);
expect(fetchSpy).not.toHaveBeenCalled();
});
-});
-describe("api-edge sandbox create", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- sandboxIndexInserts.length = 0;
- });
-
- it("indexes SSE snapshot creates before the streamed response completes", async () => {
- const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => {
- const body = [
- "event: build_log",
- 'data: {"message":"creating"}',
- "",
- "event: result",
- 'data: {"sandboxID":"sb-sse1234","workerID":"worker-1","status":"running","memoryMB":2048}',
- "",
- ].join("\n");
- return new Response(body, {
- status: 200,
- headers: { "content-type": "text/event-stream" },
- });
+ it("answers 404 for an authenticated sandbox create, forwarding nothing", async () => {
+ const { fetchSpy, resp } = call("/api/sandboxes", {
+ method: "POST",
+ headers: { "X-API-Key": "osb_test", "content-type": "application/json" },
+ body: JSON.stringify({ templateID: "base" }),
});
- vi.stubGlobal("fetch", fetchSpy);
+ expect((await resp).status).toBe(404);
+ expect(await (await resp).json()).toEqual({ error: "not found" });
+ expect(fetchSpy).not.toHaveBeenCalled();
+ });
- const resp = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", {
- method: "POST",
- headers: {
- "X-API-Key": "osb_test",
- "Content-Type": "application/json",
- Accept: "text/event-stream",
- // This case is about SSE indexing, not routing — but a create with no
- // SDK version is now refused as v1, so it has to announce itself.
- "x-oc-sdk-version": "1.0.0",
- },
- body: JSON.stringify({ snapshot: "snapshot-1", memoryMB: 1024 }),
- }),
- env,
- ctx,
- );
+ it("answers 404 for authenticated exec, snapshot and image paths", async () => {
+ for (const path of ["/api/sandboxes/sb-123/exec/run-async", "/api/snapshots", "/api/images"]) {
+ const { fetchSpy, resp } = call(path, { method: "POST", headers: { "X-API-Key": "osb_test" } });
+ expect((await resp).status, path).toBe(404);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ }
+ });
- expect(resp.status).toBe(200);
- expect(await resp.text()).toContain("event: result");
- expect(sandboxIndexInserts).toHaveLength(1);
- expect(sandboxIndexInserts[0]).toEqual([
- "sb-sse1234",
- orgID,
- userID,
- cellID,
- "worker-1",
- "running",
- 0,
- 2048,
- expect.any(Number),
- // end_at: this CP response carries no deadline, and the absence must
- // reach the column as NULL rather than as a fabricated timestamp — a
- // wrong deadline here would make a live sandbox read as expired.
- null,
- ]);
+ it("does not route preview hosts or the cell-facing internal routes", async () => {
+ for (const url of [
+ "https://sb-123-p8080.sb.opencomputer.dev/",
+ "https://app.opencomputer.dev/internal/halt-list",
+ "https://app.opencomputer.dev/internal/vms/sb-123/connect",
+ ]) {
+ const fetchSpy = vi.fn(async () => new Response("proxied", { status: 200 }));
+ vi.stubGlobal("fetch", fetchSpy);
+ const resp = await worker.fetch(new Request(url), env, ctx);
+ expect(resp.status, url).toBe(404);
+ expect(fetchSpy).not.toHaveBeenCalled();
+ }
});
});
@@ -334,71 +174,6 @@ describe("/internal/model-billing/enable — scoped-secret auth boundary", () =>
});
});
-describe("api-edge VM-DO exec routing", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- sandboxIndexInserts.length = 0;
- });
-
- // A VmSession DO namespace stub whose /exec returns `doResponse`. The exec
- // fast path is gated on SESSION_JWT_SECRET, which the base test env already sets.
- const vmEnv = (doResponse: Response) =>
- ({
- ...env,
- VM_SESSIONS: {
- idFromName: (s: string) => s,
- get: () => ({ fetch: async () => doResponse.clone() }),
- },
- }) as unknown as Env;
-
- const runAsync = (e: Env) =>
- worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/run-async", {
- method: "POST",
- headers: { "X-API-Key": "osb_test", "content-type": "application/json" },
- body: JSON.stringify({ cmd: "sh", args: ["-c", "node -v"], timeout: 60 }),
- }),
- e,
- ctx,
- );
-
- it("serves exec inline from the DO and does not hit the tunnel", async () => {
- const tunnel = vi.fn(async () => new Response("TUNNEL", { status: 200 }));
- vi.stubGlobal("fetch", tunnel);
- const resp = await runAsync(vmEnv(new Response(JSON.stringify({ exitCode: 0, stdout: "v20.0.0\n", stderr: "" }), { status: 200 })));
- expect(resp.status).toBe(200);
- expect(await resp.json()).toEqual({ exitCode: 0, stdout: "v20.0.0\n", stderr: "" });
- expect(tunnel).not.toHaveBeenCalled(); // one hop: edge→DO, no tunnel
- });
-
- it("falls back to the tunnel when the DO channel is not connected", async () => {
- const tunnel = vi.fn(async () => new Response(JSON.stringify({ execId: "e1", running: true }), { status: 200 }));
- vi.stubGlobal("fetch", tunnel);
- const resp = await runAsync(vmEnv(new Response(JSON.stringify({ connected: false }), { status: 409 })));
- expect(resp.status).toBe(200);
- expect(tunnel).toHaveBeenCalledTimes(1); // degraded → tunnel
- });
-
- it("only routes run-async to the DO — other exec sub-paths take the tunnel", async () => {
- // The result-poll (GET /exec/:id/result), files, pty, etc. must not touch the
- // DO; the fast path is scoped to POST /exec/run-async.
- const tunnel = vi.fn(async () => new Response("proxied", { status: 200 }));
- vi.stubGlobal("fetch", tunnel);
- const doGet = vi.fn();
- const e = { ...env, VM_SESSIONS: { idFromName: (s: string) => s, get: doGet } } as unknown as Env;
- const resp = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes/sb-123/exec/es-1/result", {
- headers: { "X-API-Key": "osb_test" },
- }),
- e,
- ctx,
- );
- expect(resp.status).toBe(200);
- expect(doGet).not.toHaveBeenCalled(); // result poll → tunnel, never the DO
- expect(tunnel).toHaveBeenCalledTimes(1);
- });
-});
-
describe("safeReturnTo — deferred-action deep-link validation", () => {
it("accepts same-origin paths (incl. query strings)", () => {
expect(safeReturnTo("/do?action=abc")).toBe("/do?action=abc");
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 5c94d95c..9d591113 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -1,14 +1,6 @@
// api-edge Worker — global API entry point.
//
// Implemented:
-// POST /api/sandboxes — auth (D1 api_keys) → pick org.home_cell →
-// mint capability token → proxy to that cell's
-// CP /internal/sandboxes/create → record in
-// sandboxes_index → return the CP's response
-// GET /api/sandboxes — list this org's sandboxes from sandboxes_index
-// GET /api/sandboxes/:id — one row + cell_endpoint
-// ANY /api/sandboxes/:id/* — 307 to the owning cell's CP (dumb-client path)
-// GET /internal/halt-list — HMAC-auth'd; halted org_ids from D1 (CP halt_reconciler)
// GET /auth/login — kicks off WorkOS Authkit flow
// GET /auth/callback — WorkOS code exchange → upsert user/org → session JWT cookie
// POST /auth/logout — clear session cookie
@@ -17,44 +9,16 @@
// POST /auth/cli/device/exchange — poll device authorization → one ordinary org key
// DELETE /auth/cli/credential — revoke the exact CLI-presented org key
// POST /webhooks/stripe — Stripe webhook → DO /mark-pro or /mark-free
+// ANY /api/managed-agents/* — managed agents, behind the credit gate
+// ANY /api/dashboard/* — dashboard API (dashboard.ts)
// GET /health
+//
+// The sandbox API (/api/sandboxes, snapshots, preview hosts, the cell proxy,
+// the edge pool and the VM-DO bindings) was removed in 097 step 7.2.
export { CreditAccount } from "../../shared/credit_account";
-// Shared with the vm-do worker's MicrovmSession: the same minimal HTTP/2 client,
-// used here only by the dev-only direct-exec probe.
-import { H2Grpc, openTunnel, encodeExecRequest, decodeExecResponse } from "../../shared/h2grpc";
export { PoolStock } from "./pool_stock";
-import { mintPoolCapToken } from "./pool_stock";
-// VmSession (VM-DO exec data plane) lives in its own worker
-// (cloudflare-workers/vm-do) and is bound cross-script via VM_SESSIONS —
-// deliberately NOT exported here, so the edge's deploy cadence (every merge
-// touching web/ or edge code) can't reset the DOs and sever the host-dialed
-// VM WebSockets.
import { coloDelete, coloGet, coloPut } from "./colo_cache";
-import {
- RUNTIME_MICROVM,
- SDK_VERSION_HEADER,
- effectiveRuntime,
- isRetiredRuntime,
- v1RetiredError,
- V1_RETIRED_STATUS,
- isMicrovmWorkerID,
-} from "./runtime_gate";
-import {
- ACTIVE_CELLS_SQL,
- CELL_STALE_MAX_MS,
- CELL_TTL_MS,
- CONCURRENCY_COUNT_TTL_MS,
- CONCURRENCY_STALE_MAX_MS,
- ORG_POLICY_SQL,
- ORG_POLICY_TTL_MS,
- ORG_STALE_MAX_MS,
- RUNNING_COUNT_SQL,
- keepCreateContextWarm,
- warmCreateContextColo,
- type CellRow,
- type OrgPolicy,
-} from "./create_context_cache";
import { authDashboard, handleDashboard, type DashboardEnv } from "./dashboard";
import { handleAgentFeedback, isAgentFeedbackPath, type AgentFeedbackEnv } from "./agent_feedback";
import {
@@ -78,16 +42,12 @@ import {
import {
emitPaywallShown,
handleCreditsStatus,
- insufficientCreditsLegacyResponse,
insufficientCreditsResponse,
paywallContext,
- usagePlanOf,
} from "./billing_onramp";
export { ManagedAgentBillingService } from "./managed_agent_billing_service";
import { runRetentionSweep } from "./retention";
import * as secretStores from "./secret_stores";
-import * as snapshots from "./snapshots";
-import * as templates from "./templates";
import * as webhooks from "./webhooks";
import { createAPIKey, createAPIKeyWithHash, hashAPIKey } from "./api_keys";
import { envWithD1Retry } from "./d1_retry";
@@ -145,26 +105,16 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, L
// edge's own origin is always allowed).
WIRE_HTTP_URL?: string;
COMPUTER_API_CORS_ORIGINS?: string;
- // Per-org cross-cell paused-sandbox cap (default 100). Set lower on dev to
- // exercise the promotion path without paused hundreds of boxes.
- PAUSED_CAP?: string;
// Autumn (useautumn.com) billing. AUTUMN_WEBHOOK_SECRET is the Svix signing
// secret (whsec_…) for /webhooks/autumn. AUTUMN_SECRET_KEY / AUTUMN_BASE_URL
// are inherited from DashboardEnv. Unset on deployments not yet on Autumn.
AUTUMN_WEBHOOK_SECRET: string;
- // SDK-version routing (see runtime_gate.ts). SDK_RUNTIME_GATE="0" pins every
- // unpinned org back to QEMU — the kill switch for self-service migration,
- // without touching any org row. SDK_RUNTIME_MIN_MAJOR overrides the major at
- // which an SDK counts as v2 (default 2).
- SDK_RUNTIME_GATE?: string;
- SDK_RUNTIME_MIN_MAJOR?: string;
// HMAC secret used by Browser API to submit runtime usage. Falls back to
// EVENT_SECRET in the handler when unset for compatibility during rollout.
BROWSER_USAGE_HMAC_SECRET?: string;
// Dedicated HMAC secret for finalized managed-agent runtime segments.
AGENT_RUNTIME_USAGE_HMAC_SECRET?: string;
- // Shared with every CP via Infisical /shared/ → per-cell KV/SM. Used for
- // envelope encryption of secret_store_entries.encrypted_value. Matches
+ // Lives in Infisical /shared/. Used for envelope encryption of secret_store_entries.encrypted_value. Matches
// internal/crypto.Encryptor key format (hex-encoded 32 bytes).
SECRET_ENCRYPTION_KEY: string;
// Svix API token (managed webhook delivery). Region is in the token suffix.
@@ -172,9 +122,6 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, L
// CF_API_TOKEN and CF_ZONE_ID are optional in DashboardEnv (custom domain
// feature gates on them). Inherited.
ASSETS?: Fetcher;
- // Optional alpha Burst Sandbox cell. When unset, burst=true creates
- // fail closed rather than silently landing on on-demand capacity.
- BURST_CELL_ID?: string;
// Slack Connect per signup (slack_connect.ts), sent by the OpenComputer
// Slack app: dormant unless the token
// and SINCE (unix seconds) are set.
@@ -191,82 +138,8 @@ export interface Env extends DashboardEnv, AgentFeedbackEnv, BillingEventsEnv, L
// agents backend (blue) (NOT the generic internal-auth — this route carries a
// live model key). §6.7.5.
OC_MANAGED_CRED_HMAC_SECRET: string;
- // Edge claim (pool_stock.ts): per-cell Durable Object stocking pre-reserved
- // hot pool boxes so default-shape creates are answered at the edge with zero
- // origin round trips. EDGE_CLAIM="0" is the kill switch (default on).
- POOL_STOCK: DurableObjectNamespace;
- EDGE_CLAIM?: string;
- // Which shard ids this environment uses, as a comma-separated list — e.g.
- // "1,4,6,12" for the four-way prod set, or "1" for no sharding at all.
- //
- // This has to be per-environment because a shard id is not a number, it is
- // half of a DO NAME (`${cellID}#${gen}#${id}`). The cell id is the other
- // half, so the same id names a DIFFERENT object in every cell — and placement
- // is a property of the object. The measured-into-IAD set below was probed
- // against PROD's cell and carries no information whatsoever about where dev's
- // objects of the same id landed. Sharing one hardcoded list across cells was
- // silently asserting otherwise.
- POOL_STOCK_SHARD_IDS?: string;
- // "0" stops the edge answering MicroVM exec itself, handing it to the cell.
- // Required for a cell whose boxes have no agent tunnel to dial — see the
- // dispatch in proxyToCellSDK. Unset means the edge path, which is prod.
- MICROVM_EDGE_EXEC?: string;
- // "0" stops MicroVM creates attempting edge-claim. Required for a cell that
- // keeps its warm set in process, where the stock DO can never be filled — see
- // createSandbox. Unset means edge-claim, which is prod.
- MICROVM_EDGE_CLAIM?: string;
- // "0" makes a voucher create hold ZERO connections: no binding write, no
- // finalize send. Diagnostic only — it leaves the sandbox with no row and no
- // resolvable box, so exec 404s and the box leaks. It exists to test whether
- // the unexplained ~150ms of burst create latency is our own waitUntil
- // connection use. A Worker invocation may hold six connections and each
- // waitUntil takes one, so the cost of holding them lands on the NEXT request
- // to that isolate — i.e. inside the residual, invisible to `hdl`.
- CREATE_WAITUNTIL?: string;
- // VM-DO exec data plane (vm_do_datapane_validation). One DO per sandbox holds a
- // persistent host-dialed WebSocket to the QEMU worker; exec routes edge→DO→VM
- // instead of tunnel→CP→worker, with automatic tunnel fallback when unconnected.
- // The host's /connect is authed by a per-sandbox HMAC over SESSION_JWT_SECRET
- // (see the /internal/vms/:id/connect route) — no dedicated secret.
- VM_SESSIONS: DurableObjectNamespace;
- // MicroVM exec data plane — the DO dials the box's agent directly, so exec
- // never touches the control plane. See vm-do/src/microvm_session.ts.
- MICROVM_SESSIONS: DurableObjectNamespace;
- // Off-isolate edge-claim finalize. finalizeEdgeClaim (CP claim-finalize fetch +
- // D1 index insert) was the dominant burst-create cost: run per create in
- // waitUntil, ~100 of them accumulate on the create isolate and saturate its
- // concurrent-subrequest budget, queueing every later create's pool pop. The
- // create now enqueues a tiny message and returns; the queue() consumer runs the
- // finalize on its own invocations, off the create hot path. Optional — an
- // unbound queue falls back to the old inline waitUntil (safe during rollout).
- FINALIZE_QUEUE?: Queue<FinalizeMsg>;
- DIAG?: string; // "1" enables per-op diagnostic logging (create-timing etc.)
-}
-
-// Serializable payload for the off-isolate finalize (see FINALIZE_QUEUE).
-export interface FinalizeMsg {
- orgID: string;
- userID: string | null;
- cellID: string;
- baseURL: string;
- plan: string;
- billingProvider: string;
- /** The runtime this create was ROUTED to (may be SDK-derived). */
- runtime: string;
- /**
- * The org's pin from D1 — what the cell may persist. Absent on messages
- * enqueued before this field existed; the consumer then falls back to
- * `runtime`, which is exactly the old behaviour.
- */
- runtimePin?: string;
- sandboxID: string;
- workerID: string;
- /** Voucher creates only: the box to redeem against. Absent on every other path. */
- bodyText: string;
}
-const DEFAULT_MAX_CONCURRENT_SANDBOXES = 50;
-
// ── small helpers ────────────────────────────────────────────────────────
function json(body: unknown, status = 200): Response {
@@ -283,98 +156,8 @@ const b64url = (buf: ArrayBuffer | Uint8Array): string => {
return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
};
-// Mint the capability token the regional CP expects on /internal/sandboxes/create:
-// HS256 JWT signed with SESSION_JWT_SECRET, iss="opensandbox-edge", carrying
-// org_id + cell_id + plan (+ optional user_id). Mirrors auth.CapabilityClaims
-// in Go. Plan flows through so the worker can tag usage_tick events without
-// a per-event PG lookup.
-// Cap-tokens are org+cell scoped with exp=120s — memoize for 60s so a battery's
-// ~400 mints (per-DELETE proxy, finalize, CP fallback) collapse to ~1/min of
-// HMAC CPU on the create/destroy hot path.
-const capTokenCache = new Map<string, { token: string; mintedAtMs: number }>();
-
-async function cachedCapToken(
- secret: string,
- orgID: string,
- cellID: string,
- plan: string,
- billingProvider: string,
- runtime: string,
- userID: string | null,
- effective = runtime,
-): Promise<string> {
- // Both runtimes are in the cache key deliberately. `runtime` is the org's
- // assignment, and leaving it out would mean a D1 change did not take effect
- // until the entry aged out — an org would keep landing on the old runtime for
- // up to a minute after being reassigned, with nothing to explain why.
- // `effective` has to be there for a sharper reason: under SDK-version routing
- // it differs BETWEEN CALLS for the same org, so a key without it would serve
- // one SDK's token to the other and route the create to the wrong backend.
- const key = `${orgID}|${cellID}|${plan}|${billingProvider}|${runtime}|${effective}|${userID ?? ""}`;
- const hit = capTokenCache.get(key);
- const nowMs = Date.now();
- if (hit && nowMs - hit.mintedAtMs < 60_000) return hit.token;
- const token = await mintCapToken(secret, orgID, cellID, plan, billingProvider, runtime, userID, effective);
- if (capTokenCache.size >= CACHE_MAX) capTokenCache.clear();
- capTokenCache.set(key, { token, mintedAtMs: nowMs });
- return token;
-}
-
-async function mintCapToken(
- secret: string,
- orgID: string,
- cellID: string,
- plan: string,
- billingProvider: string,
- runtime: string,
- userID: string | null,
- effective = runtime,
-): Promise<string> {
- const now = Math.floor(Date.now() / 1000);
- const header = { alg: "HS256", typ: "JWT" };
- const payload: Record<string, unknown> = {
- sub: orgID,
- iss: "opensandbox-edge",
- iat: now,
- exp: now + 120, // short-lived — it's only the edge→CP hop
- org_id: orgID,
- cell_id: cellID,
- plan,
- };
- // Only set when known; empty lets the cell keep its existing cell-PG value
- // (so a wake/preview token never clobbers an autumn flag set at create time).
- if (billingProvider) payload.billing_provider = billingProvider;
- // Which sandbox runtime this org's creates belong on (orgs.runtime). Omitted
- // when unset, and the cell reads absent as "the QEMU fleet" — so an org with
- // no assignment, and every token minted before this field existed, resolves
- // to the backend with the full feature set rather than a specialised one.
- if (runtime) payload.runtime = runtime;
- // `rt` is the runtime THIS REQUEST was routed to, which for an unpinned org
- // is decided by the calling SDK's major and therefore varies per call. It is
- // deliberately a SEPARATE claim from `runtime` above, because the cell
- // PERSISTS `runtime` into its own orgs table: writing a per-request answer
- // there turns the first create from a new SDK into a permanent org pin, after
- // which deliberately calling from an older SDK cannot move the org back.
- // Measured on dev — two unpinned orgs pinned themselves to microvm on their
- // own first create, and the rollback path stopped working.
- //
- // Omitted when it matches `runtime`, so tokens for pinned orgs are unchanged
- // and the cell's fallback (read `runtime`) is exactly the old behaviour.
- if (effective && effective !== runtime) payload.rt = effective;
- if (userID) payload.user_id = userID;
- const enc = new TextEncoder();
- const signingInput =
- b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
- const key = await hmacSignKey(secret);
- const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
- return signingInput + "." + b64url(sig);
-}
-
-// Cache the imported HMAC signing key. The secret is constant, but
-// crypto.subtle.importKey ran on every token mint — and the create hot path
-// mints per create, where the code notes the HMAC work was a top CPU item
-// driving isolate queueing at burst-100. Memoize the imported CryptoKey per
-// secret (shared Promise so concurrent first-callers don't double-import) so
+// Cache the imported HMAC signing key used to sign session JWTs. Memoized per
+// secret (shared Promise so concurrent first-callers don't double-import), so
// only sign() runs per mint. importKey is extractable:false, so the key never
// leaves the isolate.
let hmacSignKeyCache: { secret: string; key: Promise<CryptoKey> } | null = null;
@@ -391,36 +174,6 @@ function hmacSignKey(secret: string): Promise<CryptoKey> {
return key;
}
-// Mint the sandbox-scoped JWT the create response carries (direct worker
-// access: exec WS, PTY, files). Byte-compatible with Go's
-// auth.IssueSandboxToken — same shared secret, iss="opensandbox", same claim
-// names — so cells/workers validate edge-minted tokens identically to
-// CP-minted ones. 24h TTL mirrors the CP.
-async function mintSandboxToken(
- secret: string,
- orgID: string,
- sandboxID: string,
- workerID: string,
-): Promise<string> {
- const now = Math.floor(Date.now() / 1000);
- const enc = new TextEncoder();
- const header = { alg: "HS256", typ: "JWT" };
- const payload = {
- sub: orgID,
- iat: now,
- exp: now + 24 * 3600,
- iss: "opensandbox",
- org_id: orgID,
- sandbox_id: sandboxID,
- worker_id: workerID,
- };
- const signingInput =
- b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
- const key = await hmacSignKey(secret);
- const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
- return signingInput + "." + b64url(sig);
-}
-
interface Caller {
orgID: string;
userID: string | null;
@@ -481,46 +234,10 @@ function epochToISO(seconds: number | null | undefined): string | null {
: null;
}
-interface SandboxCreateResult {
- sandboxID?: string;
- workerID?: string;
- status?: string;
- memoryMB?: number;
- // RFC3339, present only when the serving runtime enforces a hard deadline.
- endAt?: string;
-}
-
function isWebSocketUpgrade(req: Request): boolean {
return req.headers.get("upgrade")?.toLowerCase() === "websocket";
}
-// Length-hiding constant-time secret compare: hash both sides to a fixed 32
-// bytes before XOR so the loop time can't leak the expected length. Used for the
-// VM-DO host-dial connect secret (vm_session.ts), which arrives as a WS
-// subprotocol value rather than an HMAC signature.
-async function tokenMatches(provided: string | null, expected: string): Promise<boolean> {
- if (!provided || !expected) return false;
- const encoder = new TextEncoder();
- const [left, right] = await Promise.all([
- crypto.subtle.digest("SHA-256", encoder.encode(provided)),
- crypto.subtle.digest("SHA-256", encoder.encode(expected)),
- ]);
- const a = new Uint8Array(left);
- const b = new Uint8Array(right);
- let mismatch = 0;
- for (let i = 0; i < a.length; i++) mismatch |= a[i] ^ b[i];
- return mismatch === 0;
-}
-
-// The host presents the connect secret as the 2nd WS subprotocol, after the
-// wire-format marker "oc-protobuf-v1". Browsers/proxies can't set arbitrary WS
-// headers but CAN set Sec-WebSocket-Protocol, so this carries the credential on
-// the upgrade without a query-string leak. Returns null if the marker is absent.
-function socketSecret(req: Request): string | null {
- const protocols = req.headers.get("sec-websocket-protocol")?.split(",").map((v) => v.trim()) ?? [];
- return protocols[0] === "oc-protobuf-v1" ? (protocols[1] ?? null) : null;
-}
-
function apiKeyFromRequest(req: Request): string | null {
const headerKey = req.headers.get("X-API-Key");
if (headerKey) return headerKey;
@@ -534,12 +251,6 @@ function apiKeyFromRequest(req: Request): string | null {
return null;
}
-function stripApiKeyQueryParam(target: string): string {
- const url = new URL(target);
- url.searchParams.delete("api_key");
- return url.toString();
-}
-
// Authenticate via X-API-Key (looked up by sha256 in D1 api_keys). For
// WebSocket Upgrade requests, also accept ?api_key= because browser WS APIs
// cannot set custom headers. Session-JWT auth (browser flows) is a TODO;
@@ -554,15 +265,11 @@ function stripApiKeyQueryParam(target: string): string {
// and throttle the last_used bump. Isolates recycle so entries are naturally
// bounded; CACHE_MAX guards pathological key cardinality.
const AUTH_TTL_MS = 60_000;
-// SWR window for the auth entry, mirroring the org-policy and active-cells
-// gates in loadCreateContext. Auth was the LAST tier on the create path with no
-// stale-while-revalidate escape: every other cold miss serves a stale value and
-// refreshes behind the response, so a cold-isolate create still paid one
-// blocking D1 read — and it paid it FIRST, before the orgID is even known, so
-// it cannot be batched with the create-context reads. Measured on dev
-// 2026-08-25 (6 sequential creates): `auth` 26-49ms on the four cold isolates
-// while `ctx` was 7-9ms once its colo tier answered — auth was the larger of
-// the two, and for a worse reason.
+// SWR window for the auth entry: a cold miss serves a stale value and refreshes
+// behind the response instead of paying a blocking D1 read before the orgID is
+// even known. (It was added for the sandbox create path, measured on dev
+// 2026-08-25 at 26-49ms of `auth` on cold isolates; that path is gone since 097
+// step 7.2, but every authenticated route still benefits.)
//
// What this widens: revocation lag for a key deleted out of band goes from
// AUTH_TTL_MS to AUTH_STALE_MAX_MS in the worst case — but only until the
@@ -581,90 +288,6 @@ interface AuthEntry {
lastBumpMs: number;
}
const authCache = new Map<string, AuthEntry>();
-const orgPolicyCache = new Map<string, { policy: OrgPolicy | null; cachedAtMs: number }>();
-// The create concurrency cap counts running sandboxes from the global
-// sandboxes_index — a per-create D1 read. That index already trails events, so
-// the cap is approximate under burst anyway; cache the count per-isolate for a
-// short window so a burst fires ~one COUNT/isolate/window instead of one per
-// create. Under burst the cached value reads low (index lag), so it stays
-// permissive — no spurious 429s.
-// Optimistic-gate stale window + headroom: a count up to 30s old may gate a
-// create IF it sits at least HEADROOM below the org's limit (see
-// loadCreateContext). Bounds the worst-case cap overshoot to ~HEADROOM boxes.
-const CONCURRENCY_STALE_HEADROOM = 8;
-const concurrencyCountCache = new Map<string, { count: number; cachedAtMs: number }>();
-// Sandbox → owning-cell route. proxyToCellSDK otherwise pays a blocking D1
-// read per sub-op (exec run-async + each result poll = 2-3 reads per SDK
-// runCommand). The route is immutable for a sandbox's lifetime — cells never
-// hand off sandboxes and org ownership never changes — so no TTL: entries are
-// dropped on DELETE and bounded by CACHE_MAX + isolate recycling. Populated at
-// create, which also closes the same-isolate race where a sub-op lands before
-// the waitUntil-deferred insertSandboxIndex write does. Never caches misses.
-const sandboxRouteCache = new Map<string, SandboxRoute>();
-
-// The route is immutable for a sandbox's lifetime, but a destroyed sandbox's
-// entry can linger — same semantics as the isolate Map (the cell 404s). 15 min
-// bounds colo-level lingering.
-const ROUTE_COLO_TTL_SEC = 900;
-
-// How long a box's agent reach-info stays cached. The AWS proxy credential is
-// minted for 60 minutes and a CLAIMED box is out of the pool, so nothing
-// re-mints it — the cache must expire comfortably before the credential does,
-// or execs would dial with a dead token and fall back for the rest of the hour.
-// 30 minutes leaves a wide margin; past it, tryMicrovmDirectExec re-fetches from
-// the cell and re-caches.
-const MVM_REACH_TTL_SEC = 1800;
-
-interface MvmReach {
- endpoint: string;
- token: string;
- port: number;
-}
-
-// resolveSandboxRoute returns a sandbox's { cellID, orgID } from the route cache,
-// falling back to the colo-shared tier (colo_cache.ts) and then a single D1 read
-// (each hit backfills the tier above it). null = no such sandbox. Shared by
-// proxyToCellSDK and the VM-DO exec fast path so both enforce the same
-// org-ownership authz off the same cached mapping. The colo tier matters for the
-// SDK's create → exec shape: the exec routinely lands on a different isolate
-// than the create that seeded the Map, and this read is the exec path's only
-// blocking D1 dependency.
-// `microvm` records which RUNTIME this sandbox landed on.
-//
-// It has to be per-sandbox. Routing a live sandbox by its ORG's runtime was
-// correct only while an org was entirely on one runtime; once creates are routed
-// by SDK version (runtime_gate.ts) a mixed org is the steady state rather than a
-// migration window, and the same org has QEMU sandboxes from one service and
-// MicroVM sandboxes from another for as long as the migration takes.
-//
-// `undefined` means UNKNOWN, not "no" — a route cached by an older deployment,
-// or a row whose worker_id is not written yet. Callers must fall back to the org
-// policy there rather than reading it as QEMU, or a MicroVM box would be sent to
-// a Durable Object that can never hold a channel for it.
-type SandboxRoute = { cellID: string; orgID: string; microvm?: boolean };
-
-async function resolveSandboxRoute(env: Env, id: string): Promise<SandboxRoute | null> {
- const warm = sandboxRouteCache.get(id);
- if (warm) return warm;
- let route = await coloGet<SandboxRoute>("route", id);
- if (!route) {
- const row = await env.OPENCOMPUTER_DB.prepare("SELECT cell_id, org_id, worker_id FROM sandboxes_index WHERE id = ?1")
- .bind(id)
- .first<{ cell_id: string; org_id: string; worker_id: string | null }>();
- if (!row) return null;
- route = { cellID: row.cell_id, orgID: row.org_id };
- // Only claim to know when worker_id is actually populated. A create still in
- // flight has none, and this entry has no TTL in the isolate map — writing
- // "not MicroVM" from a blank column would pin that wrong answer for the life
- // of the isolate.
- if (row.worker_id) route.microvm = isMicrovmWorkerID(row.worker_id);
- await coloPut("route", id, route, ROUTE_COLO_TTL_SEC);
- }
- if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- sandboxRouteCache.set(id, route);
- return route;
-}
-
function bumpLastUsed(env: Env, hash: string, entry: AuthEntry, nowMs: number): void {
if (nowMs - entry.lastBumpMs < LAST_USED_BUMP_MS) return;
entry.lastBumpMs = nowMs;
@@ -741,3015 +364,127 @@ function refreshAuth(env: Env, hash: string): Promise<void> {
// here would turn a transient D1 blip into a 401 storm.
} finally {
authRefreshInflight.delete(hash);
- }
- })();
- authRefreshInflight.set(hash, p);
- return p;
-}
-
-// Which tier answered auth, and what the slow parts cost. `auth` is one mark
-// over four possible paths (isolate, colo, stale, D1) and a 226ms reading does
-// not say which — the same ambiguity that made `ctx` unfixable until it was
-// split. tier: 0 isolate, 1 colo, 2 stale, 3 D1.
-export interface AuthProbe {
- tier: number;
- coloMs: number;
- d1Ms: number;
- hashMs: number;
-}
-
-async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {
- const apiKey = apiKeyFromRequest(req);
- if (!apiKey) return null;
- return authenticateKey(apiKey, env, ctx, probe);
-}
-
-async function authenticateKey(apiKey: string, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {
- const tHash = Date.now();
- const hash = await hashAPIKey(apiKey);
- if (probe) probe.hashMs = Date.now() - tHash;
- const nowMs = Date.now();
- const nowSec = Math.floor(nowMs / 1000);
-
- const cached = authCache.get(hash);
- if (cached && nowMs - cached.cachedAtMs < AUTH_TTL_MS) {
- if (cached.expiresAt && cached.expiresAt < nowSec) return null;
- if (probe) probe.tier = 0;
- bumpLastUsed(env, hash, cached, nowMs);
- return cached.caller;
- }
-
- // Colo tier: a fresh box's sub-ops usually land on isolates that never saw
- // this key. cachedAtMs travels with the entry so the total staleness bound
- // (revocation lag) stays AUTH_TTL_MS, not colo-TTL + isolate-TTL stacked.
- const tColo = Date.now();
- const shared = await coloGet<{ caller: Caller; expiresAt: number | null; cachedAtMs: number }>("auth", hash);
- if (probe) probe.coloMs = Date.now() - tColo;
- if (shared && nowMs - shared.cachedAtMs < AUTH_TTL_MS) {
- if (probe) probe.tier = 1;
- if (shared.expiresAt && shared.expiresAt < nowSec) return null;
- if (authCache.size >= CACHE_MAX) authCache.clear();
- const entry: AuthEntry = { caller: shared.caller, expiresAt: shared.expiresAt, cachedAtMs: shared.cachedAtMs, lastBumpMs: 0 };
- authCache.set(hash, entry);
- bumpLastUsed(env, hash, entry, nowMs);
- return shared.caller;
- }
-
- // Stale-while-revalidate. Take the FRESHEST stale copy either tier holds —
- // the isolate entry can outlive the colo entry or vice versa, and using the
- // older of the two would shorten the window for no benefit. Serving it costs
- // nothing; the refresh behind it is what keeps the entry honest.
- const staleShared = shared && nowMs - shared.cachedAtMs < AUTH_STALE_MAX_MS ? shared : null;
- const staleLocal = cached && nowMs - cached.cachedAtMs < AUTH_STALE_MAX_MS ? cached : null;
- const stale =
- staleShared && (!staleLocal || staleShared.cachedAtMs > staleLocal.cachedAtMs) ? staleShared : staleLocal;
- if (stale) {
- // Expiry is still enforced inline, exactly as on the fresh paths — the
- // stale window widens revocation lag, never expiry.
- if (stale.expiresAt && stale.expiresAt < nowSec) return null;
- if (authCache.size >= CACHE_MAX) authCache.clear();
- const entry: AuthEntry = {
- caller: stale.caller,
- expiresAt: stale.expiresAt,
- cachedAtMs: stale.cachedAtMs,
- lastBumpMs: cached?.lastBumpMs ?? 0,
- };
- authCache.set(hash, entry);
- if (probe) probe.tier = 2;
- const refresh = refreshAuth(env, hash);
- if (ctx) ctx.waitUntil(refresh);
- bumpLastUsed(env, hash, entry, nowMs);
- return stale.caller;
- }
-
- const tD1 = Date.now();
- const row = await env.OPENCOMPUTER_DB.prepare(AUTH_KEY_SQL)
- .bind(hash)
- .first<AuthRow>();
- if (probe) {
- probe.tier = 3;
- probe.d1Ms = Date.now() - tD1;
- }
- if (!row) return null; // never cache negatives — a freshly-created key must work at once
- if (row.expires_at && row.expires_at < nowSec) return null;
-
- const caller = callerFromRow(row);
- if (authCache.size >= CACHE_MAX) authCache.clear();
- const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };
- authCache.set(hash, entry);
- // TTL is the STALE bound, not AUTH_TTL_MS: an entry that evaporates at 60s
- // can never be stale-served, which would leave the SWR branch above reachable
- // only from the isolate tier — i.e. never on the cross-isolate misses that
- // are the whole reason the colo tier exists.
- await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_STALE_MAX_MS / 1000);
- bumpLastUsed(env, hash, entry, nowMs);
- return caller;
-}
-
-// Cell rows are semi-static (base_url is fixed; capacity refreshes ~30s and
-// isHealthy already tolerates 120s staleness). Every create AND every exec/
-// sub-op resolves the cell — a burst does 100 identical reads for the same 1-2
-// cells. Cache per-isolate for a short window.
-const cellCache = new Map<string, { cell: CellRow | null; cachedAtMs: number }>();
-// Per-isolate cache of the active-cells list. pickCell ran this SELECT uncached
-// on every no-cellId create — ~65ms of the burst prework. Cells change rarely,
-// so a short TTL is safe and the routing decision recomputes from cached rows.
-let activeCellsCache: { cells: CellRow[]; cachedAtMs: number } | null = null;
-
-async function listActiveCells(env: Env): Promise<CellRow[]> {
- const nowMs = Date.now();
- if (activeCellsCache && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS) return activeCellsCache.cells;
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at
- FROM cells WHERE status = 'active'`,
- ).all<CellRow>();
- const cells = results ?? [];
- activeCellsCache = { cells, cachedAtMs: nowMs };
- return cells;
-}
-
-// loadCreateContext fetches the three org-keyed reads the create hot path needs
-// — org policy, running-sandbox count, active-cells list — in a SINGLE D1 round
-// trip via db.batch(), instead of three sequential awaits. Under a cold burst
-// (fresh isolates, caches empty) that collapses ~3×D1-latency into one. Each
-// piece still honours + populates its existing per-isolate cache, so warm/
-// sustained traffic skips D1 entirely and only the cold misses are batched.
-type CreateContext = { org: OrgPolicy | null; activeCount: number; cells: CellRow[]; cellsAtMs: number };
-
-// In-flight loads, keyed by org. The three cache tiers below only help a request
-// that arrives after some earlier request has already finished populating them —
-// which is never true at the start of a burst. Measured on prod 2026-08-20 at
-// burst-100: `ctx` was 376ms median / 500ms p90, the largest term inside the
-// create handler, because all 100 creates landed with every tier cold and each
-// one independently ran the same D1 batch. Collapsing them to one read per
-// isolate is the whole fix; the losers await the winner's promise instead of
-// queueing behind it in D1.
-//
-// Keyed by org rather than global because the batch is org-scoped, and deleted
-// in a finally so a rejection can't wedge every later create for that org.
-const createContextInflight = new Map<string, Promise<CreateContext>>();
-
-// ctxProbe is filled in by the load below so the create handler can attribute
-// its `ctx` mark. `ctx` conflates three tiers — isolate map, colo cache, D1 —
-// and a 10.6s reading says nothing about WHICH, which is the only thing that
-// decides what to cut. Written, never read, by anything but telemetry.
-export interface CtxProbe {
- coloMs: number;
- d1Ms: number;
- d1Stmts: number;
- coalesced: boolean;
-}
-
-function loadCreateContext(env: Env, orgID: string, ctx?: ExecutionContext, probe?: CtxProbe): Promise<CreateContext> {
- const inflight = createContextInflight.get(orgID);
- if (inflight) {
- // Collapsed onto another request's read IN THIS ISOLATE. Distinguishing
- // these matters: if a burst shows most requests coalesced and `ctx` is
- // still large, the isolate fan-out is the problem, not the read.
- if (probe) probe.coalesced = true;
- return inflight;
- }
- const p = (async () => {
- try {
- return await loadCreateContextUncoalesced(env, orgID, ctx, probe);
- } finally {
- createContextInflight.delete(orgID);
- }
- })();
- createContextInflight.set(orgID, p);
- return p;
-}
-
-async function loadCreateContextUncoalesced(
- env: Env,
- orgID: string,
- ctx?: ExecutionContext,
- probe?: CtxProbe,
-): Promise<{ org: OrgPolicy | null; activeCount: number; cells: CellRow[]; cellsAtMs: number }> {
- const nowMs = Date.now();
- const oc = orgPolicyCache.get(orgID);
- const cc = concurrencyCountCache.get(orgID);
- const orgWarm = oc !== undefined && nowMs - oc.cachedAtMs < ORG_POLICY_TTL_MS;
- const cntWarm = cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS;
- const cellsWarm = activeCellsCache !== null && nowMs - activeCellsCache.cachedAtMs < CELL_TTL_MS;
-
- let org = orgWarm ? oc!.policy : null;
- let activeCount = cntWarm ? cc!.count : 0;
- let cells = cellsWarm ? activeCellsCache!.cells : [];
-
- // Colo tier: try the shared cache (same TTLs as the isolate caches) for the
- // cold pieces before falling to D1 — cross-isolate creates in the same colo
- // then skip the batch entirely. Parallel lookups; each hit backfills the
- // isolate cache so the next create here is a pure memory hit.
- let orgHave = orgWarm;
- let cntHave = cntWarm;
- let cellsHave = cellsWarm;
- // Stale-but-usable count for the optimistic concurrency gate below.
- let staleCount: { count: number; cachedAtMs: number } | null =
- cc !== undefined && nowMs - cc.cachedAtMs < CONCURRENCY_STALE_MAX_MS ? cc : null;
- {
- const tColo = Date.now();
- const [so, sc, scl] = await Promise.all([
- orgHave ? null : coloGet<{ policy: OrgPolicy | null; cachedAtMs: number }>("org", orgID),
- cntHave ? null : coloGet<{ count: number; cachedAtMs: number }>("count", orgID),
- cellsHave ? null : coloGet<{ cells: CellRow[]; cachedAtMs: number }>("cells", "active"),
- ]);
- if (probe) probe.coloMs = Date.now() - tColo;
- if (so && nowMs - so.cachedAtMs < ORG_POLICY_TTL_MS) {
- org = so.policy;
- orgHave = true;
- if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();
- orgPolicyCache.set(orgID, { policy: so.policy, cachedAtMs: so.cachedAtMs });
- } else if (so && nowMs - so.cachedAtMs < ORG_STALE_MAX_MS && so.policy && !so.policy.is_halted) {
- // Stale-while-revalidate (mirrors the count gate): a ≤60s-stale,
- // not-halted org policy gates this create while a background refresh
- // brings it fresh — removing the periodic org+count D1 batch (~130ms)
- // from every Nth create. Halt latency worst case = ORG_STALE_MAX_MS.
- org = so.policy;
- orgHave = true;
- if (ctx) {
- ctx.waitUntil(
- env.OPENCOMPUTER_DB.prepare(
- ORG_POLICY_SQL,
- )
- .bind(orgID)
- .first<OrgPolicy>()
- .then(async (row) => {
- const at = Date.now();
- if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();
- orgPolicyCache.set(orgID, { policy: row ?? null, cachedAtMs: at });
- await coloPut("org", orgID, { policy: row ?? null, cachedAtMs: at }, ORG_STALE_MAX_MS / 1000);
- })
- .catch(() => {}),
- );
- }
- }
- if (sc && nowMs - sc.cachedAtMs < CONCURRENCY_COUNT_TTL_MS) {
- activeCount = sc.count;
- cntHave = true;
- if (concurrencyCountCache.size >= CACHE_MAX) concurrencyCountCache.clear();
- concurrencyCountCache.set(orgID, { count: sc.count, cachedAtMs: sc.cachedAtMs });
- } else if (sc && nowMs - sc.cachedAtMs < CONCURRENCY_STALE_MAX_MS) {
- if (!staleCount || sc.cachedAtMs > staleCount.cachedAtMs) staleCount = sc;
- }
- if (scl && nowMs - scl.cachedAtMs < CELL_TTL_MS) {
- cells = scl.cells;
- cellsHave = true;
- activeCellsCache = { cells: scl.cells, cachedAtMs: scl.cachedAtMs };
- } else if (scl && scl.cells.length > 0 && nowMs - scl.cachedAtMs < CELL_STALE_MAX_MS) {
- // Stale-while-revalidate, mirroring the org-policy gate above. Only ever
- // from a NON-EMPTY snapshot: serving a stale empty list would 503 every
- // create in this colo for the length of the stale window, which is a
- // strictly worse failure than routing on slightly old capacity numbers.
- cells = scl.cells;
- cellsHave = true;
- activeCellsCache = { cells: scl.cells, cachedAtMs: scl.cachedAtMs };
- if (ctx) {
- ctx.waitUntil(
- env.OPENCOMPUTER_DB.prepare(
- ACTIVE_CELLS_SQL,
- )
- .all<CellRow>()
- .then(async ({ results }) => {
- const fresh = results ?? [];
- // An empty read here is far more likely to be a blip than a fleet
- // with no active cells, and caching it would take the colo down
- // for the whole window. Leave the last good list in place.
- if (fresh.length === 0) return;
- const at = Date.now();
- activeCellsCache = { cells: fresh, cachedAtMs: at };
- await coloPut("cells", "active", { cells: fresh, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000);
- })
- .catch(() => {}),
- );
- }
- }
- }
-
- // Optimistic concurrency gate: the COUNT read is the last per-create D1
- // dependency once org+cells are cache-served. When the org's policy is
- // already known WITHOUT D1 and a stale (≤30s) count sits comfortably below
- // the limit, use the stale value and refresh it in the background — the cap
- // stays enforced within CONCURRENCY_STALE_HEADROOM of the limit, matching the
- // gate's existing "index trails events, reads low under burst" approximate
- // semantics. Near the limit the blocking read still happens.
- //
- // `orgHave` is deliberately NOT required any more. It was, and that coupling
- // is what dragged this back onto D1 in exactly the case that hurts: a burst
- // arriving on cold isolates has no org either, so the count joined the batch
- // and every request paid the round trip. The org policy is fetched in that
- // same batch, so by the time the limit is read below it is present regardless
- // of which tier supplied it — waiting for it here bought nothing.
- if (!cntHave && staleCount) {
- const limit = org?.max_concurrent_sandboxes ?? DEFAULT_MAX_CONCURRENT_SANDBOXES;
- if (staleCount.count + CONCURRENCY_STALE_HEADROOM <= limit) {
- activeCount = staleCount.count;
- cntHave = true;
- const refresh = env.OPENCOMPUTER_DB.prepare(
- RUNNING_COUNT_SQL,
- )
- .bind(orgID)
- .first<{ n: number }>()
- .then(async (row) => {
- const n = row?.n ?? 0;
- const at = Date.now();
- if (concurrencyCountCache.size >= CACHE_MAX) concurrencyCountCache.clear();
- concurrencyCountCache.set(orgID, { count: n, cachedAtMs: at });
- await coloPut("count", orgID, { count: n, cachedAtMs: at }, CONCURRENCY_STALE_MAX_MS / 1000);
- })
- .catch(() => {});
- if (ctx) ctx.waitUntil(refresh);
- }
- }
-
- const orgWarm2 = orgHave;
- const cntWarm2 = cntHave;
- const cellsWarm2 = cellsHave;
-
- const stmts: D1PreparedStatement[] = [];
- const kinds: Array<"org" | "count" | "cells"> = [];
- if (!orgWarm2) {
- stmts.push(
- env.OPENCOMPUTER_DB.prepare(
- ORG_POLICY_SQL,
- ).bind(orgID),
- );
- kinds.push("org");
- }
- if (!cntWarm2) {
- stmts.push(
- env.OPENCOMPUTER_DB.prepare(RUNNING_COUNT_SQL).bind(orgID),
- );
- kinds.push("count");
- }
- if (!cellsWarm2) {
- stmts.push(
- env.OPENCOMPUTER_DB.prepare(
- ACTIVE_CELLS_SQL,
- ),
- );
- kinds.push("cells");
- }
-
- if (stmts.length > 0) {
- const tD1 = Date.now();
- const res = await env.OPENCOMPUTER_DB.batch(stmts);
- if (probe) {
- probe.d1Ms = Date.now() - tD1;
- probe.d1Stmts = stmts.length;
- }
- const puts: Promise<void>[] = [];
- for (let i = 0; i < kinds.length; i++) {
- if (kinds[i] === "org") {
- org = ((res[i].results?.[0] as OrgPolicy) ?? null);
- if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();
- orgPolicyCache.set(orgID, { policy: org, cachedAtMs: nowMs });
- puts.push(coloPut("org", orgID, { policy: org, cachedAtMs: nowMs }, ORG_STALE_MAX_MS / 1000));
- } else if (kinds[i] === "count") {
- activeCount = (res[i].results?.[0] as { n: number } | undefined)?.n ?? 0;
- if (concurrencyCountCache.size >= CACHE_MAX) concurrencyCountCache.clear();
- concurrencyCountCache.set(orgID, { count: activeCount, cachedAtMs: nowMs });
- puts.push(coloPut("count", orgID, { count: activeCount, cachedAtMs: nowMs }, CONCURRENCY_STALE_MAX_MS / 1000));
- } else {
- cells = (res[i].results as CellRow[]) ?? [];
- // An empty list is never cached. readCellRow already refuses to cache a
- // miss — "caching a null would let one failed read blind every isolate
- // in the colo to a live cell" — but the active-cells LIST had no such
- // guard, so an empty result would be served for CELL_TTL_MS locally and
- // CELL_STALE_MAX_MS colo-wide. There is no confirmed incident behind
- // this; it is the same asymmetry, closed.
- if (cells.length === 0) {
- console.log(
- JSON.stringify({
- level: "warn",
- msg: "active-cells query returned no rows — not caching",
- orgID,
- }),
- );
- } else {
- activeCellsCache = { cells, cachedAtMs: nowMs };
- // Entry TTL is the STALE window, not CELL_TTL_MS: an entry that expires
- // at 5s can never be served stale, which is the whole point of the
- // branch above. Freshness is decided by cachedAtMs on read.
- puts.push(coloPut("cells", "active", { cells, cachedAtMs: nowMs }, CELL_STALE_MAX_MS / 1000));
- }
- }
- }
- await Promise.all(puts);
- }
- // cellsAtMs is WHEN these rows were read, and callers must judge cell
- // heartbeat freshness against it rather than against wall-clock now.
- //
- // Without it the stale tier defeats itself: it is allowed to serve a snapshot
- // for CELL_STALE_MAX_MS (5 min) while isHealthy rejects any capacity_updated_at
- // older than CAPACITY_FRESH_SEC (2 min) — so every create served a snapshot
- // between those two ages got "no cells available with capacity" while the cell
- // was perfectly healthy in D1. Reproduced at burst-100 as 100/100 creates
- // failing instantly (hdl=0) seconds after a sequential run passed 5/5.
- return { org, activeCount, cells, cellsAtMs: activeCellsCache?.cachedAtMs ?? nowMs };
-}
-
-const CELL_ROW_SQL =
- `SELECT cell_id, cloud, region, base_url, status, available_workers, capacity_updated_at
- FROM cells WHERE cell_id = ?1`;
-
-// In-flight row reads, keyed by cell. Same single-flight shape as
-// createContextInflight and authRefreshInflight, for the same reason.
-const cellRowInflight = new Map<string, Promise<CellRow | null>>();
-
-function readCellRow(env: Env, cellID: string): Promise<CellRow | null> {
- const inflight = cellRowInflight.get(cellID);
- if (inflight) return inflight;
- const p = (async () => {
- try {
- const cell = await env.OPENCOMPUTER_DB.prepare(CELL_ROW_SQL).bind(cellID).first<CellRow>();
- const at = Date.now();
- if (cellCache.size >= CACHE_MAX) cellCache.clear();
- cellCache.set(cellID, { cell, cachedAtMs: at });
- // Only a real row goes to the shared tier. Caching a null would let one
- // failed read blind every isolate in the colo to a live cell.
- if (cell) await coloPut("cell", cellID, { cell, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000);
- return cell;
- } finally {
- cellRowInflight.delete(cellID);
- }
- })();
- cellRowInflight.set(cellID, p);
- return p;
-}
-
-// lookupCell resolves one cell's row, through the same three tiers every other
-// hot read uses: isolate map, colo cache, then D1.
-//
-// It had ONLY the isolate map, and that was the largest remaining blocking read
-// on the exec path. A burst arrives on isolates that have never seen this cell,
-// so each one went straight to D1 for a row that changes almost never —
-// measured at `cell;dur=327` per exec across a burst-100, against `route;dur=9`
-// for the sandbox lookup right beside it that does have the tiers.
-//
-// SERVING STALE IS SAFE HERE, including for placement. The volatile fields are
-// available_workers and capacity_updated_at, and isHealthy() rejects a row whose
-// capacity_updated_at has aged past CAPACITY_FRESH_SEC — so an old row can only
-// ever make a cell look UNhealthy and be skipped. It cannot make a dead cell
-// look alive, which is the direction that would hurt.
-async function lookupCell(env: Env, cellID: string): Promise<CellRow | null> {
- const nowMs = Date.now();
- const c = cellCache.get(cellID);
- if (c && nowMs - c.cachedAtMs < CELL_TTL_MS) return c.cell;
-
- const shared = await coloGet<{ cell: CellRow; cachedAtMs: number }>("cell", cellID);
- if (shared && nowMs - shared.cachedAtMs < CELL_TTL_MS) {
- if (cellCache.size >= CACHE_MAX) cellCache.clear();
- cellCache.set(cellID, { cell: shared.cell, cachedAtMs: shared.cachedAtMs });
- return shared.cell;
- }
-
- // Stale-while-revalidate. Take the fresher of the two stale copies; either
- // tier can outlive the other.
- const staleShared = shared && nowMs - shared.cachedAtMs < CELL_STALE_MAX_MS ? shared : null;
- const staleLocal = c && c.cell && nowMs - c.cachedAtMs < CELL_STALE_MAX_MS ? c : null;
- const stale =
- staleShared && (!staleLocal || staleShared.cachedAtMs > staleLocal.cachedAtMs)
- ? { cell: staleShared.cell, cachedAtMs: staleShared.cachedAtMs }
- : staleLocal;
- if (stale && stale.cell) {
- readCellRow(env, cellID).catch(() => {}); // refresh behind the response
- return stale.cell;
- }
-
- return readCellRow(env, cellID);
-}
-
-// Freshness window — the CP emits capacity events every ~30s; 120s is a
-// generous 4× margin that covers a missed sample without flapping.
-const CAPACITY_FRESH_SEC = 120;
-
-// observedAtSec is when the row was READ. Heartbeat freshness is a property of
-// the reading, not of this moment — re-judging a cached snapshot against a later
-// clock makes every cache tier expire its own contents early. Defaults to
-// nowSec, so an uncached read behaves exactly as before.
-function isHealthy(cell: CellRow, nowSec: number, observedAtSec: number = nowSec): boolean {
- if (cell.status !== "active") return false;
- if (cell.capacity_updated_at == null) return false;
- if (observedAtSec - cell.capacity_updated_at > CAPACITY_FRESH_SEC) return false;
- if (cell.available_workers <= 0) return false;
- return true;
-}
-
-// Continent buckets used by distanceRank when cells span clouds. Coarse on
-// purpose — we just need "near" vs "far" for the cascade. Unknown regions
-// fall through to tier 3 (global).
-//
-// Region names follow the cell-id convention: AWS-style hyphenated form for
-// every cloud (e.g., Azure's westus2 is mapped to us-west-2 at provision
-// time, so the cells table never sees the cloud-native variant). One table
-// for all clouds.
-const REGION_CONTINENT: Record<string, string> = {
- // North America
- "us-east-1": "na", "us-east-2": "na",
- "us-west-1": "na", "us-west-2": "na", "us-west-3": "na",
- "us-central-1": "na", "us-north-central-1": "na", "us-south-central-1": "na",
- "ca-central-1": "na", "ca-east-1": "na",
- // Europe
- "eu-west-1": "eu", "eu-west-2": "eu", "eu-west-3": "eu",
- "eu-north-1": "eu", "eu-central-1": "eu", "eu-south-1": "eu",
- "uk-south-1": "eu", "uk-west-1": "eu",
- // Asia / Pacific
- "ap-southeast-1": "ap", "ap-southeast-2": "ap",
- "ap-northeast-1": "ap", "ap-northeast-2": "ap", "ap-northeast-3": "ap",
- "ap-east-1": "ap", "ap-south-1": "ap",
-};
-
-// Tier distance from `a` to `b`. Lower is closer.
-// 0 — same cloud + same region (cell siblings)
-// 1 — same cloud, different region
-// 2 — different cloud, same continent
-// 3 — anywhere else (different continent, or unknown region)
-function distanceRank(a: CellRow, b: CellRow): number {
- if (a.cloud === b.cloud && a.region === b.region) return 0;
- if (a.cloud === b.cloud) return 1;
- const aCont = REGION_CONTINENT[a.region];
- const bCont = REGION_CONTINENT[b.region];
- if (aCont && bCont && aCont === bCont) return 2;
- return 3;
-}
-
-// pickCell — layered placement.
-// 0. Hard pin from request body (cellId) — strict; if pinned cell is
-// unhealthy/missing, fail rather than silently fall back.
-// 1. Healthy candidates (status+freshness+available_workers gates).
-// 2. Home cell first, then siblings ordered by tier-distance from home.
-// 3. First candidate with capacity wins.
-// Returns null if nothing is eligible — caller turns that into 503.
-async function pickCell(
- env: Env,
- homeCell: string,
- requestedCellID: string | null,
- prefetchedCells?: CellRow[],
- cellsObservedAtMs?: number,
-): Promise<CellRow | null> {
- const nowSec = Math.floor(Date.now() / 1000);
- const observedSec = cellsObservedAtMs ? Math.floor(cellsObservedAtMs / 1000) : nowSec;
-
- // 0. Hard pin
- if (requestedCellID) {
- const c = await lookupCell(env, requestedCellID);
- return c && isHealthy(c, nowSec) ? c : null;
- }
-
- // Active-cells list: use the batch-prefetched rows on the create hot path
- // (loadCreateContext), else fetch (cached).
- const results = prefetchedCells ?? (await listActiveCells(env));
-
- // Home anchor for distance ranking. Derive it from the active list when
- // present (no extra read); only fall back to a direct lookup if home isn't
- // active — we still want its {cloud, region} as the anchor in that case.
- let home = results.find((c) => c.cell_id === homeCell) ?? null;
- if (!home) home = await lookupCell(env, homeCell);
-
- const healthy = results.filter((c) => isHealthy(c, nowSec, prefetchedCells ? observedSec : nowSec));
- if (healthy.length === 0) return null;
-
- if (home) {
- healthy.sort((a, b) => {
- const da = distanceRank(home, a);
- const db = distanceRank(home, b);
- if (da !== db) return da - db;
- // Tie-break: home wins ties (distance 0 to itself), then alphabetical for
- // deterministic ordering across cells the same distance from home.
- if (a.cell_id === home.cell_id) return -1;
- if (b.cell_id === home.cell_id) return 1;
- return a.cell_id.localeCompare(b.cell_id);
- });
- } else {
- // Home cell not registered in the table at all — degenerate config; pick
- // alphabetically rather than randomly so behavior is at least deterministic.
- healthy.sort((a, b) => a.cell_id.localeCompare(b.cell_id));
- }
-
- return healthy[0] ?? null;
-}
-
-// ── preview URL dispatch ─────────────────────────────────────────────────
-
-// parsePreviewHost detects whether the request's hostname is a sandbox
-// preview URL of the form `sb-{id}-p{port}.{anything}` and pulls out the
-// sandbox_id + port. Returns null for anything else (the request falls
-// through to the regular /api routes / /health / etc).
-//
-// The sandbox_id itself may contain hyphens (it's "sb-" + 8 hex chars in
-// practice, but we don't lock the format here — only the trailing -p<port>
-// shape matters), so the regex anchors `-p<digits>` at the END of the first
-// subdomain label and grabs everything before it as the id.
-function parsePreviewHost(hostname: string): { sandboxID: string; port: number } | null {
- const firstLabel = hostname.split(".", 1)[0];
- if (!firstLabel.startsWith("sb-")) return null;
- const m = firstLabel.match(/^(sb-.+)-p(\d+)$/);
- if (!m) return null;
- const port = Number.parseInt(m[2], 10);
- if (!Number.isFinite(port) || port < 1 || port > 65535) return null;
- return { sandboxID: m[1], port };
-}
-
-// handlePreviewURL is the edge-routed equivalent of the cell-local
-// ControlPlaneProxy.Middleware: resolve the sandbox to its owning cell via
-// D1, then forward the request through that cell's Tunnel to its CP's
-// /internal/preview/{id}/{port}/* route. The CP synthesizes the Host
-// header the worker's SandboxProxy expects, then routes to the worker.
-//
-// Cross-cell migration becomes invisible from this design — moving a
-// sandbox from cell A to cell B updates sandboxes_index.cell_id, and the
-// next request resolves to the new cell. No DNS or hostname changes.
-async function handlePreviewURL(
- req: Request,
- env: Env,
- m: { sandboxID: string; port: number },
-): Promise<Response> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT s.cell_id, s.status, c.base_url
- FROM sandboxes_index s
- JOIN cells c ON s.cell_id = c.cell_id
- WHERE s.id = ?1`,
- )
- .bind(m.sandboxID)
- .first<{ cell_id: string; status: string; base_url: string }>();
-
- if (!row) return new Response(`sandbox ${m.sandboxID} not found`, { status: 404 });
- if (row.status === "stopped" || row.status === "error") {
- return new Response(`sandbox ${m.sandboxID} is ${row.status}`, { status: 410 });
- }
- // status="hibernated" is fine — CP's doProxy will wake-on-request.
-
- const url = new URL(req.url);
- const base = row.base_url.replace(/\/$/, "");
- const target = `${base}/internal/preview/${m.sandboxID}/${m.port}${url.pathname}${url.search}`;
-
- try {
- // Forward the request as-is via the Request copy-constructor — preserves
- // method, body (including streamed/large bodies), headers, AND the
- // Upgrade: websocket handshake. Cloudflare's fetch propagates WebSocket
- // pairs transparently when both ends speak it.
- return await fetch(new Request(target, req));
- } catch (e) {
- return new Response(
- `cell ${row.cell_id} unreachable: ${(e as Error).message}`,
- { status: 502 },
- );
- }
-}
-
-// ── route handlers ───────────────────────────────────────────────────────
-
-
-// loadOrgPolicy reads an org's routing + policy fields from D1. Returns null
-// when the org doesn't exist (callers 401).
-const orgPolicyInflight = new Map<string, Promise<OrgPolicy | null>>();
-
-// loadOrgPolicy resolves the org row every exec needs to decide how to route.
-//
-// This used to consult ONLY the per-isolate map, whose TTL is 5s. Every exec on
-// the MicroVM path calls it (tryVmDoExec reads .runtime before it can pick a
-// path), and a 100-wide burst spreads across many fresh isolates, so most of
-// those calls missed and went to D1 — whose primary is in WNAM while the burst
-// runs in IAD. Measured on prod, that was the entire unexplained remainder of
-// the exec handler: `hdl` grew 67 -> 497ms across a prewarm sweep while the
-// gRPC exec inside it got FASTER (59 -> 35ms), because tighter client
-// concurrency made more of those cold misses land at once.
-//
-// The value is already sitting in the colo tier — loadCreateContext writes it on
-// every create and the PoolStock/request-path warmers refresh it — so this only
-// ever had to read what was there. Same fix that took the create path's `ctx`
-// mark from 376ms to 2ms.
-//
-// Staleness is safe for these callers specifically: all four use it for routing
-// and cap-token minting (runtime, billing_provider), never for halt
-// enforcement, which goes through enforceCreatePolicy on the create path.
-async function loadOrgPolicy(env: Env, orgID: string, ctx?: ExecutionContext): Promise<OrgPolicy | null> {
- const nowMs = Date.now();
- const cached = orgPolicyCache.get(orgID);
- if (cached && nowMs - cached.cachedAtMs < ORG_POLICY_TTL_MS) return cached.policy;
-
- const remember = (policy: OrgPolicy | null, at: number) => {
- if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();
- orgPolicyCache.set(orgID, { policy, cachedAtMs: at });
- };
-
- const shared = await coloGet<{ policy: OrgPolicy | null; cachedAtMs: number }>("org", orgID);
- if (shared) {
- const age = nowMs - shared.cachedAtMs;
- if (age < ORG_POLICY_TTL_MS) {
- remember(shared.policy, shared.cachedAtMs);
- return shared.policy;
- }
- // Stale-but-usable: serve it and refresh behind the response, rather than
- // making this request pay a transcontinental read for a value that changes
- // approximately never.
- if (age < ORG_STALE_MAX_MS && shared.policy) {
- remember(shared.policy, shared.cachedAtMs);
- if (ctx) ctx.waitUntil(refreshOrgPolicy(env, orgID).catch(() => {}));
- return shared.policy;
- }
- }
- // Single-flight the cold read: a burst arriving on one isolate would otherwise
- // fire N identical D1 reads before any of them lands.
- const inflight = orgPolicyInflight.get(orgID);
- if (inflight) return inflight;
- const p = refreshOrgPolicy(env, orgID).finally(() => orgPolicyInflight.delete(orgID));
- orgPolicyInflight.set(orgID, p);
- return p;
-}
-
-async function refreshOrgPolicy(env: Env, orgID: string): Promise<OrgPolicy | null> {
- const policy = await env.OPENCOMPUTER_DB.prepare(ORG_POLICY_SQL).bind(orgID).first<OrgPolicy>();
- const at = Date.now();
- if (orgPolicyCache.size >= CACHE_MAX) orgPolicyCache.clear();
- orgPolicyCache.set(orgID, { policy, cachedAtMs: at });
- await coloPut("org", orgID, { policy, cachedAtMs: at }, ORG_STALE_MAX_MS / 1000);
- return policy;
-}
-
-// The 402 for a halted Autumn org, so its message fits the org: a work-minute
-// halt names its reason and links Billing; on the credit rule, free gets the
-// paywall, legacy $20 Pro the upgrade to Pro, $200 Pro no upsell. Counted as
-// billing.paywall_shown. Only read on the (rare) halted path, after the
-// self-heal re-projected the row; any failure falls back to the paywall.
-async function haltedOrgResponse(
- req: Request,
- env: Env,
- ctx: ExecutionContext,
- orgID: string,
- structured = false,
-): Promise<Response> {
- const paywall = await paywallContext(env.OPENCOMPUTER_DB, orgID);
- ctx.waitUntil(emitPaywallShown(env, orgID, paywall.haltReason));
- return structured
- ? insufficientCreditsResponse(req, paywall)
- : insufficientCreditsLegacyResponse(req, {}, paywall);
-}
-
-// enforceCreatePolicy applies every org-level gate for creating or forking a
-// sandbox, reading authoritative state from D1 (and the CreditAccount DO for
-// free orgs). Returns an error Response to short-circuit, or null when allowed.
-//
-// This is the edge's job post-cutover: cells are interchangeable executors
-// that don't know about each other, so org policy can only be enforced
-// correctly here. The concurrent limit especially — it's a count across the
-// global sandboxes_index, and a per-cell count would let an org exceed its
-// limit once its sandboxes spread across cells.
-//
-// `sizes` carries the caller-requested cpu/mem/disk; 0 means "unspecified"
-// (inherit the checkpoint's value or the default), so size gates skip it —
-// the defaults are always within limits.
-async function enforceCreatePolicy(
- req: Request,
- env: Env,
- ctx: ExecutionContext,
- orgID: string,
- org: OrgPolicy,
- sizes: { cpuCount: number; memoryMB: number; diskMB: number },
- activeCount: number,
-): Promise<Response | null> {
- const plan = org.plan === "pro" ? "pro" : "free";
-
- // Autumn orgs: Autumn owns the balance, so the credit gate is purely the
- // is_halted projection — no CreditAccount DO. On a halt, self-heal (re-check
- // Autumn) so a just-topped-up user isn't stuck behind a lagging webhook. The
- // free-tier memory/CPU/disk ceilings below are skipped for autumn orgs (they
- // pay per GB-second); only the per-org max_disk_mb cap applies.
- if (org.billing_provider === "autumn") {
- if (org.is_halted === 1 && (await selfHealHalt(env, orgID))) {
- return haltedOrgResponse(req, env, ctx, orgID);
- }
- } else if (plan === "free") {
- // Legacy free-tier gate. is_halted is the D1 fast path; otherwise ask the
- // CreditAccount DO for an authoritative balance read. Pro orgs skip this.
- if (org.is_halted === 1) {
- return insufficientCreditsLegacyResponse(req);
- }
- const doStub = env.CREDIT_ACCOUNT.get(env.CREDIT_ACCOUNT.idFromName(orgID));
- const checkResp = await doStub.fetch(`https://do/check?org_id=${encodeURIComponent(orgID)}`, { method: "POST" });
- if (checkResp.status !== 200) {
- // Don't soft-fail open — credit gating exists for a reason. A genuinely
- // down DO surfaces as a 5xx.
- return json({ error: "credit check unavailable" }, 503);
- }
- const check = await checkResp.json<{ allowed: boolean; balance_cents: number }>();
- if (!check.allowed) {
- return insufficientCreditsLegacyResponse(req, { balance_cents: check.balance_cents });
- }
- }
-
- // Free-tier ceilings: 4GB / 1 vCPU, 20GB disk. Legacy only — autumn (prepaid)
- // orgs pay per GB-second and are gated by balance/halt, so they may launch any
- // size. Disk is still bounded for everyone by the per-org max_disk_mb check below.
- if (org.billing_provider !== "autumn" && plan === "free") {
- if (sizes.memoryMB > 4096 || sizes.cpuCount > 1) {
- return json({ error: "upgrade to pro for larger instances" }, 402);
- }
- if (sizes.diskMB > 20480) {
- return json({ error: "upgrade to pro for larger disk sizes" }, 402);
- }
- }
-
- // Per-org disk ceiling (all plans). 0 in D1 means "use the 20GB default".
- if (sizes.diskMB > 0) {
- const maxDisk = org.max_disk_mb > 0 ? org.max_disk_mb : 20480;
- if (sizes.diskMB > maxDisk) {
- return json({ error: `disk size ${sizes.diskMB}MB exceeds org limit of ${maxDisk}MB` }, 403);
- }
- }
-
- // Concurrent-sandbox limit (all plans). Counts `running` only — hibernated
- // sandboxes live in S3 and don't consume worker capacity. The count spans
- // every cell via the global sandboxes_index, which is the whole reason it
- // must live at the edge and not on any single cell.
- const limit = org.max_concurrent_sandboxes ?? DEFAULT_MAX_CONCURRENT_SANDBOXES;
- // active count is pre-fetched by loadCreateContext (batched with org+cells)
- // and cached there; enforceCreatePolicy no longer reads it itself.
- const active = activeCount;
- if (active >= limit) {
- return json(
- { error: `concurrent sandbox limit reached (${active}/${limit}) — hibernate or delete one before creating another`, active, limit },
- 429,
- );
- }
-
- return null;
-}
-
-async function insertSandboxIndex(
- env: Env,
- caller: Caller,
- cellID: string,
- parsed: SandboxCreateResult,
- fallbackCpuCount: number,
- fallbackMemoryMB: number,
-): Promise<void> {
- if (!parsed.sandboxID) return;
- // Guarded upsert (was INSERT OR REPLACE): the edge-claim finalize insert runs
- // ~1.5s after the box is returned, so a destroy in that window can land a
- // 'stopped' tombstone first (see the DELETE handler). The WHERE clause makes
- // this insert refuse to resurrect a row that a concurrent destroy already
- // moved to a terminal state — closing the create→destroy leak. On a normal
- // create the row doesn't exist yet, so the plain INSERT branch runs.
- await env.OPENCOMPUTER_DB.prepare(
- `INSERT INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, end_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10)
- ON CONFLICT(id) DO UPDATE SET
- org_id=excluded.org_id, user_id=excluded.user_id, cell_id=excluded.cell_id,
- worker_id=excluded.worker_id, status=excluded.status,
- cpu_count=excluded.cpu_count, memory_mb=excluded.memory_mb,
- last_event_at=excluded.last_event_at, end_at=excluded.end_at
- WHERE sandboxes_index.status NOT IN ('stopped', 'error')`,
- )
- .bind(
- parsed.sandboxID,
- caller.orgID,
- caller.userID,
- cellID,
- parsed.workerID ?? null,
- parsed.status ?? "running",
- fallbackCpuCount,
- parsed.memoryMB ?? fallbackMemoryMB,
- Math.floor(Date.now() / 1000),
- unixFromISO(parsed.endAt),
- )
- .run();
-}
-
-function indexSandboxFromSSE(
- resp: Response,
- env: Env,
- ctx: ExecutionContext,
- caller: Caller,
- cellID: string,
- fallbackCpuCount: number,
- fallbackMemoryMB: number,
-): Response {
- if (!resp.ok || !resp.body) return resp;
-
- const decoder = new TextDecoder();
- let buffer = "";
- let eventName = "message";
- let dataLines: string[] = [];
- let indexed = false;
-
- const handleEvent = async () => {
- if (eventName !== "result" || dataLines.length === 0 || indexed) {
- eventName = "message";
- dataLines = [];
- return;
- }
-
- indexed = true;
- const data = dataLines.join("\n");
- eventName = "message";
- dataLines = [];
-
- try {
- const parsed = JSON.parse(data) as SandboxCreateResult;
- // Fire the D1 index write off the response path (waitUntil keeps it alive
- // after we return). Under a burst these serialize on D1's single writer,
- // so awaiting them here stretches the create tail; the index is also
- // reconciled by events-ingest, so a slightly-late row is harmless.
- ctx.waitUntil(
- insertSandboxIndex(env, caller, cellID, parsed, fallbackCpuCount, fallbackMemoryMB).catch((e) =>
- console.error("sandboxes_index SSE create insert failed:", e),
- ),
- );
- } catch (e) {
- console.error("sandboxes_index SSE create parse failed:", e);
- }
- };
-
- const processLine = async (line: string) => {
- if (line === "") {
- await handleEvent();
- return;
- }
- if (line.startsWith(":")) return;
- const colon = line.indexOf(":");
- const field = colon === -1 ? line : line.slice(0, colon);
- const value = colon === -1 ? "" : line.slice(colon + (line[colon + 1] === " " ? 2 : 1));
- if (field === "event") {
- eventName = value;
- } else if (field === "data") {
- dataLines.push(value);
- }
- };
-
- const stream = new TransformStream<Uint8Array, Uint8Array>({
- async transform(chunk, controller) {
- buffer += decoder.decode(chunk, { stream: true });
- const lines = buffer.split(/\r\n|\r|\n/);
- buffer = lines.pop() ?? "";
- for (const line of lines) {
- await processLine(line);
- }
- controller.enqueue(chunk);
- },
- async flush() {
- const tail = decoder.decode();
- if (tail) buffer += tail;
- if (buffer) await processLine(buffer);
- await handleEvent();
- },
- });
-
- return new Response(resp.body.pipeThrough(stream), resp);
-}
-
-// Stock shard fan-out (see pool_stock.ts for sizing): shard 0 uses the bare
-// cellID as its DO name — that's the pre-sharding instance, kept addressable so
-// its stock drains via claims + surplus-trim instead of stranding until TTL.
-//
-// SHARD_GEN: bump to mint fresh DO instances when placement went wrong — a DO
-// pins to the colo of its FIRST request forever, so shards must only ever be
-// first-touched by traffic from the cell's own metro (create from a sandbox in
-// the cell, never a laptop). g1's shards 1-7 were armed from off-metro and
-// pinned cross-country; g2 exists to re-place them. Old-gen shards strand their
-// reservations at most ENTRY_TTL + the cell's 15-min reaper.
-// g3: measured 2026-08-20 from an IAD sandbox, g2's shards answered from LAX and
-// SJC with doin=0 — every claim was a ~78ms cross-country round trip and the
-// entire cost of a ~92ms create. locationHint below could not save them because
-// placement is fixed at creation and these objects predate it. Shard 0 is folded
-// into the gen scheme here too: it had kept the bare cellID name so the
-// pre-sharding DO would drain as a first-class shard, but that cutover is long
-// done, and the bare name was permanently unplaceable — a guaranteed 1-in-8
-// cross-country claim no gen bump could ever fix.
-// g4: g3 fixed the hemisphere but not the metro. Measured on prod 2026-08-20
-// from an IAD runner, the g3 shards split MIA/IAD — `doin=0` on both, so the
-// gap is pure network: IAD shards answered a claim in 10-18ms, MIA shards in
-// 35-49ms, dragging the claim median to 35ms and create to 50ms.
-//
-// locationHint is doing its job: Miami IS eastern North America. The hint picks
-// a region, not a metro, so within enam the placement still falls out of which
-// colo touches the object first. That is the part only the arming run controls
-// — see the note above about first-touching from the cell's own metro.
-// g5 stops trying to AIM placement and starts SELECTING it. Four generations
-// were armed exactly as the note above prescribes — first-touched from a
-// sandbox inside the cell's own metro — and all four still scattered across
-// five colos. The conclusion is that first-touch-colo does not decide placement
-// within a region; Cloudflare spreads inside enam and the arming client cannot
-// override that. So placement is not something to get right, it is something to
-// measure: mint far more candidate shard names than we need, ask each one where
-// it landed (GET /internal/pool/colo-probe), and keep only the indices that
-// answer IAD. Selection is deterministic where placement is not, and it is
-// permanent for the same reason placement was a trap — a placed DO never moves.
-//
-// POOL_STOCK_SHARD_IDS is therefore a MEASUREMENT, not a configuration. Re-run
-// the probe and re-pick if the shard set is ever regenerated; do not hand-edit
-// it to indices nobody has verified.
-// Probed on prod 2026-08-21 from the control plane (IAD ingress), 64 g5
-// candidates: IAD 27, EWR 17, ATL 9, MIA 7, ORD 4. Confirms the diagnosis —
-// every candidate was first-touched by the same request, from one colo, and
-// they still scattered five ways. Placement inside enam is not ours to aim.
-//
-// The eight below are the first eight that answered IAD. There is nothing
-// special about these indices; they are simply the ones that landed where we
-// want, which is the entire idea.
-const POOL_STOCK_SHARD_GEN = "g5";
-// SHARD COUNT IS A FUNCTION OF POOL SIZE, not a free parameter. The sizing
-// invariant (pool_stock.ts) is SHARDS × TARGET_STOCK ≤ the cell pool, and it
-// binds from BOTH sides: too many shards against a small pool and every shard
-// sits at 0, so claims miss the DO and pay the control-plane fallback instead.
-// Measured on a 10-box dev pool with all eight shards at TARGET_STOCK=1:
-// stock p50=0, 4 of 10 creates took `claimmiss` at 859ms, and the burst median
-// went 886ms → 1.70s versus the same code on a 130-box pool.
-//
-// So take a PREFIX of the measured set rather than inventing indices — these are
-// the ones probed into the right colo, and a prefix keeps that property. Four
-// shards × TARGET_STOCK=2 = 8, inside a 10-box pool with headroom to spare.
-// Restore the full eight when the cell pool goes back above ~128.
-const POOL_STOCK_SHARD_IDS_ALL = [1, 4, 6, 12, 13, 14, 16, 17];
-const POOL_STOCK_SHARD_IDS_DEFAULT = POOL_STOCK_SHARD_IDS_ALL.slice(0, 4);
-// How many candidate names the probe route sweeps. Only the ones that report
-// the target colo get promoted into the shard list.
-const POOL_STOCK_CANDIDATES = 64;
-
-// Resolved once per isolate. The value cannot change under a running isolate —
-// it comes from a binding, and a binding change means a redeploy, which means a
-// new isolate.
-let poolStockShardIdsCache: number[] | null = null;
-
-/**
- * poolStockShardIds is the ordered list of shard ids this environment uses.
- *
- * SHARDING IS A THROUGHPUT TOOL AND IT IS NOT FREE. A shard is a separate
- * single-threaded Durable Object, so N shards give N concurrent claims — but
- * they also FRAGMENT the pool N ways, and a claim that lands on an empty shard
- * pays a full DO round trip to learn nothing. Measured on dev 2026-08-25: a
- * `claimmiss` cost 300-320ms at 4 shards against 84-98ms at 1, and even a
- * successful claim cost ~150ms at dotry=2 versus ~88ms at dotry=1.
- *
- * The break-even is the sizing invariant (pool_stock.ts): SHARDS × TARGET_STOCK
- * must be ≤ the cell's real pool. Below that line every extra shard is pure
- * cost, because there is no concurrency to win — there are not enough boxes to
- * keep one shard busy, let alone four. A single shard is therefore the correct
- * configuration for a small pool, not a degraded one, and "1" here is a
- * first-class setting rather than an emergency fallback.
- *
- * Above the line, add shards — but only ids that have been PROBED into the
- * target colo for THAT CELL (see the gen note above). Never promote an id
- * nobody has measured: it is a coin flip across five colos.
- */
-function poolStockShardIds(env: Env): number[] {
- if (poolStockShardIdsCache) return poolStockShardIdsCache;
- const raw = (env.POOL_STOCK_SHARD_IDS ?? "").trim();
- let ids = raw
- .split(",")
- .map((s) => Number.parseInt(s.trim(), 10))
- .filter((n) => Number.isInteger(n) && n >= 0);
- if (ids.length === 0) {
- if (raw !== "") {
- // Loud, because silently serving the prod-measured set to a cell it was
- // never measured against is precisely the failure this binding exists to
- // stop.
- console.error(`pool-stock: POOL_STOCK_SHARD_IDS=${JSON.stringify(raw)} parsed to nothing — falling back to the default set`);
- }
- ids = POOL_STOCK_SHARD_IDS_DEFAULT;
- }
- poolStockShardIdsCache = ids;
- return ids;
-}
-
-function poolStockShardName(cellID: string, id: number): string {
- return `${cellID}#${POOL_STOCK_SHARD_GEN}#${id}`;
-}
-
-/**
- * poolStockStub resolves a shard INDEX (0..shards-1) to its Durable Object.
- *
- * Index, never id. The two were conflated in runPoolKeepWarm, which mapped over
- * the ID list and passed each id in here as though it were an index: with ids
- * [1,4,6,12] the keep-warm touched {4,4,6,12}, hitting shard 4 twice and NEVER
- * touching shard 1. That shard idle-decommissioned its stock after 30 minutes
- * and its alarm lapsed after 6 hours, so it could not restock proactively and
- * only ever re-armed on a claim that had already missed. One shard in four was
- * structurally cold, and 1-in-4 claims paid a miss to discover it.
- */
-function poolStockStub(env: Env, cellID: string, shard: number): DurableObjectStub {
- const ids = poolStockShardIds(env);
- const name = poolStockShardName(cellID, ids[shard] ?? shard);
- // Deterministic placement hint: pin the stock DO to eastern North America
- // (covers eastus2 / the IAD leaderboard runner) so a claim never eats a
- // cross-colo hop even if the first touch comes from an off-metro edge. A
- // no-op for DOs already placed; guards future/new shards from the
- // first-touch-colo placement trap that previously cost ~70ms/claim.
- return env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name), { locationHint: "enam" });
-}
-
-// ---------------------------------------------------------------------------
-// Pool claim: one DO pop per create.
-//
-// There used to be a third tier here — an isolate-local "magazine" that batched
-// a refill across shards and served subsequent creates from memory. It is gone.
-// The idea was sound (amortize the DO subrequest + HMAC over a burst) but it
-// could not be made correct: a magazine lives in isolate-local memory, so a
-// burst that fragments across isolates leaves each one holding stock no other
-// create can reach, and Cloudflare may evict the isolate at any time. Sizing it
-// was a forced choice between over-fetching (boxes strand until the cell's
-// 15-min reaper) and under-fetching (misses fall through to a 9-17s cold
-// launch). Measured on dev at 100-way: of 104 boxes staged in the shards, 48
-// served creates, 24 were still in the shards, and ~32 were simply gone.
-//
-// It was also solving the wrong problem. The magazine bought back a ~10ms
-// server-side claim while every create and exec was paying ~165ms to cross the
-// continent to a control plane in westus2 for boxes in us-east-1. Removing a
-// tier of cache is worth more than tuning one: what remains has a single owner
-// (the DO) and one expiry (ENTRY_TTL), so a box cannot be in two places.
-interface PoolBox {
- id: string;
- workerID: string;
- region: string;
- sandboxDomain: string;
- token: string;
- // How to reach the box's agent, when the backend keeps its own stock and so
- // already knows. `token` above is the CUSTOMER's sandbox token; these are the
- // AWS proxy's port-scoped credential and never leave the edge. Cached at
- // create so the first exec can dial the guest without asking westus2.
- agentEndpoint?: string;
- agentToken?: string;
- agentPort?: number;
-}
-
-// claimPoolBox pops one ready-to-serve box (token already minted in the DO).
-// Returns null to fall through to the CP create.
-//
-// One /claim-batch(count:1) against a random shard. When the shards are evenly
-// stocked — the steady state, since each targets POOL_STOCK_TARGET — the first
-// call hits and a create costs exactly one DO round trip. The walk below is the
-// uneven-drain path, not the common one.
-// Per-shard stock hints, keyed by INDEX into POOL_STOCK_SHARD_IDS.
-//
-// Every claim response already reports how much stock the serving shard had
-// left, and until now the edge stamped it into server-timing and threw it away.
-// That is the exact information needed to stop walking into empty shards, and
-// it arrives for free on a response we are already waiting for — no extra round
-// trip, no extra storage, no extra subrequest.
-//
-// Why it matters: sharding fragments the pool N ways, so under burst some
-// shards are EMPTY BY CONSTRUCTION, and a claim that lands on one pays a full
-// Durable Object round trip to learn nothing. Measured on dev 2026-08-25:
-// `claimmiss` (all shards walked, none stocked) cost 300-320ms at 4 shards and
-// 84-98ms at 1, and even a successful claim cost ~150ms at dotry=2 against
-// ~88ms at dotry=1. The tax is one hop per empty shard, and it is paid on the
-// customer's create.
-//
-// Isolate-local on purpose. A colo-shared copy would help more isolates but
-// costs a Cache API read on the hot path, which is the thing this exists to
-// avoid; a burst lands on many isolates and each learns within its first claim.
-const poolStockHints = new Map<number, { stock: number; atMs: number }>();
-// Hints go stale fast because the control plane is actively restocking. Long
-// enough to steer the shards of one burst, short enough that a shard which has
-// just been refilled is not avoided. Being wrong only costs the walk we would
-// have done anyway — a stale "empty" shard is tried LAST, never skipped.
-const STOCK_HINT_TTL_MS = 1_500;
-
-function noteShardStock(shard: number, stock: number): void {
- poolStockHints.set(shard, { stock, atMs: Date.now() });
-}
-
-// poolStockWalkOrder returns every shard index, ordered so ones believed to
-// hold stock come first. It never DROPS a shard: full coverage is what fixed
-// the earlier 3-attempt walk, where 56 of 100 concurrent creates fell through
-// to a cold control-plane launch while the shards still held 22-81 boxes.
-// Believed-empty shards are demoted, not excluded.
-//
-// Both groups are shuffled rather than sorted by stock. Sorting would send
-// every isolate in a burst to the same "best" shard and serialize them against
-// one single-threaded object — recreating, at the head of the walk, exactly the
-// contention sharding exists to spread.
-// With a single shard this collapses to [0] and every branch below is dead —
-// no hint bookkeeping, no shuffle, no walk. That is the point: at one shard
-// `dotry` is always 1 and a `claimmiss` means the pool is genuinely empty
-// rather than that we guessed the wrong object.
-function poolStockWalkOrder(shards: number): number[] {
- if (shards <= 1) return [0];
- const now = Date.now();
- const likely: number[] = [];
- const unlikely: number[] = [];
- for (let i = 0; i < shards; i++) {
- const h = poolStockHints.get(i);
- // Unknown counts as likely: never having asked is not evidence of empty.
- if (h && now - h.atMs < STOCK_HINT_TTL_MS && h.stock <= 0) unlikely.push(i);
- else likely.push(i);
- }
- for (const g of [likely, unlikely]) {
- for (let i = g.length - 1; i > 0; i--) {
- const j = Math.floor(Math.random() * (i + 1));
- [g[i], g[j]] = [g[j], g[i]];
- }
- }
- return likely.concat(unlikely);
-}
-
-async function claimPoolBox(
- env: Env,
- cell: CellRow,
- orgID: string,
-): Promise<{ box: PoolBox; stock: number; doMs: number; doColo: string; attempts: number } | null> {
- const body = JSON.stringify({
- cell: { cellID: cell.cell_id, baseURL: cell.base_url },
- orgID,
- count: 1,
- });
- const order = poolStockWalkOrder(poolStockShardIds(env).length);
- for (let attempt = 0; attempt < order.length; attempt++) {
- const shard = order[attempt];
- try {
- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/claim-batch", {
- method: "POST",
- body,
- });
- if (!r.ok) {
- noteShardStock(shard, 0);
- continue;
- }
- const data = (await r.json()) as { boxes?: PoolBox[]; stock?: number; t?: number; colo?: string };
- // Record what the shard reported BEFORE deciding, so a shard that handed
- // out its last box is remembered as empty for the next create.
- noteShardStock(shard, data.stock ?? 0);
- const b = data.boxes?.[0];
- if (!b) continue;
- // attempts is 1-based: how many shards this claim had to touch to find a
- // box. Every miss above is a FULL round trip to a DO, so this is the only
- // way to tell an expensive hop from several cheap ones — `claim` alone
- // cannot distinguish "one slow shard" from "four empty shards".
- return {
- box: b,
- stock: data.stock ?? -1,
- doMs: data.t ?? -1,
- doColo: data.colo ?? "?",
- attempts: attempt + 1,
- };
- } catch {
- noteShardStock(shard, 0);
- }
- }
- return null;
-}
-
-// runPoolKeepWarm touches every shard of every active cell so the stock never
-// idle-decommissions between bursts.
-//
-// The shard's own idle policy is right for a shard nobody uses and wrong for the
-// traffic this pool actually serves. Stock is released after
-// IDLE_DECOMMISSION_MS (30 min) and the alarm stops entirely after
-// WARM_MAX_IDLE_MS (6h). But the workloads that care about create latency are
-// exactly the ones that arrive after a long quiet period AND arrive all at once:
-// a weekly benchmark, a nightly CI fan-out, an hourly cron. Each of those lands
-// on a shard set that has been fully cold for far longer than six hours, so all
-// N concurrent creates miss every shard together and fall through to
-// control-plane cold launches paced by the RunMicrovm quota — the exact 25s tail
-// the pool exists to prevent. The pool was being handed back precisely when it
-// was about to be needed.
-//
-// This creates NOTHING. It refreshes the idle clock and re-arms the alarm; the
-// alarm's ordinary restock does the reserving. That distinction is the whole
-// design: a keep-warm that created sandboxes to stay warm would leak a box every
-// tick forever, which is worse than the problem.
-//
-// Cost is one DO wake per shard per cron tick (8 shards × 1 cell = 8 wakes / 5
-// min). Failures are logged and swallowed: a cron that throws would take the
-// other scheduled jobs down with it, and a missed tick just means the next one
-// does the work.
-async function runPoolKeepWarm(env: Env): Promise<void> {
- const cells = await listActiveCells(env);
- if (cells.length === 0) return;
- let ok = 0;
- let failed = 0;
- await Promise.all(
- cells.flatMap((cell) =>
- // Map over INDICES, not ids — poolStockStub takes an index. Mapping over
- // the id list here is the bug described in poolStockStub's docstring: it
- // left one live shard permanently un-warmed.
- poolStockShardIds(env).map(async (_id, shard) => {
- try {
- const r = await poolStockStub(env, cell.cell_id, shard).fetch("https://pool-stock/touch", {
- method: "POST",
- body: JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } }),
- });
- if (r.ok) ok++;
- else failed++;
- } catch {
- failed++;
- }
- }),
- ),
- );
- if (failed > 0) {
- console.error(`pool-keepwarm: touched ${ok} shard(s), ${failed} FAILED — stock may idle-decommission before the next burst`);
- }
-}
-
-// edgeClaimEligible: a create qualifies for the edge fast path only when it
-// asks for exactly what pool boxes are manufactured as — base template at the
-// default shape (4GB/1cpu/default disk), no guest-side customization (envs,
-// secrets, image, snapshot, webhooks, preview auth). Anything else falls
-// through to the cell, which handles it exactly as before (including its own
-// pool claim for claimable shapes). metadata/timeout are pure bookkeeping the
-// finalize call persists, so they don't disqualify.
-function edgeClaimEligible(bodyText: string, b: Record<string, unknown> | null): boolean {
- if (!bodyText) return true;
- if (!b) return false; // non-empty body that didn't parse
- const template = typeof b.templateID === "string" ? b.templateID : "";
- if (template !== "" && template !== "base") return false;
- if (b.envs && Object.keys(b.envs as object).length > 0) return false;
- if (b.secretStore || b.image || b.snapshot || b.previewAuth || b.burst) return false;
- if (Array.isArray(b.webhooks) && b.webhooks.length > 0) return false;
- if (b.sandboxFamily || b.alias || b.cellId || b.networkEnabled != null) return false;
- if (typeof b.port === "number" && b.port !== 0 && b.port !== 80) return false;
- if (typeof b.cpuCount === "number" && b.cpuCount !== 0 && b.cpuCount !== 1) return false;
- if (typeof b.memoryMB === "number" && b.memoryMB !== 0 && b.memoryMB !== 4096) return false;
- if (typeof b.diskMB === "number" && b.diskMB !== 0 && b.diskMB !== 20480) return false;
- return true;
-}
-
-// finalizeEdgeClaim runs off the response path (waitUntil): D1 index row so
-// the dashboard/GET sees the box, then the cell's claim-finalize (PG rebind +
-// worker ClaimSandbox: billing on, idle timeout). On failure the box is dead —
-// mark the index row error and drop the route so the customer's next op
-// surfaces a clean failure instead of a phantom.
-async function finalizeEdgeClaim(
- env: Env,
- caller: Caller,
- cell: CellRow,
- plan: string,
- billingProvider: string,
- runtime: string,
- sandboxID: string,
- workerID: string,
- bodyText: string,
- // The org's pin. Defaults to `runtime` so callers that have only one value
- // behave as before; the create path passes both because they differ whenever
- // SDK-version routing decided this create.
- runtimePin = runtime,
-): Promise<void> {
- // Index insert is DEFERRED below the finalize call + a short delay: D1 has a
- // single writer, and a create burst otherwise queues ~100 inserts exactly
- // when cold-isolate hot-path READS (auth/route/count) need D1. The colo route
- // cache serves the box's own sub-ops, and events-ingest reconciles the row
- // regardless — the insert only backstops dashboard/list visibility.
- try {
- // Minted HERE (off the response path) rather than on the create hot path —
- // only this finalize call ever consumes it on the edge-claim route, and the
- // HMAC sign was one of the larger CPU items at burst-100 concurrency.
- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, billingProvider, runtimePin, caller.userID, runtime);
- let body: Record<string, unknown> = {};
- try {
- body = bodyText ? (JSON.parse(bodyText) as Record<string, unknown>) : {};
- } catch {
- /* eligibility already vetted the body; belt-and-braces */
- }
- body.sandboxID = sandboxID;
- // Bill/grow at the default create shape the box was manufactured as.
- if (!body.memoryMB) body.memoryMB = 4096;
- if (!body.cpuCount) body.cpuCount = 1;
- const r = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/claim-finalize", {
- method: "POST",
- headers: { authorization: "Bearer " + capToken, "content-type": "application/json" },
- body: JSON.stringify(body),
- });
- if (!r.ok) {
- const detail = await r.text();
- throw new Error(`${r.status} ${detail}`);
- }
- await new Promise((resolve) => setTimeout(resolve, 1500));
- await insertSandboxIndex(env, caller, cell.cell_id, { sandboxID, workerID, status: "running", memoryMB: 4096 }, 1, 4096).catch((e) =>
- console.error(`edge-claim: index insert failed for ${sandboxID}:`, e),
- );
- } catch (e) {
- console.error(`edge-claim: FINALIZE FAILED for ${sandboxID} — marking error:`, e);
- sandboxRouteCache.delete(sandboxID);
- const nowSec = Math.floor(Date.now() / 1000);
- await env.OPENCOMPUTER_DB.prepare(
- "UPDATE sandboxes_index SET status='error', last_event_at=?2 WHERE id=?1",
- )
- .bind(sandboxID, nowSec)
- .run()
- .catch(() => {});
- }
-}
-
-async function createSandbox(req: Request, env: Env, ctx: ExecutionContext, tTop?: number): Promise<Response> {
- // Per-phase timing → Server-Timing response header (Date.now advances on I/O
- // in Workers, so deltas attribute I/O waits; pure CPU shows ~0).
- const phases: string[] = [];
- let tPrev = Date.now();
- const tEntry = tPrev;
- // `pre` is everything before this handler ran: client send -> CF -> routing ->
- // handler entry. Every other mark starts at tPrev, i.e. AFTER this point, so
- // without it the biggest term on the burst create path is invisible. Measured
- // 2026-08-20 from IAD: create median scaled 334->551->853ms at concurrency
- // 10/25/100 while the marks stayed flat (claim 20->21->32ms), leaving ~700ms
- // unattributed even after cutting the waitUntil fan-out. This says whether
- // that time is spent getting to the handler or after the response is built.
- //
- // Client-supplied clock, so it carries the client's skew — fine against a
- // ~700ms signal, useless for anything small. Absent header => no mark.
- // `top` is OUR routing cost: Worker invocation -> this handler. Skew-free,
- // unlike `pre` below, which needs a client clock. It splits the residual in
- // two: anything before tTop happened before the isolate ran (admission,
- // transport), anything between tTop and here is ours to cut.
- if (typeof tTop === "number") phases.push(`top;dur=${tEntry - tTop}`);
- const clientSentMs = Number(req.headers.get("x-client-sent") ?? "");
- if (Number.isFinite(clientSentMs) && clientSentMs > 0) {
- phases.push(`pre;dur=${tEntry - clientSentMs}`);
- }
- const mark = (name: string): void => {
- const t = Date.now();
- phases.push(`${name};dur=${t - tPrev}`);
- tPrev = t;
- };
- const authProbe: AuthProbe = { tier: 0, coloMs: 0, d1Ms: 0, hashMs: 0 };
- const caller = await authenticate(req, env, ctx, authProbe);
- mark("auth");
- // `autht` is a TIER, not a duration — 0 isolate, 1 colo, 2 stale, 3 D1.
- // Which colo served this request. A miss in the colo-shared Cache API tier has
- // two very different causes — the cache is not holding, or the burst is spread
- // across colos so each one is legitimately cold — and they need opposite
- // fixes. `desc` is a colo code, not a duration.
- phases.push(`colo;desc=${req.headers.get("cf-ray")?.split("-")[1] ?? "?"}`);
- phases.push(
- `autht;dur=${authProbe.tier}`,
- `authcolo;dur=${authProbe.coloMs}`,
- `authd1;dur=${authProbe.d1Ms}`,
- `authhash;dur=${authProbe.hashMs}`,
- );
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
-
- // One batched D1 round-trip for org + running-count + active-cells (was three
- // serial reads on the create hot path). Cache-aware: warm isolates skip D1.
- const ctxProbe: CtxProbe = { coloMs: 0, d1Ms: 0, d1Stmts: 0, coalesced: false };
- const { org, activeCount, cells, cellsAtMs } = await loadCreateContext(env, caller.orgID, ctx, ctxProbe);
- mark("ctx");
- // Which tier `ctx` actually spent its time in. `ctxn` is a statement COUNT,
- // not a duration; Server-Timing has nowhere else to put it.
- phases.push(
- `ctxcolo;dur=${ctxProbe.coloMs}`,
- `ctxd1;dur=${ctxProbe.d1Ms}`,
- `ctxn;dur=${ctxProbe.d1Stmts}`,
- `ctxco;dur=${ctxProbe.coalesced ? 1 : 0}`,
- );
- if (!org) return json({ error: "org not found" }, 401);
- const plan = org.plan === "pro" ? "pro" : "free";
- // Which runtime this create lands on. orgs.runtime is a PIN; when it is unset
- // the calling SDK's major decides, so upgrading @opencomputer/sdk to 1.x IS
- // the migration and pinning the old major is the rollback. See runtime_gate.ts.
- //
- // Resolved once, here, and used for every runtime decision below — the
- // edge-claim gate, the finalize message, and the capability token the cell
- // reads its backend off. Reading org.runtime directly at any of those points
- // again would route the create one way and label it another.
- const runtime = effectiveRuntime(env, org.runtime, req.headers.get(SDK_VERSION_HEADER));
- // The v1 fleet it would route to no longer exists. Refused here rather than
- // forwarded, so the caller gets the upgrade instruction instead of whatever
- // a create against a shut-down fleet happens to look like.
- if (isRetiredRuntime(runtime)) return json(v1RetiredError(), V1_RETIRED_STATUS);
-
- // Read body once — used for size-gating, the hard-pin cell peek, and the
- // verbatim forward to the CP.
- let bodyText = await req.text();
- let requestedCellID: string | null = null;
- let bodyCpuCount = 0;
- let bodyMemoryMB = 0;
- let bodyDiskMB = 0;
- let burst = false;
- // Single parse, shared with edgeClaimEligible below (it used to re-parse —
- // measurable CPU at burst-100 where create cpuTime is the queueing driver).
- let parsedBody: Record<string, unknown> | null = null;
- try {
- if (bodyText) {
- parsedBody = JSON.parse(bodyText) as Record<string, unknown>;
- const parsed = parsedBody as {
- cellId?: unknown;
- cpuCount?: unknown;
- memoryMB?: unknown;
- diskMB?: unknown;
- burst?: unknown;
- image?: unknown;
- snapshot?: unknown;
- };
- if (typeof parsed.cellId === "string") requestedCellID = parsed.cellId;
- if (typeof parsed.cpuCount === "number") bodyCpuCount = parsed.cpuCount;
- if (typeof parsed.memoryMB === "number") bodyMemoryMB = parsed.memoryMB;
- if (typeof parsed.diskMB === "number") bodyDiskMB = parsed.diskMB;
- if (typeof parsed.burst === "boolean") burst = parsed.burst;
-
- if (burst) {
- if (!env.BURST_CELL_ID) {
- return json({ error: "Burst Sandboxes alpha is not configured" }, 503);
- }
- if (requestedCellID && requestedCellID !== env.BURST_CELL_ID) {
- return json({ error: "burst cannot be combined with a different cellId" }, 400);
- }
- if (parsed.image != null || parsed.snapshot != null) {
- return json({ error: "Burst Sandboxes do not support image or snapshot creates in alpha" }, 400);
- }
- parsed.burst = true;
- requestedCellID = env.BURST_CELL_ID;
- bodyText = JSON.stringify(parsed);
- }
- }
- } catch {
- /* malformed JSON — let the CP reject with a proper 400 */
- }
-
- // Every org-policy gate (billing, instance size, disk, concurrency) is
- // enforced here against D1. Cells trust the cap-token and no longer
- // re-check — see enforceCreatePolicy for why the concurrent limit in
- // particular can only be correct at the edge.
- // The org-policy gate and cell selection both depend only on `org`, so run
- // them concurrently — under a burst these were two serial D1 round-trips
- // (~90ms) sitting on the create hot path.
- const [gate, cell] = await Promise.all([
- enforceCreatePolicy(req, env, ctx, caller.orgID, org, {
- cpuCount: bodyCpuCount,
- memoryMB: bodyMemoryMB,
- diskMB: bodyDiskMB,
- }, activeCount),
- pickCell(env, org.home_cell, requestedCellID, cells, cellsAtMs),
- ]);
- mark("gatecell");
- if (gate) return gate;
- if (!cell) {
- // Why, not just that. This returned a bare 503 and logged nothing, so a
- // customer could report "no cells available with capacity" and a two-week
- // search of the edge dataset would find no trace of it — the string existed
- // only in their client. Four different conditions produce this refusal
- // (below); without naming which one fired, they are indistinguishable.
- const nowSec = Math.floor(Date.now() / 1000);
- const observedSec = Math.floor(cellsAtMs / 1000);
- console.log(
- JSON.stringify({
- level: "error",
- msg: "create refused: no cell passed the health gate",
- orgID: caller.orgID,
- requestedCellID,
- homeCell: org.home_cell,
- considered: cells.length,
- // How stale the snapshot itself was, which is its own failure mode:
- // an empty or old list is served for up to CELL_STALE_MAX_MS.
- snapshotAgeSec: nowSec - observedSec,
- cells: cells.map((c) => ({
- cell: c.cell_id,
- status: c.status,
- available: c.available_workers,
- heartbeatAgeSec:
- c.capacity_updated_at == null ? null : observedSec - c.capacity_updated_at,
- why:
- c.status !== "active"
- ? "not active"
- : c.capacity_updated_at == null
- ? "no capacity report"
- : observedSec - c.capacity_updated_at > CAPACITY_FRESH_SEC
- ? "heartbeat stale"
- : c.available_workers <= 0
- ? "no available workers"
- : "healthy",
- })),
- }),
- );
- return json(
- requestedCellID
- ? { error: `cell ${requestedCellID} is not available` }
- : { error: "no cells available with capacity" },
- 503,
- );
- }
-
- // Edge claim: for a default-shape create, pop a pre-reserved hot box from
- // this cell's PoolStock DO and answer right here — token minted at the edge,
- // zero origin round trips. Finalize (billing on, PG rebind, idle timeout)
- // runs async; exec arriving before it lands routes fine (the cell proxy
- // resolves by worker_id regardless of claim status). Miss/error falls
- // through to the normal cell create, which is never worse than before.
- // NOTE: the cap-token is NOT minted here — the edge-claim response doesn't
- // need it (finalizeEdgeClaim mints its own off the response path), and the
- // HMAC sign was one of the larger CPU items driving isolate queueing at
- // burst-100. The CP-fallback path mints it below, after a miss.
- // MICROVM_EDGE_CLAIM=0 skips edge-claim for MicroVM orgs specifically.
- //
- // Edge-claim reserves boxes from the cell's pool through PoolStock. A cell
- // running the direct-exec backend has no such pool — it keeps its warm set in
- // process and does not implement EdgeReserve at all — so the DO can never hold
- // stock for it. Every create then walks the shards, misses, and pays a CP
- // round trip anyway: measured on dev at 81-87ms of `claimmiss` on EVERY
- // create, for an outcome that was not merely unlikely but structurally
- // impossible.
- //
- // Scoped to the runtime rather than reusing EDGE_CLAIM=0, which is global. A
- // cell can serve both runtimes, and switching one cell's MicroVM data plane
- // must not turn off edge-claim for the QEMU orgs sharing it.
-
- const edgeClaimOn =
- env.EDGE_CLAIM !== "0" &&
- !(runtime === RUNTIME_MICROVM && env.MICROVM_EDGE_CLAIM === "0");
- if (edgeClaimOn && env.POOL_STOCK && edgeClaimEligible(bodyText, parsedBody)) {
- try {
- // Sharded stock (see pool_stock.ts): a single DO serializes burst claims
- // (~2ms each → ~90ms queue tail at 100-way), so claims spread across
- // POOL_STOCK_SHARDS instances. Shard 0 keeps the legacy unsharded name so
- // the pre-sharding DO (holding the fleet's stock at cutover) drains as a
- // first-class shard instead of hoarding reservations until TTL. One empty
- // shard (404) gets one retry on a different shard before the CP fallback.
- const claimBody = JSON.stringify({ cell: { cellID: cell.cell_id, baseURL: cell.base_url } });
- mark("cap");
- // One DO pop. The token was minted in the DO when it filled its stock, so
- // a hit costs one subrequest and no crypto on this isolate.
- const claimed = await claimPoolBox(env, cell, caller.orgID);
- const box = claimed?.box ?? null;
- if (box && claimed) {
- mark("claim");
- // Telemetry: stock left in the shard that served this claim. `dur` is a
- // value here, not a duration.
- phases.push(`stock;dur=${claimed.stock}`);
- // `claim` above is DO work + network to the DO. This is the DO's half,
- // so the remainder is the hop — see claimBatch. `doclo` is a colo name,
- // not a duration; Server-Timing has nowhere else to put it.
- phases.push(`doin;dur=${claimed.doMs}`, `doclo;desc=${claimed.doColo}`);
- // Shards touched, as a count not a duration. See claimPoolBox.
- phases.push(`dotry;dur=${claimed.attempts}`);
- const token = box.token;
- if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- sandboxRouteCache.set(box.id, { cellID: cell.cell_id, orgID: caller.orgID, microvm: isMicrovmWorkerID(box.workerID) });
- // Seed the colo-shared route so the first exec — which usually lands on
- // a different isolate — skips its blocking D1 route read. waitUntil is
- // race-safe here: the client can't send that exec until the 201 crosses
- // the network (≥ one RTT), and the put lands in ~5ms.
- // ONE colo write, carrying the reach info that used to be a second entry.
- // Each waitUntil holds an open connection for the life of the
- // invocation, and a Worker invocation may hold only six — this path was
- // sitting exactly on that ceiling (claim + 2 colo puts + tunnel warm +
- // VM_SESSIONS wake + queue send). Measured from IAD 2026-08-20, create
- // median scaled 334→551→853ms at concurrency 10→25→100 while every
- // server-timing mark stayed flat (claim 20→21→32ms), i.e. the growth was
- // entirely in requests waiting to be scheduled, which the marks cannot
- // see because tPrev starts at handler entry.
- //
- // TTL is the reach TTL (the longer of the two). resolveRoute's own put
- // writes this key without `reach`; that costs the next exec one cell
- // lookup and then self-heals via the mvmreach put on the exec path.
- const routeEntry: SandboxRoute & { reach?: MvmReach } = {
- cellID: cell.cell_id,
- orgID: caller.orgID,
- // Recorded at birth so the first exec never has to guess. Without it
- // the first exec on a freshly-created MicroVM box reads an unknown
- // route, falls back to the org policy — which for an org migrating by
- // SDK version says nothing — and pays the VmSession DO's 400ms entry
- // grace before giving up. That is the whole latency this routing
- // exists to avoid, on the one request most likely to be measured.
- microvm: isMicrovmWorkerID(box.workerID),
- };
- if (box.agentEndpoint && box.agentToken && box.agentPort) {
- routeEntry.reach = { endpoint: box.agentEndpoint, token: box.agentToken, port: box.agentPort };
- }
- ctx.waitUntil(coloPut("route", box.id, routeEntry, MVM_REACH_TTL_SEC));
- // Tunnel pre-warm: dial the box now (DNS+TCP+TLS+101) so this colo has a
- // live outbound connection before the customer's first exec needs one.
- //
- // This was removed in 706ab07e on the theory that create's burst scaling
- // came from holding too many concurrent connections per invocation. The
- // fully-attributed run that theory was waiting on has now happened, and
- // it does not survive: at burst-100 create's cost is `pre` (client→
- // handler transit) plus `ctx` (a cold-cache D1 stampede, fixed above),
- // while `claim` is 25ms median and `unbr` is 0 — the marks account for
- // every millisecond inside the handler, so there is no hidden scheduling
- // backlog for a held connection to explain. Removing it did cut create
- // 853→727ms, but exec regressed 102→232ms in the same change, and the
- // regression sits in `execleg` — which contains `up`, the dial this warm
- // used to pre-pay. Measured after removal: `up` 73ms median, 527ms p99.
- //
- // Net for the benchmark, which scores create+exec together, this is a
- // win. It stays in waitUntil and swallows its errors, so the worst case
- // is the first exec dialling cold exactly as it does today.
- if (routeEntry.reach) ctx.waitUntil(warmEdgeTunnel(routeEntry.reach));
- //
- // NOTE: the MicroVM exec channel is deliberately NOT warmed here. It is
- // warmed at stock-prep in pool_stock.ts, where the box sits idle for
- // minutes — warming from this path both loses the race against the
- // customer's first exec and fans out a DO subrequest per create under
- // burst. See PoolStock.warmMicrovmBox.
- mark("mintseed");
- const resp: Record<string, unknown> = {
- sandboxID: box.id,
- token,
- status: "running",
- region: box.region,
- workerID: box.workerID,
- };
- if (box.sandboxDomain) resp.sandboxDomain = box.sandboxDomain;
- // The VmSession pre-wake that used to live here is gone too. Its premise
- // — "waitUntil runs after the 201, so it cannot tax create latency" — is
- // false under burst: waitUntil keeps the invocation (and its connection
- // budget) alive, so a ~180ms DO wake per create is 100 of them in flight
- // at burst-100, competing with the claims that still have to be served.
- // The wake it was hiding lands on the first exec of a box whose DO has
- // hibernated; the durable fix for that is the shared dialer work
- // (task #167), not a per-create background wake.
- // Finalize off the create isolate: enqueue a tiny message (one cheap
- // send) instead of running the CP fetch + D1 insert here. ~100 inline
- // finalizes otherwise accumulate on the isolate and stall the burst (dev
- // A/B: 888ms→~150ms with finalize removed from the hot path). An unbound
- // queue (rollout / non-queue env) falls back to the old inline path.
- if (env.FINALIZE_QUEUE) {
- const msg: FinalizeMsg = {
- orgID: caller.orgID,
- userID: caller.userID ?? null,
- cellID: cell.cell_id,
- baseURL: cell.base_url,
- plan,
- billingProvider: org.billing_provider,
- runtime,
- runtimePin: org.runtime ?? "",
- sandboxID: box.id,
- workerID: box.workerID,
- bodyText,
- };
- ctx.waitUntil(
- env.FINALIZE_QUEUE.send(msg).catch((e) => {
- // Enqueue failed — finalize inline so the box still binds.
- console.error(`edge-claim: finalize enqueue failed for ${box.id}, running inline:`, e);
- return finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText, org.runtime ?? "");
- }),
- );
- } else {
- ctx.waitUntil(finalizeEdgeClaim(env, caller, cell, plan, org.billing_provider, runtime, box.id, box.workerID, bodyText, org.runtime ?? ""));
- }
- // Total in-handler wall time. With `pre`, the client's own measurement
- // splits three ways: pre (getting here) + hdl (this handler) + the rest
- // (response back over the wire, or time this Worker spent after the
- // return that no mark can reach).
- phases.push(`hdl;dur=${Date.now() - tEntry}`);
- if (env.DIAG === "1") console.log(`create-timing ${box.id} ${phases.join(" ")}`);
- return new Response(JSON.stringify(resp), {
- status: 201,
- headers: { "content-type": "application/json", "server-timing": phases.join(", ") },
- });
- }
- } catch (e) {
- console.error("edge-claim: falling back to cell create:", e);
- }
- }
-
- // Reaching here means edge-claim was skipped or missed. Marked separately so a
- // fallback create's header shows whether it paid for a failed claim attempt
- // (DO round-trip + retry) before falling through, or never tried at all.
- mark("claimmiss");
-
- // CP fallback from here on — mint the cap-token the cell requires (the
- // edge-claim path above returns without ever needing it).
- const capToken = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID, runtime);
- mark("capmint");
-
- // SSE build streaming: image/snapshot creates can take minutes (apt installs,
- // etc.). Preserve live streaming, but index the final `result` event inline
- // before the stream closes. Relying only on async lifecycle events leaves a
- // race where immediate GET/DELETE after create sees no sandboxes_index row.
- const wantsSSE = req.headers.get("accept") === "text/event-stream";
- if (wantsSSE) {
- try {
- const cpResp = await fetch(cell.base_url.replace(/\/$/, "") + "/internal/sandboxes/create", {
- method: "POST",
- headers: { authorization: "Bearer " + capToken, "content-type": "application/json", accept: "text/event-stream" },
- body: bodyText || "{}",
- });
- return indexSandboxFromSSE(cpResp, env, ctx, caller, cell.cell_id, bodyCpuCount, bodyMemoryMB);
- } catch (e) {
- return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);
- }
- }
-
- // One request per create, always. Coalescing concurrent creates into a
- // shared request was tried and falsified: batching 26 creates left the
- // edge→cell hop unchanged (132ms vs 126ms solo), so that hop is round-trip
- // bound rather than connection bound, and making one Worker request depend
- // on another's I/O cost 18% of a burst to CF error 1101.
- let cpCall: { status: number; text: string };
- try {
- const r = await fetch(`${cell.base_url}/internal/sandboxes/create`, {
- method: "POST",
- headers: { "content-type": "application/json", authorization: `Bearer ${capToken}` },
- body: bodyText,
- });
- cpCall = { status: r.status, text: await r.text() };
- } catch (e) {
- return json({ error: `cell ${cell.cell_id} unreachable: ${(e as Error).message}` }, 502);
- }
- // The edge→cell leg, isolated. This is the fork in the road for the fallback
- // create: `cell` covers network RTT to the cell plus everything the CP does,
- // and the CP logs its own handler time, so `cell` minus that is the tunnel.
- // Everything before it is edge compute + D1.
- mark("cell");
-
- const cpText = cpCall.text;
- // Whether this create shared a request, how many it shared with, and how long
- // it waited to be dispatched. Without these a batched burst and an unbatched
- // one are indistinguishable in the timing header, and `cell` alone cannot say
- // whether a slow create was queued or just slow.
- mark("cellbody");
- if (cpCall.status >= 200 && cpCall.status < 300) {
- let parsed: SandboxCreateResult = {};
- try {
- parsed = JSON.parse(cpText);
- } catch {
- /* leave parsed empty — still record what we can */
- }
- // Seed the route cache so this isolate's sub-ops (exec/files/delete) skip
- // the sandboxes_index read — and don't race the deferred insert below.
- if (parsed.sandboxID) {
- if (sandboxRouteCache.size >= CACHE_MAX) sandboxRouteCache.clear();
- // `runtime` is the decision THIS handler just made and the cell just
- // acted on, so it is authoritative here — more so than worker_id, which
- // the sandboxes_index row may not carry yet.
- const seeded: SandboxRoute = { cellID: cell.cell_id, orgID: caller.orgID, microvm: runtime === RUNTIME_MICROVM };
- sandboxRouteCache.set(parsed.sandboxID, seeded);
- ctx.waitUntil(coloPut("route", parsed.sandboxID, seeded, ROUTE_COLO_TTL_SEC));
- }
- // Off the response path (see indexSandboxFromSSE) — waitUntil keeps the D1
- // write alive after we return; events-ingest reconciles the row anyway.
- ctx.waitUntil(
- insertSandboxIndex(env, caller, cell.cell_id, parsed, bodyCpuCount, bodyMemoryMB).catch((e) =>
- console.error("sandboxes_index create insert failed:", e),
- ),
- );
- }
- // Total wall time inside this handler, on the edge's OWN clock. Paired with
- // the client's own (T4-T1) and the CP's own (createtrace total), this closes
- // the attribution without ever comparing two different clocks: every term is a
- // difference of two readings taken by the same machine, so skew cancels rather
- // than contaminating the result.
- //
- // What these three deliberately do NOT cover is the answer we are chasing.
- // Time spent queued before this handler ran is invisible to every mark in it —
- // `tEntry` is stamped once we are already executing — so it can only ever show
- // up as the residual (T4-T1) - hdl. That residual is the measurement; the marks
- // are just what we subtract to expose it.
- phases.push(`hdl;dur=${Date.now() - tEntry}`);
- if (env.DIAG === "1") console.log(`create-timing fallback ${cell.cell_id} ${phases.join(" ")}`);
- // Pass the CP's response through verbatim (status + body), plus the phase
- // breakdown — the edge-claim path above already returns one, and a fallback
- // create with no header is exactly the case that needed attributing.
- return new Response(cpText, {
- status: cpCall.status,
- headers: { "content-type": "application/json", "server-timing": phases.join(", ") },
- });
-}
-
-// sandboxRowToJSON reshapes a D1 sandboxes_index row into the JSON the legacy
-// CP /api/sandboxes returned — which the Go CLI's types.Sandbox struct + the
-// Python/TS SDKs all unmarshal against. Important translations:
-// id → sandboxID (Go json tag is `sandboxID`)
-// template_id → templateID
-// cell_id → cellID
-// worker_id → workerID
-// created_at → startedAt (unix int → ISO string)
-// stopped_at → endAt (unix int / null → ISO string; null becomes the
-// Go time.Time zero value, "0001-01-01T00:00:00Z")
-// cpu_count → cpuCount
-// memory_mb → memoryMB
-interface SandboxRow {
- id: string;
- cell_id: string;
- worker_id: string | null;
- status: string;
- template_id: string | null;
- cpu_count: number | null;
- memory_mb: number | null;
- created_at: number;
- last_event_at: number | null;
- stopped_at: number | null;
- end_at: number | null;
-}
-
-// unixFromISO turns the control plane's RFC3339 deadline into the unix seconds
-// the index stores. Anything unparseable becomes NULL rather than a guess: a
-// bogus deadline in the past would make a live sandbox look expired to every
-// reader that treats this column as terminal.
-function unixFromISO(v: unknown): number | null {
- if (typeof v !== "string" || v === "") return null;
- const ms = Date.parse(v);
- if (!Number.isFinite(ms) || ms <= 0) return null;
- return Math.floor(ms / 1000);
-}
-
-function isoFromUnix(secs: number | null): string {
- // Go time.Time zero value when the column is NULL. The CLI tolerates this.
- if (secs == null || secs === 0) return "0001-01-01T00:00:00Z";
- return new Date(secs * 1000).toISOString();
-}
-
-function sandboxRowToJSON(r: SandboxRow): Record<string, unknown> {
- return {
- sandboxID: r.id,
- templateID: r.template_id ?? "",
- cellID: r.cell_id,
- workerID: r.worker_id ?? "",
- status: r.status,
- cpuCount: r.cpu_count ?? 0,
- memoryMB: r.memory_mb ?? 0,
- startedAt: isoFromUnix(r.created_at),
- // "When does this sandbox end" — the actual end once it has ended, and
- // otherwise the deadline its provider will enforce. Previously this was
- // stopped_at alone, which meant a running sandbox always reported the Go
- // zero time here no matter how close it was to being terminated.
- endAt: isoFromUnix(r.stopped_at ?? r.end_at),
- };
-}
-
-async function listSandboxes(req: Request, env: Env): Promise<Response> {
- const caller = await authenticate(req, env);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,
- created_at, last_event_at, stopped_at, end_at
- FROM sandboxes_index WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,
- )
- .bind(caller.orgID)
- .all<SandboxRow>();
- return json((results ?? []).map(sandboxRowToJSON));
-}
-
-async function getSandbox(req: Request, env: Env, id: string): Promise<Response> {
- const caller = await authenticate(req, env);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, org_id, cell_id, worker_id, status, template_id, cpu_count, memory_mb,
- created_at, last_event_at, stopped_at, end_at
- FROM sandboxes_index WHERE id = ?1`,
- )
- .bind(id)
- .first<SandboxRow & { org_id: string }>();
- if (!row) {
- // No index row yet. That does NOT mean the sandbox doesn't exist: an
- // edge-claimed create answers 201 before its sandboxes_index row is written,
- // because finalize runs off the hot path through FINALIZE_QUEUE. Measured on
- // prod, the row can trail the 201 by more than 2.6s — far longer than the
- // ~1s a client needs to create, exec and then tear down.
- //
- // Returning 404 in that window is not a harmless "not yet". Our own
- // published adapter calls connect() (this route) before kill(), and treats a
- // 404 as "already gone" — so it skips the DELETE and reports success. Every
- // sandbox created and destroyed inside the finalize window therefore LEAKED,
- // holding a pool box until the 8h AWS cap. A burst-100 leaked all 100 and
- // pinned the cell at its box budget, which then degraded every subsequent
- // run. That is the whole reason this fallback exists.
- //
- // Exec and DELETE never had the bug because they resolve through
- // sandboxRouteCache / the colo route entry, both seeded at create. This
- // route just never consulted them. So consult them: a route entry is proof
- // the create happened and carries the owning org, which is all the
- // authorization check needs.
- const route = await resolveSandboxRoute(env, id);
- if (!route || route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- const cell = await lookupCell(env, route.cellID);
- // Deliberately minimal, and deliberately NOT invented: only the fields a
- // claim proves. status is "running" because a claimed box is running — the
- // finalize that would tell us otherwise is exactly what hasn't landed yet.
- return json({
- sandboxID: id,
- templateID: "",
- cellID: route.cellID,
- workerID: "",
- status: "running",
- cpuCount: 0,
- memoryMB: 0,
- startedAt: null,
- endAt: null,
- cellEndpoint: cell ? cell.base_url : null,
- });
- }
- if (row.org_id !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- const cell = await lookupCell(env, row.cell_id);
- return json({ ...sandboxRowToJSON(row), cellEndpoint: cell ? cell.base_url : null });
-}
-
-/**
- * Why an exec fell back to the tunnel.
- *
- * Both fast paths degrade to `return null`, and the dispatcher then labels the
- * result `path;desc=tunnel` — which says a fallback happened but not which of
- * the six exits took it. Under burst that share went 30% → 60% and there was no
- * way to tell a DO that reported no channel from a DO that was never asked, a
- * reach cache miss from a dial that threw. Each has a different fix.
- *
- * The DO already puts its reason on the wire ("channel unavailable: …") and the
- * edge was discarding the body along with the status. This carries it out.
- */
-// `why` is the FIRST thing that degraded (the DO, normally). `dial` is the
-// direct-dial leg's own outcome, kept separate because on the MicroVM path the
-// two are sequential: the DO declining is what makes the dial happen at all, so
-// collapsing them would hide whichever one is actually fixable.
-type Fallback = { why?: string; dial?: string };
-
-// Records the reason and returns null, so every degrade site stays a one-liner.
-// First writer wins: the outermost exit is the one that decided.
-function fallback(f: Fallback | undefined, why: string): null {
- if (f && f.why === undefined) f.why = why;
- return null;
-}
-
-// server-timing `desc` is a token: commas end the mark and spaces end the value,
-// so an un-sanitized exception message would corrupt every mark after it.
-const descSafe = (s: string): string => s.replace(/[^\w.:/-]+/g, "_").slice(0, 80);
-
-// tryVoucherExec settles ownership and runs the command in ONE round trip.
-//
-// Returns null whenever this is not a voucher sandbox, or the ladder ran out —
-// both mean "use the normal path", and neither is an error.
-//
-// The retry ladder is bounded and every attempt is independent. Nothing here
-// waits on another request's I/O: an earlier experiment that coalesced creates
-// bought 0ms and cost 18% of a burst to Cloudflare error 1101 when one
-// invocation's work was made to depend on another's.
-// Attempts against DIFFERENT boxes, each one claimed from the free list before
-// it is tried. Deep enough to ride out a handful of dead boxes without letting a
-// wedged colo walk the whole book on a customer's request.
-const VOUCHER_EXEC_ATTEMPTS = 6;
-
-
-
-// tryVmDoExec routes POST /:id/exec/run-async through the sandbox's VmSession
-// Durable Object (the VM-DO exec data plane, vm_do_datapane_validation) instead
-// of the tunnel→CP→worker chain. Returns a Response when the DO handled it (a
-// served result, or an authz 404), or null to tell the caller to fall back to
-// the tunnel (proxyToCellSDK) — the automatic, flag-free degradation whenever
-// the host→DO channel isn't live. The DO's 200 body is already the SDK's inline
-// run-async shape ({exitCode,stdout,stderr}, no execId), so exec.run()
-// short-circuits without polling — one edge→DO→host→agent hop. Authz mirrors
-// proxyToCellSDK exactly (same route lookup + org-ownership check) so the DO
-// path can't be used to exec on another org's sandbox. See vm_session.ts.
-async function tryVmDoExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, fall?: Fallback): Promise<Response | null> {
- if (!env.VM_SESSIONS) return fallback(fall, "no-binding"); // binding absent mid-cutover → tunnel
- // MicroVM-backed orgs never have a live VmSession: the host dialer that opens
- // the channel is a QEMU-worker component (internal/worker/dodialer.go), and a
- // MicroVM box has no worker behind it. So the DO can only ever answer "not
- // connected" — but it answers that only AFTER its 400ms entry grace
- // (vm_session.ts), which exists to absorb a hibernated-DO wake race that this
- // backend cannot have. Measured on prod: that grace was ~437ms of every
- // MicroVM exec — 79% of benchmark TTI, against a control plane that served
- // the exec itself in 10ms. Skip straight to the tunnel.
- //
- // Asked of the SANDBOX, not the org. Creates are routed by the calling SDK's
- // version (runtime_gate.ts), so one org runs sandboxes on both runtimes for as
- // long as its migration takes, and "this org is on MicroVM" no longer answers
- // "is this box on MicroVM". The route carries the answer and usually already
- // has it cached; the org policy is only consulted when the route predates this
- // field or the row has no worker_id yet.
- const tRt = Date.now();
- const rt = await resolveSandboxRoute(env, id);
- let polMs = Date.now() - tRt;
- if (!rt) return json({ error: "sandbox not found" }, 404);
- if (rt.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- let microvm = rt.microvm;
- if (microvm === undefined) {
- const tPol = Date.now();
- const orgPolicy = await loadOrgPolicy(env, caller.orgID, ctx);
- polMs += Date.now() - tPol;
- microvm = orgPolicy?.runtime === RUNTIME_MICROVM;
- }
- if (microvm) {
- // MICROVM_EDGE_EXEC=0 hands exec to the cell, skipping BOTH Durable
- // Objects.
- //
- // Every edge-side fast path reaches the box by dialing its AGENT TUNNEL,
- // which is what a session DO holds. A cell running the direct-exec backend
- // has no tunnel in its story at all: it answers exec with one plain HTTPS
- // POST, and its boxes are reachable no other way. Serving exec here would
- // route around the very path such a cell exists to measure — silently,
- // while still returning correct results, which is exactly how the first dev
- // run produced a 3s exec with no trace of it in the cell's logs.
- //
- // It must return rather than fall through: below this line is the VmSession
- // DO, whose 400ms entry grace is the cost the MicroVM branch was added to
- // skip in the first place. Falling through measured 830ms of vmdo to be
- // told `vm_not_connected` by a DO that could never have been connected.
- if (env.MICROVM_EDGE_EXEC === "0") return fallback(fall, "cell-owns-exec");
- return tryMicrovmDirectExec(req, env, ctx, caller, id, authMs, polMs, fall);
- }
- // Resolved and authorized above — the runtime question needed it first.
- const route = rt;
- const routeMs = 0;
- try {
- // clone() so the original request body stays readable for the tunnel
- // fallback when the DO reports the channel isn't connected.
- const body = await req.clone().text();
- const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(id)) as DurableObjectStub & {
- execCommand?: (b: unknown, sid: string) => Promise<
- | { ok: true; exitCode: number; stdout: string; stderr: string; agentMs: number; internalMs?: number }
- | { ok: false; error: string }
- >;
- };
- const tDo = Date.now();
- // Prefer the RPC entrypoint (skips HTTP serialization on the edge→DO hop);
- // fall back to the fetch route if the DO build predates it.
- if (typeof stub.execCommand === "function") {
- let parsed: unknown = {};
- try {
- parsed = body ? JSON.parse(body) : {};
- } catch {
- return json({ error: "invalid body" }, 400);
- }
- const res = await stub.execCommand(parsed, id);
- const doMs = Date.now() - tDo;
- if (res.ok) {
- return new Response(JSON.stringify({ exitCode: res.exitCode, stdout: res.stdout, stderr: res.stderr }), {
- status: 200,
- headers: {
- "content-type": "application/json",
- "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, do;dur=${doMs}, doin;dur=${res.internalMs ?? -1}, agent;dur=${res.agentMs}`,
- },
- });
- }
- console.log(`vmdo-exec ${id}: DO rpc not-connected (${res.error}) — tunnel fallback`);
- return fallback(fall, `vmdo-rpc:${descSafe(res.error)}`);
- }
- const doResp = await stub.fetch("https://do/exec?sid=" + id, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body,
- });
- const doMs = Date.now() - tDo;
- // 200 = DO ran it. 409 (connected:false / channel error) = fall back.
- if (doResp.status === 200) {
- // agent = host-side manager.Exec time (from the result frame); do − agent
- // ≈ edge→DO + DO→host WS round trips.
- const agentMs = doResp.headers.get("x-agent-ms") ?? "-1";
- return new Response(doResp.body, {
- status: 200,
- headers: {
- "content-type": "application/json",
- "server-timing": `auth;dur=${authMs}, route;dur=${routeMs}, do;dur=${doMs}, agent;dur=${agentMs}`,
- },
- });
- }
- console.log(`vmdo-exec ${id}: DO ${doResp.status} — tunnel fallback`);
- return fallback(fall, `vmdo-status:${doResp.status}`);
- } catch (e) {
- // DO unreachable — fall through to the tunnel.
- return fallback(fall, `vmdo-throw:${descSafe(String(e))}`);
- }
-}
-
-/**
- * tryMicrovmDirectExec routes POST /:id/exec/run-async straight from this
- * Worker to the sandbox's in-guest agent, and returns null to fall back to the
- * control-plane tunnel whenever it cannot.
- *
- * WHY THERE IS NO DURABLE OBJECT HERE ANY MORE
- *
- * This used to go through a MicrovmSession DO that held the agent tunnel open
- * so execs could share it. Measured on dev from an IAD client, that reuse never
- * paid for itself, because every sandbox gets its own object and the benchmark
- * shape uses it once:
- *
- * first exec, unshared boxes DO 137ms median / 389ms p90
- * direct 90ms median / 345ms p90
- * 2nd-4th exec, same box DO 49-74ms direct 44-47ms
- *
- * Direct won or tied everywhere. The DO's hop plus its per-sandbox cold start
- * cost more than the dial it was avoiding. The machinery it was built on — the
- * hand-rolled HTTP/2 client in shared/h2grpc.ts — is what this path runs on, so
- * what went away is the wrapper, not the mechanism.
- *
- * The RPC itself is the steady part of all this: unary measured 15-23ms on
- * every sample in every run. Everything above that is connection setup, which
- * is where the remaining work is.
- *
- * SCOPE: one-shot Exec only. Streaming, PTY and file transfer stay on the
- * control-plane path via the null return.
- */
-async function tryMicrovmDirectExec(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, polMs = 0, fall?: Fallback): Promise<Response | null> {
- const tRoute = Date.now();
- const route = await resolveSandboxRoute(env, id);
- const routeMs = Date.now() - tRoute;
- if (!route) return json({ error: "sandbox not found" }, 404);
- // Authorization mirrors proxyToCellSDK: this path talks to the box with a
- // credential the caller never sees, so org ownership has to be proven here.
- if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
-
- let body: Record<string, unknown>;
- try {
- body = JSON.parse((await req.clone().text()) || "{}") as Record<string, unknown>;
- } catch {
- return json({ error: "invalid body" }, 400);
- }
- // The SDK sends a single shell string; the agent's Exec takes an argv. Match
- // what the control plane does for this backend rather than word-splitting
- // here, where quoting and redirection would be silently mangled.
- const cmd = typeof body.cmd === "string" ? body.cmd : typeof body.command === "string" ? body.command : "";
- if (!cmd) return fallback(fall, "no-cmd");
- // Two request shapes reach this endpoint and only one used to be handled.
- //
- // string form: {cmd: "echo hi"} — cmd IS the shell line
- // argv form: {cmd: "sh", args: ["-c","echo hi"]} — cmd is the program
- //
- // The SDK sends the argv form (see Exec.run). Reading only `cmd` turned that
- // into `/bin/sh -lc sh` — a shell with no script, which reads stdin, gets EOF,
- // and exits 0 having printed nothing. So every SDK exec against a MicroVM box
- // came back {exitCode: 0, stdout: ""}: silent, total output loss that looks
- // like a command which simply produced nothing. Verified on prod — the string
- // form returned "hi-string\n" while the argv form returned "" on the same box.
- const execReq = buildAgentExecRequest(body, cmd);
-
- // Session-DO first, direct dial as the fallback.
- //
- // A Durable Object can hold the agent tunnel across requests; a Worker
- // isolate provably cannot — #663 held connections in a module map and got
- // hit=0 out of 100 twice, with 40-53% found dead on arrival, because the
- // socket dies with the request context that opened it. That is what task #167
- // meant by "shared dialer DO", and the object already exists: pool_stock
- // attaches AND dials it at stock-prep (warmMicrovmBox), so a pooled box
- // should reach its customer with a live channel already open.
- //
- // Tried BEFORE resolving reach: the DO holds its own credentials from attach,
- // so a hit skips that lookup entirely. 409 (channel unavailable, for any
- // reason) falls through to the dial below, which is exactly today's path.
- if (env.MICROVM_SESSIONS) {
- const tDo = Date.now();
- try {
- const ns = env.MICROVM_SESSIONS;
- const dr = await ns.get(ns.idFromName(id), { locationHint: "enam" }).fetch("https://do/exec", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ ...execReq, timeoutMs: MVM_EXEC_TIMEOUT_MS }),
- });
- const doMs = Date.now() - tDo;
- if (dr.status === 200) {
- // Split the DO's own timing back out. `dlive` is the one that matters:
- // 1 means the channel survived from a previous request or the
- // keepalive, which is the entire point of routing through here.
- const t = Object.fromEntries(
- (dr.headers.get("x-mvm-timing") ?? "")
- .split(",")
- .map((kv) => kv.split("="))
- .filter((kv) => kv.length === 2),
- ) as Record<string, string>;
- // Split mvmdo three ways using the DO's absolute enter/exit stamps.
- // mvmdo alone conflates the hop out, time spent QUEUED outside the DO's
- // handler (a Durable Object runs one invocation at a time, so a keepalive
- // alarm mid-ping blocks an arriving exec), the handler itself, and the
- // hop back — and those have entirely different fixes. Measured on dev
- // 2026-08-25: mvmdo 1098ms against dinside 56ms, with ddial only 42ms,
- // i.e. a full second was outside everything the DO could see.
- //
- // Emitted only when the DO supplied both stamps, so an older vm-do
- // deployment degrades to the previous header rather than to "0".
- const dEnter = Number(t.enter);
- const dExit = Number(t.exit);
- const haveSpan = Number.isFinite(dEnter) && Number.isFinite(dExit) && dEnter > 0;
- const span = haveSpan ? `, dto;dur=${dEnter - tDo}, dback;dur=${Date.now() - dExit}` : "";
- return new Response(dr.body, {
- status: 200,
- headers: {
- "content-type": "application/json",
- "server-timing":
- `auth;dur=${authMs}, pol;dur=${polMs}, mvmdo;dur=${doMs}, ` +
- `dlive;dur=${t.live ?? -1}, dcold;dur=${t.cold ?? -1}, ddial;dur=${t.dial ?? -1}, ` +
- `dunary;dur=${t.unary ?? -1}, dinside;dur=${t.inside ?? -1}${span}, ` +
- `dcolo;desc=${dr.headers.get("x-mvm-colo") ?? "?"}`,
- },
- });
- }
- // Not 200. The DO puts the reason in the body ("channel unavailable: …",
- // "exec failed: …") and this used to discard it along with the status,
- // which is why a 60%-tunnel burst was unattributable. Reading the body
- // costs nothing here: we are already on the slow branch.
- fallback(fall, `do:${dr.status}:${descSafe(((await dr.json().catch(() => ({}))) as { error?: string }).error ?? "")}`);
- } catch (e) {
- /* DO unreachable — the direct dial below is the fallback */
- fallback(fall, `do-throw:${descSafe(String(e))}`);
- }
- } else {
- fallback(fall, "no-mvm-binding");
- }
-
- const tReach = Date.now();
- // Create now folds reach into the "route" entry (one colo write instead of
- // two — see createSandbox). Fall back to the standalone "mvmreach" key, which
- // the refresh below still writes and which covers boxes claimed before this
- // deployed.
- let reach = (await coloGet<{ reach?: MvmReach }>("route", id))?.reach ?? null;
- if (!reach) reach = await coloGet<MvmReach>("mvmreach", id);
- let reachFromCell = false;
- if (!reach) {
- // Cache miss: a box claimed before this deployed, an expired credential, or
- // a colo that never saw the create. Ask the cell — expensive (it is in
- // westus2) but self-healing, because we cache what it returns.
- reach = await fetchMvmReach(env, caller, route.cellID, id);
- reachFromCell = true;
- if (!reach) {
- if (fall) fall.dial = "reach-null";
- return fallback(fall, "reach-null"); // not a MicroVM box, or the cell won't say — tunnel
- }
- }
- const reachMs = Date.now() - tReach;
-
- const run = async (r: MvmReach): Promise<Response> => {
- const conn = await dialAgent(r);
- try {
- const res = await conn.unary("/agent.SandboxAgent/Exec", encodeExecRequest(execReq), MVM_EXEC_TIMEOUT_MS);
- return json(decodeExecResponse(res));
- } finally {
- conn.close();
- }
- };
-
- const tExec = Date.now();
- try {
- let resp: Response;
- try {
- resp = await run(reach);
- } catch (e) {
- // A cached credential that has aged out fails here and nowhere else, and
- // it fails for every exec until the entry expires. Re-fetch once so the
- // box heals immediately instead of an hour later. Only worth doing when
- // the credential could be stale — a fresh one from the cell just failed
- // for a different reason.
- if (reachFromCell) throw e;
- const fresh = await fetchMvmReach(env, caller, route.cellID, id);
- if (!fresh) throw e;
- resp = await run(fresh);
- reach = fresh;
- }
- const execMs = Date.now() - tExec;
- // Cache whatever actually worked. On a hit this is a cheap refresh; on a
- // miss it is the whole point — the next exec in this colo skips westus2.
- ctx.waitUntil(coloPut("mvmreach", id, reach, MVM_REACH_TTL_SEC));
- return new Response(resp.body, {
- status: 200,
- headers: {
- "content-type": "application/json",
- "server-timing": `auth;dur=${authMs}, pol;dur=${polMs}, route;dur=${routeMs}, reach;dur=${reachMs}, exec;dur=${execMs}, up;dur=${lastUpgradeMs}, ready;dur=${lastReadyMs}`,
- },
- });
- } catch (e) {
- // Every failure lands here and the answer to all of them is the same: the
- // tunnel still works. Logged rather than distinguished, because a path that
- // silently degrades is worse than one that is loudly slow.
- console.log(`microvm-direct-exec ${id}: ${e} — tunnel fallback`);
- if (fall) fall.dial = descSafe(String(e));
- return fallback(fall, `dial:${descSafe(String(e))}`);
- }
-}
-
-// Bounded well under the SDK's own patience: a command that outlives this is
-// one the caller has already re-run through the tunnel.
-const MVM_EXEC_TIMEOUT_MS = 10_000;
-
-/**
- * warmEdgeTunnel dials the box and drops the connection straight away, so the
- * runtime's outbound pool in this colo has a warm entry for the first exec.
- *
- * Errors are swallowed on purpose: this is speculative work off the create
- * path, and a box that refuses now simply means the first exec pays what it
- * would have paid anyway.
- */
-async function warmEdgeTunnel(r: MvmReach): Promise<void> {
- try {
- const conn = await dialAgent(r);
- conn.close();
- } catch {
- /* first exec dials cold, exactly as it would have */
- }
-}
-
-// Last dial's split, in module scope so the exec that caused it can report the
-// two halves without threading a result object through. Single-threaded isolate,
-// and the value is read immediately after the await that sets it.
-let lastUpgradeMs = 0;
-let lastReadyMs = 0;
-
-/**
- * dialAgent opens one agent tunnel and returns an HTTP/2 client on it.
- *
- * The two legs are timed apart because they fail differently and fix
- * differently. `upgrade` is DNS + TCP + TLS + the 101, i.e. this colo's
- * connection to the box's host — a warm pooled connection makes it ~free.
- * `ready` is the guest's first SETTINGS frame, which the AWS proxy cannot
- * produce until it has connected to the guest port. A slow dial is one or the
- * other, never both, and knowing which is the whole diagnosis.
- *
- * Both budgets are sized for a box that has SUSPENDED rather than a healthy one.
- * AWS suspends a MicroVM after its idle window, and with auto-resume on the next
- * inbound request through the proxy wakes it — Lambda holding the request for the
- * length of a snapshot restore, which is longer than the 5s/8s this used to
- * allow. Cutting it short there does not fail fast, it aborts our own resume and
- * leaves the box suspended for the next caller to fail against as well. A healthy
- * box finishes both legs in tens of milliseconds and never approaches these.
- */
-const DIAL_HANDSHAKE_MS = 20_000;
-const DIAL_READY_MS = 20_000;
-
-async function dialAgent(r: MvmReach): Promise<H2Grpc> {
- const host = r.endpoint.replace(/^https?:\/\//, "").split("/")[0];
- const tUp = Date.now();
- // openTunnel, not fetch+AbortSignal.timeout — the latter kills the tunnel N ms
- // after the DIAL, not after the handshake, so warmEdgeTunnel's whole purpose
- // (hold a live connection from create until the customer's first exec) was
- // being undone 5s later, every time. See openTunnel's docstring for the
- // measurement.
- const { ws } = await openTunnel(
- `https://${host}/osb/agent-grpc`,
- { "X-aws-proxy-auth": r.token, "X-aws-proxy-port": String(r.port) },
- DIAL_HANDSHAKE_MS,
- );
- lastUpgradeMs = Date.now() - tUp;
- const tReady = Date.now();
- const conn = new H2Grpc(ws, host);
- // Wait for the GUEST, not just the AWS proxy: the 101 comes from the proxy,
- // which only connects to the guest port once payload arrives. Its SETTINGS
- // frame is the first proof the agent is actually there.
- await Promise.race([
- conn.ready,
- new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), DIAL_READY_MS)),
- ]);
- lastReadyMs = Date.now() - tReady;
- return conn;
-}
-
-/**
- * fetchMvmReach asks the owning cell how to reach a sandbox's box.
- *
- * The slow path on purpose: the cell is in Azure westus2 and this is measured
- * at 67-401ms from an IAD edge. It exists so a cache miss still works, not so
- * it can be on the hot path — the create seeds the cache precisely to avoid it.
- * Returns null for a sandbox whose backend has no such endpoint.
- */
-async function fetchMvmReach(env: Env, caller: Caller, cellID: string, id: string): Promise<MvmReach | null> {
- const cell = await lookupCell(env, cellID);
- if (!cell) return null;
- const org = await loadOrgPolicy(env, caller.orgID);
- const capToken = await cachedCapToken(
- env.SESSION_JWT_SECRET, caller.orgID, cellID, "",
- org?.billing_provider ?? "", org?.runtime ?? "", caller.userID,
- );
- const resp = await fetch(`${cell.base_url.replace(/\/$/, "")}/internal/microvm/direct/${id}`, {
- headers: { authorization: "Bearer " + capToken },
- });
- if (!resp.ok) return null;
- const info = await resp.json<MvmReach>();
- return info?.endpoint && info?.token && info?.port ? info : null;
-}
-
-/**
- * directExecProbe runs one exec straight from this Worker to the box's agent,
- * with no Durable Object anywhere in the path, and reports each leg separately.
- *
- * It exists to settle whether MicrovmSession earns its place on the exec path.
- * The DO's value is holding the tunnel open between execs; its cost is a hop
- * plus a cold start per sandbox. Only a measurement of the no-DO path makes
- * those comparable, and this is that measurement.
- *
- * Dev-only, and deliberately not wired into any customer route.
- */
-async function directExecProbe(req: Request, env: Env, id: string): Promise<Response> {
- const caller = await authenticate(req, env);
- if (!caller) return json({ error: "unauthorized" }, 401);
- const route = await resolveSandboxRoute(env, id);
- if (!route || route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
-
- let cmd = "node -v";
- try {
- const b = (await req.json()) as { cmd?: string };
- if (typeof b?.cmd === "string" && b.cmd) cmd = b.cmd;
- } catch {
- /* default command */
- }
-
- // Leg 1: reach-info. Cross-country to the control plane in westus2, and NOT
- // part of what a real direct path would cost — see the route comment.
- const tCreds = Date.now();
- const cell = await lookupCell(env, route.cellID);
- if (!cell) return json({ error: "cell not registered" }, 503);
- const org = await loadOrgPolicy(env, caller.orgID);
- const capToken = await cachedCapToken(
- env.SESSION_JWT_SECRET, caller.orgID, route.cellID, "",
- org?.billing_provider ?? "", org?.runtime ?? "", caller.userID,
- );
- const infoResp = await fetch(`${cell.base_url.replace(/\/$/, "")}/internal/microvm/direct/${id}`, {
- headers: { authorization: "Bearer " + capToken },
- });
- if (!infoResp.ok) return json({ error: `reach-info ${infoResp.status}` }, 502);
- const info = await infoResp.json<{ endpoint: string; token: string; port: number; path?: string }>();
- const credsMs = Date.now() - tCreds;
-
- // Leg 2: open the agent tunnel from here.
- const tDial = Date.now();
- const host = info.endpoint.replace(/^https?:\/\//, "").split("/")[0];
- let conn: H2Grpc;
- try {
- const up = await fetch(`https://${host}${info.path ?? "/osb/agent-grpc"}`, {
- signal: AbortSignal.timeout(5000),
- headers: {
- Upgrade: "websocket",
- "X-aws-proxy-auth": info.token,
- "X-aws-proxy-port": String(info.port),
- },
- });
- const ws = (up as unknown as { webSocket: WebSocket | null }).webSocket;
- // Report WHICH endpoint+port the upgrade was attempted against. A 502 from
- // Lambda's proxy means "nothing is listening on the declared port of that
- // microVM", and the two ways to get there — wrong port, or an endpoint that
- // no longer belongs to a live box — are indistinguishable from the status
- // alone. The token is only fingerprinted; it is a bearer credential.
- if (!ws) {
- // Same endpoint, same token, same colo — but an ORDINARY GET instead of
- // an upgrade. /healthz is served by microvm-hooks on the declared port
- // (cmd/microvm-hooks/main.go), so a 200 here proves the credential, the
- // endpoint and the network path are all fine and isolates the failure to
- // the WebSocket upgrade itself. A matching 502 means the box is simply
- // not reachable and the upgrade is incidental.
- let plain = "";
- try {
- const hz = await fetch(`https://${host}/healthz`, {
- signal: AbortSignal.timeout(5000),
- headers: { "X-aws-proxy-auth": info.token, "X-aws-proxy-port": String(info.port) },
- });
- plain = `${hz.status}: ${(await hz.text()).slice(0, 200)}`;
- } catch (e) {
- plain = `threw: ${e}`;
- }
- // Same GET with NO credential at all. AWS answers 403 to an unauthenticated
- // caller (verified from outside), so a 403 here proves this Worker reaches
- // AWS and the fault is ours; a 502 proves the subrequest never got there.
- let noAuth = "";
- try {
- const na = await fetch(`https://${host}/healthz`, { signal: AbortSignal.timeout(5000) });
- noAuth = `${na.status}: ${(await na.text()).slice(0, 120)}`;
- } catch (e) {
- noAuth = `threw: ${e}`;
- }
- return json({
- error: `tunnel upgrade failed (${up.status})`,
- upgradeBody: (await up.text().catch(() => "")).slice(0, 200),
- healthzSameTokenSameEndpoint: plain,
- healthzNoCredential: noAuth,
- endpoint: host,
- port: info.port,
- path: info.path ?? "/osb/agent-grpc",
- tokenLen: info.token?.length ?? 0,
- }, 502);
- }
- ws.accept();
- conn = new H2Grpc(ws, host);
- await Promise.race([
- conn.ready,
- new Promise((_, rej) => setTimeout(() => rej(new Error("guest did not answer")), 8000)),
- ]);
- } catch (e) {
- return json({ error: `dial: ${e}` }, 502);
- }
- const dialMs = Date.now() - tDial;
-
- // Leg 3: the RPC itself.
- const tUnary = Date.now();
- try {
- const res = await conn.unary(
- "/agent.SandboxAgent/Exec",
- encodeExecRequest({ command: "/bin/sh", args: ["-lc", cmd] }),
- 10_000,
- );
- const unaryMs = Date.now() - tUnary;
- return new Response(JSON.stringify(decodeExecResponse(res)), {
- status: 200,
- headers: {
- "content-type": "application/json",
- // creds is listed but is the excluded leg; direct = dial + unary.
- "server-timing": `creds;dur=${credsMs}, dial;dur=${dialMs}, unary;dur=${unaryMs}, direct;dur=${dialMs + unaryMs}`,
- },
- });
- } catch (e) {
- return json({ error: `unary: ${e}` }, 502);
- }
-}
-
-// attachMicrovmSession teaches a DO how to reach its box. Temporary shape: the
-// control plane is asked for endpoint+token on demand. The pool already holds
-// both (awsvm.StockEntry), so the durable version delivers them with the box at
-// claim time and this call disappears.
-async function attachMicrovmSession(
- env: Env,
- caller: Caller,
- cellID: string,
- id: string,
- stub: DurableObjectStub,
- dial = false,
-): Promise<boolean> {
- const cell = await lookupCell(env, cellID);
- if (!cell) return false;
- const org = await loadOrgPolicy(env, caller.orgID);
- const capToken = await cachedCapToken(
- env.SESSION_JWT_SECRET,
- caller.orgID,
- cellID,
- "",
- org?.billing_provider ?? "",
- org?.runtime ?? "",
- caller.userID,
- );
- const resp = await fetch(`${cell.base_url.replace(/\/$/, "")}/internal/microvm/direct/${id}`, {
- headers: { authorization: "Bearer " + capToken },
- });
- if (!resp.ok) return false;
- const info = await resp.json<{ endpoint: string; token: string; port: number }>();
- const att = await stub.fetch("https://do/attach", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ ...info, dial }),
- });
- return att.ok;
-}
-
-// Proxy the request to the owning cell's CP. Used for SDK runtime calls
-// (`/api/sandboxes/:id/exec`, `/files`, `/pty`, etc.). The caller has been
-// authenticated at the edge against D1; we mint a short-lived IdentityToken
-// the cell's PGAPIKeyMiddleware already accepts (audience `opencomputer-api`)
-// and stream the response back. Pre-fix this was a 307 redirect, which broke
-// when the SDK's API key didn't exist in cell PG (api_keys are global in D1
-// now, not mirrored per-cell).
-
-async function proxyToCellSDK(req: Request, env: Env, ctx: ExecutionContext, caller: Caller, id: string, authMs = 0, vmdoMs = 0): Promise<Response> {
- // Step timing for the data-plane path. Measured on dev, an exec through here
- // cost ~718-851ms end to end while the network legs account for only ~200ms
- // (client↔CP 118ms + CP↔box 81ms), so ~500ms was unattributed. Nothing on
- // this path emitted server-timing, which is why it stayed invisible.
- const t0 = Date.now();
- let tPrev = t0;
- const phases: string[] = [];
- if (authMs > 0) phases.push(`auth;dur=${authMs}`);
- if (vmdoMs > 0) phases.push(`vmdo;dur=${vmdoMs}`);
- const mark = (name: string): void => {
- const now = Date.now();
- phases.push(`${name};dur=${now - tPrev}`);
- tPrev = now;
- };
- // Route cache first — the sandbox→cell mapping is immutable, and the D1 read
- // it replaces is a blocking per-sub-op cost (2-3× per SDK runCommand).
- const route = await resolveSandboxRoute(env, id);
- mark("route");
- if (!route) return json({ error: "sandbox not found" }, 404);
- // Authorization: the sandbox must belong to the caller's org. Without this,
- // any authenticated org could exec/files/pty/delete/hibernate/wake another
- // org's sandbox by id (the cell trusts the edge for authz). 404 not 403 so
- // we don't leak which sandbox ids exist.
- if (route.orgID !== caller.orgID) return json({ error: "sandbox not found" }, 404);
- const cell = await lookupCell(env, route.cellID);
- mark("cell");
- if (!cell) return json({ error: `cell ${route.cellID} not registered` }, 503);
-
- const url = new URL(req.url);
- const target = stripApiKeyQueryParam(cell.base_url.replace(/\/$/, "") + url.pathname + url.search);
- // Look up the org's plan so the cap-token carries it (worker resolver uses
- // plan to tag usage_tick events; without it free-tier debit fan-out skips
- // the org).
- // Reuse the per-isolate org-policy cache instead of a separate per-request
- // SELECT plan — under a burst these are all the same org.
- const orgPol = await loadOrgPolicy(env, caller.orgID);
- mark("pol");
- // Mint a cap-token (iss=opensandbox-edge, signed with SESSION_JWT_SECRET).
- // The cell's PGAPIKeyMiddleware accepts cap-tokens too (alongside identity
- // tokens and API keys), so the same handler chain that runs for SDK
- // X-API-Key auth runs here. cell_id in the token guards against replay
- // against a different cell.
- // "" runtime: this token is for data-plane sub-ops on an EXISTING sandbox,
- // whose backend is already fixed by its persisted worker_id. Runtime only
- // decides placement, and placement has already happened.
- const token = await cachedCapToken(env.SESSION_JWT_SECRET, caller.orgID, route.cellID, orgPol?.plan ?? "free", "", "", caller.userID);
- mark("tok");
-
- const headers = new Headers();
- for (const [k, v] of req.headers.entries()) {
- const lk = k.toLowerCase();
- // Drop the caller's X-API-Key — the cell would try to validate it against
- // its own PG and fail. We replace it with the IdentityToken JWT below.
- if (lk === "host" || lk === "cookie" || lk === "x-api-key" || lk.startsWith("cf-") || lk.startsWith("x-forwarded-")) continue;
- headers.set(k, v);
- }
- headers.set("authorization", "Bearer " + token);
-
- const init: RequestInit = { method: req.method, headers };
- if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;
-
- // Intercept lifecycle ops to keep D1 sandboxes_index in sync with cell PG.
- // Edge already writes the row on CREATE; here we mirror the cell's status
- // changes on DELETE / hibernate / wake. Otherwise the dashboard accumulates
- // phantoms — D1 rows stuck at "running" after the actual sandbox stopped.
- const path = url.pathname;
- // mode mirrors hibernation_mode: customer hibernate = the paused tier, wake =
- // running (NULL). Set it here (authoritative + immediate) so the cross-cell
- // paused-cap sees the box right away; the cell's async "paused" event would
- // otherwise no-op against this write's newer last_event_at.
- let postUpdate: { status: string; setStopped: boolean; mode: string | null } | null = null;
- if (req.method === "DELETE" && path === `/api/sandboxes/${id}`) {
- postUpdate = { status: "stopped", setStopped: true, mode: null };
- sandboxRouteCache.delete(id); // route is dead once the sandbox is destroyed
- // Tell the box's session DO to stop keeping itself warm. Without this its
- // alarm keeps re-dialing a terminated endpoint until the failure counter
- // gives up — bounded, but pointless work against AWS for every destroy.
- // MicroVM only: other runtimes have no MicrovmSession, and asking for one
- // by id would instantiate a Durable Object just to tear it down.
- // Per-SANDBOX, for the same reason as tryVmDoExec: a mixed org is normal
- // once creates are routed by SDK version. `route.microvm` is undefined only
- // for a route cached before the field existed, where the org policy is the
- // best remaining answer.
- if (env.MICROVM_SESSIONS && (route.microvm ?? orgPol?.runtime === RUNTIME_MICROVM)) {
- const ns = env.MICROVM_SESSIONS;
- ctx.waitUntil(
- ns
- .get(ns.idFromName(id), { locationHint: "enam" })
- .fetch("https://do/detach", { method: "POST" })
- .then(() => undefined)
- .catch(() => undefined),
- );
- }
- } else if (req.method === "POST" && path === `/api/sandboxes/${id}/hibernate`) {
- postUpdate = { status: "hibernated", setStopped: false, mode: "paused" };
- } else if (req.method === "POST" && path === `/api/sandboxes/${id}/wake`) {
- postUpdate = { status: "running", setStopped: false, mode: null };
- // Halt-gate the wake. D1 is authoritative for is_halted. The cell-side
- // gate that used to do this read the dropped orgs table post-041 and
- // silently fell through, letting halted orgs wake. Mirror the create
- // flow's halt check here so wake gets the same treatment.
- const haltRow = await env.OPENCOMPUTER_DB.prepare(
- "SELECT is_halted, billing_provider, usage_plan FROM orgs WHERE id = ?1",
- )
- .bind(caller.orgID)
- .first<{ is_halted: number; billing_provider: string; usage_plan: string | null }>();
- if (haltRow?.is_halted === 1) {
- // Autumn orgs self-heal: re-check the authoritative balance before
- // blocking a wake, so a just-topped-up user resumes without waiting for
- // the webhook/reconciler. Legacy orgs stay hard-gated on the D1 flag.
- const stillHalted =
- haltRow.billing_provider === "autumn" ? await selfHealHalt(env, caller.orgID) : true;
- if (stillHalted) {
- return haltRow.billing_provider === "autumn"
- ? haltedOrgResponse(req, env, ctx, caller.orgID)
- : insufficientCreditsLegacyResponse(req, {}, { plan: usagePlanOf(haltRow.usage_plan) });
- }
- }
- }
-
- // WebSocket upgrade — preserve the upgrade context by cloning the inbound
- // Request, then swap Authorization. The manual fetch + Sec-WebSocket-Key
- // copy / WebSocketPair bridge dance below was buggy ("bad handshake" on
- // the CLI side because the upgrade headers got rebuilt without proper
- // accept-key derivation). CF Workers + CF Tunnel forward WebSocket
- // upgrades transparently when you pass a Request clone — same pattern
- // handlePreviewURL uses and that's verified to work end-to-end with WS.
- if (isWebSocketUpgrade(req)) {
- const fwd = new Request(target, req);
- fwd.headers.set("authorization", "Bearer " + token);
- fwd.headers.delete("x-api-key");
- return await fetch(fwd);
- }
-
- // Non-WebSocket path. Run the proxy and then, on success, fan out the
- // status update to D1 so the dashboard sees the new state immediately.
- // Otherwise the dashboard accumulates phantoms — D1 rows stuck at
- // "running" after the actual sandbox stopped.
- const resp = await fetch(target, init);
- mark("origin");
- // Copy through so the step breakdown rides along with the cell's own answer.
- // Response headers are immutable, hence the rewrap.
- const timed = new Response(resp.body, resp);
- timed.headers.set("server-timing", phases.join(", "));
- if (postUpdate && resp.status >= 200 && resp.status < 300) {
- const nowSec = Math.floor(Date.now() / 1000);
- let stmt: D1PreparedStatement;
- if (postUpdate.setStopped) {
- // Tombstone UPSERT (was a bare UPDATE ... WHERE id). On an edge-claim the
- // index row is inserted ~1.5s after the box is returned (finalizeEdgeClaim
- // deferral). A destroy inside that window would UPDATE zero rows and be
- // lost, then the deferred finalize insert would resurrect the box as
- // 'running'. Writing a durable 'stopped' tombstone here — which the
- // guarded finalize upsert (insertSandboxIndex) refuses to overwrite —
- // closes the create→destroy leak regardless of which write lands first.
- stmt = env.OPENCOMPUTER_DB.prepare(
- `INSERT INTO sandboxes_index (id, org_id, user_id, cell_id, status, hibernation_mode, created_at, last_event_at, stopped_at)
- VALUES (?1, ?2, ?3, ?4, 'stopped', ?5, ?6, ?6, ?6)
- ON CONFLICT(id) DO UPDATE SET status='stopped', hibernation_mode=?5, stopped_at=?6, last_event_at=?6`,
- ).bind(id, route.orgID, caller.userID ?? null, route.cellID, postUpdate.mode, nowSec);
- } else {
- stmt = env.OPENCOMPUTER_DB.prepare(
- "UPDATE sandboxes_index SET status = ?1, hibernation_mode = ?4, last_event_at = ?2 WHERE id = ?3",
- ).bind(postUpdate.status, nowSec, id, postUpdate.mode);
- }
- // ctx.waitUntil keeps the background D1 write alive after the response
- // returns. Without it the Worker terminates the in-flight Promise and
- // the write never runs — sandboxes_index drifts behind cell PG.
- ctx.waitUntil(
- stmt.run().catch((e) => {
- console.error(`sandboxes_index ${postUpdate!.status} update failed for ${id}:`, e);
- }),
- );
- }
- return timed;
-}
-
-// proxyToCellAuthed forwards an authenticated SDK/CLI request to a cell with an
-// edge-minted cap-token, replacing the caller's X-API-Key (which the cell can no
-// longer validate — api_keys live in D1 post-cutover). The response is streamed
-// through unbuffered, so SSE build-log streams (image/snapshot create) flow to
-// the client frame-by-frame instead of being collapsed to a single JSON blob.
-//
-// Routing:
-// - opts.cellId set → route to that specific cell (e.g. owner_cell_id of a
-// snapshot being deleted; correct in a multi-cell world where the resource
-// lives in one cell only).
-// - opts.cellId unset → route to the org's home_cell (new-resource creates).
-//
-// This single helper is the backstop for every SDK route that doesn't have a
-// dedicated D1-native handler: it gives correct auth + routing + streaming
-// without the caller's key ever reaching the cell.
-async function proxyToCellAuthed(
- req: Request,
- env: Env,
- caller: Caller,
- opts: { cellId?: string; pathOverride?: string } = {},
-): Promise<Response> {
- const org = await env.OPENCOMPUTER_DB.prepare(
- "SELECT home_cell, plan, runtime FROM orgs WHERE id = ?1",
- ).bind(caller.orgID).first<{ home_cell: string; plan: string; runtime: string | null }>();
- if (!org) return json({ error: "org not found" }, 401);
- const plan = org.plan === "pro" ? "pro" : "free";
- // POST /api/snapshots comes through here, and a template is built DIFFERENTLY
- // per runtime — a whole-disk checkpoint on QEMU, a machine image on MicroVM.
- // Minting a blank runtime (what this did) meant a 1.x SDK's sandboxes went to
- // MicroVM while its templates were built as checkpoints MicroVM cannot
- // restore: a customer would migrate successfully and then find every template
- // they built unusable. Same decision, same inputs as createSandbox.
- const runtime = effectiveRuntime(env, org.runtime, req.headers.get(SDK_VERSION_HEADER));
- // A template built for v1 is a whole-disk checkpoint, which nothing left can
- // restore. Same refusal as a create.
- if (isRetiredRuntime(runtime)) return json(v1RetiredError(), V1_RETIRED_STATUS);
-
- const cell = opts.cellId
- ? await lookupCell(env, opts.cellId)
- : await pickCell(env, org.home_cell, null);
- if (!cell) return json({ error: "no cell available to serve request" }, 503);
-
- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cell.cell_id, plan, "", org.runtime ?? "", caller.userID, runtime);
- const url = new URL(req.url);
- const target = cell.base_url.replace(/\/$/, "") + (opts.pathOverride ?? url.pathname) + url.search;
-
- // Forward all headers except the ones the cell shouldn't see: the raw
- // X-API-Key (replaced by the cap-token), the browser cookie, and CF's
- // hop-by-hop headers. WebSocket upgrades pass through transparently.
- const headers = new Headers(req.headers);
- headers.delete("x-api-key");
- headers.delete("cookie");
- headers.set("authorization", "Bearer " + token);
- if (isWebSocketUpgrade(req)) {
- const fwd = new Request(target, req);
- fwd.headers.set("authorization", "Bearer " + token);
- fwd.headers.delete("x-api-key");
- return await fetch(fwd);
- }
- const init: RequestInit = { method: req.method, headers, redirect: "manual" };
- if (req.method !== "GET" && req.method !== "HEAD") init.body = req.body;
- return fetch(target, init);
-}
-
-
-// ── /internal/halt-list ─────────────────────────────────────────────────
-
-// HMAC-auth'd endpoint the cell's halt_reconciler polls every 60s to
-// reconcile any halt webhooks it might have missed. Returns the list of
-// org_ids that the DO currently flags halted (mirrored in D1 orgs.is_halted).
-// HMAC scheme matches the DO's dispatch: "{X-Timestamp}.{path-with-query}"
-// signed with EVENT_SECRET (shared with CP), SHA-256 hex.
-async function haltList(req: Request, env: Env): Promise<Response> {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- if (!ts || !sig) return json({ error: "missing signature headers" }, 400);
- const tsNum = Number.parseInt(ts, 10);
- if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);
- const now = Math.floor(Date.now() / 1000);
- if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);
-
- const url = new URL(req.url);
- const cellID = url.searchParams.get("cell") ?? "";
- const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);
- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
-
- // Return halted orgs that have any sandbox on the requesting cell. The
- // reconciler only needs to act on orgs it can do something about — orgs
- // halted with sandboxes on a DIFFERENT cell are that cell's reconciler's
- // problem. If no `cell` param is supplied, return all halted orgs (used
- // by parity-check cron / debugging).
- let results: { id: string; halted_at: number | null }[];
- if (cellID) {
- const res = await env.OPENCOMPUTER_DB.prepare(
- `SELECT DISTINCT o.id, o.halted_at
- FROM orgs o
- JOIN sandboxes_index s ON s.org_id = o.id
- WHERE o.is_halted = 1 AND s.cell_id = ?1`,
- )
- .bind(cellID)
- .all<{ id: string; halted_at: number | null }>();
- results = res.results ?? [];
- } else {
- const res = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, halted_at FROM orgs WHERE is_halted = 1`,
- ).all<{ id: string; halted_at: number | null }>();
- results = res.results ?? [];
- }
- return json({
- org_ids: results.map((r) => r.id),
- halted_at: Object.fromEntries(results.map((r) => [r.id, r.halted_at])),
- as_of: now,
- });
+ }
+ })();
+ authRefreshInflight.set(hash, p);
+ return p;
}
-// ── /internal/org-policy ──────────────────────────────────────────────────
-
-// HMAC-auth'd endpoint the cell pulls for an org's authoritative billing
-// policy from D1. The autoscaler loop runs in-process on the cell with no
-// request or cap-token to ride, so it can't get a fresh plan the way the
-// resize handlers do (they read it off the cap-token). D1 is the source of
-// truth for plan post-cutover — the cell's create-time-stamped cell-PG copy
-// goes stale on upgrade/downgrade — so the autoscaler asks here before
-// growing a sandbox past the free-tier ceiling. Same HMAC scheme as haltList.
-async function orgPolicy(req: Request, env: Env): Promise<Response> {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- if (!ts || !sig) return json({ error: "missing signature headers" }, 400);
- const tsNum = Number.parseInt(ts, 10);
- if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);
- const now = Math.floor(Date.now() / 1000);
- if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);
-
- const url = new URL(req.url);
- const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);
- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+// Which tier answered auth, and what the slow parts cost. `auth` is one mark
+// over four possible paths (isolate, colo, stale, D1) and a 226ms reading does
+// not say which — the same ambiguity that made `ctx` unfixable until it was
+// split. tier: 0 isolate, 1 colo, 2 stale, 3 D1.
+export interface AuthProbe {
+ tier: number;
+ coloMs: number;
+ d1Ms: number;
+ hashMs: number;
+}
- const orgID = url.searchParams.get("org_id") ?? "";
- if (!orgID) return json({ error: "missing org_id" }, 400);
- const row = await env.OPENCOMPUTER_DB.prepare(
- "SELECT plan, max_memory_gb FROM orgs WHERE id = ?1",
- )
- .bind(orgID)
- .first<{ plan: string; max_memory_gb: number }>();
- if (!row) return json({ error: "org not found" }, 404);
- return json({
- plan: row.plan === "pro" ? "pro" : "free",
- maxMemoryMb: (row.max_memory_gb ?? 0) * 1024,
- });
+async function authenticate(req: Request, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {
+ const apiKey = apiKeyFromRequest(req);
+ if (!apiKey) return null;
+ return authenticateKey(apiKey, env, ctx, probe);
}
-// ── /internal/usage-parity ────────────────────────────────────────────────
+async function authenticateKey(apiKey: string, env: Env, ctx?: ExecutionContext, probe?: AuthProbe): Promise<Caller | null> {
+ const tHash = Date.now();
+ const hash = await hashAPIKey(apiKey);
+ if (probe) probe.hashMs = Date.now() - tHash;
+ const nowMs = Date.now();
+ const nowSec = Math.floor(nowMs / 1000);
-// HMAC-auth'd read-only endpoint the cell's usage-parity checker polls to
-// compare edge-measured Pro usage against the cell's authoritative
-// sandbox_scale_events. Returns per-org GB-seconds over [from,to) computed from
-// the RAW tick samples (usage_samples), not the priced meter rows — the point
-// is to validate measurement (ticks vs scale-event intervals) independent of
-// the rollup/pricing layer, and it works for legacy and unified alike because
-// GB-seconds is mode-independent.
-//
-// from/to are unix seconds; samples are keyed by ts (unix ms). Same HMAC scheme
-// as haltList/orgPolicy. NOTE: this reads usage_samples, so the sample-retention
-// window must exceed the parity lookback (samples aren't deleted at rollup, only
-// flagged rolled_up).
-async function usageParity(req: Request, env: Env): Promise<Response> {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- if (!ts || !sig) return json({ error: "missing signature headers" }, 400);
- const tsNum = Number.parseInt(ts, 10);
- if (!Number.isFinite(tsNum)) return json({ error: "invalid timestamp" }, 400);
- const now = Math.floor(Date.now() / 1000);
- if (Math.abs(now - tsNum) > 5 * 60) return json({ error: "timestamp out of window" }, 401);
+ const cached = authCache.get(hash);
+ if (cached && nowMs - cached.cachedAtMs < AUTH_TTL_MS) {
+ if (cached.expiresAt && cached.expiresAt < nowSec) return null;
+ if (probe) probe.tier = 0;
+ bumpLastUsed(env, hash, cached, nowMs);
+ return cached.caller;
+ }
+
+ // Colo tier: a fresh box's sub-ops usually land on isolates that never saw
+ // this key. cachedAtMs travels with the entry so the total staleness bound
+ // (revocation lag) stays AUTH_TTL_MS, not colo-TTL + isolate-TTL stacked.
+ const tColo = Date.now();
+ const shared = await coloGet<{ caller: Caller; expiresAt: number | null; cachedAtMs: number }>("auth", hash);
+ if (probe) probe.coloMs = Date.now() - tColo;
+ if (shared && nowMs - shared.cachedAtMs < AUTH_TTL_MS) {
+ if (probe) probe.tier = 1;
+ if (shared.expiresAt && shared.expiresAt < nowSec) return null;
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ const entry: AuthEntry = { caller: shared.caller, expiresAt: shared.expiresAt, cachedAtMs: shared.cachedAtMs, lastBumpMs: 0 };
+ authCache.set(hash, entry);
+ bumpLastUsed(env, hash, entry, nowMs);
+ return shared.caller;
+ }
- const url = new URL(req.url);
- const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);
- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
+ // Stale-while-revalidate. Take the FRESHEST stale copy either tier holds —
+ // the isolate entry can outlive the colo entry or vice versa, and using the
+ // older of the two would shorten the window for no benefit. Serving it costs
+ // nothing; the refresh behind it is what keeps the entry honest.
+ const staleShared = shared && nowMs - shared.cachedAtMs < AUTH_STALE_MAX_MS ? shared : null;
+ const staleLocal = cached && nowMs - cached.cachedAtMs < AUTH_STALE_MAX_MS ? cached : null;
+ const stale =
+ staleShared && (!staleLocal || staleShared.cachedAtMs > staleLocal.cachedAtMs) ? staleShared : staleLocal;
+ if (stale) {
+ // Expiry is still enforced inline, exactly as on the fresh paths — the
+ // stale window widens revocation lag, never expiry.
+ if (stale.expiresAt && stale.expiresAt < nowSec) return null;
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ const entry: AuthEntry = {
+ caller: stale.caller,
+ expiresAt: stale.expiresAt,
+ cachedAtMs: stale.cachedAtMs,
+ lastBumpMs: cached?.lastBumpMs ?? 0,
+ };
+ authCache.set(hash, entry);
+ if (probe) probe.tier = 2;
+ const refresh = refreshAuth(env, hash);
+ if (ctx) ctx.waitUntil(refresh);
+ bumpLastUsed(env, hash, entry, nowMs);
+ return stale.caller;
+ }
- const from = Number.parseInt(url.searchParams.get("from") ?? "", 10);
- const to = Number.parseInt(url.searchParams.get("to") ?? "", 10);
- if (!Number.isFinite(from) || !Number.isFinite(to) || to <= from) {
- return json({ error: "from/to required (unix seconds, to > from)" }, 400);
+ const tD1 = Date.now();
+ const row = await env.OPENCOMPUTER_DB.prepare(AUTH_KEY_SQL)
+ .bind(hash)
+ .first<AuthRow>();
+ if (probe) {
+ probe.tier = 3;
+ probe.d1Ms = Date.now() - tD1;
}
+ if (!row) return null; // never cache negatives — a freshly-created key must work at once
+ if (row.expires_at && row.expires_at < nowSec) return null;
- const res = await env.OPENCOMPUTER_DB.prepare(
- `SELECT org_id AS org_id,
- SUM(memory_mb * interval_s) AS mem_mb_secs,
- COUNT(*) AS samples
- FROM usage_samples
- WHERE ts >= ?1 AND ts < ?2
- GROUP BY org_id`,
- )
- .bind(from * 1000, to * 1000)
- .all<{ org_id: string; mem_mb_secs: number; samples: number }>();
+ const caller = callerFromRow(row);
+ if (authCache.size >= CACHE_MAX) authCache.clear();
+ const entry: AuthEntry = { caller, expiresAt: row.expires_at, cachedAtMs: nowMs, lastBumpMs: 0 };
+ authCache.set(hash, entry);
+ // TTL is the STALE bound, not AUTH_TTL_MS: an entry that evaporates at 60s
+ // can never be stale-served, which would leave the SWR branch above reachable
+ // only from the isolate tier — i.e. never on the cross-isolate misses that
+ // are the whole reason the colo tier exists.
+ await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: nowMs }, AUTH_STALE_MAX_MS / 1000);
+ bumpLastUsed(env, hash, entry, nowMs);
+ return caller;
+}
- const orgs = (res.results ?? []).map((r) => ({
- org_id: r.org_id,
- gb_seconds: (r.mem_mb_secs ?? 0) / 1024,
- samples: r.samples ?? 0,
- }));
- return json({ window: { from, to }, orgs, as_of: now });
+// The 402 for a halted Autumn org, so its message fits the org: a work-minute
+// halt names its reason and links Billing; on the credit rule, free gets the
+// paywall, legacy $20 Pro the upgrade to Pro, $200 Pro no upsell. Counted as
+// billing.paywall_shown. Only read on the (rare) halted path, after the
+// self-heal re-projected the row; any failure falls back to the paywall.
+async function haltedOrgResponse(
+ req: Request,
+ env: Env,
+ ctx: ExecutionContext,
+ orgID: string,
+): Promise<Response> {
+ const paywall = await paywallContext(env.OPENCOMPUTER_DB, orgID);
+ ctx.waitUntil(emitPaywallShown(env, orgID, paywall.haltReason));
+ // Structured body only: the string-`error` flavour served the sandbox routes,
+ // removed in 097 step 7.2.
+ return insufficientCreditsResponse(req, paywall);
}
async function hmacHex(secret: string, data: string): Promise<string> {
@@ -3781,10 +516,9 @@ function constantTimeEqual(a: string, b: string): boolean {
// POST /auth/refresh → rotate session JWT (extends expiry)
//
// Session JWT lives in an httpOnly Secure SameSite=Lax cookie named
-// `oc_session`. The same secret signs the cap-token, so the cell can
-// verify a session JWT presented directly (browser fetch from dashboard)
-// using the existing capTokenMiddleware — we just set Issuer="opensandbox-session"
-// to distinguish.
+// `oc_session`, signed with SESSION_JWT_SECRET under Issuer
+// "opensandbox-session" (the issuer string is kept so existing sessions stay
+// valid).
const SESSION_COOKIE = "oc_session";
const SESSION_TTL_SEC = 60 * 60 * 8; // 8h
@@ -3834,38 +568,6 @@ const SIGNUP_RETRY_WINDOW_SEC = 60 * 60;
// the 1000-char prompt limit (web/src/lib/deferred-actions.ts) through the
// WorkOS `state` round-trip — keep the two limits in sync. WorkOS documents no
// `state` maximum, so we bound it here rather than rely on a large round-trip.
-// buildAgentExecRequest shapes an SDK exec body into the agent's argv contract.
-//
-// Two request shapes reach this endpoint and only one used to be handled:
-//
-// string form: {cmd: "echo hi"} — cmd IS the shell line
-// argv form: {cmd: "sh", args: ["-c", "echo hi"]} — cmd is the program
-//
-// The SDK sends the argv form (see Exec.run). Reading only `cmd` turned that
-// into `/bin/sh -lc sh` — a shell with no script, which reads stdin, gets EOF,
-// and exits 0 having printed nothing. So every SDK exec against a MicroVM box
-// came back {exitCode: 0, stdout: ""}: silent, total output loss that reads as
-// a command which simply produced nothing. Verified on prod — the string form
-// returned "hi-string\n" while the argv form returned "" on the same box.
-//
-// Exported purely so that contract has a test; the wire format is invisible in
-// every signal except the output being empty.
-export function buildAgentExecRequest(
- body: Record<string, unknown>,
- cmd: string,
-): { command: string; args: string[]; cwd?: string; env?: Record<string, string>; timeoutSeconds?: number } {
- const argv = Array.isArray(body.args) ? (body.args as unknown[]).filter((a): a is string => typeof a === "string") : [];
- return {
- // Honour argv verbatim when present; "sh" means the guest's shell, which is
- // what /bin/sh resolves to and what the string form already assumed.
- command: argv.length > 0 ? (cmd === "sh" ? "/bin/sh" : cmd) : "/bin/sh",
- args: argv.length > 0 ? argv : ["-lc", cmd],
- cwd: typeof body.cwd === "string" ? body.cwd : undefined,
- env: (body.env as Record<string, string> | undefined) ?? undefined,
- timeoutSeconds: typeof body.timeoutSeconds === "number" ? body.timeoutSeconds : undefined,
- };
-}
-
export function safeReturnTo(raw: string | null | undefined): string | null {
if (!raw || raw.length > 4096) return null;
if (!raw.startsWith("/") || raw.startsWith("//")) return null;
@@ -4058,7 +760,6 @@ async function provisionWorkOSIdentity(
if (!orgRow) {
const orgID = crypto.randomUUID();
- const homeCell = await pickHomeCell(env, req);
const orgName = `${profile.email}'s workspace`;
let provider = "legacy";
if (env.AUTUMN_NEW_ORGS === "true" && env.AUTUMN_SECRET_KEY) {
@@ -4071,19 +772,20 @@ async function provisionWorkOSIdentity(
console.error(`signup: autumn customer create failed for ${orgID}, falling back to legacy`);
}
}
+ // home_cell is a legacy NOT NULL column from the sandbox era. A new org has
+ // no cell, so it gets '' (no cell); max_concurrent_sandboxes keeps its
+ // column default.
await env.OPENCOMPUTER_DB.prepare(
- `INSERT INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, billing_provider, max_concurrent_sandboxes, trial_started_at, created_at, updated_at)
- VALUES (?1, ?2, ?3, 'free', ?4, 1, ?5, ?7, ?8, ?9, ?6, ?6)`,
+ `INSERT INTO orgs (id, name, slug, plan, home_cell, is_personal, owner_user_id, billing_provider, trial_started_at, created_at, updated_at)
+ VALUES (?1, ?2, ?3, 'free', '', 1, ?4, ?6, ?7, ?5, ?5)`,
)
.bind(
orgID,
orgName,
slugify(profile.email + "-" + orgID.slice(0, 6)),
- homeCell,
userID,
nowSec,
provider,
- DEFAULT_MAX_CONCURRENT_SANDBOXES,
// A new Autumn customer starts on the trial plan (autoEnable).
provider === "autumn" ? nowSec : null,
)
@@ -4256,8 +958,7 @@ async function completeAuthCallback(
});
}
- // Mint session JWT — same signing secret as cap-token but a different
- // Issuer so cell middleware can distinguish.
+ // Mint session JWT (SESSION_JWT_SECRET, Issuer "opensandbox-session").
const sessionJWT = await mintSessionJWT(
env.SESSION_JWT_SECRET,
identity.org.id,
@@ -5045,48 +1746,6 @@ async function authRefresh(req: Request, env: Env): Promise<Response> {
});
}
-// pickHomeCell chooses a home cell for a brand-new org. Policy:
-// 1. If the request carries a `cf-ipcountry` header, map to a continent and
-// prefer an onboarding-eligible cell whose region is on that continent.
-// 2. Otherwise the first onboarding-eligible cell (alphabetical → deterministic).
-// 3. None eligible → "" (downstream errors loudly).
-//
-// "Onboarding-eligible" = status='active' AND accepts_new_orgs=1. That gate is a
-// property of the cell row itself — there's no separate env allowlist to keep in
-// sync, so it can't drift from the `cells` table (which is what previously left
-// new orgs with an empty home_cell). Opening a cell to new orgs is a D1 toggle,
-// not a deploy. Geo lookup is intentionally coarse — continent-level is enough.
-async function pickHomeCell(env: Env, req: Request): Promise<string> {
- const country = req.headers.get("cf-ipcountry") ?? "";
- const continent = COUNTRY_TO_CONTINENT[country.toUpperCase()] ?? "";
-
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT cell_id, region FROM cells
- WHERE status = 'active' AND accepts_new_orgs = 1
- ORDER BY cell_id`,
- ).all<{ cell_id: string; region: string }>();
- const eligible = results ?? [];
- if (eligible.length === 0) return ""; // none open for onboarding — downstream errors
-
- if (continent) {
- const onContinent = eligible.find((c) => REGION_CONTINENT[c.region] === continent);
- if (onContinent) return onContinent.cell_id;
- }
- return eligible[0].cell_id;
-}
-
-// COUNTRY_TO_CONTINENT covers the countries we'd actually see on the
-// edge. Missing entries fall through to "no continent hint" — we don't
-// need to be exhaustive; an unknown country just means we pick the
-// first active cell.
-const COUNTRY_TO_CONTINENT: Record<string, string> = {
- US: "na", CA: "na", MX: "na",
- GB: "eu", IE: "eu", DE: "eu", FR: "eu", IT: "eu", ES: "eu", NL: "eu", SE: "eu", PL: "eu", CH: "eu", AT: "eu", BE: "eu", DK: "eu", FI: "eu", NO: "eu", PT: "eu", CZ: "eu",
- JP: "ap", KR: "ap", CN: "ap", IN: "ap", SG: "ap", AU: "ap", NZ: "ap", HK: "ap", TW: "ap", ID: "ap", PH: "ap", VN: "ap", TH: "ap", MY: "ap",
- BR: "sa", AR: "sa", CL: "sa", CO: "sa", PE: "sa",
- ZA: "af", NG: "af", EG: "af", KE: "af",
-};
-
function slugify(s: string): string {
return s.toLowerCase().replace(/[^a-z0-9-]+/g, "-").replace(/^-+|-+$/g, "").slice(0, 50);
}
@@ -5341,93 +2000,12 @@ async function verifyStripeSignature(secret: string, header: string, body: strin
// ── entrypoint ───────────────────────────────────────────────────────────
-// DEFAULT_PAUSED_CAP is the max RAM-resident paused sandboxes an org may hold
-// across all cells. Paused boxes are free + off-quota, so this bounds per-tenant
-// paused RAM; the oldest excess is promoted to deep hibernation (evicted to a
-// checkpoint). Overridable per-deployment via env.PAUSED_CAP (dev lowers it to
-// exercise the path). Enforced here because only D1 has the cross-cell view.
-const DEFAULT_PAUSED_CAP = 100;
-
-// runPausedCapEnforcer promotes each over-cap org's oldest paused sandboxes to
-// deep hibernation, by calling the cell that hosts each one. Runs on the 5-min
-// cron; the cell endpoint is idempotent (no-ops if the box already resumed or
-// was promoted), so redundant calls are safe.
-async function runPausedCapEnforcer(env: Env): Promise<void> {
- const cap = Number(env.PAUSED_CAP) || DEFAULT_PAUSED_CAP;
- const overCap = await env.OPENCOMPUTER_DB.prepare(
- `SELECT org_id, COUNT(*) AS n FROM sandboxes_index
- WHERE hibernation_mode = 'paused'
- GROUP BY org_id HAVING n > ?1`,
- )
- .bind(cap)
- .all<{ org_id: string; n: number }>();
-
- for (const org of overCap.results ?? []) {
- const excess = org.n - cap;
- const victims = await env.OPENCOMPUTER_DB.prepare(
- `SELECT s.id, s.cell_id, c.base_url
- FROM sandboxes_index s
- JOIN cells c ON s.cell_id = c.cell_id
- WHERE s.org_id = ?1 AND s.hibernation_mode = 'paused'
- ORDER BY s.last_event_at ASC
- LIMIT ?2`,
- )
- .bind(org.org_id, excess)
- .all<{ id: string; cell_id: string; base_url: string }>();
-
- let promoted = 0;
- for (const v of victims.results ?? []) {
- try {
- const token = await mintCapToken(env.SESSION_JWT_SECRET, org.org_id, v.cell_id, "", "", "", null);
- const resp = await fetch(
- v.base_url.replace(/\/$/, "") + `/internal/sandboxes/${v.id}/deep-hibernate`,
- { method: "POST", headers: { authorization: "Bearer " + token } },
- );
- if (resp.ok) promoted++;
- else console.error(`paused-cap: deep-hibernate ${v.id} on ${v.cell_id} → ${resp.status}`);
- } catch (err) {
- console.error(`paused-cap: deep-hibernate ${v.id} failed`, err);
- }
- }
- console.log(`paused-cap: org ${org.org_id} at ${org.n}/${cap} paused, promoted ${promoted} oldest to deep`);
- }
-}
-
-// Isolate identity, for telling COLD START apart from admission queueing.
-//
-// A burst's "colo_admit" (the benchmark's total minus our handler) is a residual,
-// not a measurement: it holds the wire leg, client-side H2 stream scheduling, CF
-// admission, isolate scheduling and the response path all at once. Within one
-// run it decayed 189ms → 86ms → 11ms across create/exec/delete at identical
-// concurrency, which is the shape of a warm-up curve rather than a load curve —
-// and every burst so far has been the first traffic after a deploy, so every
-// isolate serving it was born cold.
-//
-// These three marks settle it. ISO_AGE says how old the isolate was when the
-// request landed; ISO_SEQ says how many requests it had already served; ISO_T
-// stamps handler entry so the SPREAD of entry times across a burst can be
-// compared against what the client observed. If 100 handler entries span 180ms,
-// admission really is serializing. If they span 10ms, the time is somewhere the
-// edge cannot see.
-const ISO_BORN = Date.now();
-let ISO_SEQ = 0;
-
export default {
async fetch(req: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
env = envWithD1Retry(env);
- const tTop = Date.now();
- ISO_SEQ++;
const url = new URL(req.url);
const path = url.pathname;
- // Sandbox preview URL dispatch — matched by HOSTNAME, not path. Has to
- // run before the path-based routes below so that a sandbox app serving
- // its own /health or /api/* doesn't get shadowed by ours.
- const preview = parsePreviewHost(url.hostname);
- if (preview) {
- return handlePreviewURL(req, env, preview);
- }
-
if (path === "/health") {
return json({ ok: true, env: env.WORKER_ENV });
}
@@ -5439,39 +2017,7 @@ export default {
return handleAgentFeedback(req, env, path, ctx);
}
-
- // VM-DO host dial: the QEMU worker host opens a persistent WebSocket to the
- // per-sandbox VmSession DO here (vm_session.ts). Auth is a per-sandbox connect
- // token = HMAC(SESSION_JWT_SECRET, "vmdo:"+id), minted by the CP and delivered
- // to the worker over the create/claim/wake gRPC; the worker holds no signing
- // secret. We re-derive it here from the id in the path and the shared secret
- // (same construction as auth.MintVMDOConnectToken) and compare to the token
- // the host presents as the 2nd WS subprotocol. No location hint on get() → CF
- // places the DO near the host's colo (eastus→IAD, westus2→SEA).
- {
- const vmConnect = path.match(/^\/internal\/vms\/([^/]+)\/connect$/);
- if (vmConnect && isWebSocketUpgrade(req)) {
- // 503 (not a crash) if the binding is absent — happens only during the
- // two-step cutover that moves VmSession between workers; hosts just
- // keep redialing until the rebind deploy lands.
- if (!env.VM_SESSIONS) return new Response("vm sessions unavailable", { status: 503 });
- const expected = env.SESSION_JWT_SECRET
- ? await hmacHex(env.SESSION_JWT_SECRET, "vmdo:" + vmConnect[1])
- : "";
- if (!expected || !(await tokenMatches(socketSecret(req), expected))) {
- return new Response("unauthorized", { status: 401 });
- }
- const stub = env.VM_SESSIONS.get(env.VM_SESSIONS.idFromName(vmConnect[1]));
- return stub.fetch(new Request("https://do/connect", req));
- }
- }
-
- if (path === "/internal/halt-list") {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return haltList(req, env);
- }
-
- // Cell/reconciler trigger for the Autumn re-check+project (EVENT_SECRET HMAC).
+ // Reconciler trigger for the Autumn re-check+project (EVENT_SECRET HMAC).
if (path === "/internal/autumn-project") {
if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
return autumnProjectInternal(req, env);
@@ -5491,24 +2037,6 @@ export default {
if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
return autumnSetProviderInternal(req, env);
}
- // Dev-only: measure what an exec would cost if the edge dialled the box
- // ITSELF instead of going through a MicrovmSession DO.
- //
- // The DO exists to hold the agent tunnel open across execs. Measured on dev
- // from an IAD client, that reuse is not paying for itself: the hop to the DO
- // plus its per-sandbox cold start costs ~77ms median, against the 22-102ms
- // dial it avoids — and it avoids it only about half the time, because every
- // sandbox gets its own object and uses it once. This route measures the
- // other side of that trade with the DO fully out of the path.
- //
- // creds;dur is reported separately and must NOT be counted against the
- // direct path: it is a round trip to the control plane in Azure westus2,
- // cross-country from this edge, and a real direct path would take the same
- // endpoint+token from the colo cache the create already passes through.
- if (path.startsWith("/internal/direct-exec-probe/") && req.method === "POST") {
- if (env.WORKER_ENV === "prod") return new Response("not found", { status: 404 });
- return directExecProbe(req, env, path.slice("/internal/direct-exec-probe/".length));
- }
// Dev-only: force an autumn-meter run (the cron is */5). 404 in prod so only
// the scheduled trigger moves money there. Deterministic testing aid.
if (path === "/internal/run-autumn-meter" && req.method === "POST") {
@@ -5516,57 +2044,6 @@ export default {
await runAutumnMeter(env, Date.now());
return json({ ok: true });
}
- // Dev-only: force a paused-cap enforcement run (cron is */5). Deterministic
- // testing aid for the promotion path.
- if (path === "/internal/run-paused-cap" && req.method === "POST") {
- if (env.WORKER_ENV === "prod") return new Response("not found", { status: 404 });
- await runPausedCapEnforcer(env);
- return json({ ok: true });
- }
- // Placement probe for the pool shards. HMAC-auth'd (CF_ADMIN_SECRET) so it
- // is safe to run against prod, which is the only place the answer matters —
- // the colo a DO lands in is a property of the account and region, and dev
- // cannot stand in for it.
- //
- // Touching a candidate PLACES it, permanently. That is the point: this
- // sweep is how a generation of shards gets minted, and its output is the
- // POOL_STOCK_SHARD_IDS list. Sweeping a gen that is already live is
- // harmless (the candidates beyond the selected ones just sit empty and
- // never claim), but do not sweep with a `target` you are not about to ship.
- //
- // ?child=1 also asks each candidate to parent a throwaway MicrovmSession
- // and report where the CHILD landed — the one measurement that decides
- // whether pinning shards also pins the session DOs warmed from them.
- if (path === "/internal/pool/colo-probe" && req.method === "GET") {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- const expected = await hmacHex(env.CF_ADMIN_SECRET, `${ts}.${path}${url.search}`);
- if (!constantTimeEqual(expected, sig)) return json({ error: "signature mismatch" }, 401);
- if (Math.abs(Math.floor(Date.now() / 1000) - Number(ts)) > 300)
- return json({ error: "timestamp out of window" }, 401);
- const cellID = url.searchParams.get("cell") ?? "";
- if (!cellID) return json({ error: "cell required" }, 400);
- const gen = url.searchParams.get("gen") ?? POOL_STOCK_SHARD_GEN;
- const n = Math.min(Number(url.searchParams.get("n")) || POOL_STOCK_CANDIDATES, 256);
- const wantChild = url.searchParams.get("child") === "1";
- const probe = async (i: number) => {
- const name = `${cellID}#${gen}#${i}`;
- const q = wantChild ? `?child=${encodeURIComponent(`probe-${gen}-${i}`)}` : "";
- try {
- const r = await env.POOL_STOCK.get(env.POOL_STOCK.idFromName(name), {
- locationHint: "enam",
- }).fetch(`https://pool-stock/colo${q}`);
- const j = (await r.json()) as { colo: string; stock: number; child: string | null };
- return { i, colo: j.colo, stock: j.stock, child: j.child };
- } catch (e) {
- return { i, colo: "err", stock: -1, child: String(e).slice(0, 60) };
- }
- };
- const results = await Promise.all(Array.from({ length: n }, (_, i) => probe(i)));
- const byColo: Record<string, number[]> = {};
- for (const r of results) (byColo[r.colo] ??= []).push(r.i);
- return json({ cell: cellID, gen, edgeColo: req.headers.get("cf-ray")?.split("-")[1] ?? "?", byColo, results });
- }
// Force a model-meter run (token billing §5.4). HMAC-auth'd (CF_ADMIN_SECRET) so
// it's safe to run in prod for testing/ops — useful to debit + push caps right
// after a Managed turn instead of waiting for the cron.
@@ -5581,16 +2058,6 @@ export default {
return json({ ok: true });
}
- if (path === "/internal/org-policy") {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return orgPolicy(req, env);
- }
-
- if (path === "/internal/usage-parity") {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return usageParity(req, env);
- }
-
// /internal/admin/do-mark-free — operator-only escape hatch to flip a
// CreditAccount DO's internal plan from "pro" back to "free" without
// running a real Stripe subscription.deleted webhook. HMAC-auth'd with
@@ -5613,8 +2080,9 @@ export default {
// /internal/warm-org — pre-populate this colo's caches for one org.
//
- // The auth and create-context tiers live in the colo cache, and every entry
- // in them expires (auth 10min, org/cells/count 5min). An API key used once
+ // The auth tier lives in the colo cache, and its entries expire (10min).
+ // (The sandbox create-context tier it also warmed is gone since 097 step
+ // 7.2.) An API key used once
// a week is therefore always cold when it matters, and a cold miss costs a
// D1 read against a primary in WNAM while the request runs in IAD —
// measured at 340ms, paid by EVERY request in a burst because the cold path
@@ -5662,10 +2130,6 @@ export default {
await coloPut("auth", row.key_hash, { caller, expiresAt: row.expires_at, cachedAtMs: at }, AUTH_STALE_MAX_MS / 1000);
warmed++;
}
- // org policy + concurrency count + the active-cell list, the other three
- // reads a cold create pays.
- await warmCreateContextColo(env.OPENCOMPUTER_DB, [parsed.org_id]);
-
return json({
warmed,
org_id: parsed.org_id,
@@ -5745,52 +2209,21 @@ export default {
return json({ key: created.key, expiresAt: created.expiresAt });
}
- // /internal/secret-stores/:id — HMAC-auth'd, called by CP at sandbox-create
- // time to materialize the encrypted entry list. CP decrypts with the
- // shared SECRET_ENCRYPTION_KEY before injecting into worker env.
- if (path === "/internal/secret-stores/by-name") {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return secretStores.internalGetStoreByName(req, env);
- }
- {
- const m = path.match(/^\/internal\/secret-stores\/([^/]+)$/);
- if (m) {
- if (req.method === "GET") return secretStores.internalGetStore(req, env, m[1]);
- if (req.method === "DELETE") return secretStores.internalDeleteStore(req, env, m[1]);
- return json({ error: "method not allowed" }, 405);
- }
- }
-
- // /internal/templates/* — HMAC-auth'd. by-name = sandbox-create lookup;
- // POST / = "save sandbox as template" registration; PUT /:id/status =
- // flip status='ready' once snapshot upload finishes.
- if (path === "/internal/templates/by-name") {
- if (req.method !== "GET") return json({ error: "method not allowed" }, 405);
- return templates.internalGetByName(req, env);
- }
- if (path === "/internal/templates") {
- if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
- return templates.internalRegister(req, env);
- }
- {
- const m = path.match(/^\/internal\/templates\/([^/]+)\/status$/);
- if (m) {
- if (req.method !== "PUT") return json({ error: "method not allowed" }, 405);
- return templates.internalUpdateStatus(req, env, m[1]);
- }
- }
-
// /internal/webhooks/register — HMAC-auth'd, called by the CP at
// sandbox-create time to register inline webhooks (Svix endpoints) BEFORE
// the sandbox emits `created`. (.agents/work/sandbox-webhooks-rearchitecture.md)
+ // Not in 097 step 7.2's strip list: it touches only Svix and D1, and goes
+ // dead on its own once the cells stop calling it. Removed with the rest of
+ // the sandbox webhooks in a follow-up.
if (path === "/internal/webhooks/register") {
if (req.method !== "POST") return json({ error: "method not allowed" }, 405);
return webhooks.registerInlineWebhooksInternal(req, env, url);
}
- // /api/secret-stores — org-scoped CRUD. Same X-API-Key auth as
- // /api/sandboxes; replaces the legacy CP-side PG routes (deleted in
- // the same PR as migration 041).
+ // /api/secret-stores — org-scoped CRUD with X-API-Key auth; replaced the
+ // legacy CP-side PG routes (deleted in the same PR as migration 041). Kept
+ // after the sandbox strip (097 step 7.2) because `oc secret` still calls it;
+ // it no longer pushes anything to cells.
if (path === "/api/secret-stores") {
const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
@@ -5824,55 +2257,6 @@ export default {
}
}
- // ── Snapshots + images (SDK/CLI, X-API-Key) ─────────────────────────
- // A snapshot is a named image; both are mirrored into D1 images_index.
- // Reads serve straight from D1 (no cell hop, multi-cell correct, survive
- // an owning-cell outage). Create routes to the org home_cell with SSE
- // build-log streaming. Delete routes to the cell that owns the bytes.
- if (path === "/api/snapshots") {
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- if (req.method === "GET") return snapshots.listSnapshots(env, caller);
- if (req.method === "POST") return proxyToCellAuthed(req, env, caller); // build → home_cell, SSE
- return json({ error: "method not allowed" }, 405);
- }
- {
- // /api/snapshots/:name, /api/snapshots/:name/patches[/:patchId],
- // /api/snapshots/:name/publish, /api/snapshots/:name/unpublish
- const m = path.match(/^\/api\/snapshots\/([^/]+)(\/patches(?:\/[^/]+)?|\/(?:un)?publish)?$/);
- if (m) {
- const name = decodeURIComponent(m[1]);
- const sub = m[2] ?? "";
- const isPatch = sub.startsWith("/patches");
- const isPublishToggle = sub === "/publish" || sub === "/unpublish";
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- // Patches, publish/unpublish, and delete are cell-work — route to the
- // cell that owns the snapshot bytes (looked up from D1), not "any active
- // cell". is_public lives in the owning cell's image_cache.
- if (isPatch || isPublishToggle || req.method === "DELETE") {
- const ownerCell = await snapshots.ownerCellOfSnapshot(env, caller, name);
- if (ownerCell) return proxyToCellAuthed(req, env, caller, { cellId: ownerCell });
- // D1 images_index can lag the cell PG right after a snapshot is built.
- // For publish/unpublish (idempotent catalog toggles), fall back to the
- // org's home_cell — where a just-created snapshot lives — and let the
- // cell be the source of truth (it returns 404 if the row is really
- // absent). Patches/delete stay strict: a missing index row means the
- // bytes aren't addressable yet.
- if (isPublishToggle) return proxyToCellAuthed(req, env, caller);
- return json({ error: "snapshot not found" }, 404);
- }
- if (req.method === "GET") return snapshots.getSnapshot(env, caller, name);
- return json({ error: "method not allowed" }, 405);
- }
- }
- if (path === "/api/images") {
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- if (req.method === "GET") return snapshots.listImages(env, caller);
- return json({ error: "method not allowed" }, 405);
- }
-
// Auth flows. CLI device auth is deliberately edge-brokered: WorkOS tokens
// never cross this boundary and the CLI receives one ordinary OC org key.
if (path === "/auth/cli/device") {
@@ -5895,11 +2279,11 @@ export default {
if (path === "/webhooks/stripe" && req.method === "POST") return stripeWebhook(req, env);
// Autumn (useautumn.com) webhook — Svix-signed; projects authoritative
- // balance/plans into D1 (is_halted, max_concurrent) + dispatches to cells.
+ // balance/plans into D1 (is_halted, usage_plan, halt_reason).
if (path === "/webhooks/autumn" && req.method === "POST") return autumnWebhook(req, env, (orgID) => syncModelCaps(env, orgID));
// Dashboard API — everything under /api/dashboard/*. Edge-native handlers
- // back D1 reads/writes; sandbox-runtime calls proxy to the sandbox's cell.
+ // back D1 reads/writes (the sandbox-cell proxy was removed in 097 step 7.2).
// Auth via the oc_session cookie minted at /auth/callback.
if (path.startsWith("/api/dashboard")) {
return handleDashboard(req, env, ctx, path);
@@ -5994,7 +2378,7 @@ export default {
selfHealHalt(env, id),
);
if (billing.status === "halted") {
- return haltedOrgResponse(req, env, ctx, caller.orgID, true);
+ return haltedOrgResponse(req, env, ctx, caller.orgID);
}
if (billing.status !== "active") {
return json({ error: "managed model billing is unavailable" }, 503);
@@ -6024,204 +2408,6 @@ export default {
);
}
- // /api/sandboxes and /api/sandboxes/:id[/...]
- if (path === "/api/sandboxes") {
- if (req.method === "POST") return createSandbox(req, env, ctx, tTop);
- if (req.method === "GET") return listSandboxes(req, env);
- return json({ error: "method not allowed" }, 405);
- }
-
- // /api/sandboxes/from-checkpoint/{checkpointID} — spawn a new sandbox
- // from a checkpoint. Routing differs from regular sandbox-scoped ops
- // because the URL has no sandbox_id; we look up the cell from
- // checkpoints_index via the checkpoint UUID. The CP-side handler
- // (createFromCheckpoint) then pulls the checkpoint disks from Tigris
- // and boots a sandbox in the owning cell.
- {
- const fc = path.match(/^\/api\/sandboxes\/from-checkpoint\/([^/]+)$/);
- if (fc && req.method === "POST") {
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- const cpID = fc[1];
- const cpRow = await env.OPENCOMPUTER_DB.prepare(
- `SELECT owner_cell_id, org_id FROM checkpoints_index WHERE id = ?1`,
- )
- .bind(cpID)
- .first<{ owner_cell_id: string; org_id: string }>();
- if (!cpRow) return json({ error: "checkpoint not found" }, 404);
- if (cpRow.org_id !== caller.orgID) return json({ error: "checkpoint not in your org" }, 403);
- const cell = await lookupCell(env, cpRow.owner_cell_id);
- if (!cell) return json({ error: `cell ${cpRow.owner_cell_id} not registered` }, 503);
- const { org, activeCount: fcActive } = await loadCreateContext(env, caller.orgID);
- if (!org) return json({ error: "org not found" }, 401);
- // Read the body so we can size-gate, forward it, and record cpu/mem to
- // register the forked sandbox in sandboxes_index — same as createSandbox.
- // Without the index row, forked sandboxes run on the cell but are
- // invisible to the edge (exec/delete/get 404).
- const fcBody = await req.text();
- let fcCpu = 0;
- let fcMem = 0;
- let fcDisk = 0;
- try {
- const b = JSON.parse(fcBody || "{}");
- if (typeof b.cpuCount === "number") fcCpu = b.cpuCount;
- if (typeof b.memoryMB === "number") fcMem = b.memoryMB;
- if (typeof b.diskMB === "number") fcDisk = b.diskMB;
- } catch {
- /* malformed JSON — let the CP reject */
- }
- // Edge-authoritative org-policy gate, same as createSandbox. Forks were
- // previously ungated at the edge and leaned on a cell-side concurrent
- // check that read stale cell PG and could only ever count one cell's
- // sandboxes — wrong once an org spans cells. Enforce from D1 here.
- const fcGate = await enforceCreatePolicy(req, env, ctx, caller.orgID, org, { cpuCount: fcCpu, memoryMB: fcMem, diskMB: fcDisk }, fcActive);
- if (fcGate) return fcGate;
- const plan = org.plan === "pro" ? "pro" : "free";
- // org.runtime, deliberately NOT the SDK-version routing createSandbox
- // uses. A fork restores a checkpoint, and only the QEMU fleet produces
- // checkpoints — routing a fork by the caller's SDK version would send it
- // to a runtime that has nothing to restore. It follows the org's pin or
- // nothing, exactly as before.
- const token = await mintCapToken(env.SESSION_JWT_SECRET, caller.orgID, cpRow.owner_cell_id, plan, org.billing_provider, org.runtime ?? "", caller.userID);
- const fcResp = await fetch(cell.base_url.replace(/\/$/, "") + path, {
- method: "POST",
- headers: { authorization: "Bearer " + token, "content-type": "application/json" },
- body: fcBody || "{}",
- });
- const fcText = await fcResp.text();
- if (fcResp.status >= 200 && fcResp.status < 300) {
- let parsed: SandboxCreateResult = {};
- try {
- parsed = JSON.parse(fcText) as SandboxCreateResult;
- } catch {
- /* leave empty */
- }
- if (parsed.sandboxID) {
- await env.OPENCOMPUTER_DB.prepare(
- `INSERT OR REPLACE INTO sandboxes_index
- (id, org_id, user_id, cell_id, worker_id, status, cpu_count, memory_mb, created_at, last_event_at, end_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?9, ?10)`,
- )
- .bind(
- parsed.sandboxID,
- caller.orgID,
- caller.userID,
- cell.cell_id,
- parsed.workerID ?? null,
- parsed.status ?? "running",
- fcCpu,
- parsed.memoryMB ?? fcMem,
- Math.floor(Date.now() / 1000),
- unixFromISO(parsed.endAt),
- )
- .run();
- }
- }
- return new Response(fcText, {
- status: fcResp.status,
- headers: { "content-type": "application/json" },
- });
- }
- }
-
- // /api/sandboxes/checkpoints/:id[/...] — checkpoint-scoped ops (publish,
- // unpublish, patches). The URL carries no sandbox_id, so the generic
- // /api/sandboxes/:id matcher below would read "checkpoints" as a sandbox id
- // and 404 ("sandbox not found"). Route by the checkpoint's owning cell
- // (checkpoints_index), like the snapshot patch/publish paths.
- {
- const cpm = path.match(/^\/api\/sandboxes\/checkpoints\/([^/]+)(\/.*)?$/);
- if (cpm) {
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- const cpRow = await env.OPENCOMPUTER_DB.prepare(
- `SELECT owner_cell_id FROM checkpoints_index WHERE id = ?1`,
- ).bind(cpm[1]).first<{ owner_cell_id: string }>();
- if (!cpRow?.owner_cell_id) return json({ error: "checkpoint not found" }, 404);
- return proxyToCellAuthed(req, env, caller, { cellId: cpRow.owner_cell_id });
- }
- }
-
- const m = path.match(/^\/api\/sandboxes\/([^/]+)(\/.*)?$/);
- if (m) {
- const id = m[1];
- const rest = m[2]; // undefined for /api/sandboxes/:id, "/exec/run" etc otherwise
- const tSubEntry = Date.now();
- // Uniform client→handler / in-handler split for /:id/* responses, whichever
- // sub-path served them. Each exec path emits its own disjoint mark set
- // (microvm-direct: reach/exec/up/ready; VM-DO: do/doin/agent; tunnel:
- // origin), so a harness that knows one set reads the others as absent and
- // silently drops those requests from its breakdown — while the client's
- // total minus the in-handler marks stays an unattributable lump. That is
- // exactly the blind spot that made create's burst regression unreadable
- // until `pre`/`hdl` landed (see createSandbox). `path` names the winner so
- // a fallback is counted rather than inferred.
- const stampSub = (resp: Response, servedBy: string, fall?: Fallback): Response => {
- // A WebSocket upgrade (pty) can't be reconstructed — pass it through.
- if (resp.status === 101 || (resp as unknown as { webSocket?: unknown }).webSocket) return resp;
- const extra = [`path;desc=${servedBy}`, `hdl;dur=${Date.now() - tSubEntry}`];
- // Only meaningful on the tunnel branch, and only there is it set.
- if (fall?.why) extra.push(`why;desc=${fall.why}`);
- if (fall?.dial) extra.push(`dialfail;desc=${fall.dial}`);
- const clientSentMs = Number(req.headers.get("x-client-sent") ?? "");
- if (Number.isFinite(clientSentMs) && clientSentMs > 0) extra.unshift(`pre;dur=${tSubEntry - clientSentMs}`);
- const out = new Response(resp.body, resp);
- const prev = out.headers.get("server-timing");
- out.headers.set("server-timing", prev ? `${prev}, ${extra.join(", ")}` : extra.join(", "));
- return out;
- };
- if (!rest) {
- if (req.method === "GET") return getSandbox(req, env, id);
- if (req.method === "DELETE") {
- const caller = await authenticate(req, env, ctx);
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- return proxyToCellSDK(req, env, ctx, caller, id);
- }
- return json({ error: "method not allowed" }, 405);
- }
- // Anything under /:id/* (exec, files, pty, hibernate, …) lives on the
- // cell — proxy with an edge-minted IdentityToken (the cell's existing
- // API-key middleware accepts that JWT shape) so we don't depend on the
- // SDK's api-key existing in cell PG.
- const tAuth = Date.now();
- const caller = await authenticate(req, env, ctx);
- const authMs = Date.now() - tAuth;
- if (!caller) return json({ error: "missing or invalid API key" }, 401);
- // Exec/delete traffic is what keeps an org's create-context entries warm
- // in THIS colo between its bursts. Off the hot path (waitUntil) and a
- // no-op unless an entry is actually aging.
- keepCreateContextWarm(env.OPENCOMPUTER_DB, ctx, caller.orgID);
- // VM-DO exec fast path: route POST /:id/exec/run-async through the
- // sandbox's VmSession DO. Automatic tunnel fallback (no flag) whenever the
- // channel isn't live (DO 409) — so this is safe even before/while workers
- // roll out the host dialer. Gated only on SESSION_JWT_SECRET (present
- // wherever the DO auth can be verified at all).
- let vmdoMs = 0;
- const fall: Fallback = {};
- if (env.SESSION_JWT_SECRET && req.method === "POST" && rest === "/exec/run-async") {
- const tVmdo = Date.now();
- const doResp = await tryVmDoExec(req, env, ctx, caller, id, authMs, fall);
- vmdoMs = Date.now() - tVmdo;
- // Name the winner from the marks it emitted rather than plumbing a label
- // back out of two functions that already disagree about their shape.
- if (doResp) {
- const st = doResp.headers.get("server-timing") ?? "";
- return stampSub(doResp, st.includes("reach;") ? "mvm-direct" : st.includes("do;") ? "vmdo" : "fast");
- }
- }
- // vmdo = time spent deciding NOT to use the VM-DO path. For MicroVM orgs
- // that decision needs an org-policy lookup, so it is not free.
- return stampSub(await proxyToCellSDK(req, env, ctx, caller, id, authMs, vmdoMs), "tunnel", fall);
- }
-
- // Generic /api/* fallback for SDK/CLI routes without a dedicated D1-native
- // handler yet (/api/usage, /api/tags, /api/capacity/*, /api/workers,
- // /api/sessions, checkpoint patches, etc.). Authenticate against D1, mint a
- // cap-token, and route to the org's home_cell. Pre-fix this forwarded the
- // raw X-API-Key to "any active cell" — which 403'd because the cell can no
- // longer validate D1-only api_keys, and would mis-route in a multi-cell
- // world. proxyToCellAuthed streams the response (SSE-safe). This is a
- // backstop; prefer adding a native handler for high-traffic resources.
// /api/whoami — return the authenticated caller's org (+ user). Lets a
// trusted service resolve an osb_ key to its OC org without custodying it.
// /api/billing/credits — API-key credit status for the CLI (plan, balance,
@@ -6260,10 +2446,13 @@ export default {
return webhooks.handleWebhooksAPI(req, env, caller, url);
}
+ // Any other /api/* path used to fall through to a sandbox cell. The cells
+ // are gone (097 step 7.2), so it is an authenticated 404: an unknown key
+ // still gets 401, and the SPA never answers an API path with index.html.
if (path.startsWith("/api/")) {
const caller = await authenticate(req, env, ctx);
if (!caller) return json({ error: "missing or invalid API key" }, 401);
- return proxyToCellAuthed(req, env, caller);
+ return json({ error: "not found" }, 404);
}
// Anything not matched above is the dashboard SPA — delegate to the
@@ -6278,7 +2467,7 @@ export default {
},
// Cron (*/5): edge-native autumn billing. Meters autumn orgs' usage_samples to
- // Autumn and halts on exhaustion — one place, not per-cell. Legacy orgs bill
+ // Autumn and halts on exhaustion. Legacy orgs bill
// via the separate billing-rollup worker; this no-ops unless AUTUMN_SECRET_KEY
// is set (dormant until the cutover switch is flipped). The same tick also runs
// the token/model-usage meter (token-billing §5.4): poll each managed OpenRouter
@@ -6286,25 +2475,12 @@ export default {
// Dormant unless OPENROUTER_PROVISIONING_KEY is set + managed keys exist.
async scheduled(_event: ScheduledController, env: Env, ctx: ExecutionContext): Promise<void> {
env = envWithD1Retry(env);
- // Cross-cell paused-cap enforcement runs regardless of billing config.
- ctx.waitUntil(
- runPausedCapEnforcer(env).catch((err) => console.error("paused-cap: run failed", err)),
- );
- // Telemetry retention, also regardless of billing config. D1 caps a database
- // at 10 GB with no way to raise it, and when events/usage_samples reach it
- // EVERY insert fails — including the capacity heartbeat, which freezes
- // cells.capacity_updated_at and takes every create in the region down with
- // "no cells available with capacity". See retention.ts.
+ // Telemetry retention, regardless of billing config. D1 caps a database at
+ // 10 GB with no way to raise it, and when events/usage_samples reach it
+ // EVERY insert fails. See retention.ts.
ctx.waitUntil(
runRetentionSweep(env).catch((err) => console.error("retention: run failed", err)),
);
- // Pool keep-warm. Deliberately ABOVE the billing-config early return below:
- // create latency must not depend on whether Autumn happens to be configured,
- // and a cell whose stock has decommissioned serves every create through the
- // slow path. Creates nothing — see runPoolKeepWarm.
- ctx.waitUntil(
- runPoolKeepWarm(env).catch((err) => console.error("pool-keepwarm: run failed", err)),
- );
// Slack Connect invite per signup, regardless of billing config. Dormant
// unless SLACK_CONNECT_TOKEN is set. See slack_connect.ts.
ctx.waitUntil(
@@ -6328,35 +2504,4 @@ export default {
);
}
},
-
- // Off-isolate edge-claim finalize consumer (see FINALIZE_QUEUE). Runs on its
- // own invocations, so the CP claim-finalize fetch + D1 index insert never
- // contend with the create hot path. finalizeEdgeClaim handles its own failure
- // (marks the box error), so a message is acked once processed; genuine
- // enqueue-side failures already fell back to inline finalize at the producer.
- async queue(batch: MessageBatch<FinalizeMsg>, env: Env): Promise<void> {
- env = envWithD1Retry(env);
- await Promise.all(
- batch.messages.map(async (m) => {
- const b = m.body;
- try {
- await finalizeEdgeClaim(
- env,
- { orgID: b.orgID, userID: b.userID } as Caller,
- { cell_id: b.cellID, base_url: b.baseURL } as CellRow,
- b.plan,
- b.billingProvider,
- b.runtime ?? "",
- b.sandboxID,
- b.workerID,
- b.bodyText,
- b.runtimePin ?? b.runtime ?? "",
- );
- } catch (e) {
- console.error(`finalize-queue: ${b.sandboxID} failed:`, e);
- }
- m.ack();
- }),
- );
- },
-} satisfies ExportedHandler<Env, FinalizeMsg>;
+} satisfies ExportedHandler<Env>;
diff --git a/cloudflare-workers/api-edge/src/loops.test.ts b/cloudflare-workers/api-edge/src/loops.test.ts
index 5656b678..c0cae873 100644
--- a/cloudflare-workers/api-edge/src/loops.test.ts
+++ b/cloudflare-workers/api-edge/src/loops.test.ts
@@ -105,7 +105,6 @@ describe("Loops client", () => {
function fakeDb(opts: { provider?: string; email?: string; org?: Record<string, unknown> } = {}) {
const org: Record<string, unknown> = {
is_halted: 0,
- autumn_concurrency_override: null,
usage_plan: "base",
payment_past_due_at: null,
trial_started_at: Math.floor(Date.now() / 1000) - 86_400,
@@ -139,9 +138,9 @@ function fakeDb(opts: { provider?: string; email?: string; org?: Record<string,
} else if (sql.includes("SET is_halted")) {
org.is_halted = args[0];
org.halted_at = args[1];
- org.usage_plan = args[3];
- org.halt_reason = args[6];
- org.billing_warning = args[7];
+ org.usage_plan = args[2];
+ org.halt_reason = args[5];
+ org.billing_warning = args[6];
}
return { meta: { changes: 1 } };
},
diff --git a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
index be1d1690..486e4ea0 100644
--- a/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
+++ b/cloudflare-workers/api-edge/src/managed_agent_credit_gate.ts
@@ -117,9 +117,8 @@ export async function getManagedAgentBillingAdmission(
.first<ManagedAgentCreditRow>();
let row = await readRow();
let isHalted = row?.is_halted === 1;
- // Like the sandbox create/wake gates: a halted Autumn org re-checks the
- // authoritative balance, so a user who just topped up isn't denied until
- // the webhook/reconciler catches up.
+ // A halted Autumn org re-checks the authoritative balance, so a user who
+ // just topped up isn't denied until the webhook/reconciler catches up.
if (isHalted && row?.billing_provider === "autumn" && selfHeal) {
isHalted = await selfHeal(orgID);
// The re-check re-projects halt_reason/usage_plan; a still-halted org's
diff --git a/cloudflare-workers/api-edge/src/pool_stock.test.ts b/cloudflare-workers/api-edge/src/pool_stock.test.ts
deleted file mode 100644
index 0fcd8b47..00000000
--- a/cloudflare-workers/api-edge/src/pool_stock.test.ts
+++ /dev/null
@@ -1,334 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-
-import { PoolStock } from "./pool_stock";
-
-// ── fakes ───────────────────────────────────────────────────────────────────
-class FakeStorage {
- map = new Map<string, unknown>();
- alarm: number | null = null;
- async get<T>(k: string): Promise<T | undefined> {
- return this.map.get(k) as T | undefined;
- }
- async put(k: string, v: unknown): Promise<void> {
- this.map.set(k, v);
- }
- async getAlarm(): Promise<number | null> {
- return this.alarm;
- }
- async setAlarm(t: number): Promise<void> {
- this.alarm = t;
- }
-}
-
-class FakeState {
- storage = new FakeStorage();
- pending: Promise<unknown>[] = [];
- async blockConcurrencyWhile<T>(cb: () => Promise<T>): Promise<T> {
- return cb();
- }
- waitUntil(p: Promise<unknown>): void {
- this.pending.push(p.catch(() => {}));
- }
- async settle(): Promise<void> {
- // Drain repeatedly: waitUntil work can itself schedule more waitUntil work.
- for (let i = 0; i < 5 && this.pending.length > 0; i++) {
- const batch = this.pending;
- this.pending = [];
- await Promise.all(batch);
- }
- }
-}
-
-const CELL = { cellID: "cell-a", baseURL: "https://cell-a.example" };
-const ORG_A = "11111111-1111-4111-8111-111111111111";
-
-interface ReserveBox {
- sandboxID: string;
- workerID: string;
- endpoint?: string;
- token?: string;
- port?: number;
-}
-
-/**
- * Stands in for the MICROVM_SESSIONS namespace, recording every attach.
- *
- * The attach count per box is the thing under test: it used to be exactly one
- * for a box's entire life, which made the warm path depend on that single call
- * landing at a moment when the box happened to be ready.
- */
-class FakeSessions {
- attaches: string[] = [];
- idFromName(name: string): string {
- return name;
- }
- get(id: string): { fetch: (url: string, init?: RequestInit) => Promise<Response> } {
- return {
- fetch: async (url: string) => {
- if (url.includes("/attach")) this.attaches.push(id);
- return Response.json({ ok: true });
- },
- };
- }
-}
-
-/** Records every origin call the DO makes, and controls what edge-reserve returns. */
-class FakeOrigin {
- reserved: ReserveBox[][] = [];
- releasedIDs: string[] = [];
- supply: ReserveBox[] = [];
- /** Control-plane process identity; changing it simulates a CP restart. */
- epoch = "epoch-1";
- handler = async (url: string, init?: RequestInit): Promise<Response> => {
- const body = JSON.parse(String(init?.body ?? "{}"));
- if (url.includes("/internal/pool/edge-reserve")) {
- const give = this.supply.splice(0, Number(body.count) || 0);
- this.reserved.push(give);
- return Response.json({
- region: "westus2",
- sandboxDomain: "sb.example",
- epoch: this.epoch,
- boxes: give,
- });
- }
- if (url.includes("/internal/pool/edge-release")) {
- this.releasedIDs.push(...(body.sandboxIDs as string[]));
- return Response.json({ ok: true });
- }
- throw new Error(`unexpected origin call: ${url}`);
- };
-}
-
-function makeDO(origin: FakeOrigin, target = "4", lowWater = "1", sessions?: FakeSessions) {
- const state = new FakeState();
- const env = {
- SESSION_JWT_SECRET: "test-secret",
- POOL_STOCK_TARGET: target,
- POOL_STOCK_LOW_WATER: lowWater,
- MICROVM_SESSIONS: sessions,
- };
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const doInstance = new PoolStock(state as any, env as any);
- vi.stubGlobal("fetch", ((input: RequestInfo | URL, init?: RequestInit) =>
- origin.handler(String(input), init)) as typeof fetch);
- return { doInstance, state };
-}
-
-const post = (doInstance: PoolStock, path: string, body: unknown): Promise<Response> =>
- doInstance.fetch(new Request(`https://pool-stock${path}`, { method: "POST", body: JSON.stringify(body) }));
-
-interface ClaimedBox {
- id: string;
- workerID: string;
- region: string;
- sandboxDomain: string;
- token: string;
-}
-
-async function claimBatch(
- doInstance: PoolStock,
- state: FakeState,
- orgID: string,
- count: number,
-): Promise<{ boxes: ClaimedBox[]; stock: number }> {
- const r = await post(doInstance, "/claim-batch", { cell: CELL, orgID, count });
- const data = (await r.json()) as { boxes?: ClaimedBox[]; stock: number };
- await state.settle();
- return { boxes: data.boxes ?? [], stock: data.stock };
-}
-
-// ── tests ───────────────────────────────────────────────────────────────────
-describe("PoolStock", () => {
- let origin: FakeOrigin;
-
- beforeEach(() => {
- vi.useFakeTimers();
- vi.setSystemTime(new Date("2026-08-19T00:00:00Z"));
- origin = new FakeOrigin();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- vi.unstubAllGlobals();
- });
-
- it("keeps re-attaching sitting stock instead of warming it exactly once", async () => {
- // The regression this pins: with a single attach per box, the whole warm
- // path hung on that one call landing while the box happened to be ready.
- // For freshly-manufactured stock it usually is not, and the box then sits
- // cold for its entire life because nothing ever tries again. Measured on
- // prod: 76 of 78 execs served on a dead channel.
- const sessions = new FakeSessions();
- origin.supply = [
- { sandboxID: "sb-1", workerID: "w-1", endpoint: "e1", token: "t1", port: 8080 },
- { sandboxID: "sb-2", workerID: "w-2", endpoint: "e2", token: "t2", port: 8080 },
- ];
- const { doInstance, state } = makeDO(origin, "2", "1", sessions);
- await claimBatch(doInstance, state, ORG_A, 0); // prime the stock
-
- const afterRestock = sessions.attaches.length;
- expect(afterRestock).toBe(2); // one attach each at reserve
-
- // Ticks with the stock full and nothing claimed: restock has nothing to do,
- // so any further attach can only come from the rotating re-warm.
- for (let i = 0; i < 3; i++) {
- await doInstance.alarm();
- await state.settle();
- }
- expect(sessions.attaches.length).toBeGreaterThan(afterRestock);
- // And it must cover the whole shard, not just re-poke the first entry.
- expect(new Set(sessions.attaches.slice(afterRestock))).toEqual(new Set(["sb-1", "sb-2"]));
- });
-
- it("reports a pre-warm it cannot perform rather than skipping in silence", async () => {
- // A cell that supplies no reach-info means every exec pays a cold dial. That
- // is a config problem with a large latency cost and no other symptom, so it
- // has to appear in the log; silently returning here is what let it hide.
- const err = vi.spyOn(console, "error").mockImplementation(() => {});
- const sessions = new FakeSessions();
- origin.supply = [
- { sandboxID: "sb-1", workerID: "w-1" }, // no endpoint/token/port
- { sandboxID: "sb-2", workerID: "w-2" },
- ];
- const { doInstance, state } = makeDO(origin, "2", "1", sessions);
- await claimBatch(doInstance, state, ORG_A, 0);
-
- expect(sessions.attaches).toEqual([]);
- expect(err).toHaveBeenCalledWith(expect.stringContaining("agent pre-warm SKIPPED"));
- err.mockRestore();
- });
-
- it("keep-warm defers decommission without reserving a single box", async () => {
- // Two properties, and the second matters more than the first. A keep-warm
- // that created sandboxes to stay warm would leak one per tick forever —
- // worse than the idle decommission it fixes — so /touch must reserve
- // nothing. What it may do is move the idle clock, which is what stops the
- // shard dumping its stock 30 minutes into a quiet period.
- origin.supply = [
- { sandboxID: "sb-1", workerID: "w-1" },
- { sandboxID: "sb-2", workerID: "w-2" },
- ];
- const { doInstance, state } = makeDO(origin, "2", "1");
- await claimBatch(doInstance, state, ORG_A, 0); // prime
- const reserveCallsAfterPrime = origin.reserved.length;
-
- // Past the 30-minute idle window, but touched along the way.
- vi.setSystemTime(Date.now() + 25 * 60_000);
- await post(doInstance, "/touch", { cell: CELL });
- await state.settle();
- expect(origin.reserved.length).toBe(reserveCallsAfterPrime); // reserved NOTHING
-
- // Now run the alarm. The shard is 25 minutes past its last real claim, so
- // without the touch it would be in the decommission branch: release
- // everything and drop to the warm-only tick. With it, the ordinary path
- // runs and the shard tops itself back up.
- //
- // Asserting on "did it restock" rather than "did it release" on purpose:
- // entries also expire on ENTRY_TTL_MS (10 min), so a release here proves
- // nothing about which branch ran, while a restock only happens on the live
- // path. Conflating the two is what made the first version of this test fail.
- origin.supply = [
- { sandboxID: "sb-3", workerID: "w-3" },
- { sandboxID: "sb-4", workerID: "w-4" },
- ];
- await doInstance.alarm();
- await state.settle();
- expect(origin.reserved.length).toBeGreaterThan(reserveCallsAfterPrime);
- });
-
- it("hands a box out exactly once", async () => {
- origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
- const { doInstance, state } = makeDO(origin);
-
- await claimBatch(doInstance, state, ORG_A, 1); // primes the stock
- const first = await claimBatch(doInstance, state, ORG_A, 1);
- expect(first.boxes.map((b) => b.id)).toEqual(["sb-1"]);
-
- // A popped box is TOKENED. It must never reappear in stock — the header's
- // lifecycle invariant, and the reason the magazine's /return route is gone.
- const again = await claimBatch(doInstance, state, ORG_A, 1);
- expect(again.boxes).toEqual([]);
- });
-
- it("serves FIFO so the stock stays young", async () => {
- origin.supply = [
- { sandboxID: "sb-1", workerID: "w-1" },
- { sandboxID: "sb-2", workerID: "w-2" },
- ];
- const { doInstance, state } = makeDO(origin);
- await claimBatch(doInstance, state, ORG_A, 0); // prime
-
- // Oldest first: sb-1 was reserved before sb-2, so it is closer to the
- // cell's 15-min destroy backstop and has to go out first.
- expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-1"]);
- expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-2"]);
- });
-
- it("releases an unclaimed (never-tokened) box back to the pool", async () => {
- // Stock that expires without ever being popped was never tokened, so it is
- // cheap and safe to re-pool rather than leave to the cell's reaper.
- origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
- const { doInstance, state } = makeDO(origin);
- await claimBatch(doInstance, state, ORG_A, 0);
-
- vi.setSystemTime(Date.now() + 11 * 60_000);
- await doInstance.alarm();
- await state.settle();
-
- expect(origin.releasedIDs).toEqual(["sb-1"]);
- });
-
- it("drops stock minted by a control plane that has since restarted", async () => {
- // The MicroVM backend binds a sandbox id to a box IN MEMORY at reserve, so a
- // CP restart invalidates every id this DO is holding. Without the fence the
- // shard keeps serving them for the full ENTRY_TTL: each one 201s a create
- // for a box with no manager binding, and the customer's first exec 500s.
- origin.supply = [{ sandboxID: "sb-old", workerID: "w-1" }];
- const { doInstance, state } = makeDO(origin);
- await claimBatch(doInstance, state, ORG_A, 0); // stock sb-old under epoch-1
-
- origin.epoch = "epoch-2"; // control plane restarted
- origin.supply = [{ sandboxID: "sb-new", workerID: "w-2" }];
- await doInstance.alarm(); // proactive top-up notices the new epoch
- await state.settle();
-
- const served = await claimBatch(doInstance, state, ORG_A, 5);
- expect(served.boxes.map((b) => b.id)).toEqual(["sb-new"]);
- });
-
- it("keeps stock when the cell sends no epoch at all", async () => {
- // A Postgres-backed cell reserves by flipping a row, so its reservations
- // survive a restart and it sends no epoch. The fence must not fire there.
- origin.supply = [{ sandboxID: "sb-1", workerID: "w-1" }];
- const { doInstance, state } = makeDO(origin);
- origin.handler = async (url: string, init?: RequestInit): Promise<Response> => {
- const body = JSON.parse(String(init?.body ?? "{}"));
- if (url.includes("/internal/pool/edge-reserve")) {
- const give = origin.supply.splice(0, Number(body.count) || 0);
- return Response.json({ region: "westus2", sandboxDomain: "sb.example", boxes: give });
- }
- origin.releasedIDs.push(...(body.sandboxIDs as string[]));
- return Response.json({ ok: true });
- };
- await claimBatch(doInstance, state, ORG_A, 0);
- await doInstance.alarm();
- await state.settle();
-
- expect((await claimBatch(doInstance, state, ORG_A, 1)).boxes.map((b) => b.id)).toEqual(["sb-1"]);
- });
-
- it("exposes no route that can re-stock an already-tokened box", async () => {
- // Regression guard. /return existed to un-strand the isolate-local
- // magazine's surplus; with the magazine deleted there is no surplus, and a
- // route that puts a tokened box back in stock is a cross-tenant hazard with
- // no remaining caller. Deleting the magazine is what retires the hazard.
- const { doInstance, state } = makeDO(origin);
- await claimBatch(doInstance, state, ORG_A, 0);
-
- const r = await post(doInstance, "/return", {
- orgID: ORG_A,
- boxes: [{ id: "sb-1", workerID: "w-1", region: "westus2", sandboxDomain: "sb.example" }],
- });
- expect(r.status).not.toBe(200);
- });
-});
diff --git a/cloudflare-workers/api-edge/src/pool_stock.ts b/cloudflare-workers/api-edge/src/pool_stock.ts
index 58ef9492..cd505485 100644
--- a/cloudflare-workers/api-edge/src/pool_stock.ts
+++ b/cloudflare-workers/api-edge/src/pool_stock.ts
@@ -1,877 +1,21 @@
-// PoolStock — per-cell Durable Object holding pre-reserved hot pool boxes so
-// default-shape sandbox creates are answered entirely at the edge (pop + mint
-// token + 201) with zero origin round trips. The cell reserved these boxes for
-// us (status='edge_reserved' in cell PG — invisible to the CP's own pool-claim
-// path, so a box can never be handed to two customers).
+// PoolStock: empty stub kept only so the Durable Object class stays exported.
//
-// Lifecycle safety (see internal/api/edge_claim.go for the server half):
-// - Popped entries get a sandbox token minted by the edge → the box must
-// NEVER return to the pool (a live foreign token on a re-issued box would
-// be cross-tenant access). Popped boxes are finalized or marked failed.
-// - Entries the DO discards UNPOPPED (stale, overshoot) were never tokened →
-// released back to 'pooled' via /internal/pool/edge-release.
-// - If the DO dies without releasing, the cell's reaper destroys the
-// reservations after 15 min (destroy, not re-pool — it can't prove they
-// were never tokened).
+// The edge sandbox pool (pre-reserved hot boxes per cell) is gone with the rest
+// of api-edge's sandbox code (097 step 7.2). The class has to stay exported
+// because wrangler's migration v2 created it: removing the export without a
+// `deleted_classes` migration fails the deploy. We deliberately add no
+// migration here, so the class lives on as a no-op. Nothing binds it any more.
//
-// One instance per cell (idFromName(cellID)); the Worker picks the cell first
-// (home-cell pinning etc.) and asks that cell's stock. All restock/release
-// concurrency is contained here: the Worker only ever calls /claim.
-
-interface StockEntry {
- id: string;
- workerID: string;
- cellID: string;
- baseURL: string;
- region: string;
- sandboxDomain: string;
- atMs: number;
- // MicroVM reach-info, when the cell supplies it. Present means exec can go
- // straight from the edge to the box's agent; absent means this cell routes
- // through a worker and exec uses the control-plane path.
- endpoint?: string;
- token?: string;
- port?: number;
-}
-
-import { WARM_ORG_LIMIT, warmCreateContextColo } from "./create_context_cache";
-
-interface PoolStockEnv {
- SESSION_JWT_SECRET: string;
- // Per-shard stock sizing, overridable per environment (wrangler.toml [vars]).
- // Defaults below are the prod values; dev sets these DOWN because its cell
- // holds ~30 boxes total, an order of magnitude under the 8×38 fleet target —
- // see the sizing invariant in the block comment below.
- POOL_STOCK_TARGET?: string;
- POOL_STOCK_LOW_WATER?: string;
- // VmSession DOs are pre-woken here at stock-prep (see reserveOnce) instead of
- // on the create hot path — a burst-100 otherwise fires ~100 prewake
- // subrequests from the create isolate, saturating its subrequest budget.
- // Optional so the binding can be absent mid-cutover (prewake just skips).
- VM_SESSIONS?: DurableObjectNamespace;
- // MicroVM exec data plane. Warmed here at stock-prep for the same reason
- // VM_SESSIONS is: doing it on the create path would fan out a subrequest per
- // box from the create isolate, and — more importantly — would lose the race
- // against the customer's first exec.
- MICROVM_SESSIONS?: DurableObjectNamespace;
- // Read-only here, and only from the alarm: the shard refreshes the colo-cache
- // entries the create path reads (see warmCreateContextColo) so a cold burst
- // finds them already populated instead of 100 isolates all missing at once.
- // Optional so a binding-less deployment just skips the warm.
- OPENCOMPUTER_DB?: D1Database;
- // Org ids (comma-separated) whose create-context entries are kept warm
- // ALWAYS, not just while they are actively claiming.
- //
- // recentOrgs alone cannot cover the case this exists for. A benchmark org is
- // silent for an hour and then fires 100 concurrent creates — by then the
- // shard has idle-decommissioned and its alarm has lapsed, so nothing has
- // refreshed the colo entries and every one of those 100 isolates misses
- // together. Pinning the org keeps the ~1 D1 batch per shard per tick running
- // through the quiet period so the burst lands on a warm cache.
- WARM_ORG_IDS?: string;
-}
-
-// Stock tuning. TARGET_STOCK mirrors ~the whole per-cell hot pool so every
-// default-shape create is answered at the edge, not just a small reserved slice.
-// A self-scheduling alarm keeps the stock topped up to TARGET proactively (every
-// ALARM_INTERVAL) so a burst always arrives against a full stock instead of the
-// old lazy-on-claim path that left the stock empty between bursts. ENTRY_TTL
-// stays well under the cell's 15-min destroy backstop so an unclaimed box is
-// released back to the pool (cheap) long before the cell would destroy it.
-const ENTRY_TTL_MS = 10 * 60_000;
-// SHARDED: a Durable Object processes requests ~serially (~2ms/claim), so one
-// stock DO serializes a burst — measured claim;dur 12ms solo → 47ms at 50-way,
-// ~90ms projected at 100-way. The edge spreads claims across POOL_STOCK_SHARDS
-// (index.ts) DO instances; 8 shards cuts the 100-way queue tail to ~25ms, and
-// past ~8 the alarm/restock machinery and shard-empty retries outgrow the gain.
-// Sizing below is PER SHARD; fleet stock = SHARDS × TARGET_STOCK = 304 — deep
-// enough that a sustained ~300-create drain (sequential or 100-way burst) is
-// served entirely from seasoned stock, never from mid-drain refill manufacture
-// (freshly-restored boxes are the p99 tail).
-//
-// SIZING INVARIANT: SHARDS × TARGET_STOCK must be ≤ the cell's actual pool
-// (OPENSANDBOX_POOL_TARGET × workers). If it exceeds the pool, every shard
-// permanently believes it is below LOW_WATER, restocks on every claim, and the
-// shards compete for a supply that can never satisfy them — boxes concentrate
-// in whichever shards win, creates that hash to an empty shard fall through to
-// the ~10× slower CP path, and the measured burst latency becomes a function of
-// shard luck rather than of the system under test. Dev hit exactly this (30-box
-// cell against a 304 target), which is why these are env-overridable.
-const DEFAULT_LOW_WATER = 18;
-const DEFAULT_TARGET_STOCK = 38; // per-shard fill level (× 8 shards = 304 fleet)
-const ALARM_INTERVAL_MS = 10_000; // proactive top-up cadence
-const RESTOCK_MAX_CALLS = 2; // reserve calls per restock pass (batch × calls ≥ TARGET)
-// Self-decommission: a shard that hasn't served a claim in this long releases
-// its whole stock and stops its alarm (a later claim re-arms it). This is what
-// lets a retired shard GENERATION (index.ts POOL_STOCK_SHARD_GEN bump — e.g.
-// after a placement mistake) drain instead of hoarding reservations forever,
-// and returns idle cells' boxes to the pool for non-default-shape creates.
-const IDLE_DECOMMISSION_MS = 30 * 60_000;
-// Cadence for the warm-only tick once the stock has been decommissioned. Slower
-// than ALARM_INTERVAL_MS because nothing is being restocked, but still inside
-// the shortest window it refreshes (count/cells, 30s) so an entry never lapses.
-const IDLE_WARM_INTERVAL_MS = 20_000;
-// Stock entries re-attached per alarm tick by rewarmSlice. Deliberately a count,
-// not a fraction: it makes background load independent of TARGET_STOCK. At the
-// default 18 this cycles the whole shard about every 45s.
-const REWARM_PER_TICK = 4;
-// Hard stop for warm-only ticking. A shard idle this long is not between bursts,
-// it is out of service, and warming it is pure cost.
-const WARM_MAX_IDLE_MS = 6 * 3600_000;
-// Warmed before traffic teaches a shard who to warm. Overridden by WARM_ORG_IDS.
-const DEFAULT_WARM_ORG_IDS =
- "1f92e6ca-fe5d-4cf4-ab3e-00fa7bedef4f,b0e1d424-b592-44c5-b8a1-cd022e04f4a5";
-
-// Synthetic org that owns parked pool boxes (db.PoolOrgID). Used as the cap
-// token subject for reserve/release calls — those endpoints are org-agnostic,
-// but the middleware wants a parseable org UUID.
-const POOL_ORG_ID = "00000000-0000-4000-8000-000000000001";
-
-// Parse a positive integer from a wrangler [vars] string, falling back to the
-// prod default when unset/blank/garbage — a bad var must never zero the stock.
-function intFromEnv(raw: string | undefined, fallback: number): number {
- if (raw === undefined || raw === "") return fallback;
- const n = Number.parseInt(raw, 10);
- return Number.isFinite(n) && n > 0 ? n : fallback;
-}
-
-const b64url = (buf: ArrayBuffer | Uint8Array): string => {
- const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf);
- let s = "";
- for (const b of bytes) s += String.fromCharCode(b);
- return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
-};
-
-// Minimal cap-token mint for the DO's own cell calls (reserve/release).
-// Duplicates index.ts's mintCapToken rather than importing it — the DO must
-// not pull in the Worker's module graph (circular import, isolate bloat).
-// Cached HMAC key for sandbox-token minting (see mintSandboxTokenDO).
-let doSignKey: Promise<CryptoKey> | null = null;
-function doHmacKey(secret: string): Promise<CryptoKey> {
- if (!doSignKey) {
- doSignKey = crypto.subtle.importKey(
- "raw",
- new TextEncoder().encode(secret),
- { name: "HMAC", hash: "SHA-256" },
- false,
- ["sign"],
- );
- }
- return doSignKey;
-}
-
-// The JWT header is constant — encode it once per isolate instead of
-// JSON.stringify + base64 on every mint.
-const JWT_HEADER_B64 = b64url(new TextEncoder().encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
-
-// mintSandboxTokenDO mints the customer-facing sandbox token INSIDE this DO, so
-// a batch claim returns ready-to-serve tokens and the create isolate performs no
-// HMAC at all. Byte-identical to index.ts's mintSandboxToken (same secret, same
-// claims) — the create path just hands this through. Duplicated rather than
-// imported: the DO must not pull in the Worker's module graph.
-async function mintSandboxTokenDO(
- secret: string,
- orgID: string,
- sandboxID: string,
- workerID: string,
-): Promise<string> {
- const now = Math.floor(Date.now() / 1000);
- const enc = new TextEncoder();
- const payload = {
- sub: orgID,
- iat: now,
- exp: now + 24 * 3600,
- iss: "opensandbox",
- org_id: orgID,
- sandbox_id: sandboxID,
- worker_id: workerID,
- };
- const signingInput = JWT_HEADER_B64 + "." + b64url(enc.encode(JSON.stringify(payload)));
- const sig = await crypto.subtle.sign("HMAC", await doHmacKey(secret), enc.encode(signingInput));
- return signingInput + "." + b64url(sig);
-}
-
-// Exported so the voucher path (voucher_book.ts, via index.ts) can authenticate
-// its off-hot-path refill with the same synthetic pool identity PoolStock uses.
-// The refill hits /internal/pool/vouchers on the same cell and the CP applies
-// the same internal check, so a second token shape would be a second thing to
-// keep correct for no gain.
-export async function mintPoolCapToken(secret: string, cellID: string): Promise<string> {
- const now = Math.floor(Date.now() / 1000);
- const enc = new TextEncoder();
- const header = { alg: "HS256", typ: "JWT" };
- const payload = {
- sub: POOL_ORG_ID,
- iss: "opensandbox-edge",
- iat: now,
- exp: now + 120,
- org_id: POOL_ORG_ID,
- cell_id: cellID,
- plan: "free",
- };
- const signingInput =
- b64url(enc.encode(JSON.stringify(header))) + "." + b64url(enc.encode(JSON.stringify(payload)));
- const key = await crypto.subtle.importKey("raw", enc.encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
- const sig = await crypto.subtle.sign("HMAC", key, enc.encode(signingInput));
- return signingInput + "." + b64url(sig);
-}
+// Existing instances may still hold an alarm from the old restock loop. When it
+// fires, alarm() below does nothing and schedules nothing, so the loop stops.
+// Boxes such an instance had reserved are destroyed by the cell's reaper.
export class PoolStock {
- private stock: StockEntry[] = [];
- private restockInFlight = false;
- private lastClaimMs = 0;
- // Rotating position for rewarmSlice. In-memory only: a shard that is evicted
- // and reloaded simply restarts the rotation, which costs nothing.
- private rewarmCursor = 0;
- // Pre-warm health. Counted and reported rather than swallowed — see
- // warmMicrovmBox for why a silent skip here is the expensive kind of quiet.
- private warmSkips = 0;
- private warmFails = 0;
- private warmSkipLoggedAt = 0;
- private warmFailLoggedAt = 0;
- // One-shot colo self-identification (diagnostics): placement is sticky at
- // first-touch; a stock DO cross-colo from the claiming edge adds per-claim RTT.
- private coloLogged = false;
- // Resolved once per isolate alongside coloLogged; reported on every claim so
- // the create path can see whether its stock DO is even in the same colo.
- private colo = "?";
- // Blocking form, for the /colo probe only — never on a claim, which must not
- // wait on a diagnostic round trip.
- private async coloNow(): Promise<string> {
- if (this.colo !== "?") return this.colo;
- this.coloLogged = true;
- try {
- const t = await fetch("https://www.cloudflare.com/cdn-cgi/trace").then((r) => r.text());
- this.colo = (t.match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
- } catch {
- /* leave "?" — the probe reports unknown rather than failing */
- }
- return this.colo;
- }
- // Last cell seen on a /claim, persisted so the proactive alarm can restock
- // without waiting for the next claim (a fresh DO after eviction still knows
- // which cell to reserve from).
- private cell: { cellID: string; baseURL: string } | null = null;
- // Orgs that have recently claimed through this shard, most-recent first.
- // The alarm refreshes their create-context colo entries; whoever is actually
- // bursting through this shard is exactly who benefits from a warm cache, and
- // the list is capped so this can't grow into a scan of every org that ever
- // touched it. Persisted so a shard re-created after eviction warms the right
- // orgs on its FIRST alarm rather than after the next claim.
- private recentOrgs: string[] = [];
- // The control-plane process that issued the stock we are holding, when that
- // cell's reservations are process-local (see edge_claim.go processEpoch).
- // Persisted alongside the stock because it is only meaningful paired with it.
- private epoch: string | null = null;
- // Resolved once per isolate from env (see the sizing invariant above).
- private readonly targetStock: number;
- private readonly lowWater: number;
- private readonly restockBatch: number;
+ constructor(_state: DurableObjectState, _env: unknown) {}
- constructor(
- private state: DurableObjectState,
- private env: PoolStockEnv,
- ) {
- this.targetStock = intFromEnv(env.POOL_STOCK_TARGET, DEFAULT_TARGET_STOCK);
- // Low-water must stay under target or a restock is triggered on every claim.
- this.lowWater = Math.min(
- this.targetStock - 1,
- intFromEnv(env.POOL_STOCK_LOW_WATER, DEFAULT_LOW_WATER),
- );
- // One reserve call per restock pass was sized to cover the whole target
- // (batch × RESTOCK_MAX_CALLS ≥ target); keep that relationship as target moves.
- this.restockBatch = this.targetStock;
- this.state.blockConcurrencyWhile(async () => {
- this.stock = (await this.state.storage.get<StockEntry[]>("stock")) ?? [];
- this.cell = (await this.state.storage.get<{ cellID: string; baseURL: string }>("cell")) ?? null;
- this.epoch = (await this.state.storage.get<string>("epoch")) ?? null;
- this.recentOrgs = (await this.state.storage.get<string[]>("recentOrgs")) ?? [];
- });
+ async fetch(_req: Request): Promise<Response> {
+ return new Response("PoolStock is retired", { status: 410 });
}
- async fetch(req: Request): Promise<Response> {
- const url = new URL(req.url);
- if (req.method === "POST" && url.pathname === "/claim") {
- return this.claim(req);
- }
- if (req.method === "POST" && url.pathname === "/claim-batch") {
- return this.claimBatch(req);
- }
- if (req.method === "GET" && url.pathname === "/status") {
- return Response.json({ stock: this.stock.length, restocking: this.restockInFlight });
- }
- // Keep-warm touch: refresh the idle clock and make sure the alarm is armed,
- // WITHOUT handing out a box.
- //
- // A shard decommissions its whole stock after IDLE_DECOMMISSION_MS and stops
- // ticking entirely after WARM_MAX_IDLE_MS, which is correct for a shard
- // nobody is using but wrong for the traffic pattern this pool actually
- // serves. The benchmark that grades us runs WEEKLY; a CI tenant runs nightly
- // and a cron tenant hourly. All of them arrive after the shard has gone
- // fully cold, and all of them arrive as a BURST — so the first hundred
- // creates race one empty shard set, miss all eight, and fall through to
- // control-plane cold launches paced by the RunMicrovm quota. The pool exists
- // precisely to make that not happen, and idle decommission was handing back
- // the stock that would have prevented it.
- //
- // Touching from the cron keeps lastClaim inside the idle window, so stock
- // stays at target between visits. It reserves nothing on its own — the
- // alarm's normal restock does that — so a shard that has genuinely gone
- // unused costs one DO wake per cron tick and nothing else.
- if (req.method === "POST" && url.pathname === "/touch") {
- const body = (await req.json().catch(() => ({}))) as { cell?: { cellID: string; baseURL: string } };
- if (body.cell?.cellID) this.cell = body.cell;
- this.lastClaimMs = Date.now();
- await this.state.storage.put("lastClaim", this.lastClaimMs);
- await this.ensureAlarm();
- return Response.json({ stock: this.stock.length, target: this.targetStock, cell: this.cell?.cellID ?? null });
- }
- // Placement probe. A DO pins to a colo at first touch, permanently, and
- // locationHint only picks a REGION — four generations of shards were armed
- // from an in-metro client and still scattered across five colos inside
- // enam. So placement is not something to aim; it is something to measure
- // and then select on. /colo reports where this object actually landed.
- //
- // ?child=<name> additionally asks a MicrovmSession this shard parents where
- // IT landed. That is the load-bearing question for stock-prep warming: if a
- // child inherits its parent's colo, pinning the shards pins every session
- // DO with them; if it does not, session placement needs its own lever.
- //
- // ANSWERED, on prod 2026-08-21 over 64 parent/child pairs: it does not.
- // A child matches its parent's colo 34/64 of the time, and parent-IAD
- // yields child-IAD only 12/27 (44%) against a 30% background rate. So
- // parentage biases placement without deciding it. Pinning the shards is
- // still worth doing — deterministic for the claim hop, and it lifts the
- // session DOs from 21% IAD to ~44% for free — but the other half of them
- // need a lever this has now ruled out.
- if (req.method === "GET" && url.pathname === "/colo") {
- const self = await this.coloNow();
- const child = url.searchParams.get("child");
- const ns = this.env.MICROVM_SESSIONS;
- let childColo: string | null = null;
- if (child && ns) {
- childColo = await ns
- .get(ns.idFromName(child), { locationHint: "enam" })
- .fetch("https://do/colo")
- .then((r) => r.json() as Promise<{ colo: string }>)
- .then((j) => j.colo)
- .catch(() => "err");
- }
- return Response.json({ colo: self, stock: this.stock.length, child: childColo });
- }
- return new Response("not found", { status: 404 });
- }
-
- private async claim(req: Request): Promise<Response> {
- if (!this.coloLogged) {
- this.coloLogged = true;
- void fetch("https://www.cloudflare.com/cdn-cgi/trace")
- .then(async (r) => {
- const colo = ((await r.text()).match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
- console.log(`pool-stock colo=${colo}`);
- })
- .catch(() => {});
- }
- let cell: { cellID: string; baseURL: string } | null = null;
- try {
- const body = (await req.json()) as { cell?: { cellID: string; baseURL: string } };
- cell = body.cell ?? null;
- } catch {
- /* no cell hint — claim still works, restock doesn't */
- }
- if (cell) this.rememberCell(cell);
-
- // Expire stale entries (never handed out → safe to release back to the
- // pool). Done inline, synchronously over the in-memory array, so a
- // concurrent claim can't double-pop across an await.
- const now = Date.now();
- const fresh: StockEntry[] = [];
- const stale: StockEntry[] = [];
- for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);
- this.stock = fresh;
- if (stale.length > 0) {
- this.state.waitUntil(this.release(stale));
- }
-
- // FIFO — oldest first keeps the stock young.
- const entry = this.stock.shift();
- this.lastClaimMs = Date.now();
- void this.state.storage.put("lastClaim", this.lastClaimMs, { allowUnconfirmed: true });
- this.persist();
-
- // Ensure the proactive top-up loop is running, and kick an immediate restock
- // if this claim dropped us below the low-water mark (don't wait for the tick).
- this.state.waitUntil(this.ensureAlarm());
- if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {
- this.state.waitUntil(this.restockToTarget(cell));
- }
-
- if (!entry) {
- return new Response(JSON.stringify({ error: "stock empty" }), { status: 404 });
- }
- // `stock` = entries left in this shard after the pop (telemetry #7): lets the
- // create path surface shard depletion via Server-Timing.
- return Response.json({ ...entry, stock: this.stock.length });
- }
-
- // claimBatch pops up to `count` entries in ONE call and returns them with
- // their sandbox tokens already minted. This is the magazine refill (see
- // index.ts): instead of a burst doing one DO subrequest + one HMAC per create
- // on the saturated create isolate, one call serves ~N creates from isolate
- // memory with zero further subrequests and zero edge crypto. Popped entries
- // are TOKENED, so — exactly like /claim — they must never return to the pool;
- // an isolate that dies holding them leaves them to the cell's reaper.
- private async claimBatch(req: Request): Promise<Response> {
- // Split the create path's `claim;dur` into DO work vs the network to get
- // here. Both halves have completely different fixes — token minting and
- // stock bookkeeping are ours to cut, cross-colo RTT is a placement problem —
- // and from the edge they are indistinguishable.
- const tDo = Date.now();
- if (!this.coloLogged) {
- this.coloLogged = true;
- void fetch("https://www.cloudflare.com/cdn-cgi/trace")
- .then(async (r) => {
- this.colo = ((await r.text()).match(/^colo=(\w+)/m) ?? [])[1] ?? "?";
- console.log(`pool-stock colo=${this.colo}`);
- })
- .catch(() => {});
- }
- let cell: { cellID: string; baseURL: string } | null = null;
- let orgID = "";
- let count = 1;
- try {
- const body = (await req.json()) as {
- cell?: { cellID: string; baseURL: string };
- orgID?: string;
- count?: number;
- };
- cell = body.cell ?? null;
- orgID = typeof body.orgID === "string" ? body.orgID : "";
- count = Math.max(1, Math.min(Number(body.count) || 1, this.targetStock));
- } catch {
- /* fall through with defaults */
- }
- if (!orgID) return new Response(JSON.stringify({ error: "orgID required" }), { status: 400 });
- if (cell) this.rememberCell(cell);
- this.rememberOrg(orgID);
-
- // Same inline stale-expiry as claim(), synchronous over the in-memory array
- // so a concurrent claim can't double-pop across an await.
- const now = Date.now();
- const fresh: StockEntry[] = [];
- const stale: StockEntry[] = [];
- for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);
- this.stock = fresh;
- if (stale.length > 0) this.state.waitUntil(this.release(stale));
-
- // FIFO — oldest first keeps the stock young.
- const entries = this.stock.splice(0, count);
- this.lastClaimMs = Date.now();
- void this.state.storage.put("lastClaim", this.lastClaimMs, { allowUnconfirmed: true });
- this.persist();
-
- this.state.waitUntil(this.ensureAlarm());
- if (cell && !this.restockInFlight && this.stock.length < this.lowWater) {
- this.state.waitUntil(this.restockToTarget(cell));
- }
-
- // Mint every token here (one isolate, N signs) rather than N times on the
- // create isolate. Parallel — crypto.subtle.sign is async.
- const boxes = await Promise.all(
- entries.map(async (e) => ({
- id: e.id,
- workerID: e.workerID,
- region: e.region,
- sandboxDomain: e.sandboxDomain,
- token: await mintSandboxTokenDO(this.env.SESSION_JWT_SECRET, orgID, e.id, e.workerID),
- // How to reach the box's agent directly. Named apart from `token` above,
- // which is the CUSTOMER's sandbox token — these are the AWS proxy's
- // port-scoped credential and are never handed to a customer.
- //
- // Carried out with the box so the create isolate can cache them
- // colo-locally: that is what lets a later exec dial the agent itself
- // instead of asking the control plane in westus2 for reach-info it has
- // already been told once. Absent for backends with no in-memory stock.
- agentEndpoint: e.endpoint,
- agentToken: e.token,
- agentPort: e.port,
- })),
- );
- return Response.json({ boxes, stock: this.stock.length, t: Date.now() - tDo, colo: this.colo });
- }
-
- // rememberCell persists the cell coordinates so the alarm can restock even on
- // a fresh (post-eviction) DO instance that has never served a claim yet.
- private rememberCell(cell: { cellID: string; baseURL: string }): void {
- if (this.cell && this.cell.cellID === cell.cellID && this.cell.baseURL === cell.baseURL) return;
- this.cell = cell;
- void this.state.storage.put("cell", cell);
- }
-
- // rememberOrg moves an org to the front of the warm list. Only persists when
- // the ORDER actually changed — a burst is thousands of claims from the same
- // org, and writing storage on each one would add a disk write to the hottest
- // path this DO has for information that did not change.
- private rememberOrg(orgID: string): void {
- if (this.recentOrgs[0] === orgID) return;
- this.recentOrgs = [orgID, ...this.recentOrgs.filter((o) => o !== orgID)].slice(0, WARM_ORG_LIMIT);
- void this.state.storage.put("recentOrgs", this.recentOrgs, { allowUnconfirmed: true });
- }
-
- // warmOrgs is who this shard refreshes: configured pins first, then the orgs
- // that have actually claimed here. Pins exist so a shard that has never served
- // a claim — a fresh deploy, a re-placed shard — still warms something useful;
- // in steady state recentOrgs is what carries this.
- private warmOrgs(): string[] {
- const pinned = (this.env.WARM_ORG_IDS ?? DEFAULT_WARM_ORG_IDS)
- .split(",")
- .map((s) => s.trim())
- .filter(Boolean);
- const seen = new Set<string>();
- const out: string[] = [];
- for (const id of [...pinned, ...this.recentOrgs]) {
- if (seen.has(id)) continue;
- seen.add(id);
- out.push(id);
- }
- return out.slice(0, WARM_ORG_LIMIT);
- }
-
- private async warmColo(): Promise<void> {
- const db = this.env.OPENCOMPUTER_DB;
- if (!db) return;
- const orgs = this.warmOrgs();
- if (orgs.length === 0) return;
- await warmCreateContextColo(db, orgs);
- }
-
- private async ensureAlarm(): Promise<void> {
- if ((await this.state.storage.getAlarm()) === null) {
- await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
- }
- }
-
- // alarm — the proactive top-up. Fires on ALARM_INTERVAL_MS: refreshes stale
- // reservations and refills the stock to TARGET_STOCK so a create burst always
- // hits a full stock. Reschedules itself as long as we know which cell to
- // reserve from, so the stock stays warm without depending on claim traffic.
- async alarm(): Promise<void> {
- const cell = this.cell;
- if (!cell) return; // no cell known yet → nothing to reserve; a claim will arm it
- // Idle self-decommission (see IDLE_DECOMMISSION_MS): release the stock, but
- // keep the cheap half of the tick running.
- //
- // Stock and cache warmth decommission on different schedules because they
- // cost different things. Held boxes are real capacity another shard could
- // use, so they go back immediately. The create-context colo entries cost one
- // D1 batch per tick and holding them is what makes a bursty-after-idle
- // tenant — CI, crons, agent workloads, a weekly benchmark — land on a warm
- // cache instead of having ~100 isolates all miss at once. Dropping both
- // together is what made the first create after a quiet period the most
- // expensive one a customer ever sees.
- const lastClaim = this.lastClaimMs || ((await this.state.storage.get<number>("lastClaim")) ?? 0);
- const idleMs = Date.now() - lastClaim;
- if (idleMs > IDLE_DECOMMISSION_MS) {
- if (this.stock.length > 0) {
- const all = this.stock.splice(0);
- await this.release(all);
- this.persist();
- }
- // Past WARM_MAX_IDLE_MS nobody is coming back and this stops entirely —
- // otherwise a shard that served one create last month would warm forever.
- if (idleMs > WARM_MAX_IDLE_MS || this.warmOrgs().length === 0) return;
- await this.warmColo();
- await this.state.storage.setAlarm(Date.now() + IDLE_WARM_INTERVAL_MS);
- return;
- }
- // Expire+release anything past TTL before topping up, so held boxes go back
- // to the pool well before the cell's 15-min destroy backstop.
- const now = Date.now();
- const fresh: StockEntry[] = [];
- const stale: StockEntry[] = [];
- for (const e of this.stock) (now - e.atMs < ENTRY_TTL_MS ? fresh : stale).push(e);
- this.stock = fresh;
- if (stale.length > 0) await this.release(stale);
- // Surplus trim: release anything above the per-shard target back to the
- // pool. This is how the pre-sharding legacy DO (which becomes shard 0 and
- // held the whole fleet's stock) sheds down to TARGET_STOCK so the other
- // shards can reserve those boxes; it also self-heals any future oversizing.
- if (this.stock.length > this.targetStock) {
- const surplus = this.stock.splice(this.targetStock);
- await this.release(surplus);
- }
- if (this.stock.length < this.targetStock) await this.restockToTarget(cell);
- this.persist();
- // Keep the create path's colo entries warm. Ordered AFTER the top-up on
- // purpose: stock is what a create cannot proceed without, and this is a
- // latency optimization — it must never delay or fail the restock. The 10s
- // cadence sits inside every window it refreshes (cells 30s, count 30s, org
- // 60s), so an entry written here is always current when the next burst
- // lands, and the shard is placed in-metro with the traffic it serves, so
- // the colo it warms is the colo that will read it.
- await this.warmColo();
- this.rewarmSlice();
- await this.state.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS);
- }
-
- // rewarmSlice re-attaches a bounded, rotating slice of the sitting stock.
- //
- // This used to be nothing at all, and the comment where it used to be argued
- // that warming every entry on every tick was too expensive — 8 shards ×
- // TARGET_STOCK DO pokes per ALARM_INTERVAL of sustained load on the vm-do
- // worker, competing with this object's own claim serving. That argument is
- // still right, and this does not do that.
- //
- // What it replaces is the part that was wrong: with no re-warm at all, the
- // single attach in reserveOnce was the ONLY one a box ever got. Its whole
- // warm life then hung on one call landing at one moment — and for a freshly
- // manufactured box that moment is the worst possible one, because the agent
- // may not be answering yet. The MicrovmSession keepalive would fail its five
- // pings, drop to its slow cadence (before that fix: stop forever), and nothing
- // would ever re-attach. Measured on prod against a just-manufactured pool: 76
- // of 78 execs served on a dead channel, each paying the full re-dial, versus
- // 100 of 100 live on a pool old enough to have been attached while healthy.
- //
- // A rotating cursor makes the cost independent of stock depth: REWARM_PER_TICK
- // pokes per shard per tick regardless of TARGET_STOCK, so at the default 18
- // every box is re-attached about every 45s for roughly a fifth of the load the
- // rejected every-entry version would have cost. Re-attach is idempotent — an
- // already-live channel just refreshes warmUntil.
- private rewarmSlice(): void {
- if (this.stock.length === 0) return;
- const n = Math.min(REWARM_PER_TICK, this.stock.length);
- for (let i = 0; i < n; i++) {
- const e = this.stock[this.rewarmCursor % this.stock.length];
- this.rewarmCursor++;
- if (!e.endpoint) continue; // cell routes through a worker; nothing to attach
- this.warmMicrovmBox({ sandboxID: e.id, endpoint: e.endpoint, token: e.token, port: e.port });
- }
- // Keep the cursor from growing without bound over a long-lived shard.
- if (this.rewarmCursor > 1e9) this.rewarmCursor = 0;
- }
-
- // prewakeBox wakes one box's VmSession DO isolate (best-effort, off any hot
- // path). Called from reserveOnce when a box enters the stock.
- private prewakeBox(sandboxID: string): void {
- const vs = this.env.VM_SESSIONS;
- if (!vs) return;
- this.state.waitUntil(
- vs.get(vs.idFromName(sandboxID)).fetch("https://do/status").then(() => {}).catch(() => {}),
- );
- }
-
- // warmMicrovmBox hands a box's reach-info to its MicrovmSession DO and has it
- // open the agent tunnel, best-effort and off every hot path.
- //
- // Doing this at stock-prep rather than at create is the whole point. The
- // WebSocket 101 comes from the AWS proxy, which only connects to the guest
- // port when payload first arrives — so the ~1.1s cost of actually reaching the
- // agent lands on whoever sends first. Warming at create loses that race (the
- // customer's exec arrives one RTT after the 201), and warming lazily on first
- // exec IS the race. Here there is no race: the box sits in stock for minutes.
- private warmMicrovmBox(b: { sandboxID: string; endpoint?: string; token?: string; port?: number }): void {
- const ns = this.env.MICROVM_SESSIONS;
- // A silent skip here is indistinguishable from a warm that worked, and this
- // is the single most load-bearing call on the fast path: without it every
- // exec in the next burst pays a full re-dial. Every reason it can be skipped
- // is a misconfiguration or a cell that changed shape, so say so — rate
- // limited to one line per minute per shard, because under a restock storm
- // this would otherwise be the noisiest line in the log.
- if (!ns || !b.endpoint || !b.token || !b.port) {
- this.warmSkips++;
- const now = Date.now();
- if (now - this.warmSkipLoggedAt > 60_000) {
- this.warmSkipLoggedAt = now;
- const missing = !ns
- ? "MICROVM_SESSIONS binding"
- : [!b.endpoint && "endpoint", !b.token && "token", !b.port && "port"].filter(Boolean).join("+");
- console.error(
- `pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm SKIPPED (${this.warmSkips} total) — missing ${missing}. ` +
- `Every exec on these boxes will pay a cold dial.`,
- );
- }
- return;
- }
- this.state.waitUntil(
- ns
- .get(ns.idFromName(b.sandboxID), { locationHint: "enam" })
- .fetch("https://do/attach", {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ endpoint: b.endpoint, token: b.token, port: b.port, dial: true }),
- })
- .then(async (r) => {
- if (r.ok) return;
- this.warmFails++;
- const now = Date.now();
- if (now - this.warmFailLoggedAt > 60_000) {
- this.warmFailLoggedAt = now;
- console.error(
- `pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm attach failed ${r.status} (${this.warmFails} total)`,
- );
- }
- })
- .catch((e) => {
- this.warmFails++;
- const now = Date.now();
- if (now - this.warmFailLoggedAt > 60_000) {
- this.warmFailLoggedAt = now;
- console.error(`pool-stock ${this.cell?.cellID ?? "?"}: agent pre-warm attach error (${this.warmFails} total): ${e}`);
- }
- }),
- );
- }
-
- // coolMicrovmBox drops a DO's channel when its box leaves this stock without
- // ever reaching a customer.
- //
- // Not just tidiness: the box goes back to anonymous pool stock and will be
- // reissued under a DIFFERENT sandbox id, so a DO still holding a live tunnel
- // under the OLD id is a channel into a box that now belongs to someone else.
- // The id stops resolving in D1, which is the real guard, but leaving an armed
- // channel behind it is not a thing to rely on.
- private coolMicrovmBox(sandboxID: string): void {
- const ns = this.env.MICROVM_SESSIONS;
- if (!ns) return;
- this.state.waitUntil(
- ns
- .get(ns.idFromName(sandboxID), { locationHint: "enam" })
- .fetch("https://do/detach", { method: "POST" })
- .then(() => {})
- .catch(() => {}),
- );
- }
-
- private persist(): void {
- // allowUnconfirmed skips the output gate: the claim response leaves ~10ms
- // sooner instead of waiting for the write to be durable. Failure window
- // (DO crash after responding, before the write lands) resurrects a popped
- // entry → a later claim double-pops it → the second claim-finalize loses
- // the `edge_reserved` CAS and fails cleanly. Rare + already-handled, and
- // the claim hop is the entire cost of an edge create, so the ~10ms wins.
- void this.state.storage.put("stock", this.stock, { allowUnconfirmed: true });
- void this.state.storage.put("epoch", this.epoch, { allowUnconfirmed: true });
- }
-
- // restockToTarget fills the stock up to TARGET_STOCK by issuing up to
- // RESTOCK_MAX_CALLS edge-reserve calls (each up to RESTOCK_BATCH boxes). It
- // stops early when the stock is full or the cell pool is drained (a reserve
- // returns fewer boxes than asked) so we don't hammer an empty pool.
- private async restockToTarget(cell: { cellID: string; baseURL: string }): Promise<void> {
- if (this.restockInFlight) return;
- this.restockInFlight = true;
- try {
- for (let call = 0; call < RESTOCK_MAX_CALLS; call++) {
- const want = Math.min(this.restockBatch, this.targetStock - this.stock.length);
- if (want <= 0) return;
- const got = await this.reserveOnce(cell, want);
- if (got < want) return; // pool drained (or error) — don't spin
- }
- } finally {
- this.restockInFlight = false;
- }
- }
-
- // reserveOnce reserves up to `want` boxes from the cell pool and appends them
- // to the stock. Returns how many were actually added.
- private async reserveOnce(cell: { cellID: string; baseURL: string }, want: number): Promise<number> {
- try {
- const token = await mintPoolCapToken(this.env.SESSION_JWT_SECRET, cell.cellID);
- const r = await fetch(cell.baseURL.replace(/\/$/, "") + "/internal/pool/edge-reserve", {
- method: "POST",
- headers: { authorization: "Bearer " + token, "content-type": "application/json" },
- body: JSON.stringify({ count: want }),
- });
- if (!r.ok) {
- console.error(`pool-stock ${cell.cellID}: reserve failed ${r.status} ${await r.text()}`);
- return 0;
- }
- const data = (await r.json()) as {
- region: string;
- sandboxDomain: string;
- epoch?: string;
- // endpoint/token/port are present only for cells whose backend can be
- // reached directly (MicroVM); worker-backed cells omit them.
- boxes: Array<{ sandboxID: string; workerID: string; endpoint?: string; token?: string; port?: number }>;
- };
- // Epoch fence. A cell that stamps an epoch is telling us its edge
- // reservations live in that process's memory, not in Postgres — so when
- // the value changes, every id we are holding was minted by a control
- // plane that no longer exists. Those boxes have no manager binding: a
- // create served from them 201s and the customer's first exec 500s,
- // because routing goes through a sandbox→box map that died with the
- // process. Drop the lot rather than serve one.
- //
- // Not released back to the pool — the new process has no record of these
- // ids, so an edge-release would be a no-op round trip. The cell's own
- // reaper owns the boxes now.
- //
- // Absent epoch = a Postgres-backed cell, whose reservations are rows and
- // survive a restart. No fence, and no behaviour change for those cells.
- if (data.epoch && this.epoch && data.epoch !== this.epoch && this.stock.length > 0) {
- console.log(
- `pool-stock ${cell.cellID}: control-plane epoch changed (${this.epoch} → ${data.epoch}) — dropping ${this.stock.length} stale entr(ies)`,
- );
- this.stock = [];
- }
- if (data.epoch) this.epoch = data.epoch;
- const now = Date.now();
- const have = new Set(this.stock.map((e) => e.id));
- let added = 0;
- for (const b of data.boxes) {
- if (have.has(b.sandboxID)) continue;
- this.stock.push({
- id: b.sandboxID,
- workerID: b.workerID,
- cellID: cell.cellID,
- baseURL: cell.baseURL,
- region: data.region,
- sandboxDomain: data.sandboxDomain,
- atMs: now,
- endpoint: b.endpoint,
- token: b.token,
- port: b.port,
- });
- added++;
- // Open and guest-attach this box's agent tunnel NOW, while it is still
- // stock and nobody is waiting on it.
- this.warmMicrovmBox(b);
- // Pre-wake the box's VmSession DO now (stock-prep), off any hot path, so
- // the create burst doesn't fan out ~100 prewake subrequests from the
- // create isolate. The alarm (prewakeStock) keeps it warm while it sits.
- this.prewakeBox(b.sandboxID);
- }
- this.persist();
- return added;
- } catch (e) {
- console.error(`pool-stock ${cell.cellID}: restock error:`, e);
- return 0;
- }
- }
-
- private async release(entries: StockEntry[]): Promise<void> {
- // Tear down any agent tunnel first — this box is about to be reissued under
- // a different sandbox id. See coolMicrovmBox.
- for (const e of entries) if (e.endpoint) this.coolMicrovmBox(e.id);
- // Group by cell (entries could straddle a base_url change).
- const byCell = new Map<string, { cellID: string; ids: string[] }>();
- for (const e of entries) {
- const g = byCell.get(e.baseURL) ?? { cellID: e.cellID, ids: [] };
- g.ids.push(e.id);
- byCell.set(e.baseURL, g);
- }
- for (const [baseURL, g] of byCell) {
- try {
- const token = await mintPoolCapToken(this.env.SESSION_JWT_SECRET, g.cellID);
- await fetch(baseURL.replace(/\/$/, "") + "/internal/pool/edge-release", {
- method: "POST",
- headers: { authorization: "Bearer " + token, "content-type": "application/json" },
- body: JSON.stringify({ sandboxIDs: g.ids }),
- });
- } catch (e) {
- // Best-effort — the cell's stale-reservation reaper is the backstop.
- console.error(`pool-stock: release to ${baseURL} failed:`, e);
- }
- }
- }
+ async alarm(): Promise<void> {}
}
diff --git a/cloudflare-workers/api-edge/src/runtime_gate.test.ts b/cloudflare-workers/api-edge/src/runtime_gate.test.ts
deleted file mode 100644
index e8212824..00000000
--- a/cloudflare-workers/api-edge/src/runtime_gate.test.ts
+++ /dev/null
@@ -1,99 +0,0 @@
-import { describe, it, expect } from "vitest";
-import {
- RUNTIME_MICROVM,
- RUNTIME_QEMU,
- effectiveRuntime,
- isMicrovmWorkerID,
- sdkMajor,
-} from "./runtime_gate";
-
-const on = {}; // gate enabled, default threshold
-const off = { SDK_RUNTIME_GATE: "0" };
-
-// The cutoff is the package's first stable major, not the "v2" the docs use for
-// the platform generation. Every version ever published is 0.x.
-const NEW = "1.0.0";
-const OLD = "0.15.7";
-
-describe("sdkMajor", () => {
- it("reads the major", () => {
- expect(sdkMajor("2.0.0")).toBe(2);
- expect(sdkMajor("10.4.1")).toBe(10);
- expect(sdkMajor(" 2.1.0 ")).toBe(2);
- });
-
- // Everything unrecognisable is an SDK that does not announce itself, and that
- // population must land on QEMU. A parse that fell through to "new runtime"
- // would migrate every curl user and every old SDK at once.
- it("is 0 for anything it cannot read", () => {
- for (const bad of [null, undefined, "", " ", "v2", "abc", "-3", "0.1.0"]) {
- expect(sdkMajor(bad)).toBe(0);
- }
- });
-});
-
-describe("effectiveRuntime", () => {
- it("routes an unpinned org by the calling SDK — this is the migration", () => {
- expect(effectiveRuntime(on, null, NEW)).toBe(RUNTIME_MICROVM);
- expect(effectiveRuntime(on, "", NEW)).toBe(RUNTIME_MICROVM);
- expect(effectiveRuntime(on, null, OLD)).toBe("");
- expect(effectiveRuntime(on, null, null)).toBe("");
- });
-
- // Every 0.x release in npm's history has to land on QEMU. Getting this wrong
- // migrates the entire existing customer base on the next deploy.
- it("holds the whole published 0.x line on the fleet", () => {
- for (const v of ["0.15.7", "0.15.0", "0.14.0", "0.13.1", "0.9.9", "0.0.1"]) {
- expect(effectiveRuntime(on, null, v), v).toBe("");
- }
- });
-
- // A migrated org must not be dragged back by one stale service still on an
- // old SDK — its templates and checkpoints only exist on the runtime it moved
- // to.
- it("keeps a microvm-pinned org on microvm for old SDKs", () => {
- expect(effectiveRuntime(on, RUNTIME_MICROVM, OLD)).toBe(RUNTIME_MICROVM);
- expect(effectiveRuntime(on, RUNTIME_MICROVM, null)).toBe(RUNTIME_MICROVM);
- });
-
- // ...and the opt-out has to survive an upgrade, or an org that needs
- // checkpoints loses them by bumping a dependency.
- it("keeps a qemu-pinned org on qemu for new SDKs", () => {
- expect(effectiveRuntime(on, RUNTIME_QEMU, NEW)).toBe(RUNTIME_QEMU);
- });
-
- // The token carries this value. Synthesising "qemu" for an org that never set
- // it would have the token assert a decision nobody made.
- it("never invents an explicit qemu for an unset org", () => {
- expect(effectiveRuntime(on, null, OLD)).toBe("");
- expect(effectiveRuntime(off, null, NEW)).toBe("");
- });
-
- it("SDK_RUNTIME_GATE=0 turns the whole thing off without touching pins", () => {
- expect(effectiveRuntime(off, null, NEW)).toBe("");
- expect(effectiveRuntime(off, RUNTIME_MICROVM, OLD)).toBe(RUNTIME_MICROVM);
- });
-
- it("honours a configured threshold", () => {
- const env = { SDK_RUNTIME_MIN_MAJOR: "3" };
- expect(effectiveRuntime(env, null, "2.9.0")).toBe("");
- expect(effectiveRuntime(env, null, "3.0.0")).toBe(RUNTIME_MICROVM);
- // Garbage falls back to the default rather than to 0, which would route
- // EVERY versioned SDK to microvm.
- expect(effectiveRuntime({ SDK_RUNTIME_MIN_MAJOR: "junk" }, null, OLD)).toBe("");
- expect(effectiveRuntime({ SDK_RUNTIME_MIN_MAJOR: "junk" }, null, NEW)).toBe(RUNTIME_MICROVM);
- });
-});
-
-describe("isMicrovmWorkerID", () => {
- it("recognises both prefixes internal/api/microvm_common.go writes", () => {
- expect(isMicrovmWorkerID("vmhost:microvm-abc123")).toBe(true);
- expect(isMicrovmWorkerID("microvm:abc123")).toBe(true);
- });
-
- it("does not claim a QEMU worker or an unknown row", () => {
- for (const other of ["worker-eastus2-3", "oc-worker-01", "", null, undefined]) {
- expect(isMicrovmWorkerID(other)).toBe(false);
- }
- });
-});
diff --git a/cloudflare-workers/api-edge/src/runtime_gate.ts b/cloudflare-workers/api-edge/src/runtime_gate.ts
deleted file mode 100644
index 6a87e305..00000000
--- a/cloudflare-workers/api-edge/src/runtime_gate.ts
+++ /dev/null
@@ -1,178 +0,0 @@
-// Which runtime serves a create, and how a customer moves between them.
-//
-// Before this, the answer was one D1 column: orgs.runtime, set by us, one org
-// at a time. That works for a handful of design partners and does not work for
-// a migration — every customer who wants to move has to ask, and every customer
-// we move has to be moved back by hand if it goes badly.
-//
-// So the column now expresses a PIN, and the calling SDK's major version
-// decides for everyone who is not pinned:
-//
-// orgs.runtime = 'microvm' -> MicroVM, whatever SDK is calling
-// orgs.runtime = 'qemu' -> QEMU, whatever SDK is calling
-// orgs.runtime NULL or '' -> the SDK decides: 1.x+ MicroVM, 0.x QEMU
-//
-// The unpinned case is the new one and it is the whole point: `npm i
-// @opencomputer/sdk@1` is the migration, and pinning the previous major is the
-// rollback. Neither needs us.
-//
-// The pins are not vestigial. 'microvm' is how an org that has FINISHED
-// migrating stays migrated even when one script in their fleet is still on an
-// old version — without it, a single stale dependency would quietly start
-// creating sandboxes on the other runtime, against templates that do not exist
-// there. 'qemu' is the opt-out for an org that needs something MicroVM does not
-// have yet (checkpoints, fork) and should not be moved by upgrading a package.
-
-/**
- * Header the SDK sends its own version in (sdks/typescript/src/version.ts).
- * Duplicated rather than imported: the Worker does not depend on the SDK
- * package, and runtime_gate.test.ts pins the string on this side.
- */
-export const SDK_VERSION_HEADER = "x-oc-sdk-version";
-
-/** orgs.runtime value routing to the AWS MicroVM backend. */
-export const RUNTIME_MICROVM = "microvm";
-
-/** orgs.runtime value pinning an org to the QEMU worker fleet. */
-export const RUNTIME_QEMU = "qemu";
-
-/**
- * Default major at which an SDK routes to MicroVM.
- *
- * 1, because every version @opencomputer/sdk has ever published is 0.x — so the
- * first stable release is also, for free, an exact split between "everything
- * that exists today" and "the new one". The docs call this platform generation
- * v2; the package major is 1. They are not the same number and nothing here
- * should assume they are.
- *
- * Overridable (SDK_RUNTIME_MIN_MAJOR) because the version this ships under is a
- * release decision that can change after this code is written, and getting it
- * wrong should cost an env var rather than a re-release of the SDK.
- */
-export const DEFAULT_MIN_SDK_MAJOR = 1;
-
-/**
- * Major version from the SDK's x-oc-sdk-version header, or 0.
- *
- * 0 for absent, malformed, or non-numeric — every one of which means "an SDK
- * that does not announce itself", which is exactly the population that must
- * keep landing on QEMU. Unparseable input therefore has to fail toward the old
- * runtime, never toward the new one.
- */
-export function sdkMajor(header: string | null | undefined): number {
- if (!header) return 0;
- const major = Number.parseInt(header.trim().split(".")[0] ?? "", 10);
- // A 0.x SDK reports 0, which is also what an unreadable header reports. That
- // is deliberate and not a collision worth removing: both mean "not a caller we
- // route to MicroVM", and the threshold is >= 1.
- return Number.isFinite(major) && major > 0 ? major : 0;
-}
-
-export interface RuntimeGateEnv {
- /** "0" disables SDK-version routing; every unpinned org stays on QEMU. */
- SDK_RUNTIME_GATE?: string;
- /** Major at and above which an SDK routes to MicroVM. Default 2. */
- SDK_RUNTIME_MIN_MAJOR?: string;
-}
-
-function minMajor(env: RuntimeGateEnv): number {
- const configured = Number.parseInt(env.SDK_RUNTIME_MIN_MAJOR ?? "", 10);
- return Number.isFinite(configured) && configured > 0 ? configured : DEFAULT_MIN_SDK_MAJOR;
-}
-
-/**
- * The runtime this create belongs on: "microvm", "qemu", or "" (the QEMU
- * fleet, unstated — what the cap token has always carried for an unset org).
- *
- * "" and "qemu" are both the fleet and are deliberately NOT collapsed: the
- * value is echoed into the capability token, and rewriting an org's unset
- * runtime to an explicit "qemu" would make the token claim a decision nobody
- * made. Only the MicroVM answer is ever synthesised here.
- */
-export function effectiveRuntime(
- env: RuntimeGateEnv,
- orgRuntime: string | null | undefined,
- sdkVersionHeader: string | null | undefined,
-): string {
- const pinned = (orgRuntime ?? "").trim();
- if (pinned) return pinned; // pin wins, in both directions
- if (env.SDK_RUNTIME_GATE === "0") return "";
- return sdkMajor(sdkVersionHeader) >= minMajor(env) ? RUNTIME_MICROVM : "";
-}
-
-// ── which runtime an EXISTING sandbox is on ──────────────────────────────────
-
-// Prefixes internal/api/microvm_common.go writes into sandboxes_index.worker_id
-// (microvmWorkerPrefix and legacyWorkerPrefix). A sandbox's worker_id names the
-// box that holds it, so it is the only per-sandbox record of which runtime that
-// sandbox actually landed on — D1 has no runtime column on the sandbox row.
-const MICROVM_WORKER_PREFIXES = ["vmhost:", "microvm:"];
-
-/**
- * Whether an existing sandbox is MicroVM-backed, from its worker_id.
- *
- * Routing a request for a LIVE sandbox by its org's runtime was correct only
- * while an org was entirely on one runtime. Under SDK-version routing a mixed
- * org is the steady state, not a migration window — the same org creates
- * MicroVM sandboxes from a v2 service and QEMU sandboxes from a v1 one, for as
- * long as the migration takes. Asking the sandbox rather than the org is what
- * keeps both working: a QEMU box never gets dialled as if it had a MicroVM
- * proxy, and a MicroVM box never pays the VmSession DO's 400ms entry grace
- * waiting for a channel that cannot exist.
- *
- * `undefined` (worker_id not yet known — an in-flight create, or a route cached
- * before this field was recorded) returns false, which routes through the
- * generic path. That path works for both runtimes; it is merely slower.
- */
-export function isMicrovmWorkerID(workerID: string | null | undefined): boolean {
- if (!workerID) return false;
- return MICROVM_WORKER_PREFIXES.some((p) => workerID.startsWith(p));
-}
-
-// ── v1 retirement ────────────────────────────────────────────────────────────
-
-/**
- * The v1 fleet is gone.
- *
- * `effectiveRuntime` still answers "" for a caller that routes to QEMU, because
- * that answer is what the capability token has always carried and the cell
- * still reads. What changed is that there is no longer anything on the other
- * end: the Azure workers that served it have been shut down. So the decision is
- * unchanged and the *outcome* is refusal — a request that would have gone to
- * QEMU is answered here rather than forwarded to a fleet that cannot serve it.
- *
- * Kept beside the routing it mirrors so the two cannot drift: if the threshold
- * moves, the population that gets this message moves with it.
- */
-export function isRetiredRuntime(runtime: string): boolean {
- return runtime !== RUNTIME_MICROVM;
-}
-
-/** Where a caller is sent to fix it. One string, used by every refusal. */
-export const V1_MIGRATION_GUIDE_URL =
- "https://docs.opencomputer.dev/migrating-from-v1";
-
-/**
- * What a retired-runtime caller is told.
- *
- * Names the cause, the fix, and where the fix is written down. `code` is there
- * so a caller can branch on this without matching prose, and the SDK can turn
- * it into a typed error later without another API change.
- */
-export function v1RetiredError(): {
- error: string;
- code: string;
- migration_guide: string;
-} {
- return {
- error:
- "OpenComputer v1 sandboxes have been retired. Upgrade to the v2 SDK — " +
- "`npm install @opencomputer/sdk@^1` (or `pip install -U opencomputer`) — " +
- `and see ${V1_MIGRATION_GUIDE_URL}. Existing v1 sandboxes are no longer reachable.`,
- code: "v1_retired",
- migration_guide: V1_MIGRATION_GUIDE_URL,
- };
-}
-
-/** The status a retired-runtime request is refused with: the fleet is Gone. */
-export const V1_RETIRED_STATUS = 410;
diff --git a/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts b/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts
deleted file mode 100644
index e004f69f..00000000
--- a/cloudflare-workers/api-edge/src/runtime_gate_wiring.test.ts
+++ /dev/null
@@ -1,280 +0,0 @@
-import { afterEach, describe, expect, it, vi } from "vitest";
-import worker, { type Env } from "./index";
-import { SDK_VERSION_HEADER } from "./runtime_gate";
-
-// runtime_gate.test.ts covers the decision. This covers the WIRING, which is
-// where the equivalent work has failed before: a rule that is correct in
-// isolation and simply never consulted on the path that matters. The assertion
-// is deliberately made on the capability token the cell actually reads its
-// backend off, not on any intermediate value.
-
-// A fresh org per case. loadCreateContext memoises the org row in a
-// module-level isolate cache that outlives a single test, so reusing one id
-// would have the second case read the first case's runtime.
-let seq = 0;
-let orgID = "org-0";
-let apiKey = "osb_test_0";
-function freshOrg(runtime: string | null): void {
- seq += 1;
- orgID = `org-${seq}`;
- apiKey = `osb_test_${seq}`;
- orgRuntime = runtime;
-}
-
-const cellID = "azure-us-east-2-a";
-const cellURL = "https://cp-us-east-2.opencomputer.dev";
-
-let orgRuntime: string | null = null;
-
-class FakeStatement {
- constructor(private sql: string) {}
- bind(..._args: unknown[]) {
- return this;
- }
- async first<T>(): Promise<T | null> {
- if (this.sql.includes("FROM api_keys")) {
- return { org_id: orgID, created_by: "user-1", expires_at: null } as T;
- }
- if (this.sql.includes("FROM cells WHERE cell_id")) return cellRow<T>();
- if (this.sql.includes("SELECT home_cell, plan, runtime FROM orgs")) {
- return { home_cell: cellID, plan: "pro", runtime: orgRuntime } as T;
- }
- if (this.sql.includes("SELECT home_cell, plan, is_halted")) {
- return {
- home_cell: cellID,
- plan: "pro",
- is_halted: 0,
- max_concurrent_sandboxes: 10,
- max_disk_mb: 262144,
- runtime: orgRuntime,
- } as T;
- }
- if (this.sql.includes("COUNT(*) AS n FROM sandboxes_index")) return { n: 0 } as T;
- return null;
- }
- async all<T>() {
- if (this.sql.includes("FROM cells WHERE status = 'active'")) {
- return { results: [await cellRow<T>()] } as { results: T[] };
- }
- return { results: [] as T[] };
- }
- async run() {
- return {};
- }
- async batchResult<T>(): Promise<{ results: T[] }> {
- if (this.sql.includes("WHERE status = 'active'")) return (await this.all<T>()) as { results: T[] };
- const row = await this.first<T>();
- return { results: row ? [row] : [] };
- }
-}
-
-function cellRow<T>(): T {
- return {
- cell_id: cellID,
- cloud: "azure",
- region: "us-east-2",
- base_url: cellURL,
- status: "active",
- available_workers: 1,
- capacity_updated_at: Math.floor(Date.now() / 1000),
- } as T;
-}
-
-function makeEnv(extra: Partial<Env> = {}): Env {
- return {
- OPENCOMPUTER_DB: {
- prepare: (sql: string) => new FakeStatement(sql),
- batch: async (stmts: FakeStatement[]) => Promise.all(stmts.map((s) => s.batchResult())),
- },
- SESSION_JWT_SECRET: "test-secret",
- WORKER_ENV: "test",
- // No POOL_STOCK binding: edge-claim is structurally unavailable, so the
- // create takes the CP-fallback path and mints the cap token we assert on.
- ...extra,
- } as unknown as Env;
-}
-
-const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() } as unknown as ExecutionContext;
-
-/** Decoded claims from the Bearer token the edge sent the cell. */
-function claims(headers: HeadersInit | undefined): { runtime?: string; rt?: string } {
- const auth = new Headers(headers).get("authorization") ?? "";
- const payload = auth.replace(/^Bearer /, "").split(".")[1];
- if (!payload) throw new Error(`no JWT in authorization header: ${auth}`);
- return JSON.parse(atob(payload.replace(/-/g, "+").replace(/_/g, "/")));
-}
-
-/** The runtime this create was ROUTED to — `rt`, falling back to the pin. */
-function runtimeClaim(headers: HeadersInit | undefined): string {
- const c = claims(headers);
- return c.rt ?? c.runtime ?? "";
-}
-
-/** The org's PIN — the only value the cell is allowed to persist. */
-function pinClaim(headers: HeadersInit | undefined): string {
- return claims(headers).runtime ?? "";
-}
-
-let lastHeaders: HeadersInit | undefined;
-
-async function createRaw(
- sdkVersion: string | null,
- opts: { runtime?: string | null; env?: Env } = {},
-): Promise<{ resp: Response; fetchSpy: ReturnType<typeof vi.fn> }> {
- freshOrg(opts.runtime ?? null);
- const env = opts.env ?? makeEnv();
- const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) =>
- new Response(JSON.stringify({ sandboxID: "sb-1" }), { status: 201 }),
- );
- vi.stubGlobal("fetch", fetchSpy);
- const headers: Record<string, string> = { "X-API-Key": apiKey, "content-type": "application/json" };
- if (sdkVersion) headers[SDK_VERSION_HEADER] = sdkVersion;
- const resp = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/sandboxes", { method: "POST", headers, body: "{}" }),
- env,
- ctx,
- );
- return { resp, fetchSpy };
-}
-
-async function createWith(
- sdkVersion: string | null,
- opts: { runtime?: string | null; env?: Env } = {},
-): Promise<string> {
- const { resp, fetchSpy } = await createRaw(sdkVersion, opts);
- expect(resp.status, `create failed: ${await resp.clone().text()}`).toBe(201);
- expect(fetchSpy).toHaveBeenCalled();
- lastHeaders = fetchSpy.mock.calls[0][1]?.headers;
- return runtimeClaim(lastHeaders);
-}
-
-describe("create routes by SDK version", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- orgRuntime = null;
- });
-
- it("sends an unpinned org's v2 create to microvm", async () => {
- expect(await createWith("1.0.0")).toBe("microvm");
- });
-
- // A microvm pin still wins over an old SDK: that is how an org that has
- // finished migrating stays migrated when one stale script is left behind.
- it("honours a microvm pin over an old calling SDK", async () => {
- expect(await createWith("0.15.7", { runtime: "microvm" })).toBe("microvm");
- });
-
- // The kill switch used to hold every unpinned create on the fleet. The fleet
- // is gone, so what it now does is refuse them — worth pinning, because an env
- // var left set to 0 would take every create down rather than roll anything
- // back.
- it("SDK_RUNTIME_GATE=0 now refuses instead of rolling back", async () => {
- const { resp } = await createRaw("1.0.0", {
- env: makeEnv({ SDK_RUNTIME_GATE: "0" } as Partial<Env>),
- });
- expect(resp.status).toBe(410);
- });
-});
-
-// A template is built differently per runtime, so the snapshot path has to make
-// the same decision the create path does. It did not: it minted a blank runtime
-// unconditionally, which would have let a customer migrate their sandboxes and
-// then build every template as a checkpoint the new runtime cannot restore.
-describe("snapshot builds route by SDK version", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- orgRuntime = null;
- });
-
- async function snapshotRaw(
- sdkVersion: string | null,
- runtime: string | null = null,
- ): Promise<{ resp: Response; fetchSpy: ReturnType<typeof vi.fn> }> {
- freshOrg(runtime);
- const fetchSpy = vi.fn(async (_url: string, _init?: RequestInit) => new Response("{}", { status: 200 }));
- vi.stubGlobal("fetch", fetchSpy);
- const headers: Record<string, string> = { "X-API-Key": apiKey, "content-type": "application/json" };
- if (sdkVersion) headers[SDK_VERSION_HEADER] = sdkVersion;
- const resp = await worker.fetch(
- new Request("https://app.opencomputer.dev/api/snapshots", {
- method: "POST",
- headers,
- body: JSON.stringify({ name: "tools", image: {} }),
- }),
- makeEnv(),
- ctx,
- );
- return { resp, fetchSpy };
- }
-
- async function snapshotWith(sdkVersion: string | null, runtime: string | null = null): Promise<string> {
- const { resp, fetchSpy } = await snapshotRaw(sdkVersion, runtime);
- expect(resp.status, `snapshot create failed: ${await resp.clone().text()}`).toBe(200);
- return runtimeClaim(fetchSpy.mock.calls[0][1]?.headers);
- }
-
- it("builds a v2 caller's template on microvm", async () => {
- expect(await snapshotWith("1.0.0")).toBe("microvm");
- });
-
- // A v1 template is a whole-disk checkpoint and nothing left can restore one,
- // so the build is refused with the same message as a create rather than
- // producing an artifact that cannot be used.
- it("refuses an older caller's template build", async () => {
- const { resp } = await snapshotRaw("0.15.7");
- expect(resp.status).toBe(410);
- expect(((await resp.json()) as Record<string, string>).code).toBe("v1_retired");
- });
-
- it("refuses a template build for an org still pinned to qemu", async () => {
- const { resp } = await snapshotRaw("1.0.0", "qemu");
- expect(resp.status).toBe(410);
- });
-});
-
-// The bug a dev run found, and the reason `rt` exists as a separate claim.
-//
-// The cell PERSISTS the token's `runtime` into its own orgs table
-// (UpsertOrgFromCapToken). When that field carried the SDK-derived answer, an
-// unpinned org's very first create from a new SDK wrote itself in as a pin —
-// and from then on the org resolved to MicroVM even for a call deliberately
-// made from an older SDK. Measured: two dev orgs pinned themselves this way,
-// and the rollback path stopped working. Routing must be reversible.
-describe("SDK routing does not pin the org", () => {
- afterEach(() => {
- vi.unstubAllGlobals();
- orgRuntime = null;
- });
-
- it("sends an empty pin for an unpinned org routed to microvm by its SDK", async () => {
- expect(await createWith("1.0.0")).toBe("microvm");
- expect(pinClaim(lastHeaders), "the cell would persist this as the org's runtime").toBe("");
- });
-
- it("still sends a real pin when the org actually has one", async () => {
- expect(await createWith("0.15.7", { runtime: "microvm" })).toBe("microvm");
- expect(pinClaim(lastHeaders)).toBe("microvm");
- });
-
- // The v1 fleet is gone, so the population that used to route to it is now
- // refused here rather than forwarded to a cell that cannot serve it.
- it("refuses an old SDK with the migration guide, and forwards nothing", async () => {
- const { resp, fetchSpy } = await createRaw("0.15.7");
- expect(resp.status).toBe(410);
- const body = (await resp.json()) as Record<string, string>;
- expect(body.code).toBe("v1_retired");
- expect(body.migration_guide).toBe("https://docs.opencomputer.dev/migrating-from-v1");
- expect(body.error).toContain("@opencomputer/sdk@^1");
- expect(fetchSpy, "a retired create must never reach a cell").not.toHaveBeenCalled();
- });
-
- it("refuses a client that does not announce a version at all", async () => {
- const { resp } = await createRaw(null);
- expect(resp.status).toBe(410);
- });
-
- it("refuses an org still pinned to qemu, pin or no pin", async () => {
- const { resp } = await createRaw("1.2.3", { runtime: "qemu" });
- expect(resp.status).toBe(410);
- });
-});
diff --git a/cloudflare-workers/api-edge/src/secret_stores.ts b/cloudflare-workers/api-edge/src/secret_stores.ts
index 93d378d7..dd55eb12 100644
--- a/cloudflare-workers/api-edge/src/secret_stores.ts
+++ b/cloudflare-workers/api-edge/src/secret_stores.ts
@@ -1,9 +1,8 @@
// Edge-side secret stores — replaces the legacy per-cell PG-backed
// /api/secret-stores routes. Stores live in D1; entries are envelope-
-// encrypted at the edge with SECRET_ENCRYPTION_KEY (Infisical /shared/,
-// also distributed to every CP). The CP fetches encrypted blobs from the
-// /internal/secret-stores/:id HMAC endpoint at sandbox-create time and
-// decrypts inside the cell using internal/crypto.
+// encrypted at the edge with SECRET_ENCRYPTION_KEY. The cell-facing side
+// (the /internal/secret-stores HMAC endpoints and the refresh fan-out) was
+// removed with the sandbox code in 097 step 7.2; only the D1 CRUD remains.
//
// JSON shapes mirror internal/api/projects.go (camelCase) so the existing
// CLI/SDK and dashboard talk to the edge unchanged.
@@ -13,7 +12,6 @@ import { encryptSecret } from "./crypto";
export interface SecretStoresEnv {
OPENCOMPUTER_DB: D1Database;
SECRET_ENCRYPTION_KEY: string;
- EVENT_SECRET: string;
}
interface Caller {
@@ -204,100 +202,10 @@ export async function setEntry(
.bind(id, storeID, name, encrypted, JSON.stringify(hosts), now)
.run();
- // Fan the new value out to running sandboxes via /internal/secret-refresh
- // on every active cell. Each CP checks its local sandbox_sessions for the
- // store-binding column and pushes the new value to the right workers over
- // gRPC, so live sandboxes don't need a restart to pick up the change.
- // Wire format: encrypted blob over HMAC; CP decrypts with its copy of the
- // shared SECRET_ENCRYPTION_KEY so plaintext never crosses the cell boundary.
- const fanout = await fanoutSecretRefresh(env, storeID, name, encrypted);
- return json({ name, status: "set", refreshed: fanout.refreshed, cellsContacted: fanout.cells, failures: fanout.failures });
-}
-
-// fanoutSecretRefresh queries D1 for active cells, signs an HMAC POST per
-// cell with the encrypted blob, and aggregates the per-cell refresh counts.
-// Total time-bounded: a slow cell can't stall the user's PUT past ~12s.
-async function fanoutSecretRefresh(
- env: SecretStoresEnv,
- storeID: string,
- name: string,
- encryptedValue: Uint8Array,
-): Promise<{ refreshed: number; cells: number; failures: string[] }> {
- const { results: cells } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT cell_id, base_url FROM cells WHERE status = 'active'`,
- ).all<{ cell_id: string; base_url: string }>();
- const active = cells ?? [];
- if (active.length === 0) return { refreshed: 0, cells: 0, failures: [] };
-
- const encryptedB64 = btoa(String.fromCharCode(...encryptedValue));
- const body = JSON.stringify({ storeId: storeID, name, encryptedValueB64: encryptedB64 });
- const ts = Math.floor(Date.now() / 1000).toString();
-
- // Sign once — every cell shares EVENT_SECRET so the same signature works
- // across the fan-out. Body is part of the signed payload to prevent body
- // swap, matching the AdminAuth scheme on the CP side ("{ts}.{body}").
- const sig = await hmacBody(env.EVENT_SECRET, ts, body);
-
- // Per-cell timeout — bounded so one slow cell doesn't block the others.
- // The CP-side fanoutSecretRefresh already has its own 15s ceiling against
- // worker gRPC calls; this is the outer bound the user's PUT waits on.
- const perCellTimeoutMs = 12_000;
-
- const settled = await Promise.allSettled(
- active.map(async (c) => {
- const ctrl = new AbortController();
- const t = setTimeout(() => ctrl.abort(), perCellTimeoutMs);
- try {
- const resp = await fetch(c.base_url.replace(/\/$/, "") + "/internal/secret-refresh", {
- method: "POST",
- headers: {
- "content-type": "application/json",
- "X-Timestamp": ts,
- "X-Signature": sig,
- },
- body,
- signal: ctrl.signal,
- });
- const text = await resp.text();
- if (resp.status !== 200) {
- return { cell: c.cell_id, refreshed: 0, error: `status ${resp.status}: ${text.slice(0, 200)}` };
- }
- const parsed = JSON.parse(text) as { refreshed?: number; failures?: string[] };
- return { cell: c.cell_id, refreshed: parsed.refreshed ?? 0, error: null as string | null };
- } catch (e) {
- return { cell: c.cell_id, refreshed: 0, error: (e as Error).message };
- } finally {
- clearTimeout(t);
- }
- }),
- );
-
- let totalRefreshed = 0;
- const failures: string[] = [];
- for (const s of settled) {
- if (s.status === "fulfilled") {
- totalRefreshed += s.value.refreshed;
- if (s.value.error) failures.push(`${s.value.cell}: ${s.value.error}`);
- } else {
- failures.push(`unknown cell: ${s.reason}`);
- }
- }
- return { refreshed: totalRefreshed, cells: active.length, failures };
-}
-
-// hmacBody returns hex(HMAC-SHA256(secret, ts + "." + body)) — matches the
-// CP-side controlplane.AdminAuth verifier so /internal/secret-refresh
-// accepts our signature.
-async function hmacBody(secret: string, ts: string, body: string): Promise<string> {
- const key = await crypto.subtle.importKey(
- "raw",
- new TextEncoder().encode(secret),
- { name: "HMAC", hash: "SHA-256" },
- false,
- ["sign"],
- );
- const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(`${ts}.${body}`));
- return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
+ // This used to fan the new value out to running sandboxes on every active
+ // cell. The cells are retired (097 step 7.2), so nothing is refreshed; the
+ // response keeps its shape for the CLI.
+ return json({ name, status: "set", refreshed: 0, cellsContacted: 0, failures: [] });
}
export async function deleteEntry(
@@ -335,102 +243,3 @@ export async function listEntries(
// Never return plaintext or ciphertext on the user-facing route — names only.
return json((results ?? []).map((r) => entryToJSON(r, false)));
}
-
-// ── /internal/secret-stores/:id (HMAC, called by CP at sandbox-create) ──
-
-// HMAC scheme matches /internal/halt-list: "{X-Timestamp}.{path-with-query}"
-// signed with EVENT_SECRET (shared between edge + every CP), SHA-256 hex.
-async function hmacHex(secret: string, data: string): Promise<string> {
- const key = await crypto.subtle.importKey(
- "raw",
- new TextEncoder().encode(secret),
- { name: "HMAC", hash: "SHA-256" },
- false,
- ["sign"],
- );
- const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));
- return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
-}
-
-function constantTimeEqual(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- let diff = 0;
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
- return diff === 0;
-}
-
-async function verifyHMAC(req: Request, env: SecretStoresEnv): Promise<boolean> {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- if (!ts || !sig) return false;
- const tsNum = Number.parseInt(ts, 10);
- if (!Number.isFinite(tsNum)) return false;
- if (Math.abs(Math.floor(Date.now() / 1000) - tsNum) > 5 * 60) return false;
- const url = new URL(req.url);
- const expected = await hmacHex(env.EVENT_SECRET, `${ts}.${url.pathname}${url.search}`);
- return constantTimeEqual(expected, sig);
-}
-
-async function bundleStore(env: SecretStoresEnv, store: StoreRow): Promise<Response> {
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, store_id, name, encrypted_value, allowed_hosts, created_at, updated_at
- FROM secret_store_entries WHERE store_id = ?1`,
- )
- .bind(store.id)
- .all<EntryRow>();
- return json({
- store: storeToJSON(store),
- entries: (results ?? []).map((r) => entryToJSON(r, true)),
- });
-}
-
-export async function internalGetStore(req: Request, env: SecretStoresEnv, storeID: string): Promise<Response> {
- if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);
- // No org scoping — CP already validated the cap-token whose claims pinned org_id.
- const store = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, org_id, name, egress_allowlist, created_at, updated_at FROM secret_stores WHERE id = ?1`,
- )
- .bind(storeID)
- .first<StoreRow>();
- if (!store) return json({ error: "secret store not found" }, 404);
- return bundleStore(env, store);
-}
-
-export async function internalDeleteStore(req: Request, env: SecretStoresEnv, storeID: string): Promise<Response> {
- if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);
- const url = new URL(req.url);
- const orgID = url.searchParams.get("org_id") ?? "";
- if (!orgID) return json({ error: "org_id is required" }, 400);
-
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id FROM secret_stores WHERE id = ?1 AND org_id = ?2`,
- )
- .bind(storeID, orgID)
- .first<{ id: string }>();
- if (!row) return json({ error: "secret store not found" }, 404);
-
- await env.OPENCOMPUTER_DB.batch([
- env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_store_entries WHERE store_id = ?1`).bind(storeID),
- env.OPENCOMPUTER_DB.prepare(`DELETE FROM secret_stores WHERE id = ?1 AND org_id = ?2`).bind(storeID, orgID),
- ]);
- return new Response(null, { status: 204 });
-}
-
-// Lookup by (org_id, name) — what CP's resolveSecretStoreInto calls with
-// the user-supplied cfg.SecretStore string at sandbox-create time. Same
-// HMAC scheme as internalGetStore. Returns 404 if no store matches.
-export async function internalGetStoreByName(req: Request, env: SecretStoresEnv): Promise<Response> {
- if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);
- const url = new URL(req.url);
- const orgID = url.searchParams.get("org_id") ?? "";
- const name = url.searchParams.get("name") ?? "";
- if (!orgID || !name) return json({ error: "org_id and name are required" }, 400);
- const store = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, org_id, name, egress_allowlist, created_at, updated_at
- FROM secret_stores WHERE org_id = ?1 AND name = ?2`,
- )
- .bind(orgID, name)
- .first<StoreRow>();
- if (!store) return json({ error: "secret store not found" }, 404);
- return bundleStore(env, store);
-}
diff --git a/cloudflare-workers/api-edge/src/snapshots.ts b/cloudflare-workers/api-edge/src/snapshots.ts
deleted file mode 100644
index 11a0ce75..00000000
--- a/cloudflare-workers/api-edge/src/snapshots.ts
+++ /dev/null
@@ -1,97 +0,0 @@
-// Edge-native snapshot + image reads. Snapshots and images are both backed by
-// the cell's image_cache table, mirrored into D1's images_index by the
-// events-ingest worker (image_cache_ready / image_cache_deleted events).
-// A "snapshot" is just a *named* image. Because D1 is the global source of
-// truth, the edge serves list/get directly — no cell round-trip, works across
-// any number of cells, and survives an owning-cell outage.
-//
-// Create + delete are cell-work (build bytes / delete bytes) and route to a
-// cell via proxyToCellAuthed in index.ts.
-
-export interface SnapshotsEnv {
- OPENCOMPUTER_DB: D1Database;
-}
-
-interface Caller {
- orgID: string;
- userID: string | null;
-}
-
-interface ImageRow {
- id: string;
- org_id: string;
- owner_cell_id: string;
- content_hash: string;
- checkpoint_id: string | null;
- name: string | null;
- manifest: string | null;
- status: string;
- created_at: number;
- last_used_at: number;
-}
-
-function json(body: unknown, status = 200): Response {
- return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
-}
-
-// rowToJSON maps an images_index row to the shape the TS/Python SDKs unmarshal
-// (SnapshotInfo / ImageCacheItem) — camelCase, ISO timestamps, parsed manifest.
-function rowToJSON(r: ImageRow): Record<string, unknown> {
- let manifest: unknown = {};
- if (r.manifest) {
- try { manifest = JSON.parse(r.manifest); } catch { /* leave {} */ }
- }
- return {
- id: r.id,
- orgId: r.org_id,
- cellId: r.owner_cell_id,
- contentHash: r.content_hash,
- checkpointId: r.checkpoint_id ?? undefined,
- name: r.name ?? undefined,
- manifest,
- status: r.status,
- createdAt: new Date(r.created_at * 1000).toISOString(),
- lastUsedAt: new Date(r.last_used_at * 1000).toISOString(),
- };
-}
-
-const SELECT_COLS =
- "id, org_id, owner_cell_id, content_hash, checkpoint_id, name, manifest, status, created_at, last_used_at";
-
-// GET /api/snapshots — named images only (a snapshot is a named image).
-export async function listSnapshots(env: SnapshotsEnv, caller: Caller): Promise<Response> {
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT ${SELECT_COLS} FROM images_index
- WHERE org_id = ?1 AND name IS NOT NULL AND name <> ''
- ORDER BY created_at DESC LIMIT 200`,
- ).bind(caller.orgID).all<ImageRow>();
- return json((results ?? []).map(rowToJSON));
-}
-
-// GET /api/snapshots/:name
-export async function getSnapshot(env: SnapshotsEnv, caller: Caller, name: string): Promise<Response> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT ${SELECT_COLS} FROM images_index WHERE org_id = ?1 AND name = ?2 LIMIT 1`,
- ).bind(caller.orgID, name).first<ImageRow>();
- if (!row) return json({ error: "snapshot not found" }, 404);
- return json(rowToJSON(row));
-}
-
-// GET /api/images — all images for the org (named + auto-cached).
-export async function listImages(env: SnapshotsEnv, caller: Caller): Promise<Response> {
- const { results } = await env.OPENCOMPUTER_DB.prepare(
- `SELECT ${SELECT_COLS} FROM images_index
- WHERE org_id = ?1 ORDER BY created_at DESC LIMIT 200`,
- ).bind(caller.orgID).all<ImageRow>();
- return json((results ?? []).map(rowToJSON));
-}
-
-// ownerCellOfSnapshot looks up which cell owns a named snapshot so a
-// delete/patch can route to the cell holding the bytes. Returns null if the
-// snapshot isn't in D1 (caller gets 404 upstream).
-export async function ownerCellOfSnapshot(env: SnapshotsEnv, caller: Caller, name: string): Promise<string | null> {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT owner_cell_id FROM images_index WHERE org_id = ?1 AND name = ?2 LIMIT 1`,
- ).bind(caller.orgID, name).first<{ owner_cell_id: string }>();
- return row?.owner_cell_id ?? null;
-}
diff --git a/cloudflare-workers/api-edge/src/templates.ts b/cloudflare-workers/api-edge/src/templates.ts
deleted file mode 100644
index 80455c6b..00000000
--- a/cloudflare-workers/api-edge/src/templates.ts
+++ /dev/null
@@ -1,223 +0,0 @@
-// Edge-side templates — HMAC fetch + register endpoints called by the CP.
-//
-// Templates have no user-facing CRUD today (no /api/templates routes); they
-// are created via the CP's "save sandbox as template" snapshot flow and
-// looked up by name at sandbox-create time. After migration 041 strips the
-// per-cell `templates` table, both paths route through these /internal/*
-// HMAC endpoints so D1 becomes the single source of truth.
-
-export interface TemplatesEnv {
- OPENCOMPUTER_DB: D1Database;
- EVENT_SECRET: string;
-}
-
-function json(body: unknown, status = 200): Response {
- return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } });
-}
-
-interface TemplateRow {
- id: string;
- org_id: string | null;
- name: string;
- tag: string;
- template_type: string;
- image_ref: string | null;
- rootfs_s3_key: string | null;
- workspace_s3_key: string | null;
- dockerfile: string | null;
- is_public: number;
- status: string;
- cells_available: string;
- created_at: number;
-}
-
-// Mirrors db.Template (Go) field-by-field, camelCase JSON keys to match
-// existing dashboard/SDK responses.
-function templateToJSON(row: TemplateRow): Record<string, unknown> {
- let cells: string[] = [];
- try {
- cells = JSON.parse(row.cells_available) as string[];
- } catch {
- /* malformed JSON — degrade to empty list */
- }
- return {
- id: row.id,
- orgID: row.org_id,
- name: row.name,
- tag: row.tag,
- templateType: row.template_type,
- imageRef: row.image_ref,
- rootfsS3Key: row.rootfs_s3_key,
- workspaceS3Key: row.workspace_s3_key,
- dockerfile: row.dockerfile,
- isPublic: !!row.is_public,
- status: row.status,
- cellsAvailable: cells,
- createdAt: row.created_at,
- };
-}
-
-// ── HMAC (matches secret_stores.ts) ─────────────────────────────────────
-
-async function hmacHex(secret: string, data: string): Promise<string> {
- const key = await crypto.subtle.importKey(
- "raw",
- new TextEncoder().encode(secret),
- { name: "HMAC", hash: "SHA-256" },
- false,
- ["sign"],
- );
- const sig = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(data));
- return [...new Uint8Array(sig)].map((b) => b.toString(16).padStart(2, "0")).join("");
-}
-
-function constantTimeEqual(a: string, b: string): boolean {
- if (a.length !== b.length) return false;
- let diff = 0;
- for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
- return diff === 0;
-}
-
-async function verifyHMAC(req: Request, env: TemplatesEnv, bodyText?: string): Promise<boolean> {
- const ts = req.headers.get("X-Timestamp") ?? "";
- const sig = req.headers.get("X-Signature") ?? "";
- if (!ts || !sig) return false;
- const tsNum = Number.parseInt(ts, 10);
- if (!Number.isFinite(tsNum)) return false;
- if (Math.abs(Math.floor(Date.now() / 1000) - tsNum) > 5 * 60) return false;
- const url = new URL(req.url);
- // POST/PUT include the body in the signed payload to prevent body-swap
- // attacks; GET signs path+query only.
- const data = bodyText !== undefined ? `${ts}.${url.pathname}${url.search}.${bodyText}` : `${ts}.${url.pathname}${url.search}`;
- const expected = await hmacHex(env.EVENT_SECRET, data);
- return constantTimeEqual(expected, sig);
-}
-
-// ── /internal/templates/by-name ─────────────────────────────────────────
-
-// Org-scoped lookup with public fallback — mirrors db.Store.GetTemplateByName.
-// Sandbox-create on the CP calls this with cfg.Template (the user-supplied
-// name) and the cap-token's claims.OrgID. If the org has a private template
-// with that name it wins; otherwise we fall back to the public catalog.
-export async function internalGetByName(req: Request, env: TemplatesEnv): Promise<Response> {
- if (!(await verifyHMAC(req, env))) return json({ error: "signature mismatch" }, 401);
- const url = new URL(req.url);
- const orgID = url.searchParams.get("org_id") ?? "";
- const name = url.searchParams.get("name") ?? "";
- if (!name) return json({ error: "name is required" }, 400);
-
- // Private (org-scoped) first.
- if (orgID) {
- const row = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,
- dockerfile, is_public, status, cells_available, created_at
- FROM templates
- WHERE org_id = ?1 AND name = ?2
- ORDER BY created_at DESC LIMIT 1`,
- )
- .bind(orgID, name)
- .first<TemplateRow>();
- if (row) return json(templateToJSON(row));
- }
- // Public fallback.
- const pub = await env.OPENCOMPUTER_DB.prepare(
- `SELECT id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,
- dockerfile, is_public, status, cells_available, created_at
- FROM templates
- WHERE is_public = 1 AND name = ?1
- ORDER BY created_at DESC LIMIT 1`,
- )
- .bind(name)
- .first<TemplateRow>();
- if (!pub) return json({ error: "template not found" }, 404);
- return json(templateToJSON(pub));
-}
-
-// ── /internal/templates (POST) — register a new template in D1 ─────────
-
-// CP's "save sandbox as template" flow uploads the rootfs/workspace to Tigris
-// (already implemented via internal/blobstore.Store), then calls this to
-// register the metadata row. Replaces the local PG INSERT at
-// internal/db/store.go:1750.
-interface RegisterReq {
- id?: string;
- orgID?: string | null;
- name?: string;
- tag?: string;
- templateType?: string;
- imageRef?: string | null;
- rootfsS3Key?: string | null;
- workspaceS3Key?: string | null;
- dockerfile?: string | null;
- isPublic?: boolean;
- status?: string;
- cellsAvailable?: string[];
- createdBySandboxID?: string | null;
-}
-
-export async function internalRegister(req: Request, env: TemplatesEnv): Promise<Response> {
- // Read body once for both verification and parsing — POST signs payload too.
- const bodyText = await req.text();
- if (!(await verifyHMAC(req, env, bodyText))) return json({ error: "signature mismatch" }, 401);
- let body: RegisterReq;
- try {
- body = JSON.parse(bodyText) as RegisterReq;
- } catch {
- return json({ error: "invalid JSON" }, 400);
- }
- if (!body.name) return json({ error: "name is required" }, 400);
-
- const id = body.id ?? crypto.randomUUID();
- const tag = body.tag ?? "latest";
- const cellsJSON = JSON.stringify(body.cellsAvailable ?? []);
- const now = Math.floor(Date.now() / 1000);
-
- try {
- await env.OPENCOMPUTER_DB.prepare(
- `INSERT INTO templates
- (id, org_id, name, tag, template_type, image_ref, rootfs_s3_key, workspace_s3_key,
- dockerfile, is_public, status, cells_available, created_at)
- VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)`,
- )
- .bind(
- id,
- body.orgID ?? null,
- body.name,
- tag,
- body.templateType ?? "dockerfile",
- body.imageRef ?? null,
- body.rootfsS3Key ?? null,
- body.workspaceS3Key ?? null,
- body.dockerfile ?? null,
- body.isPublic ? 1 : 0,
- body.status ?? "ready",
- cellsJSON,
- now,
- )
- .run();
- } catch (e) {
- const msg = (e as Error).message ?? "";
- if (/UNIQUE/.test(msg)) return json({ error: "template (org, name, tag) already exists" }, 409);
- throw e;
- }
- return json({ id, name: body.name, tag, status: body.status ?? "ready" }, 201);
-}
-
-// Status update — CP flips status='ready' once a snapshot finishes uploading.
-// Matches db.Store.UpdateTemplateStatus.
-export async function internalUpdateStatus(req: Request, env: TemplatesEnv, id: string): Promise<Response> {
- const bodyText = await req.text();
- if (!(await verifyHMAC(req, env, bodyText))) return json({ error: "signature mismatch" }, 401);
- let body: { status?: string };
- try {
- body = JSON.parse(bodyText);
- } catch {
- return json({ error: "invalid JSON" }, 400);
- }
- if (!body.status) return json({ error: "status is required" }, 400);
- const res = await env.OPENCOMPUTER_DB.prepare(`UPDATE templates SET status = ?1 WHERE id = ?2`)
- .bind(body.status, id)
- .run();
- if ((res.meta?.changes ?? 0) === 0) return json({ error: "template not found" }, 404);
- return json({ id, status: body.status });
-}