-
Notifications
You must be signed in to change notification settings - Fork 440
feat(e2e): add retry for transient BAPI errors in integration tests #8081
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
jacekradko
wants to merge
12
commits into
main
Choose a base branch
from
jacek/rate-limit-retry-bapi
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+96
−1
Open
Changes from all commits
Commits
Show all changes
12 commits
Select commit
Hold shift + click to select a range
5e92535
feat(integration): add rate-limit retry wrapper for Clerk backend client
jacekradko 30a2889
feat(integration): apply rate-limit retry wrapper to BAPI client
jacekradko 6db0806
fix(integration): avoid double invocation in rate-limit proxy
jacekradko c173fb8
fix(integration): handle retryAfter edge cases in rate-limit wrapper
jacekradko da6b998
feat(e2e): add rate-limit retry summary to teardown output
jacekradko 1e7b53e
Merge branch 'main' into jacek/rate-limit-retry-bapi
jacekradko 532bd76
Merge branch 'main' into jacek/rate-limit-retry-bapi
jacekradko 6b39c0f
Merge branch 'main' into jacek/rate-limit-retry-bapi
jacekradko 12355ba
Merge branch 'main' into jacek/rate-limit-retry-bapi
jacekradko 61c7ec6
feat(e2e): retry on transient server errors (502, 503, 504)
jacekradko d4f44b2
Merge branch 'main' into jacek/rate-limit-retry-bapi
jacekradko da7d936
style: format retryableClerkClient
jacekradko File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| import type { ClerkClient } from '@clerk/backend'; | ||
| import { isClerkAPIResponseError } from '@clerk/shared/error'; | ||
|
|
||
| const MAX_RETRIES = 5; | ||
| const BASE_DELAY_MS = 1000; | ||
| const JITTER_MAX_MS = 500; | ||
| const MAX_RETRY_DELAY_MS = 30_000; | ||
| const RETRYABLE_STATUS_CODES = new Set([429, 502, 503, 504]); | ||
|
|
||
| const retryStats = { totalRetries: 0, callsRetried: new Set<string>() }; | ||
|
|
||
| function sleep(ms: number): Promise<void> { | ||
| return new Promise(resolve => setTimeout(resolve, ms)); | ||
| } | ||
|
|
||
| function getRetryDelay(error: unknown, attempt: number): number { | ||
| if (isClerkAPIResponseError(error) && typeof error.retryAfter === 'number') { | ||
| return Math.min(error.retryAfter * 1000, MAX_RETRY_DELAY_MS); | ||
| } | ||
| return BASE_DELAY_MS * Math.pow(2, attempt) + Math.random() * JITTER_MAX_MS; | ||
| } | ||
|
|
||
| function recordRetry(path: string): void { | ||
| retryStats.totalRetries++; | ||
| retryStats.callsRetried.add(path); | ||
| } | ||
|
|
||
| export function printRetrySummary(): void { | ||
| if (retryStats.totalRetries === 0) { | ||
| console.log('[Retry] No retries occurred during this run.'); | ||
| return; | ||
| } | ||
| const methods = [...retryStats.callsRetried].join(', '); | ||
| console.warn( | ||
| `[Retry] Summary: ${retryStats.totalRetries} retries across ${retryStats.callsRetried.size} API calls (${methods})`, | ||
| ); | ||
| } | ||
|
|
||
| async function retryOnFailure<T>(firstAttempt: Promise<T>, fn: () => Promise<T>, path: string): Promise<T> { | ||
| for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { | ||
| try { | ||
| return attempt === 0 ? await firstAttempt : await fn(); | ||
| } catch (error) { | ||
| const isRetryable = isClerkAPIResponseError(error) && RETRYABLE_STATUS_CODES.has(error.status); | ||
| if (!isRetryable || attempt === MAX_RETRIES) { | ||
| throw error; | ||
| } | ||
| recordRetry(path); | ||
| const delayMs = getRetryDelay(error, attempt); | ||
| console.warn( | ||
| `[Retry] ${error.status} for ${path}, attempt ${attempt + 1}/${MAX_RETRIES}, waiting ${Math.round(delayMs)}ms`, | ||
| ); | ||
| await sleep(delayMs); | ||
| } | ||
| } | ||
| // Unreachable, but satisfies TypeScript | ||
| throw new Error('Unreachable'); | ||
| } | ||
|
|
||
| function createProxy(target: unknown, path: string[] = []): unknown { | ||
| if (target === null || (typeof target !== 'object' && typeof target !== 'function')) { | ||
| return target; | ||
| } | ||
|
|
||
| return new Proxy(target as object, { | ||
| get(obj, prop, receiver) { | ||
| if (typeof prop === 'symbol') { | ||
| return Reflect.get(obj, prop, receiver); | ||
| } | ||
| const value = Reflect.get(obj, prop, receiver); | ||
| if (typeof value === 'function') { | ||
| return (...args: unknown[]) => { | ||
| const result = value.apply(obj, args); | ||
| // Only wrap promises (async API calls), pass through sync returns | ||
| if (result && typeof result === 'object' && typeof result.then === 'function') { | ||
| const fullPath = [...path, prop].join('.'); | ||
| return retryOnFailure(result, () => value.apply(obj, args), fullPath); | ||
| } | ||
| return result; | ||
| }; | ||
| } | ||
| if (typeof value === 'object' && value !== null) { | ||
| return createProxy(value, [...path, prop]); | ||
| } | ||
| return value; | ||
| }, | ||
| }); | ||
| } | ||
|
|
||
| export function withRetry(client: ClerkClient): ClerkClient { | ||
| return createProxy(client) as ClerkClient; | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: clerk/javascript
Length of output: 105
Add tests for the retry utility.
This new utility contains significant retry logic (exponential backoff, retry conditions, status code filtering, proxy-based interception) that should have test coverage. Consider tests for:
retryAfterheader handling🤖 Prompt for AI Agents