-
Notifications
You must be signed in to change notification settings - Fork 402
fix(clerk-js): Correct init retry logic [WIP] #7128
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
base: main
Are you sure you want to change the base?
Conversation
|
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughThis PR introduces a new retry utility with exponential backoff and jitter, refactors the Clerk initialization flow to leverage retry logic for resilience against transient failures, updates error handling to propagate root causes, and adds comprehensive tests for both retry behavior and initialization recovery scenarios. Changes
Sequence Diagram(s)sequenceDiagram
participant App as Application
participant Clerk as Clerk.load()
participant Retry as withRetry wrapper
participant Init as initializeClerk
participant Env as Environment API
participant Client as Client API
App->>Clerk: load()
Clerk->>Retry: invoke(maxAttempts: 2, jitter: true)
loop Retry Attempts
Retry->>Init: execute attempt
Init->>Env: fetch/update environment
alt Env Success
Env-->>Init: environment data
Init->>Client: fetch/update client
alt Client Success
Client-->>Init: client data
Init-->>Retry: success ✓
Note over Retry: Ready state reached
else 4xx Client Error
Client-->>Init: error
Init-->>Retry: throw (no retry)
else Network Error
Client-->>Init: error
Init-->>Retry: error (check shouldRetry)
end
else Fetch Failed
Env-->>Init: error
Init->>Env: use cached snapshot
Init->>Client: attempt with cached env
Init-->>Retry: error or retry
end
alt shouldRetry: true & attempt < maxAttempts
Retry->>Retry: calculate backoff with jitter
Retry->>Retry: sleep(backoff)
else shouldRetry: false or final attempt
Retry-->>Clerk: throw error
Clerk-->>App: initialization failed
end
end
Retry-->>Clerk: initialization succeeded
Clerk->>Clerk: mount components, set ready
Clerk-->>App: ready
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Poem
Pre-merge checks and finishing touches✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
f9b5aa2 to
aec61e8
Compare
@clerk/agent-toolkit
@clerk/astro
@clerk/backend
@clerk/chrome-extension
@clerk/clerk-js
@clerk/dev-cli
@clerk/elements
@clerk/clerk-expo
@clerk/expo-passkeys
@clerk/express
@clerk/fastify
@clerk/localizations
@clerk/nextjs
@clerk/nuxt
@clerk/clerk-react
@clerk/react-router
@clerk/remix
@clerk/shared
@clerk/tanstack-react-start
@clerk/testing
@clerk/themes
@clerk/types
@clerk/upgrade
@clerk/vue
commit: |
|
Found 4 test failures on Blacksmith runners:
|
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.
Actionable comments posted: 2
📜 Review details
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Disabled knowledge base sources:
- Linear integration is disabled by default for public repositories
You can enable these sources in your CodeRabbit configuration.
📒 Files selected for processing (6)
packages/clerk-js/src/core/__tests__/clerk.test.ts(3 hunks)packages/clerk-js/src/core/clerk.ts(2 hunks)packages/clerk-js/src/core/errors.ts(1 hunks)packages/clerk-js/src/utils/__tests__/retry.test.ts(1 hunks)packages/clerk-js/src/utils/retry.ts(1 hunks)packages/clerk-js/tsconfig.json(1 hunks)
🧰 Additional context used
📓 Path-based instructions (10)
**/*.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
**/*.{js,jsx,ts,tsx}: All code must pass ESLint checks with the project's configuration
Follow established naming conventions (PascalCase for components, camelCase for variables)
Maintain comprehensive JSDoc comments for public APIs
Use dynamic imports for optional features
All public APIs must be documented with JSDoc
Provide meaningful error messages to developers
Include error recovery suggestions where applicable
Log errors appropriately for debugging
Lazy load components and features when possible
Implement proper caching strategies
Use efficient data structures and algorithms
Profile and optimize critical paths
Validate all inputs and sanitize outputs
Implement proper logging with different levels
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{js,jsx,ts,tsx,json,css,scss,md,yaml,yml}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use Prettier for consistent code formatting
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/tsconfig.jsonpackages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{ts,tsx,d.ts}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Packages should export TypeScript types alongside runtime code
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
Use proper TypeScript error types
**/*.{ts,tsx}: Always define explicit return types for functions, especially public APIs
Use proper type annotations for variables and parameters where inference isn't clear
Avoidanytype - preferunknownwhen type is uncertain, then narrow with type guards
Useinterfacefor object shapes that might be extended
Usetypefor unions, primitives, and computed types
Preferreadonlyproperties for immutable data structures
Useprivatefor internal implementation details
Useprotectedfor inheritance hierarchies
Usepublicexplicitly for clarity in public APIs
Preferreadonlyfor properties that shouldn't change after construction
Prefer composition and interfaces over deep inheritance chains
Use mixins for shared behavior across unrelated classes
Implement dependency injection for loose coupling
Let TypeScript infer when types are obvious
Useconst assertionsfor literal types:as const
Usesatisfiesoperator for type checking without widening
Use mapped types for transforming object types
Use conditional types for type-level logic
Leverage template literal types for string manipulation
Use ES6 imports/exports consistently
Use default exports sparingly, prefer named exports
Use type-only imports:import type { ... } from ...
Noanytypes without justification
Proper error handling with typed errors
Consistent use ofreadonlyfor immutable data
Proper generic constraints
No unused type parameters
Proper use of utility types instead of manual type construction
Type-only imports where possible
Proper tree-shaking friendly exports
No circular dependencies
Efficient type computations (avoid deep recursion)
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
**/*.{js,ts,tsx,jsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Support multiple Clerk environment variables (CLERK_, NEXT_PUBLIC_CLERK_, etc.) for configuration.
Files:
packages/clerk-js/src/core/errors.tspackages/clerk-js/src/core/clerk.tspackages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/utils/retry.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
packages/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Unit tests should use Jest or Vitest as the test runner.
Files:
packages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
packages/{clerk-js,elements,themes}/**/*.{test,spec}.{js,jsx,ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Visual regression testing should be performed for UI components.
Files:
packages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
**/__tests__/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/typescript.mdc)
**/__tests__/**/*.{ts,tsx}: Create type-safe test builders/factories
Use branded types for test isolation
Implement proper mock types that match interfaces
Files:
packages/clerk-js/src/utils/__tests__/retry.test.tspackages/clerk-js/src/core/__tests__/clerk.test.ts
packages/*/tsconfig.json
📄 CodeRabbit inference engine (.cursor/rules/monorepo.mdc)
Type checking must be performed with TypeScript and publint.
Files:
packages/clerk-js/tsconfig.json
🧬 Code graph analysis (3)
packages/clerk-js/src/core/clerk.ts (7)
packages/clerk-js/src/core/resources/Environment.ts (1)
Environment(17-100)packages/clerk-js/src/utils/localStorage.ts (1)
SafeLocalStorage(17-68)packages/shared/src/errors/helpers.ts (3)
is4xxError(33-36)isNetworkError(43-47)isClerkRuntimeError(83-85)packages/clerk-js/src/core/jwt-client.ts (1)
createClientFromJwt(19-100)packages/clerk-js/src/utils/errors.ts (1)
isError(4-6)packages/clerk-js/src/utils/retry.ts (1)
withRetry(19-46)packages/clerk-js/src/core/errors.ts (1)
clerkErrorInitFailed(19-21)
packages/clerk-js/src/utils/__tests__/retry.test.ts (1)
packages/clerk-js/src/utils/retry.ts (1)
withRetry(19-46)
packages/clerk-js/src/core/__tests__/clerk.test.ts (2)
packages/clerk-js/src/core/clerk.ts (1)
Clerk(198-2989)packages/clerk-js/src/core/auth/AuthCookieService.ts (1)
AuthCookieService(40-255)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (28)
- GitHub Check: Integration Tests (nextjs, chrome, 16)
- GitHub Check: Integration Tests (nextjs, chrome, 15)
- GitHub Check: Integration Tests (astro, chrome)
- GitHub Check: Integration Tests (react-router, chrome)
- GitHub Check: Integration Tests (nuxt, chrome)
- GitHub Check: Integration Tests (handshake:staging, chrome)
- GitHub Check: Integration Tests (machine, chrome)
- GitHub Check: Integration Tests (quickstart, chrome, 16)
- GitHub Check: Integration Tests (tanstack-react-start, chrome)
- GitHub Check: Integration Tests (quickstart, chrome, 15)
- GitHub Check: Integration Tests (custom, chrome)
- GitHub Check: Integration Tests (vue, chrome)
- GitHub Check: Integration Tests (expo-web, chrome)
- GitHub Check: Integration Tests (billing, chrome)
- GitHub Check: Integration Tests (sessions, chrome)
- GitHub Check: Integration Tests (nextjs, chrome, 14)
- GitHub Check: Integration Tests (localhost, chrome)
- GitHub Check: Integration Tests (handshake, chrome)
- GitHub Check: Integration Tests (ap-flows, chrome)
- GitHub Check: Integration Tests (generic, chrome)
- GitHub Check: Integration Tests (sessions:staging, chrome)
- GitHub Check: Integration Tests (elements, chrome)
- GitHub Check: Integration Tests (express, chrome)
- GitHub Check: Publish with pkg-pr-new
- GitHub Check: Unit Tests (22, **)
- GitHub Check: Static analysis
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/tsconfig.json (1)
10-10: Cause-enabled lib entry looks goodAdding
es2022.errorkeeps the compiler aware ofErroroptions withcause, aligning tsconfig with the new error handling.packages/clerk-js/src/core/errors.ts (1)
19-21: Wrapping the init failure with a cause is spot onPassing the underlying error as
causesharpens debugging and meshes with the retry utilities.packages/clerk-js/src/utils/__tests__/retry.test.ts (1)
1-156: Great coverage on retry behaviorThe suite nails first-try success, retry gating, async predicates, and backoff timing—including jitter—so regressions here should be caught quickly.
packages/clerk-js/src/core/__tests__/clerk.test.ts (1)
1-282: Retry regression tests read wellThe new fixtures and expectations around dev-browser recovery and network error propagation exercise the retry path end-to-end, which should keep future init changes safe.
| const initEnvironmentPromise = Environment.getInstance() | ||
| .fetch({ touch: shouldTouchEnv }) | ||
| .then(res => this.updateEnvironment(res)) | ||
| .catch(() => { | ||
| ++initializationDegradedCounter; | ||
| const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>( | ||
| CLERK_ENVIRONMENT_STORAGE_ENTRY, | ||
| null, | ||
| ); | ||
|
|
||
| try { | ||
| const initEnvironmentPromise = Environment.getInstance() | ||
| .fetch({ touch: shouldTouchEnv }) | ||
| .then(res => this.updateEnvironment(res)) | ||
| .catch(() => { | ||
| ++initializationDegradedCounter; | ||
| const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>( | ||
| CLERK_ENVIRONMENT_STORAGE_ENTRY, | ||
| null, | ||
| ); | ||
| if (environmentSnapshot) { | ||
| this.updateEnvironment(new Environment(environmentSnapshot)); | ||
| } | ||
| }); |
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.
Don’t swallow the environment fetch failure when no cache exists.
When the very first /environment request fails (e.g., transient network blip on a cold start), this catch clause increments the degraded counter, finds no snapshot in localStorage, and then resolves. Because the error never bubbles out, withRetry treats the attempt as a success and skips the second pass, so load() completes with this.environment still holding the empty singleton. That leaves the UI without required config until the user hard refreshes. Please rethrow when we can’t hydrate from cache so the retry wrapper can actually run:
- .catch(() => {
+ .catch(error => {
++initializationDegradedCounter;
const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>(
CLERK_ENVIRONMENT_STORAGE_ENTRY,
null,
);
if (environmentSnapshot) {
this.updateEnvironment(new Environment(environmentSnapshot));
+ return;
}
+
+ throw error;
});📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const initEnvironmentPromise = Environment.getInstance() | |
| .fetch({ touch: shouldTouchEnv }) | |
| .then(res => this.updateEnvironment(res)) | |
| .catch(() => { | |
| ++initializationDegradedCounter; | |
| const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>( | |
| CLERK_ENVIRONMENT_STORAGE_ENTRY, | |
| null, | |
| ); | |
| try { | |
| const initEnvironmentPromise = Environment.getInstance() | |
| .fetch({ touch: shouldTouchEnv }) | |
| .then(res => this.updateEnvironment(res)) | |
| .catch(() => { | |
| ++initializationDegradedCounter; | |
| const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>( | |
| CLERK_ENVIRONMENT_STORAGE_ENTRY, | |
| null, | |
| ); | |
| if (environmentSnapshot) { | |
| this.updateEnvironment(new Environment(environmentSnapshot)); | |
| } | |
| }); | |
| const initEnvironmentPromise = Environment.getInstance() | |
| .fetch({ touch: shouldTouchEnv }) | |
| .then(res => this.updateEnvironment(res)) | |
| .catch(error => { | |
| +initializationDegradedCounter; | |
| const environmentSnapshot = SafeLocalStorage.getItem<EnvironmentJSONSnapshot | null>( | |
| CLERK_ENVIRONMENT_STORAGE_ENTRY, | |
| null, | |
| ); | |
| if (environmentSnapshot) { | |
| this.updateEnvironment(new Environment(environmentSnapshot)); | |
| return; | |
| } | |
| throw error; | |
| }); |
🤖 Prompt for AI Agents
In packages/clerk-js/src/core/clerk.ts around lines 2575 to 2588, the catch
block for Environment.getInstance().fetch currently swallows errors when no
cached snapshot exists causing withRetry to think the attempt succeeded; change
the catch to receive the error (catch(err)) and after incrementing
initializationDegradedCounter and attempting to read the local snapshot, if no
snapshot is found rethrow the original error (or wrap and throw it) so the retry
wrapper can run; if a snapshot exists, continue to hydrate environment as before
and do not rethrow.
| export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> { | ||
| let lastError: unknown; | ||
|
|
||
| for (let attempt = 0; attempt < options.maxAttempts; attempt++) { | ||
| try { | ||
| return await fn(); | ||
| } catch (error) { | ||
| lastError = error; | ||
|
|
||
| const shouldRetry = await Promise.resolve(options.shouldRetry(error)); | ||
|
|
||
| if (!shouldRetry) { | ||
| throw error; | ||
| } | ||
|
|
||
| const isLastAttempt = attempt === options.maxAttempts - 1; | ||
|
|
||
| if (isLastAttempt) { | ||
| throw error; | ||
| } | ||
|
|
||
| const backoffMs = calculateBackoff(attempt, options.jitter ?? true); | ||
| await sleep(backoffMs); | ||
| } | ||
| } | ||
|
|
||
| throw lastError; |
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.
Guard against zero maxAttempts before looping
If a caller passes maxAttempts = 0, the loop body never runs, lastError stays undefined, and the final throw lastError ends up throwing undefined, masking the configuration bug. Adding an upfront guard keeps the failure explicit and avoids throwing a useless value.
-export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> {
- let lastError: unknown;
+export async function withRetry<T>(fn: () => Promise<T>, options: RetryOptions): Promise<T> {
+ if (options.maxAttempts < 1) {
+ throw new Error('withRetry requires maxAttempts to be at least 1');
+ }
+
+ let lastError: unknown;🤖 Prompt for AI Agents
In packages/clerk-js/src/utils/retry.ts around lines 19 to 45, the function can
throw undefined when options.maxAttempts is 0 because the loop never runs and
lastError stays undefined; add an upfront guard that validates
options.maxAttempts is a positive integer (e.g., if
(!Number.isInteger(options.maxAttempts) || options.maxAttempts <= 0) throw new
Error("withRetry: maxAttempts must be a positive integer")), so callers get a
clear, immediate error instead of throwing undefined.
Description
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Bug Fixes
Tests