From cfa41e595678996bd8895195835dd297c5164f5e Mon Sep 17 00:00:00 2001 From: yetone Date: Fri, 6 Nov 2026 19:51:18 +0800 Subject: [PATCH] gcp-ai 0.2.2: retry a 401 without buffering every body (#739) Reuse an in-memory body on a 401 instead of cloning every request up front, and return a 401 on a stream that cannot be sent twice. Concurrent 401s share one token refresh. Keep the token cache in a WeakMap keyed by the fetch function, and replace Promise.withResolvers in tests so the suite runs on Node 20. Co-authored-by: Cursor Agent --- packages/gcp-ai/README.md | 2 +- packages/gcp-ai/index.mjs | 43 ++++- packages/gcp-ai/lib/credentials.mjs | 38 ++++- packages/gcp-ai/lib/history.mjs | 16 +- packages/gcp-ai/package.json | 4 +- packages/gcp-ai/test/plugin.test.mjs | 245 ++++++++++++++++++++++++++- 6 files changed, 315 insertions(+), 33 deletions(-) diff --git a/packages/gcp-ai/README.md b/packages/gcp-ai/README.md index c58acbc..1d9d499 100644 --- a/packages/gcp-ai/README.md +++ b/packages/gcp-ai/README.md @@ -8,7 +8,7 @@ You sign in once with your own Google account. No service accounts, no JSON keys ## Token caching and request latency -With an `authorized_user` ADC, the access token is cached per account until 60 seconds before it expires and refreshed directly against Google's OAuth token endpoint; concurrent callers share one in-flight refresh. In gcloud mode every token still comes from gcloud, unchanged. The endpoint check runs in the background, so it never sits in front of the first model call — only a rejected credential (401) is surfaced on later requests. +With an `authorized_user` ADC, the access token is cached per account until 60 seconds before it expires and refreshed directly against Google's OAuth token endpoint; concurrent callers share one in-flight refresh, including when several requests are refused at once and have to fetch again. A refused model call is retried once with that token when its body is already in memory; a stream is sent once rather than copied on the way out. In gcloud mode every token still comes from gcloud, unchanged. The endpoint check runs in the background, so it never sits in front of the first model call — only a rejected credential (401) is surfaced on later requests. ## Requirements diff --git a/packages/gcp-ai/index.mjs b/packages/gcp-ai/index.mjs index 3495f9c..4437b19 100644 --- a/packages/gcp-ai/index.mjs +++ b/packages/gcp-ai/index.mjs @@ -83,6 +83,26 @@ function geminiRoute(pathname, base) { return GEMINI_ROUTE.test(pathname.slice(base.length)) } +// A body the caller already holds. A 401 can send it again without copying. +// A stream is not one of these: buffering it on the way out would copy every +// request in case the token was stale, so a 401 on a stream is returned as it is. +function heldBody(body) { + if (typeof body === "string") return true + if (body instanceof URLSearchParams) return true + if (typeof Blob !== "undefined" && body instanceof Blob) return true + if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return true + if (typeof FormData !== "undefined" && body instanceof FormData) return true + return false +} + +// The body a 401 can send again: the hardened JSON, or the caller's own +// in-memory body. Undefined means there is nothing cheap to replay. +function replayBody(init, hardened) { + if (hardened !== undefined) return hardened + if (init && Object.prototype.hasOwnProperty.call(init, "body") && heldBody(init.body)) return init.body + return undefined +} + // A probe is remembered for the process, but only a credential refusal blocks // requests. That verdict expires so a later load can retry recovered credentials. const tested = new Map() @@ -223,21 +243,30 @@ export const GoogleVertexAuthPlugin = async (input = {}, pluginOptions = {}) => // Gemini's history rules: a conversation ending or opening with // the model's turn, or a tool's response beside the user's words, // is sent in the shape Vertex takes instead of answered 400 (#734) - const request = await hardenRequest(asked) + const { request, body: hardened } = await hardenRequest(asked) const headers = new Headers(request.headers) headers.delete("x-goog-api-key") headers.delete("x-api-key") headers.set("authorization", `Bearer ${await getToken()}`) headers.set("x-goog-user-project", identity.project) - // Keep the body available if Vertex rejects a cached credential. - const retry = request.clone() - const response = await fetch(new Request(request, { headers, redirect: "error" })) + // Replay a body that is already in memory. Do not clone the request + // up front: that buffers every body on the chance of a 401. A stream + // cannot be sent twice, so a 401 on one is returned as it is. + const retryBody = replayBody(init, hardened) + const canRetry = retryBody !== undefined || request.body == null + const send = (body) => body === undefined + ? fetch(new Request(request, { headers, redirect: "error" })) + : fetch(new Request(request.url, { method: request.method, headers, body, redirect: "error", signal: request.signal })) + const response = await send() if (response.status !== 401) return response + if (!canRetry) { + getToken.invalidate() + return response + } // Free the connection before the retry: this reply is not returned. await response.body?.cancel().catch(() => {}) - getToken.invalidate() - headers.set("authorization", `Bearer ${await getToken()}`) - return fetch(new Request(retry, { headers, redirect: "error" })) + headers.set("authorization", `Bearer ${await getToken.refresh()}`) + return send(retryBody) }, } }, diff --git a/packages/gcp-ai/lib/credentials.mjs b/packages/gcp-ai/lib/credentials.mjs index c8cde37..aa2d6ed 100644 --- a/packages/gcp-ai/lib/credentials.mjs +++ b/packages/gcp-ai/lib/credentials.mjs @@ -288,10 +288,12 @@ export async function listUsableProjects(token, request = fetch) { // All callers for an identity share a cache and in-flight refresh, so a // background endpoint probe and a real request do not refresh separately. -const tokenCache = new Map() -// Injected run and request functions are told apart, so a provider handed its -// own functions never serves a token another provider fetched. The defaults are -// one reference each, so real callers still share one cache per identity. +// The cache is keyed by the fetch function it was given, so a fetch the caller +// has dropped can be collected and the tokens it fetched go with it. The +// default fetch is one function, and real callers still share one cache per +// identity through it. `run` stays in the inner key so two injected runners +// never serve each other's token. +const tokenCaches = new WeakMap() const callerIds = new WeakMap() let nextCallerId = 0 function callerId(fn) { @@ -299,15 +301,22 @@ function callerId(fn) { return callerIds.get(fn) } -export function tokenProvider(options = {}, run = runGcloud, request = fetch) { +function tokenState(options, run, request) { + let states = tokenCaches.get(request) + if (!states) tokenCaches.set(request, states = new Map()) const key = JSON.stringify([ cloudsdkConfig(options) || "", options.project || "", options.account || "", options.authMode || process.env.VERTEX_GCLOUD_AUTH_MODE || "auto", - callerId(run), callerId(request), + callerId(run), ]) + let state = states.get(key) // The first provider for an identity supplies its injected run and request. - if (!tokenCache.has(key)) tokenCache.set(key, { pending: undefined, cached: undefined, run, request }) - const state = tokenCache.get(key) + if (!state) states.set(key, state = { pending: undefined, cached: undefined, refreshing: undefined, run, request }) + return state +} + +export function tokenProvider(options = {}, run = runGcloud, request = fetch) { + const state = tokenState(options, run, request) // Only the OAuth response supplies an expiry; gcloud can print a token near // expiry, so its result is shared concurrently but never cached here. Resolve // auto mode on every call before using the cache, since ADC can be removed. @@ -355,6 +364,19 @@ export function tokenProvider(options = {}, run = runGcloud, request = fetch) { state.cached = undefined state.pending = undefined } + // A 401 drops the cached token and fetches again. Concurrent 401s share this + // promise. invalidate() and then getToken() does not: the second invalidate + // clears the in-flight entry the first refresh just started. + getToken.refresh = () => { + if (state.refreshing) return state.refreshing + state.cached = undefined + state.pending = undefined + const refreshing = getToken().finally(() => { + if (state.refreshing === refreshing) state.refreshing = undefined + }) + state.refreshing = refreshing + return refreshing + } return getToken } diff --git a/packages/gcp-ai/lib/history.mjs b/packages/gcp-ai/lib/history.mjs index 5d086cd..7957e31 100644 --- a/packages/gcp-ai/lib/history.mjs +++ b/packages/gcp-ai/lib/history.mjs @@ -86,16 +86,18 @@ export function harden(body) { // these rules are for. export const CONVERSATION_ROUTE = /:(?:generateContent|streamGenerateContent)$/ -// hardenRequest is request with its body hardened when it is a model call -// whose contents needed it; otherwise request as it came, body untouched. +// hardenRequest is the request to send. `body` is set only when this had to +// build a new one: that string is already in memory, so a 401 retry can send +// it again. Otherwise `request` is the one that came in, body untouched. export async function hardenRequest(request) { - if (request.method !== "POST" || !CONVERSATION_ROUTE.test(new URL(request.url).pathname)) return request + if (request.method !== "POST" || !CONVERSATION_ROUTE.test(new URL(request.url).pathname)) return { request } const text = await request.clone().text() let parsed - try { parsed = JSON.parse(text) } catch { return request } - const { body, changed } = harden(parsed) - if (!changed) return request + try { parsed = JSON.parse(text) } catch { return { request } } + const hardened = harden(parsed) + if (!hardened.changed) return { request } const headers = new Headers(request.headers) headers.delete("content-length") - return new Request(request, { body: JSON.stringify(body), headers }) + const body = JSON.stringify(hardened.body) + return { request: new Request(request, { body, headers }), body } } diff --git a/packages/gcp-ai/package.json b/packages/gcp-ai/package.json index e253e3f..e0fe268 100644 --- a/packages/gcp-ai/package.json +++ b/packages/gcp-ai/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-gcp-ai-auth", - "version": "0.2.1", + "version": "0.2.2", "description": "Vertex AI models and Google Cloud promotional credits, signed with your own gcloud / ADC login", "type": "module", "main": "./opencode.mjs", @@ -20,7 +20,7 @@ "scripts": { "check": "node --check index.mjs && node --check lib/browser.mjs && node --check lib/credentials.mjs && node --check lib/credits.mjs && node --check lib/endpoint.mjs && node --check lib/models.mjs && node --check lib/fetch_credits.mjs && node --check lib/history.mjs", "models": "node lib/fetch_credits.mjs models", - "test": "node --test test/*.test.mjs", + "test": "node --expose-gc --test test/*.test.mjs", "credits": "node lib/fetch_credits.mjs credits", "login": "node lib/fetch_credits.mjs login", "credentials": "node lib/fetch_credits.mjs credentials" diff --git a/packages/gcp-ai/test/plugin.test.mjs b/packages/gcp-ai/test/plugin.test.mjs index c0e07b0..525b64f 100644 --- a/packages/gcp-ai/test/plugin.test.mjs +++ b/packages/gcp-ai/test/plugin.test.mjs @@ -16,6 +16,13 @@ import { availableModels, toProviderModels } from "../lib/models.mjs" import { assertConsoleSession } from "../lib/browser.mjs" import { main } from "../lib/fetch_credits.mjs" +// Promise.withResolvers is Node 22. The suite still runs on Node 20. +function deferred() { + let resolve, reject + const promise = new Promise((res, rej) => { resolve = res; reject = rej }) + return { promise, resolve, reject } +} + const headers = ["Credit name", "Status", "Percent remaining", "Remaining value", "Original value", "Type", "Credit ID", "Usage scope", "Start date", "End date"] const row = (id, remaining, original = "$10.00", status = "Available", start = "July 15, 2026", end = "July 1, 2027") => ["Example benefit", status, "100%", remaining, original, "One-time", id, "All Google Cloud services", start, end] const now = Date.parse("2026-10-18T12:00:00Z") @@ -324,7 +331,7 @@ test("ADC tokens are cached only with a usable expiry beyond the renewal margin" test("token invalidation clears shared cached and pending tokens without restoring an old refresh", async () => { const fixture = await fakeGcloud() - const entered = Promise.withResolvers(), release = Promise.withResolvers() + const entered = deferred(), release = deferred() let pending try { await fixture.setAdc() @@ -1181,8 +1188,8 @@ test("every model answering 404 is a broken read, not an empty provider", { time test("closing a login waits for its pending identity work before fetch is restored", { timeout: 30000 }, async () => { const fixture = await fakeGcloud() const original = globalThis.fetch - const entered = Promise.withResolvers() - const release = Promise.withResolvers() + const entered = deferred() + const release = deferred() let login globalThis.fetch = async (...args) => { entered.resolve() @@ -1213,7 +1220,7 @@ for (const retryStatus of [200, 401]) { test(`a model 401 refreshes the cached token and retries once even when the retry returns ${retryStatus}`, async () => { const fixture = await fakeGcloud() const original = globalThis.fetch - const probed = Promise.withResolvers() + const probed = deferred() let tokens = 0, models = 0 const body = JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hello" }] }] }) globalThis.fetch = async (input) => { @@ -1256,11 +1263,233 @@ for (const retryStatus of [200, 401]) { }) } +test("a 401 replays an in-memory body without cloning it, and does not retry a stream", async () => { + const fixture = await fakeGcloud() + const originalFetch = globalThis.fetch + const originalClone = Request.prototype.clone + let clones = 0 + Request.prototype.clone = function () { + clones++ + return originalClone.call(this) + } + const probed = deferred() + let tokens = 0, models = 0, pulls = 0 + let mode = "bytes" + const bytes = new TextEncoder().encode(JSON.stringify({ contents: [{ role: "user", parts: [{ text: "bytes" }] }] })) + const hardened = JSON.stringify({ + contents: [ + { role: "user", parts: [{ text: "fix the bug" }] }, + { role: "model", parts: [{ text: "done" }] }, + ], + }) + globalThis.fetch = async (input) => { + const url = String(input?.url ?? input) + if (url === "https://oauth2.googleapis.com/token") return Response.json({ access_token: `token-${++tokens}`, expires_in: 3600 }) + if (url.includes("/v1/projects/")) { probed.resolve(); return Response.json({}, { status: 403 }) } + models++ + const token = input.headers.get("authorization") + const text = await input.text() + if (mode === "bytes") { + assert.equal(text, new TextDecoder().decode(bytes)) + if (models === 1) return Response.json({}, { status: 401 }) + assert.equal(token, "Bearer token-2") + return Response.json({ tokens: 1 }) + } + if (mode === "stream") return Response.json({}, { status: 401 }) + if (mode === "again") { + assert.equal(token, "Bearer token-3") + assert.equal(text, new TextDecoder().decode(bytes)) + return Response.json({ tokens: 1 }) + } + const sent = JSON.parse(text) + assert.equal(sent.contents.at(-1).role, "user", "the retry sends the hardened conversation") + assert.notEqual(text, hardened) + if (models === 1) return Response.json({}, { status: 401 }) + assert.equal(token, "Bearer token-4") + return Response.json({ ok: true }) + } + try { + await fixture.setAdc() + const hooks = await plugin() + const auth = { project: "body-project", accountId: "body@example.com", authMode: "adc", cloudsdkConfig: fixture.sdk } + const loaded = await hooks.auth.loader(async () => auth) + await probed.promise + await new Promise((resolve) => setImmediate(resolve)) + const countURL = `${loaded.baseURL}/models/gemini-2.5-flash:countTokens` + const counted = await loaded.fetch(countURL, { method: "POST", body: bytes, headers: { "content-type": "application/json" } }) + assert.equal(counted.status, 200) + assert.equal(models, 2) + assert.equal(tokens, 2) + assert.equal(clones, 0, "an in-memory body is replayed without cloning the request") + + mode = "stream" + models = 0 + const stream = new ReadableStream({ + pull(controller) { + pulls++ + controller.enqueue(bytes) + controller.close() + }, + }) + const refused = await loaded.fetch(countURL, { method: "POST", body: stream, duplex: "half", headers: { "content-type": "application/json" } }) + assert.equal(refused.status, 401) + assert.equal(models, 1, "a stream that cannot be replayed is not retried") + assert.equal(clones, 0, "a stream is not cloned to prepare a retry") + assert.equal(pulls, 1, "the stream is read once, not copied for a retry") + assert.deepEqual(await refused.json(), {}) + assert.equal(tokens, 2, "skipping the retry does not fetch a token up front") + + // The rejected token was dropped, so the next call mints a new one. + mode = "again" + models = 0 + const again = await loaded.fetch(countURL, { method: "POST", body: bytes, headers: { "content-type": "application/json" } }) + assert.equal(again.status, 200) + assert.equal(tokens, 3) + assert.equal(models, 1) + + mode = "harden" + models = 0 + const before = clones + const rewritten = await loaded.fetch(`${loaded.baseURL}/models/gemini-2.5-flash:generateContent`, { + method: "POST", body: hardened, headers: { "content-type": "application/json" }, + }) + assert.equal(rewritten.status, 200) + assert.equal(models, 2) + assert.equal(tokens, 4) + assert.equal(clones, before + 1, "reading the conversation to harden it is the only clone") + } finally { + Request.prototype.clone = originalClone + globalThis.fetch = originalFetch + await fixture.close() + } +}) + +test("concurrent 401s share one in-flight token refresh", async () => { + const fixture = await fakeGcloud() + const entered = deferred(), release = deferred() + let calls = 0 + try { + await fixture.setAdc() + const request = async () => { + const call = ++calls + if (call === 2) { entered.resolve(); await release.promise } + return { ok: true, json: async () => ({ access_token: `token-${call}`, expires_in: 3600 }) } + } + const run = () => assert.fail("OAuth should supply the token") + const options = { authMode: "adc", cloudsdkConfig: fixture.sdk, account: "refresh@example.com", project: "refresh-project" } + const first = tokenProvider(options, run, request) + const second = tokenProvider(options, run, request) + assert.equal(await first(), "token-1") + const one = first.refresh() + await entered.promise + const two = second.refresh() + assert.equal(one, two) + assert.equal(calls, 2) + release.resolve() + assert.equal(await one, "token-2") + assert.equal(await two, "token-2") + assert.equal(calls, 2) + assert.equal(await second(), "token-2") + } finally { release.resolve(); await fixture.close() } +}) + +test("concurrent model 401s refresh the cached token once", { timeout: 10000 }, async () => { + const fixture = await fakeGcloud() + const original = globalThis.fetch + const probed = deferred(), release = deferred(), refreshEntered = deferred() + let tokens = 0, models = 0 + const body = JSON.stringify({ contents: [{ role: "user", parts: [{ text: "hello" }] }] }) + globalThis.fetch = async (input) => { + const url = String(input?.url ?? input) + if (url === "https://oauth2.googleapis.com/token") { + const call = ++tokens + if (call >= 2) { refreshEntered.resolve(); await release.promise } + return Response.json({ access_token: `token-${call}`, expires_in: 3600 }) + } + if (url.includes("/v1/projects/")) { probed.resolve(); return Response.json({}, { status: 403 }) } + const attempt = ++models + const token = input.headers.get("authorization") + assert.equal(await input.text(), body) + if (token === "Bearer token-1") { + // The second refusal waits until a refresh is in flight, so its own + // refresh either joins that one or starts another we can count. + if (attempt === 2) await refreshEntered.promise + return Response.json({}, { status: 401 }) + } + assert.equal(token, "Bearer token-2") + return Response.json({ ok: true }) + } + try { + await fixture.setAdc() + const hooks = await plugin() + const auth = { project: "concurrent-project", accountId: "concurrent@example.com", authMode: "adc", cloudsdkConfig: fixture.sdk } + const loaded = await hooks.auth.loader(async () => auth) + await probed.promise + await new Promise((resolve) => setImmediate(resolve)) + assert.equal(tokens, 1) + const url = `${loaded.baseURL}/models/gemini-2.5-flash:generateContent` + const init = { method: "POST", body, headers: { "content-type": "application/json" } } + const pair = Promise.all([loaded.fetch(url, init), loaded.fetch(url, init)]) + await refreshEntered.promise + // A second refresh would be another token call, after the credential file is read. + let stableSince = Date.now(), last = tokens + const start = Date.now() + while (Date.now() - start < 1000) { + await new Promise((resolve) => setTimeout(resolve, 10)) + if (tokens !== last) { last = tokens; stableSince = Date.now() } + else if (Date.now() - stableSince >= 50) break + } + assert.equal(tokens, 2) + release.resolve() + const responses = await pair + assert.deepEqual(responses.map((response) => response.status), [200, 200]) + assert.equal(tokens, 2) + assert.equal(models, 4) + } finally { release.resolve(); globalThis.fetch = original; await fixture.close() } +}) + +test("token cache is per fetch function and does not keep a dropped fetch", async () => { + const fixture = await fakeGcloud() + try { + await fixture.setAdc() + const run = () => assert.fail("OAuth should supply the token") + const options = { authMode: "adc", account: "cache@example.com", project: "cache-project", cloudsdkConfig: fixture.sdk } + let a = 0, b = 0 + const fetchA = async () => ({ ok: true, json: async () => ({ access_token: `a-${++a}`, expires_in: 3600 }) }) + const fetchB = async () => ({ ok: true, json: async () => ({ access_token: `b-${++b}`, expires_in: 3600 }) }) + const first = tokenProvider(options, run, fetchA) + const again = tokenProvider(options, run, fetchA) + const otherRun = tokenProvider(options, () => assert.fail("other run"), fetchA) + const otherFetch = tokenProvider(options, run, fetchB) + assert.equal(await first(), "a-1") + assert.equal(await again(), "a-1") + assert.equal(await otherRun(), "a-2") + assert.equal(await otherFetch(), "b-1") + assert.equal(a, 2) + assert.equal(b, 1) + assert.equal(await first(), "a-1") + + let orphan = async () => ({ ok: true, json: async () => ({ access_token: "orphan", expires_in: 3600 }) }) + const ref = new WeakRef(orphan) + // The provider has to be out of this frame: its promise would otherwise + // keep the fetch alive until the test function itself returns. + await (async (request) => { + await tokenProvider({ ...options, account: "orphan@example.com" }, run, request)() + })(orphan) + orphan = undefined + if (typeof global.gc === "function") { + await new Promise((resolve) => setImmediate(resolve)) + for (let i = 0; i < 8; i++) global.gc() + assert.equal(ref.deref(), undefined) + } + } finally { await fixture.close() } +}) + for (const status of [429, 500, 502, 503, 504, "network", 401]) { test(`a background probe returning ${status} ${status === 401 ? "blocks" : "does not block"} a later model request`, async () => { const fixture = await fakeGcloud() const original = globalThis.fetch - const probed = Promise.withResolvers() + const probed = deferred() let models = 0, projectReads = 0 globalThis.fetch = async (input) => { const url = String(input.url ?? input) @@ -1296,7 +1525,7 @@ for (const status of [429, 500, 502, 503, 504, "network", 401]) { test("a probe refused a stale cached token refreshes it and does not block requests", async () => { const fixture = await fakeGcloud() const original = globalThis.fetch - const refreshed = Promise.withResolvers() + const refreshed = deferred() let tokens = 0, reads = 0, models = 0 globalThis.fetch = async (input, init) => { const url = String(input?.url ?? input) @@ -1339,7 +1568,7 @@ test("a probe refused a stale cached token refreshes it and does not block reque test("background endpoint probe does not block requests and shares failures", async () => { const original = globalThis.fetch - const entered = Promise.withResolvers(), release = Promise.withResolvers(), finished = Promise.withResolvers() + const entered = deferred(), release = deferred(), finished = deferred() let probes = 0, models = 0 globalThis.fetch = async (input) => { const url = String(input.url ?? input) @@ -1386,7 +1615,7 @@ test("account settings beat the row, and row settings beat environment defaults" billingAccount: "DDDDDD-EEEEEE-FFFFFF", profile: join(fixture.directory, "account-profile"), cloudsdkConfig: join(fixture.directory, "account-sdk"), } const requests = [] - const probesFinished = Promise.withResolvers() + const probesFinished = deferred() let probes = 0 globalThis.fetch = async (input) => { const url = String(input.url ?? input)