diff --git a/lib/OnyxCache.ts b/lib/OnyxCache.ts index 8e4a26cbe..2fd0ed804 100644 --- a/lib/OnyxCache.ts +++ b/lib/OnyxCache.ts @@ -401,12 +401,18 @@ class OnyxCache { return returnPromise; } - /** Check if the value has changed. Uses reference equality as a fast path, falls back to deep equality. */ + /** + * Check if the value has changed. Uses reference equality as a fast path, then a cheap check of the top-level + * primitive properties (which catches most values that really changed), and falls back to deep equality. + */ hasValueChanged(key: OnyxKey, value: OnyxValue): boolean { const currentValue = this.storageMap[key]; if (currentValue === value) { return false; } + if (utils.hasTopLevelPrimitiveChange(currentValue, value)) { + return true; + } return !deepEqual(currentValue, value); } diff --git a/lib/OnyxUtils.ts b/lib/OnyxUtils.ts index 580060f83..e7c02e596 100644 --- a/lib/OnyxUtils.ts +++ b/lib/OnyxUtils.ts @@ -802,6 +802,29 @@ function prepareKeyValuePairsForStorage( return {pairs, keysToRemove}; } +/** + * Splits prepared key-value pairs into the ones whose value differs from the cached value and the keys whose value is + * deep-equal to it, using the same `cache.hasValueChanged()` check as `setWithRetry`. + * + * Bulk set paths keep the cached object for the unchanged keys instead of replacing it with an equal copy, so + * reference-based consumers (subscribers, derived values, React) see no change for them. Pass the pairs returned by + * `prepareKeyValuePairsForStorage()`, so the comparison uses the value the cache would actually hold (without nested nulls). + */ +function partitionPairsByCacheChange(pairs: StorageKeyValuePair[]): {changedPairs: StorageKeyValuePair[]; unchangedKeys: Set} { + const changedPairs: StorageKeyValuePair[] = []; + const unchangedKeys = new Set(); + + for (const pair of pairs) { + if (cache.hasValueChanged(pair[0], pair[1])) { + changedPairs.push(pair); + } else { + unchangedKeys.add(pair[0]); + } + } + + return {changedPairs, unchangedKeys}; +} + /** * Merges an array of changes with an existing value or creates a single change. * @@ -1208,6 +1231,8 @@ function multiSetWithRetry(data: OnyxMultiSetInput, retryAttempt?: number): Prom } >(); + const unchangedKeys = new Set(); + for (const [key, value] of keyValuePairsToSet) { // When we use multiSet to set a key we want to clear the current delta changes from Onyx.merge that were queued // before the value was set. If Onyx.merge is currently reading the old value from storage, it will then not apply the changes. @@ -1215,6 +1240,13 @@ function multiSetWithRetry(data: OnyxMultiSetInput, retryAttempt?: number): Prom delete OnyxUtils.getMergeQueue()[key]; } + // Like setWithRetry, a value deep-equal to the cached one keeps the cached object and is neither + // re-cached nor notified, so reference-based consumers see no change for it. + if (!cache.hasValueChanged(key, value)) { + unchangedKeys.add(key); + continue; + } + const collectionKey = OnyxKeys.getCollectionKey(key); if (collectionKey && OnyxKeys.isCollectionMemberKey(collectionKey, key)) { // Capture the previous cached value before calling cache.set() so notifyCollection() @@ -1274,7 +1306,12 @@ function multiSetWithRetry(data: OnyxMultiSetInput, retryAttempt?: number): Prom const keyValuePairsToStore = keyValuePairsToSet.filter((keyValuePair) => { const [key] = keyValuePair; // Filter out the RAM-only key value pairs, as they should not be saved to storage - return !OnyxKeys.isRamOnlyKey(key); + if (OnyxKeys.isRamOnlyKey(key)) { + return false; + } + // Unchanged values are already in storage, so writing them again is redundant. On a retry the cache + // already holds the new values (every key looks unchanged), so storage must still get the full write. + return !!retryAttempt || !unchangedKeys.has(key); }); const keysToRemoveFromStorage = keysToRemove.filter((key) => !OnyxKeys.isRamOnlyKey(key)); @@ -1357,13 +1394,22 @@ function setCollectionWithRetry({collectionKey, // Capture the previous collection before cache mutations so notifyCollection() can diff removed members. const previousCollection = OnyxUtils.getCachedCollection(collectionKey); - for (const [key, value] of keyValuePairs) cache.set(key, value); + // Members deep-equal to their cached value keep the cached object and are left out of the notification. + const {changedPairs, unchangedKeys} = partitionPairsByCacheChange(keyValuePairs); + + for (const [key, value] of changedPairs) cache.set(key, value); for (const key of keysToRemove) cache.drop(key); // Skip subscriber notification on retry — already notified on attempt 0. if (!retryAttempt) { // Removed members are notified as undefined, matching mergeCollection/multiSet. - const partialForNotify = Object.fromEntries(Object.entries(mutableCollection).map(([key, value]) => [key, value ?? undefined])); + const partialForNotify: OnyxInputKeyValueMapping = {}; + for (const [key, value] of Object.entries(mutableCollection)) { + if (unchangedKeys.has(key)) { + continue; + } + partialForNotify[key] = value ?? undefined; + } notifyCollection(collectionKey, partialForNotify, previousCollection); } @@ -1375,9 +1421,13 @@ function setCollectionWithRetry({collectionKey, const inFlightKeys = new Set(keyValuePairs.map(([key]) => key)); + // Unchanged members are already in storage, so they are skipped. On a retry the cache already holds + // the new values (every member looks unchanged), so storage must still get the full write. + const keyValuePairsToStore = retryAttempt ? keyValuePairs : changedPairs; + // One batched removal = one cross-tab sync event instead of one per key. A failed removal is // logged, not retried — keysToRemove cannot be re-derived after the cache update. - const storagePromises = [Storage.multiSet(keyValuePairs)]; + const storagePromises = [Storage.multiSet(keyValuePairsToStore)]; if (keysToRemove.length > 0) { storagePromises.push(Storage.removeItems(keysToRemove).catch((error) => Logger.logAlert(`setCollection failed to remove keys from storage. Error: ${error}`))); } @@ -1645,13 +1695,22 @@ function partialSetCollection({collectionKey, co // Capture the previous collection before cache mutations so notifyCollection() can diff removed members. const previousCollection = getCachedCollection(collectionKey, existingKeys); - for (const [key, value] of keyValuePairs) cache.set(key, value); + // Members deep-equal to their cached value keep the cached object and are left out of the notification. + const {changedPairs, unchangedKeys} = partitionPairsByCacheChange(keyValuePairs); + + for (const [key, value] of changedPairs) cache.set(key, value); for (const key of keysToRemove) cache.drop(key); // Skip subscriber notification on retry — already notified on attempt 0. if (!retryAttempt) { // Removed members are notified as undefined, matching mergeCollection/multiSet. - const partialForNotify = Object.fromEntries(Object.entries(mutableCollection).map(([key, value]) => [key, value ?? undefined])); + const partialForNotify: OnyxInputKeyValueMapping = {}; + for (const [key, value] of Object.entries(mutableCollection)) { + if (unchangedKeys.has(key)) { + continue; + } + partialForNotify[key] = value ?? undefined; + } notifyCollection(collectionKey, partialForNotify, previousCollection); } @@ -1662,9 +1721,13 @@ function partialSetCollection({collectionKey, co const inFlightKeys = new Set(keyValuePairs.map(([key]) => key)); + // Unchanged members are already in storage, so they are skipped. On a retry the cache already holds + // the new values (every member looks unchanged), so storage must still get the full write. + const keyValuePairsToStore = retryAttempt ? keyValuePairs : changedPairs; + // One batched removal = one cross-tab sync event instead of one per key. A failed removal is // logged, not retried — keysToRemove cannot be re-derived after the cache update. - const storagePromises = [Storage.multiSet(keyValuePairs)]; + const storagePromises = [Storage.multiSet(keyValuePairsToStore)]; if (keysToRemove.length > 0) { storagePromises.push(Storage.removeItems(keysToRemove).catch((error) => Logger.logAlert(`setCollection failed to remove keys from storage. Error: ${error}`))); } diff --git a/lib/utils.ts b/lib/utils.ts index 41f432057..32ce908ba 100644 --- a/lib/utils.ts +++ b/lib/utils.ts @@ -236,6 +236,39 @@ function areDeepEqualArrays(a: unknown, b: unknown): boolean { return Array.isArray(a) && Array.isArray(b) && deepEqual(a, b); } +/** Checks whether the value is a non-null object that isn't an array. */ +function isNonArrayObject(value: unknown): value is Record { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * Cheap pre-check for a deep comparison: reports whether two plain objects differ in a top-level primitive property. + * It allocates nothing and returns at the first difference, so a value that really changed usually skips the full + * `deepEqual()` (which allocates both objects' key lists before comparing anything). `true` always means "not deep-equal"; + * `false` means "unknown", so the caller still has to run the full comparison. + */ +function hasTopLevelPrimitiveChange(a: unknown, b: unknown): boolean { + if (!isNonArrayObject(a) || !isNonArrayObject(b)) { + return false; + } + + // oxlint-disable-next-line core/no-restricted-syntax, guard-for-in + for (const key in a) { + const valueA = a[key]; + const valueB = b[key]; + if (valueA === valueB || (typeof valueA === 'object' && valueA !== null) || (typeof valueB === 'object' && valueB !== null)) { + continue; + } + // Both are primitives (or nullish) and differ. Two NaNs count as equal, matching `deepEqual()`. + // oxlint-disable-next-line no-self-compare + if (valueA === valueA || valueB === valueB) { + return true; + } + } + + return false; +} + /** * Reports whether a value needs cleaning (nested null/undefined, or the replace-object mark) before it's * safe to store by reference. Read-only, non-allocating. @@ -430,6 +463,7 @@ export default { formatActionName, removeNestedNullValues, needsNormalization, + hasTopLevelPrimitiveChange, checkCompatibilityWithExistingValue, pick, omit, diff --git a/tests/perf-test/useOnyx.perf-test.tsx b/tests/perf-test/useOnyx.perf-test.tsx index 95b58a05c..21577ec83 100644 --- a/tests/perf-test/useOnyx.perf-test.tsx +++ b/tests/perf-test/useOnyx.perf-test.tsx @@ -461,5 +461,74 @@ describe('useOnyx', () => { afterEach: clearOnyxAfterEachMeasure, }); }); + + /** + * Expected renders: 1. + * + * Setting deep-equal members (arrays included) keeps the cached references, so a subscriber without a selector doesn't re-render. + */ + test('setting deep-equal members with setCollection does not re-render', async () => { + const key = ONYXKEYS.COLLECTION.TEST_KEY; + await measureRenders(, { + beforeEach: async () => { + await Onyx.setCollection(key, createObjectArrayCollection(key, 3)); + }, + scenario: async () => { + await screen.findByText(dataMatcher(key, createObjectArrayCollection(key, 3))); + + await act(async () => { + await Onyx.setCollection(key, createObjectArrayCollection(key, 3)); + }); + + await screen.findByText(dataMatcher(key, createObjectArrayCollection(key, 3))); + }, + afterEach: clearOnyxAfterEachMeasure, + }); + }); + + /** + * Expected renders: 2 (the initial render and one commit for the update). + * + * Large list of members, each subscribing to its own collection member key, with the whole collection set + * again (like a full reconnect response) and a single member really changed. Deep-equal members keep their + * cached references, so only that member's item re-renders inside the commit, which shows in the render duration. + */ + test('large list of members, setCollection with a single member changed', async () => { + const SCALE = 100; + const createScaledCollection = (changedIndex?: number) => + Object.fromEntries(Array.from({length: SCALE}, (_, index) => [`${ONYXKEYS.COLLECTION.TEST_KEY}${index}`, {name: index === changedIndex ? 'changed' : `n${index}`}])); + + function ScaledItem({index}: {index: number}) { + const [data] = useOnyx(`${ONYXKEYS.COLLECTION.TEST_KEY}${index}`); + return {`item_${index}_${JSON.stringify(data)}`}; + } + + function ScaledList() { + return ( + + {Array.from({length: SCALE}, (_, index) => ( + + ))} + + ); + } + + await measureRenders(, { + beforeEach: async () => { + await Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, createScaledCollection()); + }, + scenario: async () => { + await screen.findByText(`item_0_${JSON.stringify({name: 'n0'})}`); + + Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, createScaledCollection(1)); + + await screen.findByText(`item_1_${JSON.stringify({name: 'changed'})}`); + }, + afterEach: clearOnyxAfterEachMeasure, + }); + }); }); }); diff --git a/tests/unit/onyxTest.ts b/tests/unit/onyxTest.ts index 764dacfa1..dc26213c3 100644 --- a/tests/unit/onyxTest.ts +++ b/tests/unit/onyxTest.ts @@ -3444,6 +3444,251 @@ describe('Onyx', () => { }); }); + describe('bulk set keeps deep-equal values', () => { + const routeA = `${ONYX_KEYS.COLLECTION.ROUTES}A`; + const routeB = `${ONYX_KEYS.COLLECTION.ROUTES}B`; + const routeC = `${ONYX_KEYS.COLLECTION.ROUTES}C`; + let memberConnection: Connection | undefined; + + afterEach(() => { + memberConnection?.unsubscribe(); + memberConnection = undefined; + }); + + it('setCollection should keep the cached object of a deep-equal member and not notify its subscribers', async () => { + // Given a cached collection member and a subscriber to it + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', stops: [{id: 1}, {id: 2}]}, + [routeB]: {name: 'Route B'}, + }); + const cachedRouteA = cache.get(routeA); + const memberCallback = jest.fn(); + memberConnection = Onyx.connect({key: routeA, callback: memberCallback}); + await waitForPromisesToResolve(); + memberCallback.mockClear(); + + // When the collection is set again with a new object for that member that is deep-equal to the cached one, + // which is what a full reconnect response does for every member that didn't change + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', stops: [{id: 1}, {id: 2}]}, + [routeB]: {name: 'New Route B'}, + }); + + // Then the cache still holds the old object, so reference-based consumers see no change for it, + // and its subscriber isn't called since nothing about it changed + expect(cache.get(routeA)).toBe(cachedRouteA); + expect(memberCallback).not.toHaveBeenCalled(); + expect(cache.get(routeB)).toEqual({name: 'New Route B'}); + }); + + it('setCollection should hand collection subscribers the old object of a deep-equal member', async () => { + // Given a cached collection and a subscriber to the whole collection + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + const cachedRouteA = cache.get(routeA); + let collection: OnyxCollection; + connection = Onyx.connect({ + key: ONYX_KEYS.COLLECTION.ROUTES, + callback: (value) => { + collection = value; + }, + }); + await waitForPromisesToResolve(); + + // When only one member really changes + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'New Route B'}, + }); + + // Then the collection subscriber gets the update, and the unchanged member in it is the old object, + // so consumers that diff members by reference (e.g. derived values) only see the changed one + expect(collection?.[routeA]).toBe(cachedRouteA); + expect(collection?.[routeB]).toEqual({name: 'New Route B'}); + }); + + it('setCollection should not notify collection subscribers when no member changed', async () => { + // Given a cached collection and a subscriber to the whole collection + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + const collectionCallback = jest.fn(); + connection = Onyx.connect({key: ONYX_KEYS.COLLECTION.ROUTES, callback: collectionCallback}); + await waitForPromisesToResolve(); + collectionCallback.mockClear(); + + // When the same collection is set again with new but deep-equal objects + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + + // Then nothing changed, so the collection subscriber isn't called + expect(collectionCallback).not.toHaveBeenCalled(); + }); + + it('setCollection should replace a member whose nested field changed', async () => { + // Given a cached member with a nested object and a subscriber to it + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', details: {distance: 10, stops: [1, 2]}}, + }); + const cachedRouteA = cache.get(routeA); + const memberCallback = jest.fn(); + memberConnection = Onyx.connect({key: routeA, callback: memberCallback}); + await waitForPromisesToResolve(); + memberCallback.mockClear(); + + // When the member is set again with only a deeply nested value changed + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', details: {distance: 10, stops: [1, 3]}}, + }); + + // Then the deep comparison finds the difference, so the member gets the new object and its subscriber is called + const newRouteA = {name: 'Route A', details: {distance: 10, stops: [1, 3]}}; + expect(cache.get(routeA)).not.toBe(cachedRouteA); + expect(cache.get(routeA)).toEqual(newRouteA); + expect(memberCallback).toHaveBeenCalledTimes(1); + expect(memberCallback).toHaveBeenCalledWith(newRouteA, routeA); + expect(await StorageMock.getItem(routeA)).toEqual(newRouteA); + }); + + it('setCollection should compare a member without its nested null values', async () => { + // Given a cached member + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', details: {distance: 10}}, + }); + const cachedRouteA = cache.get(routeA); + + // When it is set again with extra nested null values, which Onyx strips before caching + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', pendingAction: null, details: {distance: 10, comment: null}}, + }); + + // Then the value the cache would hold is deep-equal to the cached one, as Onyx.set would also decide, + // so the old object is kept + expect(cache.get(routeA)).toBe(cachedRouteA); + }); + + it('setCollection should still remove and notify members missing from the new collection', async () => { + // Given two cached members and a subscriber to the one that the new collection will leave out + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + const cachedRouteA = cache.get(routeA); + const removedMemberCallback = jest.fn(); + memberConnection = Onyx.connect({key: routeB, callback: removedMemberCallback}); + await waitForPromisesToResolve(); + removedMemberCallback.mockClear(); + + // When the collection is set with only the unchanged member + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + }); + + // Then the unchanged member keeps its object, while the missing one is still removed from cache and + // storage and its subscriber is told about it, since setCollection replaces the whole collection + expect(cache.get(routeA)).toBe(cachedRouteA); + expect(cache.get(routeB)).toBeUndefined(); + expect(await StorageMock.getItem(routeB)).toBeNull(); + expect(removedMemberCallback).toHaveBeenCalledTimes(1); + expect(removedMemberCallback).toHaveBeenCalledWith(undefined, routeB); + }); + + it('setCollection should only write changed members to storage', async () => { + // Given two cached members + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + jest.mocked(StorageMock.multiSet).mockClear(); + + // When the collection is set with one unchanged, one changed and one new member + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'New Route B'}, + [routeC]: {name: 'Route C'}, + }); + + // Then the unchanged member is already in storage, so only the other two are written, + // and storage still matches the cache for all three + expect(StorageMock.multiSet).toHaveBeenCalledTimes(1); + const writtenKeys = jest.mocked(StorageMock.multiSet).mock.calls[0][0].map(([key]) => key); + expect(writtenKeys).toEqual([routeB, routeC]); + expect(await StorageMock.getItem(routeA)).toEqual({name: 'Route A'}); + expect(await StorageMock.getItem(routeB)).toEqual({name: 'New Route B'}); + expect(await StorageMock.getItem(routeC)).toEqual({name: 'Route C'}); + }); + + it('multiSet should keep the cached objects of deep-equal collection members and plain keys', async () => { + // Given a cached collection member and a cached plain key, each with a subscriber + await Onyx.multiSet({ + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + [ONYX_KEYS.TEST_KEY]: {id: 1, tags: ['a']}, + }); + const cachedRouteA = cache.get(routeA); + const cachedTestKey = cache.get(ONYX_KEYS.TEST_KEY); + const memberCallback = jest.fn(); + const plainKeyCallback = jest.fn(); + memberConnection = Onyx.connect({key: routeA, callback: memberCallback}); + connection = Onyx.connect({key: ONYX_KEYS.TEST_KEY, callback: plainKeyCallback}); + await waitForPromisesToResolve(); + memberCallback.mockClear(); + plainKeyCallback.mockClear(); + jest.mocked(StorageMock.multiSet).mockClear(); + + // When multiSet writes deep-equal copies of both, a changed member and a changed plain key + await Onyx.multiSet({ + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'New Route B'}, + [ONYX_KEYS.TEST_KEY]: {id: 1, tags: ['a']}, + [ONYX_KEYS.OTHER_TEST]: 'changed', + }); + + // Then, as with Onyx.set, the unchanged values keep their old objects, aren't notified and aren't rewritten, + // while the changed ones are updated and stored + expect(cache.get(routeA)).toBe(cachedRouteA); + expect(cache.get(ONYX_KEYS.TEST_KEY)).toBe(cachedTestKey); + expect(memberCallback).not.toHaveBeenCalled(); + expect(plainKeyCallback).not.toHaveBeenCalled(); + expect(cache.get(routeB)).toEqual({name: 'New Route B'}); + expect(cache.get(ONYX_KEYS.OTHER_TEST)).toEqual('changed'); + const writtenKeys = jest.mocked(StorageMock.multiSet).mock.calls[0][0].map(([key]) => key); + expect(writtenKeys).toEqual([routeB, ONYX_KEYS.OTHER_TEST]); + expect(await StorageMock.getItem(routeB)).toEqual({name: 'New Route B'}); + expect(await StorageMock.getItem(ONYX_KEYS.OTHER_TEST)).toEqual('changed'); + }); + + it('update with SET_COLLECTION should keep the cached objects of deep-equal members', async () => { + // Given a cached collection + await Onyx.setCollection(ONYX_KEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'Route B'}, + }); + const cachedRouteA = cache.get(routeA); + + // When a server response applies the collection again through Onyx.update, like a full reconnect does + await Onyx.update([ + { + onyxMethod: Onyx.METHOD.SET_COLLECTION, + key: ONYX_KEYS.COLLECTION.ROUTES, + value: { + [routeA]: {name: 'Route A'}, + [routeB]: {name: 'New Route B'}, + }, + }, + ]); + + // Then only the changed member gets a new object + expect(cache.get(routeA)).toBe(cachedRouteA); + expect(cache.get(routeB)).toEqual({name: 'New Route B'}); + }); + }); + describe('skippable collection member ids', () => { it('should skip the collection member id value when using Onyx.set()', async () => { let testKeyValue: unknown; diff --git a/tests/unit/onyxUtilsTest.ts b/tests/unit/onyxUtilsTest.ts index 2a54d5d0d..03a73538c 100644 --- a/tests/unit/onyxUtilsTest.ts +++ b/tests/unit/onyxUtilsTest.ts @@ -196,6 +196,48 @@ describe('OnyxUtils', () => { connection.unsubscribe(); }); + + it('should keep the cached object of a deep-equal member and only write changed members to storage', async () => { + const routeA = `${ONYXKEYS.COLLECTION.ROUTES}A`; + const routeB = `${ONYXKEYS.COLLECTION.ROUTES}B`; + const routeC = `${ONYXKEYS.COLLECTION.ROUTES}C`; + + // Given three cached members and a subscriber to one that will be written again unchanged + await Onyx.setCollection(ONYXKEYS.COLLECTION.ROUTES, { + [routeA]: {name: 'Route A', stops: [{id: 1}]}, + [routeB]: {name: 'Route B'}, + [routeC]: {name: 'Route C'}, + }); + const cachedRouteA = OnyxCache.get(routeA); + const cachedRouteC = OnyxCache.get(routeC); + const memberCallback = jest.fn(); + const connection = Onyx.connect({key: routeA, callback: memberCallback}); + await waitForPromisesToResolve(); + memberCallback.mockClear(); + jest.mocked(StorageMock.multiSet).mockClear(); + + // When a partial set writes a deep-equal copy of that member and a changed one + await OnyxUtils.partialSetCollection({ + collectionKey: ONYXKEYS.COLLECTION.ROUTES, + collection: { + [routeA]: {name: 'Route A', stops: [{id: 1}]}, + [routeB]: {name: 'New Route B'}, + }, + }); + + // Then the unchanged member keeps its old object, isn't notified and isn't rewritten to storage, + // the changed one is replaced, and the member left out of the partial set stays untouched + expect(OnyxCache.get(routeA)).toBe(cachedRouteA); + expect(memberCallback).not.toHaveBeenCalled(); + expect(OnyxCache.get(routeB)).toEqual({name: 'New Route B'}); + expect(OnyxCache.get(routeC)).toBe(cachedRouteC); + const writtenKeys = jest.mocked(StorageMock.multiSet).mock.calls[0][0].map(([key]) => key); + expect(writtenKeys).toEqual([routeB]); + expect(await StorageMock.getItem(routeA)).toEqual({name: 'Route A', stops: [{id: 1}]}); + expect(await StorageMock.getItem(routeB)).toEqual({name: 'New Route B'}); + + connection.unsubscribe(); + }); }); describe('multiSetWithRetry', () => { @@ -984,6 +1026,42 @@ describe('OnyxUtils', () => { expect(collectionCallback).toHaveBeenCalledTimes(1); }); + + describe('a retry still writes every value to storage', () => { + const collectionKey = ONYXKEYS.COLLECTION.TEST_KEY; + const unchangedMemberKey = `${collectionKey}1`; + const changedMemberKey = `${collectionKey}2`; + const newCollection = { + [unchangedMemberKey]: {value: 'same'}, + [changedMemberKey]: {value: 'changed'}, + }; + + it.each([ + ['Onyx.multiSet', () => Onyx.multiSet(newCollection)], + ['Onyx.setCollection', () => Onyx.setCollection(collectionKey, newCollection)], + ['OnyxUtils.partialSetCollection', () => OnyxUtils.partialSetCollection({collectionKey, collection: newCollection})], + ])('%s', async (_name, write) => { + // Given one member that will be written again unchanged and one that will change + await Onyx.multiSet({ + [unchangedMemberKey]: {value: 'same'}, + [changedMemberKey]: {value: 'initial'}, + }); + + // When the first storage write fails with a retriable error + StorageMock.multiSet = jest.fn(originalMultiSet).mockRejectedValueOnce(transientError); + await write(); + + // Then the first attempt only wrote the changed member. By the retry the cache already holds the new + // values, so every value looks unchanged there, and the retry must not skip them or the changed + // member would never reach storage. + const multiSetMock = jest.mocked(StorageMock.multiSet); + expect(multiSetMock).toHaveBeenCalledTimes(2); + expect(multiSetMock.mock.calls[0][0].map(([key]) => key)).toEqual([changedMemberKey]); + expect(multiSetMock.mock.calls[1][0].map(([key]) => key)).toEqual([unchangedMemberKey, changedMemberKey]); + expect(await StorageMock.getItem(changedMemberKey)).toEqual({value: 'changed'}); + expect(await StorageMock.getItem(unchangedMemberKey)).toEqual({value: 'same'}); + }); + }); }); describe('mergeCollection pre-warm', () => { diff --git a/tests/unit/useOnyxTest.ts b/tests/unit/useOnyxTest.ts index 9df4debba..25f480419 100644 --- a/tests/unit/useOnyxTest.ts +++ b/tests/unit/useOnyxTest.ts @@ -1034,6 +1034,49 @@ describe('useOnyx', () => { }); }); + describe('bulk set of deep-equal values', () => { + it('should not re-render collection and member subscribers when setCollection writes deep-equal members', async () => { + const memberKey1 = `${ONYXKEYS.COLLECTION.TEST_KEY}1`; + const memberKey2 = `${ONYXKEYS.COLLECTION.TEST_KEY}2`; + + // Given a cached collection and components subscribed to the collection and to one member + await Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, { + [memberKey1]: {id: 1, items: [{name: 'a'}]}, + [memberKey2]: {id: 2}, + }); + + let collectionRenderCount = 0; + const {result: collectionResult} = renderHook(() => { + collectionRenderCount++; + return useOnyx(ONYXKEYS.COLLECTION.TEST_KEY); + }); + let memberRenderCount = 0; + const {result: memberResult} = renderHook(() => { + memberRenderCount++; + return useOnyx(memberKey1); + }); + await act(async () => waitForPromisesToResolve()); + const initialCollection = collectionResult.current[0]; + const initialMember = memberResult.current[0]; + const collectionRendersBefore = collectionRenderCount; + const memberRendersBefore = memberRenderCount; + + // When the same collection is set again with new but deep-equal objects, like a full reconnect response + await act(async () => + Onyx.setCollection(ONYXKEYS.COLLECTION.TEST_KEY, { + [memberKey1]: {id: 1, items: [{name: 'a'}]}, + [memberKey2]: {id: 2}, + }), + ); + + // Then both components keep the same objects and don't re-render, since nothing changed + expect(collectionResult.current[0]).toBe(initialCollection); + expect(memberResult.current[0]).toBe(initialMember); + expect(collectionRenderCount).toBe(collectionRendersBefore); + expect(memberRenderCount).toBe(memberRendersBefore); + }); + }); + describe('loading status', () => { it('should report loading while a pending merge is in flight, then loaded once it resolves', async () => { Onyx.merge(ONYXKEYS.TEST_KEY, 'test1'); diff --git a/tests/unit/utilsTest.ts b/tests/unit/utilsTest.ts index f6b60bddd..846b054fa 100644 --- a/tests/unit/utilsTest.ts +++ b/tests/unit/utilsTest.ts @@ -645,6 +645,33 @@ describe('utils', () => { }); }); + describe('hasTopLevelPrimitiveChange', () => { + it('should report a change when a top-level primitive property differs', () => { + // Given objects that differ only in one top-level primitive, a property missing on one side, or null vs a value + // Then the pre-check finds the difference without a deep comparison + expect(utils.hasTopLevelPrimitiveChange({a: 1, b: {c: 1}}, {a: 2, b: {c: 1}})).toBe(true); + expect(utils.hasTopLevelPrimitiveChange({a: 1, b: 'x'}, {a: 1})).toBe(true); + expect(utils.hasTopLevelPrimitiveChange({a: null}, {a: 'x'})).toBe(true); + }); + + it('should not report a change it cannot see, leaving it to the deep comparison', () => { + // Given differences that are nested, only in extra keys of the second object, or between primitive and object + // Then the pre-check returns false ("unknown"), since only the full comparison can decide these + expect(utils.hasTopLevelPrimitiveChange({a: 1, b: {c: 1}}, {a: 1, b: {c: 2}})).toBe(false); + expect(utils.hasTopLevelPrimitiveChange({a: 1}, {a: 1, b: 2})).toBe(false); + expect(utils.hasTopLevelPrimitiveChange({a: 1}, {a: {}})).toBe(false); + expect(utils.hasTopLevelPrimitiveChange([1, 2], [1, 3])).toBe(false); + expect(utils.hasTopLevelPrimitiveChange('a', 'b')).toBe(false); + expect(utils.hasTopLevelPrimitiveChange(undefined, {a: 1})).toBe(false); + }); + + it('should never report a change for deep-equal values', () => { + // Given deep-equal values, including NaN and -0, which deepEqual treats as equal to NaN and 0 + // Then the pre-check agrees with deepEqual, so it can never turn an unchanged value into a changed one + expect(utils.hasTopLevelPrimitiveChange({a: NaN, b: -0, c: {d: [1]}, e: undefined}, {a: NaN, b: 0, c: {d: [1]}, e: undefined})).toBe(false); + }); + }); + describe('chunkArray', () => { it('should return an empty array when given an empty array', () => { expect(utils.chunkArray([], 3)).toEqual([]);