Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 71 additions & 10 deletions lib/Onyx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ function init({
for (const [collectionKey, {partial, previous}] of collectionBatches) {
OnyxUtils.notifyCollection(collectionKey, partial, previous);
}
});
}, PendingWrites.reportOtherInstanceWrite);
}

OnyxUtils.initStoreValues(keys, initialKeyStates, evictableKeys);
Expand Down Expand Up @@ -437,9 +437,19 @@ function clear(keysToPreserve: OnyxKey[] = []): Promise<void> {
// Writes can land while storage clears (e.g. a new sign-in's session), so record them to avoid clobbering them.
// Matching on values instead would confuse them with reads refilling the cache from storage.
const keysWrittenDuringClear = new Set<OnyxKey>();
// Keys this tab writes during the final readback of the other tab's keys.
let keysWrittenDuringReadback: Set<OnyxKey> | undefined;
const removeWriteListener = PendingWrites.addWriteListener((keys) => {
for (const key of keys) {
keysWrittenDuringClear.add(key);
keysWrittenDuringReadback?.add(key);
}
});
// Keys another tab writes during the clear stay in storage and are read back at the end.
const keysWrittenByOtherInstanceDuringClear = new Set<OnyxKey>();
const removeOtherInstanceWriteListener = PendingWrites.addOtherInstanceWriteListener((keys) => {
for (const key of keys) {
keysWrittenByOtherInstanceDuringClear.add(key);
}
});

Expand Down Expand Up @@ -531,31 +541,78 @@ function clear(keysToPreserve: OnyxKey[] = []): Promise<void> {
}, {}),
);

// Remove only the items that we want cleared from storage, and reset others to default
let keysWrittenByOtherInstance = new Set<OnyxKey>();
const collectKeysWrittenByOtherInstance = () =>
new Set(Object.keys(valuesSetByClear).filter((key) => keysWrittenByOtherInstanceDuringClear.has(key) && !OnyxKeys.isRamOnlyKey(key)));
const wasWrittenOnlyByThisInstance = (key: OnyxKey): boolean => wasWrittenDuringClear(key) && !keysWrittenByOtherInstance.has(key);

const resetDefaults = () => {
keysWrittenByOtherInstance = collectKeysWrittenByOtherInstance();
return Storage.multiSet(defaultKeyValuePairs.filter(([key]) => !keysWrittenByOtherInstance.has(key)));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

NAB

a customer who signs out in one web tab stays signed in when a second tab on the same account refreshes its auth token during the sign-out.

is it intended that any write another tab makes to a default key during clear survives, not only a new sign-in? a tab still on the old account merging into session now lands after the defaults and gets read back here.

};
// Write defaults before the slow removal, so another tab's write lands after them, not under them.
const resetDefaultsPromise = resetDefaults();

// Remove only the items that we want cleared from storage
for (const key of keysToBeClearedFromStorage) cache.drop(key);
return Storage.removeItems(keysToBeClearedFromStorage)
const removeItemsPromise = Storage.removeItems(keysToBeClearedFromStorage);
// A full store may fit the defaults only after the removal frees space.
return Promise.all([removeItemsPromise, resetDefaultsPromise.catch(() => removeItemsPromise.then(resetDefaults))])
.then(() => {
// Save written keys again in case `removeItems` deleted them after they were stored.
keysWrittenByOtherInstance = collectKeysWrittenByOtherInstance();
// Save this tab's writes again, the removal may have deleted them.
const writtenKeyValuePairs = Object.keys(valuesSetByClear)
.filter((key) => !OnyxKeys.isRamOnlyKey(key) && wasWrittenDuringClear(key))
.filter((key) => !OnyxKeys.isRamOnlyKey(key) && wasWrittenOnlyByThisInstance(key))
.map((key): [OnyxKey, OnyxValue<OnyxKey>] => [key, cache.get(key)]);
return Storage.multiSet([...defaultKeyValuePairs.filter(([key]) => !wasWrittenDuringClear(key)), ...writtenKeyValuePairs]);
return writtenKeyValuePairs.length > 0 ? Storage.multiSet(writtenKeyValuePairs) : undefined;
})
.then(() => {
keysWrittenByOtherInstance = collectKeysWrittenByOtherInstance();
keysWrittenDuringReadback = new Set();
return keysWrittenByOtherInstance.size > 0 ? Storage.multiGet([...keysWrittenByOtherInstance]) : [];
Comment thread
elirangoshen marked this conversation as resolved.
Resolved
})
.then((pairsWrittenByOtherInstance) => {
for (const [key, storedValue] of pairsWrittenByOtherInstance) {
// A write this tab made during the read is newer than the value read
if (keysWrittenDuringReadback?.has(key)) {
keysWrittenByOtherInstance.delete(key);
continue;
}
const storedOrDefault = storedValue ?? OnyxUtils.getNullFreeDefaultKeyState(key) ?? undefined;
const value = utils.needsNormalization(storedOrDefault) ? utils.removeNestedNullValues(storedOrDefault) : storedOrDefault;
if (value === undefined) {
cache.drop(key);
} else {
cache.set(key, value);
}
const collectionKey = OnyxKeys.getCollectionKey(key);
if (collectionKey) {
if (!keyValuesToResetAsCollection[collectionKey]) {
keyValuesToResetAsCollection[collectionKey] = {oldValues: {}, newValues: {}};
}
if (!(key in keyValuesToResetAsCollection[collectionKey].oldValues)) {
keyValuesToResetAsCollection[collectionKey].oldValues[key] = valuesSetByClear[key] ?? undefined;
}
keyValuesToResetAsCollection[collectionKey].newValues[key] = value;
} else {
keyValuesToResetIndividually[key] = value;
}
}

DevTools.clearState(keysToPreserve);

onyxSubscriptionManager.resetCacheMissReports();

// Notify the subscribers for each key/value group so they can receive the new values.
// Keys written during the clear are skipped, their subscribers already have the newer value.
// Keys this tab wrote during the clear are skipped, their subscribers already have the newer value.
for (const [key, value] of Object.entries(keyValuesToResetIndividually)) {
if (wasWrittenDuringClear(key)) {
if (wasWrittenOnlyByThisInstance(key)) {
continue;
}
OnyxUtils.notifyKey(key, value);
}
for (const [key, value] of Object.entries(keyValuesToResetAsCollection)) {
const writtenMemberKeys = Object.keys(value.newValues).filter(wasWrittenDuringClear);
const writtenMemberKeys = Object.keys(value.newValues).filter(wasWrittenOnlyByThisInstance);
for (const memberKey of writtenMemberKeys) {
delete value.newValues[memberKey];
delete value.oldValues[memberKey];
Expand All @@ -572,7 +629,11 @@ function clear(keysToPreserve: OnyxKey[] = []): Promise<void> {
return cache.captureTask(TASK.CLEAR, promise) as Promise<void>;
}),
);
clearPromise.then(removeWriteListener, removeWriteListener);
const removeListeners = () => {
removeWriteListener();
removeOtherInstanceWriteListener();
};
clearPromise.then(removeListeners, removeListeners);
return clearPromise;
}

Expand Down
22 changes: 22 additions & 0 deletions lib/PendingWrites.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ const pendingGlobalWrites = new Set<Promise<unknown>>();

// Told about every write as it is issued, so Onyx.clear can tell writes apart from reads refilling the cache.
const writeListeners = new Set<(keys: OnyxKey[]) => void>();
// Told about keys another tab writes, so Onyx.clear doesn't overwrite them.
const otherInstanceWriteListeners = new Set<(keys: OnyxKey[]) => void>();

/**
* Registers an in-flight write under each key it can change, so `scheduleInitialSubscriberNotification`
Expand Down Expand Up @@ -64,6 +66,23 @@ function addWriteListener(listener: (keys: OnyxKey[]) => void): () => void {
return () => writeListeners.delete(listener);
}

/**
* Calls `listener` with the keys another tab writes from now on, until the returned function is called.
*/
function addOtherInstanceWriteListener(listener: (keys: OnyxKey[]) => void): () => void {
otherInstanceWriteListeners.add(listener);
return () => otherInstanceWriteListeners.delete(listener);
}

/**
* Reports keys another tab wrote to shared storage.
*/
function reportOtherInstanceWrite(keys: OnyxKey[]): void {
for (const listener of otherInstanceWriteListeners) {
listener(keys);
}
}

/**
* In-flight writes that can change the value delivered to a subscriber of `key`: writes to the key
* itself, writes to any member when `key` is a collection root, and global writes (clear).
Expand Down Expand Up @@ -111,12 +130,15 @@ function clearPendingWrites(): void {
pendingWritesByKey.clear();
pendingGlobalWrites.clear();
writeListeners.clear();
otherInstanceWriteListeners.clear();
}

export default {
trackPendingWrite,
trackPendingGlobalWrite,
addWriteListener,
addOtherInstanceWriteListener,
reportOtherInstanceWrite,
getPendingWritesForKey,
scheduleInitialSubscriberNotification,
clearPendingWrites,
Expand Down
1 change: 1 addition & 0 deletions lib/storage/InstanceSync/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ const InstanceSync = {
multiSet: NOOP,
mergeItem: NOOP,
clear: <T extends () => void>(callback: T) => Promise.resolve(callback()),
noteLocalWrite: NOOP,
};

export default InstanceSync;
44 changes: 41 additions & 3 deletions lib/storage/InstanceSync/index.web.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
import * as Logger from '../../Logger';
import type {OnyxKey} from '../../types';
import NoopProvider from '../providers/NoopProvider';
import type {StorageKeyList, OnStorageKeysChanged} from '../providers/types';
import type {StorageKeyList, OnStorageKeysChanged, OnStorageKeysAnnounced} from '../providers/types';
import type StorageProvider from '../providers/types';

const SYNC_ONYX = 'SYNC_ONYX';
Expand Down Expand Up @@ -92,12 +92,47 @@ function raiseStorageSyncEvent(onyxKey: OnyxKey) {

let storage = NoopProvider;

// Reads for another tab's changes, with the keys this tab wrote meanwhile (newer than what the read returns).
const readsInProgress = new Set<{keys: Set<OnyxKey>; writtenLocally: Set<OnyxKey>}>();

/**
* Reads the keys another tab changed. Keys this tab wrote during the read are read again.
*/
function readChangedKeys(onyxKeys: StorageKeyList, onStorageKeysChanged: OnStorageKeysChanged) {
const read = {keys: new Set(onyxKeys), writtenLocally: new Set<OnyxKey>()};
readsInProgress.add(read);
storage
.multiGet(onyxKeys)
.then((pairs) => {
readsInProgress.delete(read);
onStorageKeysChanged(pairs.filter(([key]) => !read.writtenLocally.has(key)));
if (read.writtenLocally.size > 0) {
readChangedKeys(Array.from(read.writtenLocally), onStorageKeysChanged);
}
})
.finally(() => readsInProgress.delete(read));
}

/**
* Records keys this tab is about to write, so values read for another tab's event don't overwrite them.
*/
function noteLocalWrite(onyxKeys: StorageKeyList) {
for (const read of readsInProgress) {
for (const onyxKey of onyxKeys) {
if (read.keys.has(onyxKey)) {
read.writtenLocally.add(onyxKey);
}
}
}
}

const InstanceSync = {
shouldBeUsed: true,
/**
* @param {Function} onStorageKeysChanged Storage synchronization mechanism keeping all opened tabs in sync
* @param onStorageKeysAnnounced Called with the changed keys as soon as the event arrives
*/
init: (onStorageKeysChanged: OnStorageKeysChanged, store: StorageProvider<unknown>) => {
init: (onStorageKeysChanged: OnStorageKeysChanged, store: StorageProvider<unknown>, onStorageKeysAnnounced?: OnStorageKeysAnnounced) => {
storage = store;

// Coalesce storage events into one dispatch per tick: a per-key sender would otherwise re-run
Expand All @@ -112,6 +147,8 @@ const InstanceSync = {
}

const onyxKeys = parseSyncOnyxStorageEventValue(event.newValue);
// Reported before the read, so a running Onyx.clear doesn't overwrite these keys meanwhile
onStorageKeysAnnounced?.(onyxKeys);

if (pendingSyncKeys) {
for (const onyxKey of onyxKeys) {
Expand All @@ -124,7 +161,7 @@ const InstanceSync = {
setTimeout(() => {
const keys = Array.from(pendingSyncKeys ?? []);
pendingSyncKeys = null;
storage.multiGet(keys).then((pairs) => onStorageKeysChanged(pairs));
readChangedKeys(keys, onStorageKeysChanged);
}, 0);
});
},
Expand All @@ -134,6 +171,7 @@ const InstanceSync = {
multiMerge: raiseStorageSyncManyKeysEvent,
multiSet: raiseStorageSyncManyKeysEvent,
mergeItem: raiseStorageSyncEvent,
noteLocalWrite,
clear: (clearImplementation: () => void) => {
let allKeys: StorageKeyList;

Expand Down
44 changes: 36 additions & 8 deletions lib/storage/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import InstanceSync from './InstanceSync';
import MemoryOnlyProvider from './providers/MemoryOnlyProvider';
import {StorageErrorClass} from './errors';
import type StorageProvider from './providers/types';
import type {StorageKeyValuePair} from './providers/types';
import type {StorageKeyList, StorageKeyValuePair} from './providers/types';

let provider = PlatformStorage as StorageProvider<unknown>;

Expand Down Expand Up @@ -114,6 +114,9 @@ const storage: Storage = {
*/
setItem: (key, value) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite([key]);
}
const promise = provider.setItem(key, value);

if (shouldKeepInstancesSync) {
Expand All @@ -128,6 +131,9 @@ const storage: Storage = {
*/
multiSet: (pairs) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite(pairs.map((pair) => pair[0]));
}
const promise = provider.multiSet(pairs);

if (shouldKeepInstancesSync) {
Expand All @@ -142,6 +148,9 @@ const storage: Storage = {
*/
mergeItem: (key, change, replaceNullPatches) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite([key]);
}
const promise = provider.mergeItem(key, change, replaceNullPatches);

if (shouldKeepInstancesSync) {
Expand All @@ -157,6 +166,9 @@ const storage: Storage = {
*/
multiMerge: (pairs) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite(pairs.map((pair) => pair[0]));
}
const promise = provider.multiMerge(pairs);

if (shouldKeepInstancesSync) {
Expand All @@ -171,6 +183,9 @@ const storage: Storage = {
*/
removeItem: (key) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite([key]);
}
const promise = provider.removeItem(key);

if (shouldKeepInstancesSync) {
Expand All @@ -185,6 +200,9 @@ const storage: Storage = {
*/
removeItems: (keys) =>
tryOrDegradePerformance(() => {
if (shouldKeepInstancesSync) {
InstanceSync.noteLocalWrite(keys);
}
const promise = provider.removeItems(keys);

if (shouldKeepInstancesSync) {
Expand Down Expand Up @@ -223,18 +241,28 @@ const storage: Storage = {

/**
* @param onStorageKeysChanged - Storage synchronization mechanism keeping all opened tabs in sync (web only)
* @param onStorageKeysAnnounced - Called with the keys another tab changed, before their values are read (web only)
*/
keepInstancesSync(onStorageKeysChanged) {
keepInstancesSync(onStorageKeysChanged, onStorageKeysAnnounced) {
// If InstanceSync shouldn't be used, it means we're on a native platform and we don't need to keep instances in sync
if (!InstanceSync.shouldBeUsed) return;

shouldKeepInstancesSync = true;
InstanceSync.init((pairs: StorageKeyValuePair[]) => {
if (provider === MemoryOnlyProvider) {
return;
}
onStorageKeysChanged(pairs);
}, this);
InstanceSync.init(
(pairs: StorageKeyValuePair[]) => {
if (provider === MemoryOnlyProvider) {
return;
}
onStorageKeysChanged(pairs);
},
this,
(keys: StorageKeyList) => {
if (provider === MemoryOnlyProvider) {
return;
}
onStorageKeysAnnounced?.(keys);
},
);
},
};

Expand Down
8 changes: 6 additions & 2 deletions lib/storage/providers/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ type DatabaseSize = {
/** Called with the full batch of key/value pairs that changed together in a single cross-tab sync event. */
type OnStorageKeysChanged = (pairs: StorageKeyValuePair[]) => void;

/** Called with the keys another tab changed, before their values are read. */
type OnStorageKeysAnnounced = (keys: StorageKeyList) => void;

type StorageProvider<TStore> = {
store: TStore;

Expand Down Expand Up @@ -99,9 +102,10 @@ type StorageProvider<TStore> = {

/**
* @param onStorageKeysChanged Storage synchronization mechanism keeping all opened tabs in sync
* @param onStorageKeysAnnounced Called with the changed keys before their values are read
*/
keepInstancesSync?: (onStorageKeysChanged: OnStorageKeysChanged) => void;
keepInstancesSync?: (onStorageKeysChanged: OnStorageKeysChanged, onStorageKeysAnnounced?: OnStorageKeysAnnounced) => void;
};

export default StorageProvider;
export type {StorageKeyList, StorageKeyValuePair, OnStorageKeysChanged};
export type {StorageKeyList, StorageKeyValuePair, OnStorageKeysChanged, OnStorageKeysAnnounced};
Loading
Loading