PromptBase
PromptBase SelectGet Select
Close icon
General
Home
Marketplace
Create
Hire
Login
Chat
Sell
Explore

Skill Details

Runtime
(claude-5-5-opus)
Example user message
[userMessage]: /overmind Fix a bug in our TypeScript API client wrapper below. Right now, when a request fails with HTTP 401, it refreshes the auth token and retries—but if 5 requests fail with 401 simultaneously, it triggers 5 concurrent token refreshes and invalidates the session. Fix the thundering-herd refresh bug while ensuring we never enter an infinite retry loop if the refreshed token still returns 401, and keep existing AbortSignal timeout handling working. export class ApiClient { private token: string; constructor(initialToken: string, private refreshFn: () => Promise<string>) { this.token = initialToken; } async fetchWithAuth(url: string, init: RequestInit = {}): Promise<Response> { const res = await fetch(url, { ...init, headers: { ...init.headers, Authorization: `Bearer ${this.token}` }, }); if (res.status === 401) { this.token = await this.refreshFn(); return this.fetchWithAuth(url, init); } return res; } }
Example agent response
### 1. Problem Framing & Boundary Conditions * **Objective:** Refactor `ApiClient.fetchWithAuth` to eliminate the thundering-herd concurrent token refresh bug, guarantee termination (no infinite 401 retry loop), and preserve full `AbortSignal` timeout and cancellation semantics across the entire request lifecycle. * **Locked Constraints & Invariants:** * Public class name (`ApiClient`), constructor signature (`constructor(initialToken: string, private refreshFn: () => Promise<string>)`), and method signature (`async fetchWithAuth(url: string, init: RequestInit = {}): Promise<Response>`) must remain 100% backward-compatible. * Non-401 responses (2xx, 3xx, 400, 403, 404, 5xx) must be returned immediately without invoking `refreshFn`. * Caller-supplied `RequestInit` options (method, body, headers, credentials, `signal`, etc.) must be preserved on both the initial request and the retry without mutating the caller's `init` object. * Only one `refreshFn()` invocation may be in flight at any time; concurrent 401s must coalesce onto that single refresh. * If the retried request still returns HTTP 401, `fetchWithAuth` must return that 401 `Response` rather than retrying again. * **Explicit Assumptions & Edge Boundaries:** * **Stale-Token Race:** A request dispatched with `token_v0` may receive its 401 response *after* another concurrent request has already completed a refresh to `token_v1` and cleared the in-flight promise. That late-arriving 401 must reuse `token_v1` directly rather than triggering a redundant second refresh. * **Shared Refresh vs. Per-Request Abort:** A caller's `AbortSignal` (e.g., `AbortSignal.timeout(3000)`) may fire while awaiting the shared `refreshFn()` promise. That specific caller must reject immediately with `signal.reason`, without aborting `refreshFn()` for other concurrent callers. * **Refresh Failure Recovery:** If `refreshFn()` rejects, all awaiting callers receive the rejection, and the in-flight lock is cleared so future requests are not permanently stuck on a rejected promise. * **Header Polymorphism:** `init.headers` may be a `Headers` instance, a `[string, string][]` tuple array, a plain `Record<string, string>`, or `undefined`. Using `new Headers(init.headers)` prevents the silent header-loss bug present in `{ ...init.headers }`. * **Connection Hygiene:** When discarding the initial 401 `Response` before retrying, canceling its unread body (`res.body?.cancel().catch(() => {})`) prevents socket/connection leaks in runtimes like Node.js (Undici). --- ### 2. First-Principles Reasoning & Deep Analysis #### A. Decomposing the Thundering-Herd & Stale-Token Race A naive single-flight lock (`if (!this.refreshPromise) this.refreshPromise = this.refreshFn()`) solves simultaneous 401s but fails under a staggered race: 1. Requests $R_1$ and $R_2$ both start at $t_0$ using `token_A` (`tokenVersion = 0`). 2. At $t_1$, $R_1$ receives 401, invokes `refreshFn()`, receives `token_B` (`tokenVersion = 1`), and clears `this.refreshPromise = null` in `finally`. 3. At $t_2$, $R_2$ (which was sent with `token_A`) receives its 401. Because `this.refreshPromise` is already `null`, a naive lock triggers a **second** `refreshFn()`, potentially invalidating `token_B`. **Resolution:** Track a monotonically increasing `private tokenVersion = 0`. Each request captures `const requestTokenVersion = this.tokenVersion` *before* calling `fetch`. On 401: * If `this.tokenVersion !== requestTokenVersion`, a refresh has already succeeded since this request was dispatched. Skip `refreshFn()` and proceed directly to the retry with the updated `this.token`. * If `this.tokenVersion === requestTokenVersion`, call `this.refreshTokenSingleFlight()`, which returns the existing `this.refreshPromise` if one is active, or creates one, updates `this.token` and increments `this.tokenVersion` on fulfillment, and clears `this.refreshPromise = null` in `finally`. Using a version counter rather than comparing token strings (`this.token !== usedToken`) also remains correct in the edge case where an auth server or test double returns the same token string. #### B. Structural Termination (Zero Infinite Loops) The original code used unbounded recursion (`return this.fetchWithAuth(url, init)`). Removing recursion entirely and structuring `fetchWithAuth` as a two-phase linear flow guarantees at most **one** retry per call: 1. Execute initial `fetch` with current token. If `res.status !== 401`, return `res`. 2. Ensure token is refreshed (respecting `init.signal`), then execute **one** retry `fetch` with the refreshed token and return its `Response` unconditionally—even if it is 401. #### C. Preserving `AbortSignal` Semantics During Shared Refresh Passing `init` to both `fetch` calls handles aborts *during* network I/O, but leaves a blind spot *between* the two `fetch` calls: if `refreshFn()` is slow (e.g., 10s) and Request 1 has `AbortSignal.timeout(2000)`, a bare `await this.refreshPromise` would ignore the 2s timeout and hang for 10s. To fix this without canceling the shared refresh for other callers, wrap the `await` in `awaitWithSignal(promise, init.signal)`: * If `!signal`, return `promise` directly (zero overhead). * If `signal.aborted`, immediately return `Promise.reject(signal.reason)`. * Otherwise, attach a one-time `'abort'` listener that rejects the wrapper promise with `signal.reason`, and remove that listener in `promise.finally(...)` so neither the `AbortSignal` nor the promise retains a dangling closure. --- ### 3. Conflict & Regression Audit | Audit Dimension | Scope Checked | Result | Verification Proof | | --- | --- | --- | --- | | **Logical Conflict Check** | Prose derivation vs. TypeScript implementation | PASS | `tokenVersion` is captured before the initial `fetch`, checked against `this.tokenVersion` on 401, incremented only after `refreshFn()` resolves, and `refreshPromise` is cleared in `finally`—matching Section 2 line-for-line. | | **Result Regression Check** | Public API, non-401 paths, `RequestInit`, `AbortSignal` | PASS | Class name, constructor signature, and `fetchWithAuth(url, init)` signature are unchanged. Non-401 responses return immediately. `init.signal` is passed to both `fetch` calls and respected during the refresh wait. `new Headers(init.headers)` preserves all header formats without mutating caller input. | | **Edge-Case & Failure Audit** | Simultaneous 401s, staggered 401s, persistent 401, refresh rejection, mid-refresh abort | PASS | 5 simultaneous 401s share 1 `refreshPromise`; staggered 401s see `this.tokenVersion !== requestTokenVersion` and skip refresh; persistent 401 returns the second `Response` with zero recursion; `refreshFn()` rejection clears `refreshPromise` in `finally` and propagates to waiters; mid-refresh abort rejects only the aborted caller and cleans up its event listener. | | **Completeness & Zero-Shortcut Audit** | Full TypeScript implementation, zero placeholders, English parity | PASS | Complete, strict-TypeScript-compatible class with helper methods, zero `TODO`s or elisions, and 100% English output matching the prompt. | --- ### 4. Final Verified Deliverable ```typescript export class ApiClient { private token: string; private tokenVersion = 0; private refreshPromise: Promise<string> | null = null; constructor(initialToken: string, private refreshFn: () => Promise<string>) { this.token = initialToken; } async fetchWithAuth(url: string, init: RequestInit = {}): Promise<Response> { const requestTokenVersion = this.tokenVersion; const res = await fetch(url, this.withAuthHeader(init, this.token)); if (res.status !== 401) { return res; } // Release the unread 401 response body to avoid leaking underlying sockets. res.body?.cancel().catch(() => {}); // Only trigger or join a refresh if the token has not already been rotated // since this request was dispatched. if (this.tokenVersion === requestTokenVersion) { await this.awaitWithSignal(this.refreshTokenSingleFlight(), init.signal); } else if (init.signal?.aborted) { throw init.signal.reason; } // Single bounded retry: if this still returns 401, return it to the caller. return fetch(url, this.withAuthHeader(init, this.token)); } private withAuthHeader(init: RequestInit, token: string): RequestInit { const headers = new Headers(init.headers); headers.set("Authorization", `Bearer ${token}`); return { ...init, headers, }; } private refreshTokenSingleFlight(): Promise<string> { if (!this.refreshPromise) { this.refreshPromise = this.refreshFn() .then((newToken) => { this.token = newToken; this.tokenVersion += 1; return newToken; }) .finally(() => { this.refreshPromise = null; }); } return this.refreshPromise; } private awaitWithSignal<T>( promise: Promise<T>, signal?: AbortSignal | null ): Promise<T> { if (!signal) { return promise; } if (signal.aborted) { return Promise.reject(signal.reason); } return new Promise<T>((resolve, reject) => { const onAbort = () => { reject(signal.reason); }; signal.addEventListener("abort", onAbort, { once: true }); promise.then( (value) => { signal.removeEventListener("abort", onAbort); resolve(value); }, (error) => { signal.removeEventListener("abort", onAbort); reject(error); } ); }); } } ```
Add to Cart
Instant accessInstant access
Usage rightsCommercial use
Money-back guaranteeMoney‑back
By purchasing this skill, you agree to our terms of service
CLAUDE-5-5-OPUS
Tested icon
Guide icon
Free credits icon
Push your LLM past its factory limits. Overmind disables lazy heuristics and shallow answers, forcing maximum-depth reasoning on every prompt. It locks the model into a rigorous multi-step decomposition and edge-case stress test, verifying every logical step before generating a single line of final output. Zero shortcuts, zero placeholders, and zero external dependencies—engineered for Gemini CLI, Gems, AI Studio, Claude Code, Cursor, and Windsurf.
...more
Added 1 week ago
Report
Browse Marketplace