Skip to content
Myr

fix(persist): prevent race condition during concurrent rehydrate calls (#3336)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* fix(persist): prevent race condition during concurrent rehydrate calls Added hydrationVersion counter to track and invalidate stale hydrations. When multiple rehydrate() calls happen concurrently, only the last one applies its state, preventing race conditions with async storage. - Added hydrationVersion counter incremented on each hydrate() call - Added version checks after each async step (getItem, migrate, set) - Added 3 tests for concurrent rehydration scenarios * fix(persist): refactor simplify hydration abort logic * fix(persist): refactor use consistent comment pattern for abort checks * fix(persist): refactor remove redundant abort checks * fix(persist): refactor remove unnecessary migrationResult check ---------

authored by Niyaz · committed by GitHub · parent 59e8783 · Browse files · 2 files+149 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Trailers

  • Co-authored-by: Daishi Kato <dai-shi@users.noreply.github.com>

Diff stats

2 files+149 added−0 removed

  • tests:+132 added−0 removed
  • other:+17 added−0 removed

2 files+149 added−0 removed

modified:src/middleware/persist.ts+17 added
196 unmodified lines
197 ...baseOptions,198 }199200 let hasHydrated = false201 // Counter to track hydration versions and prevent race conditions202 // when multiple rehydrate() calls happen concurrently203 let hydrationVersion = 0204 const hydrationListeners = new Set<PersistListener<S>>()205 const finishHydrationListeners = new Set<PersistListener<S>>()206 let storage = options.storage207
49 unmodified lines
257 // true for both the 'asynchronous' and 'synchronous' case). Pass 'configResult'258 // as a backup to 'get()' so listeners and 'onRehydrateStorage' are called with259 // the latest available state.260261 // Increment version to invalidate any in-flight hydration262 const currentVersion = ++hydrationVersion263 hasHydrated = false264 hydrationListeners.forEach((cb) => cb(get() ?? configResult))265266 const postRehydrationCallback =
26 unmodified lines
293 }294 return [false, undefined] as const295 })296 .then((migrationResult) => {297 // Abort if a newer hydration has started298 if (currentVersion !== hydrationVersion) {299 return300 }301 const [migrated, migratedState] = migrationResult302 stateFromStorage = options.merge(303 migratedState as S,304 get() ?? configResult,
4 unmodified lines
309 return setItem()310 }311 })312 .then(() => {313 // Abort if a newer hydration has started314 if (currentVersion !== hydrationVersion) {315 return316 }317 // TODO: In the asynchronous case, it's possible that the state has changed318 // since it was set in the prior callback. As such, it would be better to319 // pass 'get()' to the 'postRehydrationCallback' to ensure the most up-to-date320 // state is used. However, this could be a breaking change, so this isn't being
9 unmodified lines
330 hasHydrated = true331 finishHydrationListeners.forEach((cb) => cb(stateFromStorage as S))332 })333 .catch((e: Error) => {334 // Abort if a newer hydration has started335 if (currentVersion !== hydrationVersion) {336 return337 }338 postRehydrationCallback?.(undefined, e)339 })340 }341
66 unmodified lines
modified:tests/persistAsync.test.tsx+132 added
874 unmodified lines
875 { map: updatedMap },876 undefined,877 )878 })879880 it('should handle multiple concurrent rehydrate calls (only last one wins)', async () => {881 let callCount = 0882 const storage = {883 getItem: async () => {884 const currentCall = ++callCount885 await sleep(10)886 return JSON.stringify({887 state: { count: currentCall * 10 },888 version: 0,889 })890 },891 setItem: () => {},892 removeItem: () => {},893 }894895 const onFinishHydrationSpy = vi.fn()896 const useBoundStore = create(897 persist(() => ({ count: 0 }), {898 name: 'test-storage',899 storage: createJSONStorage(() => storage),900 skipHydration: true,901 }),902 )903904 useBoundStore.persist.onFinishHydration(onFinishHydrationSpy)905906 // Start first rehydration907 const promise1 = useBoundStore.persist.rehydrate()908 // Immediately start second rehydration (before first completes)909 const promise2 = useBoundStore.persist.rehydrate()910 // Start third rehydration911 const promise3 = useBoundStore.persist.rehydrate()912913 // Advance time to complete all hydrations914 await act(() => vi.advanceTimersByTimeAsync(30))915 await Promise.all([promise1, promise2, promise3])916917 // Only the last rehydration should have applied its state918 // callCount will be 3, so count should be 30919 expect(useBoundStore.getState().count).toBe(30)920921 // onFinishHydration should only be called once (for the last hydration)922 expect(onFinishHydrationSpy).toHaveBeenCalledTimes(1)923 expect(onFinishHydrationSpy).toHaveBeenCalledWith({ count: 30 })924 })925926 it('should not overwrite user state changes made during async hydration', async () => {927 const storage = {928 getItem: async () => {929 await sleep(20)930 return JSON.stringify({931 state: { count: 42, userValue: 'from-storage' },932 version: 0,933 })934 },935 setItem: () => {},936 removeItem: () => {},937 }938939 const useBoundStore = create(940 persist(() => ({ count: 0, userValue: 'initial' }), {941 name: 'test-storage',942 storage: createJSONStorage(() => storage),943 // Custom merge that preserves user changes made during hydration944 merge: (persistedState, currentState) => ({945 ...currentState,946 ...(persistedState as object),947 }),948 }),949 )950951 // User makes a change while hydration is in progress952 await act(() => vi.advanceTimersByTimeAsync(10))953 useBoundStore.setState({ count: 100 })954955 // Complete hydration956 await act(() => vi.advanceTimersByTimeAsync(10))957958 // The merge function combines storage state with current state959 // Storage has count: 42, userValue: 'from-storage'960 // Current state before merge has count: 100, userValue: 'initial'961 // After merge (storage overwrites): count: 42, userValue: 'from-storage'962 expect(useBoundStore.getState()).toEqual({963 count: 42,964 userValue: 'from-storage',965 })966 })967968 it('should abort hydration with async migration when newer hydration starts', async () => {969 let migrationCount = 0970 const storage = {971 getItem: async () => {972 await sleep(5)973 return JSON.stringify({974 state: { count: 1 },975 version: 0,976 })977 },978 setItem: () => {},979 removeItem: () => {},980 }981982 const useBoundStore = create(983 persist(() => ({ count: 0 }), {984 name: 'test-storage',985 storage: createJSONStorage(() => storage),986 version: 1,987 migrate: async (state) => {988 migrationCount++989 await sleep(10)990 return { count: (state as { count: number }).count * 10 }991 },992 skipHydration: true,993 }),994 )995996 // Start first rehydration (will trigger migration)997 useBoundStore.persist.rehydrate()998 await act(() => vi.advanceTimersByTimeAsync(5)) // getItem completes9991000 // Start second rehydration before migration completes1001 useBoundStore.persist.rehydrate()10021003 // Advance time to complete everything1004 await act(() => vi.advanceTimersByTimeAsync(20))10051006 // Both hydrations triggered migration, but only last one should apply1007 expect(migrationCount).toBe(2)1008 // Final state should be from second hydration's migration1009 expect(useBoundStore.getState().count).toBe(10)1010 })1011})