Repository navigation
fix: race condition use localization config - #3258
Conversation
…onfig - Replaced state management for session with a ref to prevent unnecessary re-renders. - Updated the effect dependencies to only react to settings changes, improving performance. - Added logic to handle session updates without triggering re-renders, ensuring smoother localization updates.
…calizationConfig - Added checks to prevent unnecessary updates when session settings match current localization settings. - Improved session handling by ensuring that the session reference is consistently used, optimizing performance during the first mount.
…seLocalizationConfig - Enhanced the first mount logic to prevent unnecessary session updates when no URL binding matches. - Ensured consistent use of session reference for improved performance and reliability during localization updates.
- Introduced a new function to streamline hostname checks, allowing for easier identification of development and preview environments. - Simplified the logic in matchURLBinding to enhance readability and maintainability, ensuring proper handling of subdomain and path-based bindings. - Removed redundant checks related to localhost and development mode, improving overall performance during URL matching.
WalkthroughThree files refactored for improved initialization and state management: hostname-checking logic centralized, session state converted to useRef to prevent cascade re-renders, and store hydration timing adjusted to prevent early data overwrites. Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested labels
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/sdk/localization/useLocalizationConfig.tsx (1)
37-66:⚠️ Potential issue | 🔴 CriticalMove all hooks to the top level—this early return violates React Rules of Hooks.
Lines 29–31 contain a conditional early return that skips the
useRefanduseEffectcalls on lines 37–66. React requires all hooks to be called unconditionally at the top level in the same order on every render. Remove the early return and move thesettingsreconciliation logic inside auseEffector checksettingsconditionally within the effects.As a secondary concern,
sessionRefis initialized with the current store snapshot before async IDB hydration completes. Ifsettingschanges during hydration, the sync effect uses a stale session value. Consider waiting for or detecting hydration completion before syncing.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx` around lines 37 - 66, The hooks (useRef/useEffect) must be called unconditionally in useLocalizationConfig; remove the early return that prevents them from running and move the settings reconciliation logic into a dedicated useEffect that runs when settings changes (e.g., useEffect(() => { ... }, [settings])) so hooks remain top-level and stable; inside that effect, read the freshest session from sessionStore (or wait for a session-store "hydrated" flag / subscribe until IDB hydration completes) instead of relying on the initial sessionRef snapshot to avoid stale-session syncs, update channel/locale/currency into a newSession, compare and call sessionStore.set(newSession) only when different.
🧹 Nitpick comments (2)
packages/sdk/src/store/persisted.ts (1)
56-59: Fire-and-forget async call is intentional but consider adding a catch.Calling
handler()withoutawaitis correct here (can't block initialization), and the innergetIDBalready swallows errors. However, if future changes tohandlerintroduce throwing code paths, an unhandled rejection could slip through. A defensive.catch(() => {})keeps the pattern explicit.🛡️ Optional: make the fire-and-forget explicit
- handler() + handler().catch(() => { + /* Errors already handled in getIDB; this silences unhandled rejection warnings */ + })🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/sdk/src/store/persisted.ts` around lines 56 - 59, The immediate call to handler() is intentionally fire-and-forget but should explicitly handle rejected promises to avoid future unhandled rejections; update the invocation of handler() so the returned promise is chained with a .catch handler (e.g., handler().catch(() => {})) to explicitly swallow any errors (or log them if preferred), referencing the handler() call in persisted.ts to locate the change.packages/core/src/sdk/localization/match-url.ts (1)
16-17: Hoist URL parsing out of the locale scan
new URL(href)andskipHostnameare invariant per call but currently recomputed for each locale entry. Hoisting them avoids repeated parsing and keeps the callback focused on per-binding checks.♻️ Suggested diff
export function matchURLBinding(href: string) { let binding + const hostURLObject = new URL(href) + const skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname) const matchedConfig = Object.entries(config.localization.locales).find( ([_, langConfig]: [string, any]) => { - const hostURLObject = new URL(href) - const skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname) - binding = langConfig.bindings.find(({ url }: { url: string }) => { const configURLObject = new URL(url)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/core/src/sdk/localization/match-url.ts` around lines 16 - 17, Hoist the URL parsing and hostname-skip check out of the per-locale scan: compute const hostURLObject = new URL(href) and const skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname) once before iterating over locales (instead of inside the per-binding callback), then pass/use those precomputed values inside the locale check logic so the callback only performs per-binding checks.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/core/src/sdk/localization/match-url.ts`:
- Around line 46-50: The current early return when isSubdomainBinding &&
skipHostname causes all subdomain bindings to fail silently; instead implement a
deterministic behavior: when isSubdomainBinding is true and skipHostname is
true, perform an explicit subdomain comparison using the available host/path
info (e.g., extract subdomain segment from the request host or a provided host
parameter) and compare it to the binding's expected subdomain, returning true
when they match, or otherwise return false and surface the fallback (e.g.,
return a distinct result or allow the caller in useLocalizationConfig.tsx to
log/handle the fallback). Modify the logic in match-url.ts (the block
referencing isSubdomainBinding and skipHostname) to do this deterministic
subdomain check rather than simply returning !skipHostname so configured
subdomain bindings are respected in relaxed-host environments.
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 37-41: sessionRef is seeded from a render-time snapshot but
sessionStore.subscribe() doesn’t replay the current value, so late hydration can
leave sessionRef stale and the sync effect (the effect that applies
locale/channel/currency referenced around line 66) never reruns; fix by making
the subscribe callback not only update sessionRef.current but also trigger a
React state change (or set a "hydrated" flag) when a different session arrives
so the sync effect will rerun once the first hydrated session lands, or
alternatively delay running the sync effect until you detect sessionStore has
finished hydration; update the subscribe handler in useLocalizationConfig (the
sessionRef / sessionStore subscribe logic) to compare newSession to
sessionRef.current and call setState/setHydrated to force one rerun when they
differ.
---
Outside diff comments:
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx`:
- Around line 37-66: The hooks (useRef/useEffect) must be called unconditionally
in useLocalizationConfig; remove the early return that prevents them from
running and move the settings reconciliation logic into a dedicated useEffect
that runs when settings changes (e.g., useEffect(() => { ... }, [settings])) so
hooks remain top-level and stable; inside that effect, read the freshest session
from sessionStore (or wait for a session-store "hydrated" flag / subscribe until
IDB hydration completes) instead of relying on the initial sessionRef snapshot
to avoid stale-session syncs, update channel/locale/currency into a newSession,
compare and call sessionStore.set(newSession) only when different.
---
Nitpick comments:
In `@packages/core/src/sdk/localization/match-url.ts`:
- Around line 16-17: Hoist the URL parsing and hostname-skip check out of the
per-locale scan: compute const hostURLObject = new URL(href) and const
skipHostname = shouldSkipHostnameCheck(hostURLObject.hostname) once before
iterating over locales (instead of inside the per-binding callback), then
pass/use those precomputed values inside the locale check logic so the callback
only performs per-binding checks.
In `@packages/sdk/src/store/persisted.ts`:
- Around line 56-59: The immediate call to handler() is intentionally
fire-and-forget but should explicitly handle rejected promises to avoid future
unhandled rejections; update the invocation of handler() so the returned promise
is chained with a .catch handler (e.g., handler().catch(() => {})) to explicitly
swallow any errors (or log them if preferred), referencing the handler() call in
persisted.ts to locate the change.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 7c1b1d0b-88e5-4c56-bf0b-092b02eaefaa
📒 Files selected for processing (3)
packages/core/src/sdk/localization/match-url.tspackages/core/src/sdk/localization/useLocalizationConfig.tsxpackages/sdk/src/store/persisted.ts
| // Subdomain bindings rely on hostname, so when the hostname check | ||
| // is skipped we can only match path-based bindings. | ||
| if (isSubdomainBinding) { | ||
| return true | ||
| return !skipHostname | ||
| } |
There was a problem hiding this comment.
Subdomain bindings are effectively disabled in relaxed-host environments
At Line 49, return !skipHostname makes every subdomain binding fail on localhost/development/.vtex.app. In the current caller (packages/core/src/sdk/localization/useLocalizationConfig.tsx, Lines 126-132), that silently falls back to default settings, so configured locale/binding can be ignored without signal. Please keep a deterministic subdomain match path (or explicitly surface that fallback) instead of returning no match.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/sdk/localization/match-url.ts` around lines 46 - 50, The
current early return when isSubdomainBinding && skipHostname causes all
subdomain bindings to fail silently; instead implement a deterministic behavior:
when isSubdomainBinding is true and skipHostname is true, perform an explicit
subdomain comparison using the available host/path info (e.g., extract subdomain
segment from the request host or a provided host parameter) and compare it to
the binding's expected subdomain, returning true when they match, or otherwise
return false and surface the fallback (e.g., return a distinct result or allow
the caller in useLocalizationConfig.tsx to log/handle the fallback). Modify the
logic in match-url.ts (the block referencing isSubdomainBinding and
skipHostname) to do this deterministic subdomain check rather than simply
returning !skipHostname so configured subdomain bindings are respected in
relaxed-host environments.
| const sessionRef = useRef(sessionStore.read() ?? sessionStore.readInitial()) | ||
|
|
||
| useEffect(() => { | ||
| return sessionStore.subscribe((newSession) => { | ||
| setSession(newSession) | ||
| sessionRef.current = newSession |
There was a problem hiding this comment.
Late session hydration still reopens the race.
Line 37 seeds the ref from a render-time snapshot, but packages/sdk/src/store/base.ts:42-48 does not replay the current value on subscribe(). Since sessionStore is persisted (packages/sdk/src/session/index.ts:70-74, packages/sdk/src/store/composed.ts:7-22), hydration can arrive after mount with a different session. Line 41 only mutates the ref, and Line 66 prevents the sync effect from running again, so locale/channel/currency can still be applied against stale session data. Trigger one rerun when the first hydrated session lands, or delay this effect until hydration completes.
Also applies to: 45-66
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/core/src/sdk/localization/useLocalizationConfig.tsx` around lines 37
- 41, sessionRef is seeded from a render-time snapshot but
sessionStore.subscribe() doesn’t replay the current value, so late hydration can
leave sessionRef stale and the sync effect (the effect that applies
locale/channel/currency referenced around line 66) never reruns; fix by making
the subscribe callback not only update sessionRef.current but also trigger a
React state change (or set a "hydrated" flag) when a different session arrives
so the sync effect will rerun once the first hydrated session lands, or
alternatively delay running the sync effect until you detect sessionStore has
finished hydration; update the subscribe handler in useLocalizationConfig (the
sessionRef / sessionStore subscribe logic) to compare newSession to
sessionRef.current and call setState/setHydrated to force one rerun when they
differ.
What's the purpose of this pull request?
How it works?
How to test it?
Starters Deploy Preview
References
Checklist
You may erase this after checking them all 😉
PR Title and Commit Messages
feat,fix,chore,docs,style,refactor,ciandtestPR Description
breaking change,bug,contributing,performance,documentation..Dependencies
pnpm-lock.yamlfile when there were changes to the packagesDocumentation
@Mariana-Caetanoto review and update (Or submit a doc request)Summary by CodeRabbit
Release Notes