Skip to content

An open-source, faster Devin alternative

TypeScript

perf(edge): warm the auth entry too, so a cold IAD isolate never opens a D1 connection

Brian Reardon64e2b9b4c120
diff --git a/cloudflare-workers/api-edge/src/auth_warm.test.ts b/cloudflare-workers/api-edge/src/auth_warm.test.ts
new file mode 100644
index 00000000..bde2dbea
--- /dev/null
+++ b/cloudflare-workers/api-edge/src/auth_warm.test.ts
@@ -0,0 +1,170 @@
+// The warmed auth entry must be readable by authenticate().
+//
+// This is a shape contract between two files, and the failure mode if it drifts
+// is silence: authenticate() simply misses, falls through to D1, and everything
+// still returns the right answer. Nothing throws, no test fails, and the only
+// symptom is that the first request from a cold isolate goes back to costing
+// what it cost before — measured on prod from IAD, 16,723ms.
+//
+// So the assertion here is the round trip, not the written bytes: warm, then
+// authenticate, then require that D1 was never touched.
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import worker, { type Env } from "./index";
+import { warmCreateContextColo } from "./create_context_cache";
+
+const orgID = "22222222-2222-4222-8222-222222222222";
+const userID = "11111111-1111-4111-8111-111111111111";
+
+async function sha256Hex(s: string): Promise<string> {
+ const d = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(s));
+ return [...new Uint8Array(d)].map((b) => b.toString(16).padStart(2, "0")).join("");
+}
+
+// Minimal stand-in for caches.default — vitest has no Cache API, and without one
+// coloPut/coloGet no-op and this test would pass vacuously.
+function installCacheStub(): Map<string, string> {
+ const store = new Map<string, string>();
+ (globalThis as unknown as { caches: unknown }).caches = {
+ default: {
+ async match(url: string): Promise<Response | undefined> {
+ const v = store.get(String(url));
+ return v === undefined ? undefined : new Response(v);
+ },
+ async put(url: string, res: Response): Promise<void> {
+ store.set(String(url), await res.text());
+ },
+ },
+ };
+ return store;
+}
+
+class WarmDB {
+ apiKeyLookups = 0;
+ constructor(private readonly keys: { key_hash: string; expires_at: number | null }[]) {}
+
+ prepare(sql: string) {
+ const db = this;
+ const stmt = {
+ bind() {
+ return stmt;
+ },
+ async first<T>(): Promise<T | null> {
+ if (sql.includes("FROM api_keys WHERE key_hash")) db.apiKeyLookups++;
+ return null;
+ },
+ async all<T>(): Promise<{ results: T[] }> {
+ return { results: [] as T[] };
+ },
+ async run(): Promise<Record<string, never>> {
+ return {};
+ },
+ _sql: sql,
+ };
+ return stmt;
+ }
+
+ async batch(stmts: { _sql: string }[]): Promise<{ results: unknown[] }[]> {
+ return stmts.map((s) => {
+ if (s._sql.includes("FROM api_keys WHERE org_id")) {
+ return {
+ results: this.keys.map((k) => ({
+ key_hash: k.key_hash,
+ org_id: orgID,
+ created_by: userID,
+ expires_at: k.expires_at,
+ })),
+ };
+ }
+ if (s._sql.includes("FROM cells")) {
+ return {
+ results: [
+ {
+ cell_id: "azure-us-east-2-a",
+ cloud: "azure",
+ region: "us-east-2",
+ base_url: "https://cell.example",
+ status: "active",
+ available_workers: 4,
+ capacity_updated_at: null,
+ },
+ ],
+ };
+ }
+ if (s._sql.includes("FROM orgs")) {
+ return {
+ results: [
+ {
+ home_cell: "azure-us-east-2-a",
+ plan: "pro",
+ is_halted: 0,
+ max_concurrent_sandboxes: 100,
+ max_disk_mb: 100000,
+ billing_provider: "autumn",
+ runtime: "microvm",
+ },
+ ],
+ };
+ }
+ return { results: [{ n: 0 }] };
+ });
+ }
+}
+
+function testEnv(db: WarmDB): Env {
+ return {
+ OPENCOMPUTER_DB: db,
+ SESSIONS_KV: {},
+ WORKER_ENV: "test",
+ CF_ADMIN_SECRET: "",
+ EVENT_SECRET: "",
+ } as unknown as Env;
+}
+
+const ctx = {
+ waitUntil: vi.fn(),
+ passThroughOnException: vi.fn(),
+} as unknown as ExecutionContext;
+
+describe("warmed auth entries", () => {
+ beforeEach(() => {
+ installCacheStub();
+ });
+
+ it("are accepted by authenticate without touching D1", async () => {
+ const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
+ const db = new WarmDB([{ key_hash: await sha256Hex(key), expires_at: null }]);
+
+ await warmCreateContextColo(db as unknown as D1Database, [orgID]);
+
+ const res = await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", {
+ headers: { "X-API-Key": key },
+ }),
+ testEnv(db),
+ ctx,
+ );
+
+ expect(res.status).not.toBe(401);
+ expect(db.apiKeyLookups).toBe(0);
+ });
+
+ it("skips expired keys rather than publishing them as valid", async () => {
+ const key = `osb_${crypto.randomUUID().replace(/-/g, "")}`;
+ const expired = Math.floor(Date.now() / 1000) - 60;
+ const db = new WarmDB([{ key_hash: await sha256Hex(key), expires_at: expired }]);
+
+ await warmCreateContextColo(db as unknown as D1Database, [orgID]);
+
+ await worker.fetch(
+ new Request("https://app.opencomputer.dev/api/sandboxes", {
+ headers: { "X-API-Key": key },
+ }),
+ testEnv(db),
+ ctx,
+ );
+
+ // No warmed entry to hit, so the request must fall through to D1 — which is
+ // the safe direction: an expired key gets re-checked, never served warm.
+ expect(db.apiKeyLookups).toBe(1);
+ });
+});
diff --git a/cloudflare-workers/api-edge/src/create_context_cache.ts b/cloudflare-workers/api-edge/src/create_context_cache.ts
index 0a6123bf..5bf53258 100644
--- a/cloudflare-workers/api-edge/src/create_context_cache.ts
+++ b/cloudflare-workers/api-edge/src/create_context_cache.ts
@@ -73,6 +73,23 @@ 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'";
+// The org's API keys, so the auth entry can be warmed alongside the rest of the
+// create context. Bounded and most-recently-used first: an org may hold many
+// keys but a burst arrives on one, and this rides inside a 10s alarm.
+export const ORG_KEYS_SQL =
+ "SELECT key_hash, org_id, created_by, expires_at FROM api_keys WHERE org_id = ?1 ORDER BY last_used DESC LIMIT 8";
+
+// How long a warmed auth entry stays usable. Must equal index.ts's AUTH_TTL_MS
+// — authenticate() reads these entries and applies that bound itself, so a
+// longer TTL here would only produce entries it rejects on arrival.
+export const AUTH_TTL_MS = 60_000;
+
+interface KeyRow {
+ key_hash: string;
+ org_id: string;
+ created_by: string | null;
+ expires_at: number | null;
+}
// 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:
@@ -143,6 +160,7 @@ export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): P
for (const id of orgs) {
stmts.push(db.prepare(ORG_POLICY_SQL).bind(id));
stmts.push(db.prepare(RUNNING_COUNT_SQL).bind(id));
+ stmts.push(db.prepare(ORG_KEYS_SQL).bind(id));
}
// One round trip for everything: the whole reason this is worth doing from
// a 10s alarm rather than N separate reads.
@@ -158,9 +176,36 @@ export async function warmCreateContextColo(db: D1Database, orgIDs: string[]): P
puts.push(coloPut("cells", "active", { cells, cachedAtMs: at }, CELL_STALE_MAX_MS / 1000));
}
+ const nowSec = Math.floor(at / 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;
+ const policy = (res[1 + i * 3]?.results?.[0] as OrgPolicy | undefined) ?? null;
+ const n = (res[2 + i * 3]?.results?.[0] as { n: number } | undefined)?.n ?? 0;
+ // Auth entries, in the shape authenticate() reads. This is the one read on
+ // the create path that no warmer covered, and it is the most expensive to
+ // miss: measured on prod from IAD, a cold isolate's FIRST D1 touch cost
+ // 16,723ms while the same read from SJC — where the primary lives — cost
+ // 57ms. authenticate() runs before everything else, so it pays that
+ // establishment and every later read on the request rides the open
+ // connection (`ctx` was 125ms on the very same request).
+ //
+ // Revocation is unaffected: a deleted key simply stops coming back from
+ // this query, so its entry lapses within AUTH_TTL_MS exactly as it does
+ // today. Expired keys are skipped rather than published as valid.
+ for (const k of (res[3 + i * 3]?.results as KeyRow[] | undefined) ?? []) {
+ if (k.expires_at !== null && k.expires_at < nowSec) continue;
+ puts.push(
+ coloPut(
+ "auth",
+ k.key_hash,
+ {
+ caller: { orgID: k.org_id, userID: k.created_by },
+ expiresAt: k.expires_at,
+ cachedAtMs: at,
+ },
+ AUTH_TTL_MS / 1000,
+ ),
+ );
+ }
// 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.
diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.ts
index 8376d6bd..f5ac7feb 100644
--- a/cloudflare-workers/api-edge/src/index.ts
+++ b/cloudflare-workers/api-edge/src/index.ts
@@ -32,6 +32,7 @@ export { PoolStock } from "./pool_stock";
import { coloGet, coloPut } from "./colo_cache";
import {
ACTIVE_CELLS_SQL,
+ AUTH_TTL_MS,
CELL_STALE_MAX_MS,
CELL_TTL_MS,
CONCURRENCY_COUNT_TTL_MS,
@@ -375,7 +376,6 @@ function stripApiKeyQueryParam(target: string): string {
// per-isolate for a few seconds so a burst collapses to a handful of D1 reads,
// 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 org policy in the colo tier: a ≤60s-stale not-halted policy
// may gate a create while a background refresh runs (see loadCreateContext).
const LAST_USED_BUMP_MS = 60_000; // at most once/min/key/isolate