-
Notifications
You must be signed in to change notification settings - Fork 402
feat(clerk-js): Update SessionTokenCache only if un-cached #7105
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
Conversation
🦋 Changeset detectedLatest commit: bed5cdf The changes in this PR will be included in the next version bump. This PR includes changesets to release 3 packages
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
WalkthroughSession token caching logic was tightened: hydrateCache returns early on null, computes tokenId once, and only writes the cache when an entry is absent. Tests were added/updated to verify cache deduplication and that SessionTokenCache.set always broadcasts via postMessage. Changes
Sequence Diagram(s)sequenceDiagram
participant Session
participant TokenCache as SessionTokenCache
participant Broadcaster as postMessage
rect rgb(230, 245, 255)
Session->>Session: hydrateCache(token)
alt token is null
Session-->>Session: return (no cache ops)
else token present
Session->>Session: compute tokenId (local)
Session->>TokenCache: get(tokenId)
alt cache entry exists
TokenCache-->>Session: entry found
Session-->>TokenCache: (skip set)
else no cache entry
Session->>TokenCache: set(tokenId, { tokenPromise })
TokenCache-->>Session: set resolved
end
end
end
sequenceDiagram
participant Caller
participant TokenCache as SessionTokenCache
participant Broadcaster as postMessage
Caller->>TokenCache: set(tokenId, payload)
TokenCache->>Broadcaster: postMessage({ tokenId }) %% broadcast always expected by test
Broadcaster-->>Caller: acknowledged
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
Comment |
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: 0
🧹 Nitpick comments (1)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
281-314: Consider verifying cache state in addition to broadcast behavior.The test correctly verifies that
postMessageis called on eachsetoperation. However, it doesn't verify whether the cache entry itself is updated on the second call. Given the PR objective is about updating the cache only when un-cached, it would strengthen this test to also assert the cache state.Consider adding cache state verification:
SessionTokenCache.set({ tokenId, tokenResolver }); await Promise.resolve(); expect(mockBroadcastChannel.postMessage).toHaveBeenCalledTimes(1); const firstCall = mockBroadcastChannel.postMessage.mock.calls[0][0]; expect(firstCall.tokenId).toBe(tokenId); + expect(SessionTokenCache.size()).toBe(1); + const firstCacheEntry = SessionTokenCache.get({ tokenId }); mockBroadcastChannel.postMessage.mockClear(); const tokenResolver2 = Promise.resolve( new Token({ id: tokenId, jwt: mockJwt, object: 'token', }) as TokenResource, ); SessionTokenCache.set({ tokenId, tokenResolver: tokenResolver2 }); await Promise.resolve(); expect(mockBroadcastChannel.postMessage).toHaveBeenCalledTimes(1); + expect(SessionTokenCache.size()).toBe(1); + const secondCacheEntry = SessionTokenCache.get({ tokenId }); + // Verify whether cache entry was replaced or kept (depending on expected behavior)
📜 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 (3)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts(1 hunks)packages/clerk-js/src/core/resources/Session.ts(1 hunks)packages/clerk-js/src/core/resources/__tests__/Session.test.ts(12 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.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/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/__tests__/tokenCache.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/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/__tests__/tokenCache.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/resources/__tests__/Session.test.tspackages/clerk-js/src/core/resources/Session.tspackages/clerk-js/src/core/__tests__/tokenCache.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/core/resources/__tests__/Session.test.tspackages/clerk-js/src/core/__tests__/tokenCache.test.ts
🧬 Code graph analysis (3)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (2)
packages/clerk-js/src/test/core-fixtures.ts (1)
clerkMock(249-256)packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(407-407)
packages/clerk-js/src/core/resources/Session.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(407-407)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(407-407)
⏰ 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). (2)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (4)
packages/clerk-js/src/core/resources/Session.ts (1)
133-146: LGTM! Clean implementation of conditional caching.The changes correctly implement the PR objective:
- Early return for null tokens avoids unnecessary operations
- Computing
tokenIdonce ensures consistency between the get and set operations- The guard clause prevents duplicate cache entries when Session objects are reconstructed with the same token
This optimization eliminates redundant cache operations while maintaining correct behavior.
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (3)
38-38: Good type safety improvement.Removing the
as anytype assertion improves compile-time type checking without affecting runtime behavior.Also applies to: 79-79, 104-106, 149-149, 177-177, 212-212, 233-233, 252-252, 314-314, 335-335, 360-360, 387-387, 409-409, 436-436
103-146: Excellent test coverage for the cache deduplication behavior.This test comprehensively verifies that reconstructing a Session with the same token doesn't duplicate cache entries or trigger unnecessary API requests. The assertions properly validate:
- Cache size remains 1 after reconstruction
- Same token is returned from both session instances
- No API calls are made
148-172: Good coverage for degraded mode recovery.This test ensures that tokens from cookies are properly cached during degraded mode recovery, preventing unnecessary API calls when the token is already available.
@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: |
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: 0
🧹 Nitpick comments (1)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (1)
38-38: Good refactor: Improved type safety.Removing the
as anycasts fromclerkMock()improves type safety by relying on the proper typing from the fixture. This makes the tests more maintainable and helps catch type errors at compile time.Also applies to: 79-79, 177-177, 212-212, 233-233, 252-252, 314-314, 335-335, 360-360, 387-387, 409-409, 436-436
📜 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 (2)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts(1 hunks)packages/clerk-js/src/core/resources/__tests__/Session.test.ts(12 hunks)
🧰 Additional context used
📓 Path-based instructions (9)
**/*.{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/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.test.ts
packages/**/*.{ts,tsx}
📄 CodeRabbit inference engine (.cursor/rules/development.mdc)
TypeScript is required for all packages
Files:
packages/clerk-js/src/core/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/core/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/core/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.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/core/__tests__/tokenCache.test.tspackages/clerk-js/src/core/resources/__tests__/Session.test.ts
🧬 Code graph analysis (2)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(407-407)
packages/clerk-js/src/core/resources/__tests__/Session.test.ts (3)
packages/clerk-js/src/test/core-fixtures.ts (1)
clerkMock(249-256)packages/clerk-js/src/core/tokenCache.ts (1)
SessionTokenCache(407-407)packages/clerk-js/src/core/resources/Session.ts (1)
Session(44-433)
🪛 Gitleaks (8.28.0)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts
[high] 284-284: Detected a Generic API Key, potentially exposing access to various services and sensitive operations.
(generic-api-key)
⏰ 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). (5)
- GitHub Check: Build Packages
- GitHub Check: Formatting | Dedupe | Changeset
- GitHub Check: Analyze (javascript-typescript)
- GitHub Check: semgrep-cloud-platform/scan
- GitHub Check: semgrep-cloud-platform/scan
🔇 Additional comments (3)
packages/clerk-js/src/core/__tests__/tokenCache.test.ts (1)
281-314: LGTM! Test correctly validates cache broadcast behavior.This test properly verifies that
SessionTokenCache.setalways broadcasts viapostMessage, regardless of whether a token with the sametokenIdis already cached. This behavior is essential for multi-tab synchronization, while the optimization (avoiding unnecessary set calls) is handled at the Session class level via the updatedhydrateCachemethod.Note on static analysis hint:
The Gitleaks warning for line 284 is a false positive. The value'sess_2GbDB4enNdCa5vS1zpC3Xzg9tK9'is a mock session ID for testing purposes, not a real API key.packages/clerk-js/src/core/resources/__tests__/Session.test.ts (2)
103-146: Excellent test coverage for cache deduplication.This test validates the core optimization introduced in this PR: when a Session is reconstructed with the same token,
hydrateCachechecks for an existing cache entry and avoids redundant cache operations. The assertions correctly verify:
- Single cache entry after multiple Session constructions
- Token retrieval works without triggering API requests
- Cache sharing between session instances
148-172: Good coverage for degraded mode recovery scenario.This test validates an important edge case where tokens from cookies during degraded mode recovery are properly cached on Session construction. The test correctly verifies that the cached token can be retrieved without triggering API requests, which is essential for resilient operation during network issues.
Description
Small optimization to only cache a token in SessionTokenCache when it's not already there. This prevents the session token to get broadcast needlessly.
Checklist
pnpm testruns as expected.pnpm buildruns as expected.Type of change
Summary by CodeRabbit
Tests
Bug Fixes
Chores