-
Notifications
You must be signed in to change notification settings - Fork 74
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
#15321: Only one tab writes to the DB #382
Changes from 32 commits
5c50c31
870d715
55a1394
bb8be0a
c61749e
fb4cd2f
24e4cb8
c78e71a
d1fbe0d
e4a318e
d839fab
8e7aa3b
685c8f7
ce15ce8
86fb581
37580f3
88ee143
63dd112
c38b935
d12b355
76fd53f
8c4bfd1
f0d3cf4
b6db16e
9efe824
8205872
5234f41
4e9a741
8bd842c
b0ae970
842789a
8f4b3b0
cee3473
4f0638e
cd9e9e9
831b8bc
7127185
f57f3f9
0dbd4b0
dd5dea9
cdb2680
833d39a
d8a1e22
c72152c
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
/** | ||
* Determines when the client is ready. We need to wait till the init method is called and the leader message is sent. | ||
*/ | ||
declare function isReady(): Promise<void>; | ||
|
||
/** | ||
* Subscribes to the broadcast channel to listen for messages from other tabs, so that | ||
* all tabs agree on who the leader is, which should always be the last tab to open. | ||
*/ | ||
declare function init(): void; | ||
|
||
/** | ||
* Returns a boolean indicating if the current client is the leader. | ||
*/ | ||
declare function isClientTheLeader(): boolean; | ||
|
||
/** | ||
* Subscribes to when the client changes. | ||
*/ | ||
declare function subscribeToClientChange(callback: () => {}): void; | ||
|
||
export {isReady, init, isClientTheLeader, subscribeToClientChange}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
/** | ||
* For native devices, there will never be more than one | ||
* client running at a time, so this lib is a big no-op | ||
*/ | ||
|
||
function isReady() { | ||
return Promise.resolve(); | ||
} | ||
|
||
function isClientTheLeader() { | ||
return true; | ||
} | ||
|
||
function init() {} | ||
|
||
function subscribeToClientChange() {} | ||
|
||
export { | ||
isClientTheLeader, | ||
init, | ||
isReady, | ||
subscribeToClientChange, | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,99 @@ | ||
/** | ||
* When you have many tabs in one browser, the data of Onyx is shared between all of them. Since we persist write requests in Onyx, we need to ensure that | ||
* only one tab is processing those saved requests or we would be duplicating data (or creating errors). | ||
* This file ensures exactly that by tracking all the clientIDs connected, storing the most recent one last and it considers that last clientID the "leader". | ||
*/ | ||
|
||
import * as Str from '../Str'; | ||
import * as Broadcast from '../broadcast'; | ||
|
||
const NEW_LEADER_MESSAGE = 'NEW_LEADER'; | ||
const REMOVED_LEADER_MESSAGE = 'REMOVE_LEADER'; | ||
|
||
const clientID = Str.guid(); | ||
const subscribers = []; | ||
let timestamp = null; | ||
|
||
let activeClient = null; | ||
roryabraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
let resolveSavedSelfPromise = () => {}; | ||
roryabraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
const savedSelfPromise = new Promise((resolve) => { | ||
roryabraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
resolveSavedSelfPromise = resolve; | ||
}); | ||
|
||
/** | ||
* Determines when the client is ready. We need to wait both till we saved our ID in onyx AND the init method was called | ||
* @returns {Promise} | ||
*/ | ||
function isReady() { | ||
return savedSelfPromise; | ||
} | ||
|
||
/** | ||
* Returns a boolean indicating if the current client is the leader. | ||
* | ||
* @returns {Boolean} | ||
*/ | ||
function isClientTheLeader() { | ||
return activeClient === clientID; | ||
} | ||
|
||
/** | ||
* Subscribes to when the client changes. | ||
* @param {Function} callback | ||
*/ | ||
function subscribeToClientChange(callback) { | ||
subscribers.push(callback); | ||
} | ||
|
||
/** | ||
* Subscribe to the broadcast channel to listen for messages from other tabs, so that | ||
* all tabs agree on who the leader is, which should always be the last tab to open. | ||
*/ | ||
function init() { | ||
Broadcast.subscribe((message) => { | ||
switch (message.data.type) { | ||
case NEW_LEADER_MESSAGE: { | ||
// Only update the active leader if the message received was from another | ||
// tab that initialized after the current one; if the timestamps are the | ||
// same, it uses the client ID to tie-break | ||
const isTimestampEqual = timestamp === message.data.timestamp; | ||
const isTimestampNewer = timestamp > message.data.timestamp; | ||
if (isClientTheLeader() && (isTimestampNewer || (isTimestampEqual && clientID > message.data.clientID))) { | ||
return; | ||
} | ||
activeClient = message.data.clientID; | ||
|
||
subscribers.forEach(callback => callback()); | ||
BeeMargarida marked this conversation as resolved.
Show resolved
Hide resolved
|
||
break; | ||
} | ||
case REMOVED_LEADER_MESSAGE: | ||
activeClient = clientID; | ||
timestamp = Date.now(); | ||
Broadcast.sendMessage({type: NEW_LEADER_MESSAGE, clientID, timestamp}); | ||
subscribers.forEach(callback => callback()); | ||
BeeMargarida marked this conversation as resolved.
Show resolved
Hide resolved
|
||
break; | ||
default: | ||
break; | ||
} | ||
}); | ||
|
||
activeClient = clientID; | ||
timestamp = Date.now(); | ||
|
||
Broadcast.sendMessage({type: NEW_LEADER_MESSAGE, clientID, timestamp}); | ||
resolveSavedSelfPromise(); | ||
BeeMargarida marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
window.addEventListener('beforeunload', () => { | ||
if (!isClientTheLeader()) { | ||
return; | ||
} | ||
Broadcast.sendMessage({type: REMOVED_LEADER_MESSAGE, clientID}); | ||
}); | ||
} | ||
|
||
export { | ||
isClientTheLeader, | ||
init, | ||
isReady, | ||
subscribeToClientChange, | ||
}; |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,8 @@ import * as Str from './Str'; | |
import createDeferredTask from './createDeferredTask'; | ||
import * as PerformanceUtils from './metrics/PerformanceUtils'; | ||
import Storage from './storage'; | ||
import * as Broadcast from './broadcast'; | ||
import * as ActiveClientManager from './ActiveClientManager'; | ||
import utils from './utils'; | ||
import unstable_batchedUpdates from './batch'; | ||
|
||
|
@@ -19,6 +21,8 @@ const METHOD = { | |
CLEAR: 'clear', | ||
}; | ||
|
||
const ON_CLEAR = 'on_clear'; | ||
|
||
// Key/value store of Onyx key and arrays of values to merge | ||
const mergeQueue = {}; | ||
const mergeQueuePromise = {}; | ||
|
@@ -49,6 +53,12 @@ let defaultKeyStates = {}; | |
// Connections can be made before `Onyx.init`. They would wait for this task before resolving | ||
const deferredInitTask = createDeferredTask(); | ||
|
||
// The promise of the clear function, saved so that no writes happen while it's executing | ||
let ongoingClear = false; | ||
roryabraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
// Callback to be executed after the clear execution ends | ||
let onClearCallback = null; | ||
|
||
let batchUpdatesPromise = null; | ||
let batchUpdatesQueue = []; | ||
|
||
|
@@ -1060,6 +1070,15 @@ function removeNullValues(key, value) { | |
* @returns {Promise} | ||
*/ | ||
function set(key, value) { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
Broadcast.sendMessage({type: METHOD.SET, key, value}); | ||
roryabraham marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return Promise.resolve(); | ||
} | ||
|
||
if (ongoingClear) { | ||
return Promise.resolve(); | ||
} | ||
|
||
const valueWithoutNull = removeNullValues(key, value); | ||
|
||
if (valueWithoutNull === null) { | ||
|
@@ -1106,6 +1125,15 @@ function prepareKeyValuePairsForStorage(data) { | |
* @returns {Promise} | ||
*/ | ||
function multiSet(data) { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
Broadcast.sendMessage({type: METHOD.MULTI_SET, data}); | ||
return Promise.resolve(); | ||
} | ||
|
||
if (ongoingClear) { | ||
return Promise.resolve(); | ||
} | ||
|
||
const keyValuePairs = prepareKeyValuePairsForStorage(data); | ||
|
||
const updatePromises = _.map(data, (val, key) => { | ||
|
@@ -1176,6 +1204,15 @@ function applyMerge(existingValue, changes, shouldRemoveNullObjectValues) { | |
* @returns {Promise} | ||
*/ | ||
function merge(key, changes) { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
Broadcast.sendMessage({type: METHOD.MERGE, key, changes}); | ||
return Promise.resolve(); | ||
} | ||
|
||
if (ongoingClear) { | ||
return Promise.resolve(); | ||
} | ||
|
||
// Top-level undefined values are ignored | ||
// Therefore we need to prevent adding them to the merge queue | ||
if (_.isUndefined(changes)) { | ||
|
@@ -1229,7 +1266,7 @@ function merge(key, changes) { | |
const updatePromise = broadcastUpdate(key, modifiedData, hasChanged, 'merge'); | ||
|
||
// If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead. | ||
if (!hasChanged) { | ||
if (!hasChanged || ongoingClear) { | ||
BeeMargarida marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return updatePromise; | ||
} | ||
|
||
|
@@ -1283,6 +1320,17 @@ function initializeWithDefaultKeyStates() { | |
* @returns {Promise<void>} | ||
*/ | ||
function clear(keysToPreserve = []) { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
Broadcast.sendMessage({type: METHOD.CLEAR, keysToPreserve}); | ||
return Promise.resolve(); | ||
} | ||
|
||
if (ongoingClear) { | ||
return Promise.resolve(); | ||
} | ||
|
||
ongoingClear = true; | ||
|
||
return getAllKeys() | ||
.then((keys) => { | ||
const keysToBeClearedFromStorage = []; | ||
|
@@ -1341,7 +1389,11 @@ function clear(keysToPreserve = []) { | |
|
||
// Remove only the items that we want cleared from storage, and reset others to default | ||
_.each(keysToBeClearedFromStorage, key => cache.drop(key)); | ||
return Storage.removeItems(keysToBeClearedFromStorage).then(() => Storage.multiSet(defaultKeyValuePairs)).then(() => Promise.all(updatePromises)); | ||
return Storage.removeItems(keysToBeClearedFromStorage).then(() => Storage.multiSet(defaultKeyValuePairs)).then(() => { | ||
ongoingClear = false; | ||
Broadcast.sendMessage({type: METHOD.CLEAR, keysToPreserve}); | ||
return Promise.all(updatePromises); | ||
}); | ||
}); | ||
} | ||
|
||
|
@@ -1491,6 +1543,48 @@ function setMemoryOnlyKeys(keyList) { | |
cache.setRecentKeysLimit(Infinity); | ||
} | ||
|
||
/** | ||
* Sets the callback to be called when the clear finishes executing. | ||
* @param {Function} callback | ||
*/ | ||
function onClear(callback) { | ||
onClearCallback = callback; | ||
} | ||
|
||
/** | ||
* Subscribes to the Broadcast channel and executes actions based on the | ||
* types of events. | ||
*/ | ||
function subscribeToEvents() { | ||
Broadcast.subscribe(({data}) => { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
return; | ||
} | ||
switch (data.type) { | ||
case METHOD.CLEAR: | ||
clear(data.keysToPreserve); | ||
break; | ||
case METHOD.SET: | ||
set(data.key, data.value); | ||
break; | ||
case METHOD.MULTI_SET: | ||
multiSet(data.key, data.value); | ||
break; | ||
case METHOD.MERGE: | ||
merge(data.key, data.changes); | ||
break; | ||
case ON_CLEAR: | ||
if (!onClearCallback) { | ||
break; | ||
} | ||
onClearCallback(); | ||
BeeMargarida marked this conversation as resolved.
Show resolved
Hide resolved
|
||
break; | ||
default: | ||
break; | ||
} | ||
}); | ||
} | ||
|
||
/** | ||
* Initialize the store with actions and listening for storage events | ||
* | ||
|
@@ -1525,6 +1619,21 @@ function init({ | |
shouldSyncMultipleInstances = Boolean(global.localStorage), | ||
debugSetState = false, | ||
} = {}) { | ||
ActiveClientManager.init(); | ||
|
||
ActiveClientManager.isReady().then(() => { | ||
if (!ActiveClientManager.isClientTheLeader()) { | ||
return; | ||
} | ||
subscribeToEvents(); | ||
}); | ||
|
||
// If the active client changes an the current client is the leader, | ||
// subscribes to the events | ||
ActiveClientManager.subscribeToClientChange(() => { | ||
subscribeToEvents(); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I'm confused why we would need this, and concerned that we're adding subscriptions without every cleaning them up There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I think we don't need it at all. Every time we opened or closed a tab (yes, it pushed a callback when a tab was closed instead of removing it) it added the same callback to the subscriptions array. And every time a message was received it run all the callbacks in the array were called. For non-leader tabs it returned early so it wasn't a problem but if there was i.e. 8 callbacks in the subscriptions array it would be called 8 times. For a new tab aka the leader tab we have always 2 different subscriptions and it's ok. I removed this part of code and it works fine. For non leader tabs we also have only two callbacks in the subscriptions array. So I think now we don't need to add the unsubscribe logic here anymore. |
||
}); | ||
|
||
if (captureMetrics) { | ||
// The code here is only bundled and applied when the captureMetrics is set | ||
// eslint-disable-next-line no-use-before-define | ||
|
@@ -1587,6 +1696,10 @@ const Onyx = { | |
setMemoryOnlyKeys, | ||
tryGetCachedValue, | ||
hasPendingMergeForKey, | ||
onClear, | ||
isClientManagerReady: ActiveClientManager.isReady, | ||
isClientTheLeader: ActiveClientManager.isClientTheLeader, | ||
subscribeToClientChange: ActiveClientManager.subscribeToClientChange, | ||
}; | ||
|
||
/** | ||
|
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.
Just realizing that this comment is a bit out-of-date. This code no longer has anything to do with processing write requests.