An open-source, faster Devin alternative
TypeScript
Merge remote-tracking branch 'origin/main' into parity-mvm
Brian Reardonc81ea9207091
diff --cc cloudflare-workers/api-edge/src/index.tsindex fe81adb6,ea6a301f..f828c02c--- a/cloudflare-workers/api-edge/src/index.ts+++ b/cloudflare-workers/api-edge/src/index.ts@@@ -513,65 -470,7 +514,84 @@@ function bumpLastUsed(env: Env, hash: s.catch(() => {});}- const AUTH_KEY_SQL = "SELECT org_id, created_by, expires_at FROM api_keys WHERE key_hash = ?1";-async function authenticate(req: Request, env: Env): Promise<Caller | null> {++const AUTH_KEY_SQL = `SELECT k.org_id, k.created_by, k.expires_at,++ CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS role++ FROM api_keys k++ LEFT JOIN org_memberships m++ ON m.org_id = k.org_id AND m.user_id = k.created_by++ WHERE k.key_hash = ?1`;++++// One row shape for both readers. refreshAuth repopulates the same cache tiers++// the hot path reads, so a role column present in one and absent in the other++// would drop an admin to member on the first background refresh.++type AuthRow = {++ org_id: string;++ created_by: string | null;++ expires_at: number | null;++ role: string | null;++};++// In-flight auth refreshes, keyed by hash — same single-flight shape as+// createContextInflight and for the same reason: a burst that all lands stale+// would otherwise fire one D1 read per request, which is precisely the+// stampede the cache tiers exist to prevent.+const authRefreshInflight = new Map<string, Promise<void>>();++// refreshAuth re-reads the key row and repopulates both cache tiers. It runs+// BEHIND a response that was already served from a stale entry, so its latency+// is off the hot path; what matters is that it is authoritative — including+// when the row is gone, where it evicts rather than leaving a revoked key+// working until its TTL expires.+function refreshAuth(env: Env, hash: string): Promise<void> {+ const inflight = authRefreshInflight.get(hash);+ if (inflight) return inflight;+ const p = (async () => {+ try {+ const row = await env.OPENCOMPUTER_DB.prepare(AUTH_KEY_SQL)+ .bind(hash)- .first<{ org_id: string; created_by: string | null; expires_at: number | null }>();++ .first<AuthRow>();+ if (!row) {+ authCache.delete(hash);+ await coloDelete("auth", hash);+ return;+ }+ const at = Date.now();- const caller: Caller = { orgID: row.org_id, userID: row.created_by };++ const caller: Caller = {++ orgID: row.org_id,++ userID: row.created_by,++ ...(row.role ? { role: row.role } : {}),++ };+ if (authCache.size >= CACHE_MAX) authCache.clear();+ authCache.set(hash, {+ caller,+ expiresAt: row.expires_at,+ cachedAtMs: at,+ lastBumpMs: authCache.get(hash)?.lastBumpMs ?? 0,+ });+ await coloPut("auth", hash, { caller, expiresAt: row.expires_at, cachedAtMs: at }, AUTH_STALE_MAX_MS / 1000);+ } catch {+ // Keep serving the stale entry; the next request retries. Failing closed+ // 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;// Act-as-org provisioning token (sessions-api): a signed JWT, not an osb_ key.@@@ -615,41 -508,21 +635,41 @@@return shared.caller;}- const row = await env.OPENCOMPUTER_DB.prepare(- `SELECT k.org_id, k.created_by, k.expires_at,- CASE WHEN m.role IN ('owner', 'admin') THEN 'admin' ELSE m.role END AS role- FROM api_keys k- LEFT JOIN org_memberships m- ON m.org_id = k.org_id AND m.user_id = k.created_by- WHERE k.key_hash = ?1`,- )+ // 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<{ org_id: string; created_by: string | null; expires_at: number | null }>();- .first<{- org_id: string;- created_by: string | null;- expires_at: number | null;- role: string | null;- }>();++ .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 onceif (row.expires_at && row.expires_at < nowSec) return null;