An open-source, faster Devin alternative
TypeScript
api-edge: retry D1 overload errors and recover failed login callbacks
Slack U06G42NTEK1380affff2ed2
diff --git a/cloudflare-workers/api-edge/src/auth_callback_recovery.test.ts b/cloudflare-workers/api-edge/src/auth_callback_recovery.test.tsnew file mode 100644index 00000000..d7d559ee--- /dev/null+++ b/cloudflare-workers/api-edge/src/auth_callback_recovery.test.ts@@ -0,0 +1,129 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import worker, { type Env } from "./index";++// Login-path recovery from D1 overload: the retry wrapper absorbs short blips,+// and a callback that still fails after the WorkOS exchange restarts the login+// once instead of throwing (Cloudflare 1101).++const OVERLOADED = "D1_ERROR: D1 DB is overloaded. Requests queued for too long.";++function makeEnv(overloadedCalls: number) {+ let remaining = overloadedCalls;+ const executed: string[] = [];+ const maybeFail = (sql: string) => {+ executed.push(sql.split(/\s+/).slice(0, 3).join(" "));+ if (remaining === Infinity || remaining-- > 0) throw new Error(OVERLOADED);+ };+ const user = { id: "user-1", email: "[email protected]", name: "U" };+ const membership = {+ id: "org-1", name: "U's workspace", plan: "free", is_personal: 1,+ workos_org_id: null, membership_created_at: 1, org_created_at: 1,+ };+ const stmt = (sql: string) => ({+ bind: () => stmt(sql),+ first: async () => {+ maybeFail(sql);+ if (sql.includes("FROM users")) return user;+ if (sql.includes("org_memberships")) return membership;+ return null;+ },+ all: async () => {+ maybeFail(sql);+ return { results: [] };+ },+ run: async () => {+ maybeFail(sql);+ return { success: true, meta: {} };+ },+ });+ const env = {+ OPENCOMPUTER_DB: { prepare: stmt, batch: async () => [] },+ SESSION_JWT_SECRET: "test-secret",+ WORKOS_API_KEY: "sk_test",+ WORKOS_CLIENT_ID: "client_test",+ WORKER_ENV: "test",+ } as unknown as Env;+ return { env, executed };+}++const ctx = { waitUntil: vi.fn(), passThroughOnException: vi.fn() } as unknown as ExecutionContext;++const callback = (state?: object) => {+ const u = new URL("https://app.opencomputer.dev/auth/callback?code=c1");+ if (state) u.searchParams.set("state", JSON.stringify(state));+ return new Request(u);+};++describe("auth callback under D1 overload", () => {+ beforeEach(() => {+ vi.stubGlobal(+ "fetch",+ vi.fn(async () =>+ Response.json({ user: { id: "wos-1", email: "[email protected]", first_name: "U" } }),+ ),+ );+ vi.spyOn(console, "error").mockImplementation(() => {});+ });+ afterEach(() => {+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ });++ it("logs the user in when the first query is overloaded once (retry absorbs it)", async () => {+ const { env, executed } = makeEnv(1);+ const resp = await worker.fetch(callback(), env, ctx);+ expect(resp.status).toBe(302);+ expect(resp.headers.get("location")).toBe("https://app.opencomputer.dev/dashboard");+ expect(resp.headers.get("set-cookie")).toMatch(/^oc_session=/);+ expect(executed[0]).toBe(executed[1]); // same query re-sent once+ });++ it("restarts the login once when D1 stays overloaded, keeping returnTo", async () => {+ const { env } = makeEnv(Infinity);+ const resp = await worker.fetch(callback({ returnTo: "/projects" }), env, ctx);+ expect(resp.status).toBe(302);+ const loc = new URL(resp.headers.get("location")!);+ expect(loc.pathname).toBe("/auth/login");+ expect(loc.searchParams.get("retried")).toBe("1");+ expect(loc.searchParams.get("returnTo")).toBe("/projects");+ expect(resp.headers.get("set-cookie")).toBeNull();+ });++ it("shows a retry page instead of looping on the second failure", async () => {+ const { env } = makeEnv(Infinity);+ const resp = await worker.fetch(callback({ retried: true }), env, ctx);+ expect(resp.status).toBe(503);+ expect(await resp.text()).toContain('href="/auth/login"');+ });++ it("carries the retried flag through WorkOS state on the restarted login", async () => {+ const { env } = makeEnv(0);+ const resp = await worker.fetch(+ new Request("https://app.opencomputer.dev/auth/login?retried=1&returnTo=/projects"),+ env,+ ctx,+ );+ const state = JSON.parse(new URL(resp.headers.get("location")!).searchParams.get("state")!);+ expect(state).toEqual({ returnTo: "/projects", retried: true });+ });++ it("leaves a normal login's state unchanged", async () => {+ const { env } = makeEnv(0);+ const plain = await worker.fetch(new Request("https://app.opencomputer.dev/auth/login"), env, ctx);+ expect(new URL(plain.headers.get("location")!).searchParams.get("state")).toBeNull();+ const deep = await worker.fetch(+ new Request("https://app.opencomputer.dev/auth/login?returnTo=/projects"),+ env,+ ctx,+ );+ expect(JSON.parse(new URL(deep.headers.get("location")!).searchParams.get("state")!)).toEqual({+ returnTo: "/projects",+ });+ });++ it("still lands on returnTo after a clean login", async () => {+ const { env } = makeEnv(0);+ const resp = await worker.fetch(callback({ returnTo: "/projects", retried: true }), env, ctx);+ expect(resp.headers.get("location")).toBe("https://app.opencomputer.dev/projects");+ });+});diff --git a/cloudflare-workers/api-edge/src/d1_retry.test.ts b/cloudflare-workers/api-edge/src/d1_retry.test.tsnew file mode 100644index 00000000..28f2df2d--- /dev/null+++ b/cloudflare-workers/api-edge/src/d1_retry.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it } from "vitest";+import { envWithD1Retry, isD1Overloaded, withD1Retry } from "./d1_retry";++const OVERLOADED = new Error("D1_ERROR: D1 DB is overloaded. Requests queued for too long.");++// Fake D1 whose executions fail with `failures` errors (in order) before succeeding.+function fakeDB(failures: Error[]) {+ const calls: string[] = [];+ const queue = [...failures];+ const exec = (label: string) => {+ calls.push(label);+ const next = queue.shift();+ return next ? Promise.reject(next) : Promise.resolve({ label });+ };+ const stmt = (sql: string, args: unknown[] = []): D1PreparedStatement =>+ ({+ sql,+ args,+ bind: (...a: unknown[]) => stmt(sql, a),+ first: () => exec(`first:${sql}:${args.join(",")}`),+ all: () => exec(`all:${sql}`),+ run: () => exec(`run:${sql}`),+ raw: () => exec(`raw:${sql}`),+ }) as unknown as D1PreparedStatement;+ const batched: unknown[][] = [];+ const db = {+ prepare: (sql: string) => stmt(sql),+ batch: (stmts: D1PreparedStatement[]) => {+ batched.push(stmts);+ return exec(`batch:${stmts.length}`);+ },+ exec: (sql: string) => exec(`exec:${sql}`),+ withSession: () => db,+ } as unknown as D1Database;+ return { db, calls, batched };+}++const noSleep = { sleep: async () => {} };++describe("isD1Overloaded", () => {+ it("matches only the overload error", () => {+ expect(isD1Overloaded(OVERLOADED)).toBe(true);+ expect(isD1Overloaded(new Error("D1_ERROR: UNIQUE constraint failed: users.email"))).toBe(false);+ expect(isD1Overloaded(new Error("D1_ERROR: Network connection lost."))).toBe(false);+ });+});++describe("withD1Retry", () => {+ it("retries an overloaded read and returns the result", async () => {+ const { db, calls } = fakeDB([OVERLOADED]);+ const r = await withD1Retry(db, noSleep).prepare("SELECT 1 WHERE x = ?1").bind("a").first();+ expect(r).toEqual({ label: "first:SELECT 1 WHERE x = ?1:a" });+ expect(calls).toHaveLength(2);+ });++ it("retries run/all/raw", async () => {+ for (const m of ["run", "all", "raw"] as const) {+ const { db, calls } = fakeDB([OVERLOADED]);+ await withD1Retry(db, noSleep).prepare("Q")[m]();+ expect(calls).toHaveLength(2);+ }+ });++ it("gives up after two retries and rethrows the overload error", async () => {+ const { db, calls } = fakeDB([OVERLOADED, OVERLOADED, OVERLOADED, OVERLOADED]);+ await expect(withD1Retry(db, noSleep).prepare("Q").run()).rejects.toBe(OVERLOADED);+ expect(calls).toHaveLength(3);+ });++ it("never retries other errors", async () => {+ const constraint = new Error("D1_ERROR: UNIQUE constraint failed: users.email");+ const { db, calls } = fakeDB([constraint]);+ await expect(withD1Retry(db, noSleep).prepare("INSERT").run()).rejects.toBe(constraint);+ expect(calls).toHaveLength(1);+ });++ it("hands batch() the raw statements and retries the whole batch", async () => {+ const { db, calls, batched } = fakeDB([OVERLOADED]);+ const w = withD1Retry(db, noSleep);+ const a = w.prepare("A").bind(1);+ const b = w.prepare("B");+ await w.batch([a, b]);+ expect(calls).toEqual(["batch:2", "batch:2"]);+ expect((batched[0] as D1PreparedStatement[])[0]).not.toBe(a); // raw, not the wrapper+ expect((batched[0] as Array<{ sql: string }>).map((s) => s.sql)).toEqual(["A", "B"]);+ });++ it("wraps sessions too", async () => {+ const { db, calls } = fakeDB([OVERLOADED]);+ await withD1Retry(db, noSleep).withSession("first-primary").prepare("Q").first();+ expect(calls).toHaveLength(2);+ });++ it("waits between attempts with growing delays", async () => {+ const waits: number[] = [];+ const { db } = fakeDB([OVERLOADED, OVERLOADED]);+ await withD1Retry(db, { sleep: async (ms) => void waits.push(ms) }).prepare("Q").run();+ expect(waits).toHaveLength(2);+ expect(waits[0]).toBeGreaterThanOrEqual(100);+ expect(waits[0]).toBeLessThan(200);+ expect(waits[1]).toBeGreaterThanOrEqual(300);+ expect(waits[1]).toBeLessThan(600);+ });+});++describe("envWithD1Retry", () => {+ it("leaves the original env and other bindings untouched", () => {+ const { db } = fakeDB([]);+ const env = { OPENCOMPUTER_DB: db, WORKER_ENV: "prod" };+ const wrapped = envWithD1Retry(env);+ expect(env.OPENCOMPUTER_DB).toBe(db);+ expect(wrapped.OPENCOMPUTER_DB).not.toBe(db);+ expect(wrapped.WORKER_ENV).toBe("prod");+ expect(envWithD1Retry(env).OPENCOMPUTER_DB).toBe(wrapped.OPENCOMPUTER_DB);+ });+});diff --git a/cloudflare-workers/api-edge/src/d1_retry.ts b/cloudflare-workers/api-edge/src/d1_retry.tsnew file mode 100644index 00000000..955fe30a--- /dev/null+++ b/cloudflare-workers/api-edge/src/d1_retry.ts@@ -0,0 +1,98 @@+// D1 overload retry. D1 sheds load with "D1 DB is overloaded. Requests queued+// for too long." when its request queue backs up. Cloudflare lists it as+// retryable: the query was rejected while queued and never ran, so re-sending+// it cannot double-apply a write. Only that exact error is retried; every other+// error (constraint violations, syntax, timeouts after execution started)+// propagates unchanged on the first attempt.++const OVERLOADED = "D1 DB is overloaded";+const DEFAULT_DELAYS_MS = [100, 300];++export function isD1Overloaded(err: unknown): boolean {+ const msg = err instanceof Error ? err.message : String(err);+ return msg.includes(OVERLOADED);+}++type Sleep = (ms: number) => Promise<void>;+const realSleep: Sleep = (ms) => new Promise((r) => setTimeout(r, ms));++export interface D1RetryOptions {+ delaysMs?: number[];+ sleep?: Sleep;+}++async function withRetry<T>(fn: () => Promise<T>, opts: Required<D1RetryOptions>): Promise<T> {+ for (let attempt = 0; ; attempt++) {+ try {+ return await fn();+ } catch (err) {+ if (!isD1Overloaded(err) || attempt >= opts.delaysMs.length) throw err;+ const base = opts.delaysMs[attempt];+ await opts.sleep(base + Math.floor(Math.random() * base));+ }+ }+}++// Wrapped statements remember their raw statement so batch() can hand D1 the+// objects it expects.+const rawStatement = new WeakMap<object, D1PreparedStatement>();++function wrapStatement(stmt: D1PreparedStatement, opts: Required<D1RetryOptions>): D1PreparedStatement {+ const wrapped = new Proxy(stmt, {+ get(target, prop) {+ if (prop === "bind") {+ return (...args: unknown[]) => wrapStatement(target.bind(...args), opts);+ }+ if (prop === "first" || prop === "all" || prop === "run" || prop === "raw") {+ return (...args: unknown[]) =>+ withRetry(() => (target[prop] as (...a: unknown[]) => Promise<unknown>).apply(target, args), opts);+ }+ const v = Reflect.get(target, prop, target);+ return typeof v === "function" ? v.bind(target) : v;+ },+ });+ rawStatement.set(wrapped, stmt);+ return wrapped;+}++function unwrap(stmts: D1PreparedStatement[]): D1PreparedStatement[] {+ return stmts.map((s) => rawStatement.get(s) ?? s);+}++function wrapQueryable<T extends D1Database | D1DatabaseSession>(db: T, opts: Required<D1RetryOptions>): T {+ return new Proxy(db, {+ get(target, prop) {+ if (prop === "prepare") {+ return (sql: string) => wrapStatement(target.prepare(sql), opts);+ }+ if (prop === "batch") {+ return (stmts: D1PreparedStatement[]) => withRetry(() => target.batch(unwrap(stmts)), opts);+ }+ if (prop === "withSession" && "withSession" in target) {+ return (...args: unknown[]) =>+ wrapQueryable((target as D1Database).withSession(...(args as [string?])), opts);+ }+ const v = Reflect.get(target, prop, target);+ return typeof v === "function" ? v.bind(target) : v;+ },+ });+}++const wrappedDBs = new WeakMap<D1Database, D1Database>();++export function withD1Retry(db: D1Database, opts: D1RetryOptions = {}): D1Database {+ const full = { delaysMs: opts.delaysMs ?? DEFAULT_DELAYS_MS, sleep: opts.sleep ?? realSleep };+ if (opts.delaysMs || opts.sleep) return wrapQueryable(db, full);+ let w = wrappedDBs.get(db);+ if (!w) {+ w = wrapQueryable(db, full);+ wrappedDBs.set(db, w);+ }+ return w;+}++// Per-invocation env with the retrying binding. The original env is never+// mutated, so Durable Objects and anything holding the raw env are unaffected.+export function envWithD1Retry<E extends { OPENCOMPUTER_DB: D1Database }>(env: E): E {+ return { ...env, OPENCOMPUTER_DB: withD1Retry(env.OPENCOMPUTER_DB) };+}diff --git a/cloudflare-workers/api-edge/src/index.ts b/cloudflare-workers/api-edge/src/index.tsindex 275ae3a6..3b8a9c0a 100644--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@ -85,6 +85,7 @@ import * as snapshots from "./snapshots";import * as templates from "./templates";import * as webhooks from "./webhooks";import { createAPIKey, hashAPIKey } from "./api_keys";+import { envWithD1Retry } from "./d1_retry";import {handleAgentWebhookInvocation,handleManagedGitHubCallback,@@ -3768,7 +3769,12 @@ async function authLogin(req: Request, env: Env): Promise<Response> {// the OAuth `state` param so the callback can land the user back on it (incl.// a /do?action=… deferred action). Only same-origin paths survive validation.const returnTo = safeReturnTo(reqURL.searchParams.get("returnTo"));- if (returnTo) authURL.searchParams.set("state", JSON.stringify({ returnTo }));+ // `retried` marks a login restarted by a failed callback; it rides `state` so+ // the callback restarts at most once instead of looping on a WorkOS session.+ const retried = reqURL.searchParams.get("retried") === "1";+ if (returnTo || retried) {+ authURL.searchParams.set("state", JSON.stringify({ ...(returnTo ? { returnTo } : {}), ...(retried ? { retried: true } : {}) }));+ }return Response.redirect(authURL.toString(), 302);}@@ -4019,6 +4025,43 @@ async function authCallback(req: Request, env: Env): Promise<Response> {return json({ error: `workos exchange failed: ${tokenResp.status}: ${errText}` }, 401);}const tokenBody = await tokenResp.json<{ user: WorkOSProfile; organization_id?: string; access_token?: string }>();+ // The code is spent from here on, so a throw would leave the user on a 1101+ // whose refresh fails with "code already exchanged". Restart the login once+ // (WorkOS issues a fresh code); a second failure gets a plain retry page.+ try {+ return await completeAuthCallback(req, env, reqURL, tokenBody);+ } catch (err) {+ console.error("auth callback: post-exchange failure", err);+ const state = parseAuthState(reqURL.searchParams.get("state"));+ if (state.retried) {+ return new Response(+ `<!doctype html><title>Sign-in failed</title><p>Sign-in hit a temporary error. <a href="/auth/login">Try again</a>.</p>`,+ { status: 503, headers: { "content-type": "text/html; charset=utf-8", "retry-after": "5" } },+ );+ }+ const retry = new URL("/auth/login", reqURL.origin);+ retry.searchParams.set("retried", "1");+ if (state.returnTo) retry.searchParams.set("returnTo", state.returnTo);+ return Response.redirect(retry.toString(), 302);+ }+}++function parseAuthState(raw: string | null): { returnTo: string | null; retried: boolean } {+ if (!raw) return { returnTo: null, retried: false };+ try {+ const parsed = JSON.parse(raw) as { returnTo?: string; retried?: boolean };+ return { returnTo: safeReturnTo(parsed.returnTo), retried: parsed.retried === true };+ } catch {+ return { returnTo: null, retried: false };+ }+}++async function completeAuthCallback(+ req: Request,+ env: Env,+ reqURL: URL,+ tokenBody: { user: WorkOSProfile; organization_id?: string; access_token?: string },+): Promise<Response> {const profile = tokenBody.user;// WorkOS session id (sid) for the hosted logout flow — carried in our session JWT.const workosSessionID = workosSessionIdFromAccessToken(tokenBody.access_token);@@ -4043,15 +4086,7 @@ async function authCallback(req: Request, env: Env): Promise<Response> {// Land on the deferred deep link if `state` carried a valid one, else the// dashboard. Re-validate here: `state` is attacker-influenceable, so the path// is only trusted after safeReturnTo passes a second time.- let returnTo: string | null = null;- const stateRaw = reqURL.searchParams.get("state");- if (stateRaw) {- try {- returnTo = safeReturnTo((JSON.parse(stateRaw) as { returnTo?: string }).returnTo);- } catch {- returnTo = null;- }- }+ const returnTo = parseAuthState(reqURL.searchParams.get("state")).returnTo;const landingURL = `${reqURL.origin}${returnTo ?? "/dashboard"}`;return new Response(null, {status: 302,@@ -5074,6 +5109,7 @@ 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);@@ -5894,6 +5930,7 @@ export default {// key's spend → debit Autumn `model_spend` → push the markup-correct cap + halt.// 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)),@@ -5930,6 +5967,7 @@ export default {// (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;diff --git a/cloudflare-workers/api-edge/wrangler.prod.toml b/cloudflare-workers/api-edge/wrangler.prod.tomlindex 41951f28..0956b7f2 100644--- a/cloudflare-workers/api-edge/wrangler.prod.toml+++ b/cloudflare-workers/api-edge/wrangler.prod.toml@@ -20,6 +20,12 @@ routes = [{ pattern = "*.sb.opencomputer.dev/*", zone_name = "opencomputer.dev" },]+# Workers Logs: without this, exceptions behind a Cloudflare 1101 Ray ID are+# only visible to a live `wrangler tail`.+[observability]+enabled = true+head_sampling_rate = 1+# Static assets — the dashboard SPA. Built from `web/` by the deploy script.[assets]directory = "./assets"