Skip to content
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

Merged
merged 44 commits into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from 32 commits
Commits
Show all changes
44 commits
Select commit Hold shift + click to select a range
5c50c31
feat: ActiveClientManager port
BeeMargarida Sep 4, 2023
870d715
feat: broadcast
BeeMargarida Sep 4, 2023
55a1394
feat: only leader can write to DB
BeeMargarida Sep 4, 2023
bb8be0a
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Sep 27, 2023
c61749e
fix: typo in import
BeeMargarida Sep 28, 2023
fb4cd2f
feat: e2e test app setup
BeeMargarida Sep 28, 2023
24e4cb8
test: playwright e2e tests setup
BeeMargarida Sep 28, 2023
c78e71a
revert: added unsubscrive
BeeMargarida Sep 29, 2023
d1fbe0d
test: tabs e2e tests
BeeMargarida Sep 29, 2023
e4a318e
feat: playwright config
BeeMargarida Oct 2, 2023
d839fab
revert: test ignore
BeeMargarida Oct 2, 2023
8e7aa3b
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 2, 2023
685c8f7
chore: update package-lock
BeeMargarida Oct 2, 2023
ce15ce8
test: cleanup simple tests
BeeMargarida Oct 3, 2023
86fb581
test: use getByRole instead of getByTestId
BeeMargarida Oct 3, 2023
37580f3
test: comment out webkit from playwright config
BeeMargarida Oct 3, 2023
88ee143
fix: ignore e2e in jest config
BeeMargarida Oct 3, 2023
63dd112
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 4, 2023
c38b935
fix: set correct default values and better docs
BeeMargarida Oct 4, 2023
d12b355
test: rename test file and suite
BeeMargarida Oct 4, 2023
76fd53f
refactor: simplify conditional
BeeMargarida Oct 4, 2023
8c4bfd1
fix: review fixes
BeeMargarida Oct 4, 2023
f0d3cf4
fix: remove unsubscribe unused method
BeeMargarida Oct 4, 2023
b6db16e
fix: small regression
BeeMargarida Oct 4, 2023
9efe824
docs: add comment
BeeMargarida Oct 4, 2023
8205872
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 5, 2023
5234f41
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 6, 2023
4e9a741
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 9, 2023
8bd842c
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 10, 2023
b0ae970
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 11, 2023
842789a
Merge branch 'main' into feat/tab_leader_write
BeeMargarida Oct 13, 2023
8f4b3b0
fix: resolve conflicts
koko57 Oct 24, 2023
cee3473
fix: rename a variable
koko57 Oct 27, 2023
4f0638e
Merge branch 'main' into feat/tab_leader_write
koko57 Nov 9, 2023
cd9e9e9
fix: resolve conflicts
koko57 Nov 9, 2023
831b8bc
feat: add e2e workflow
koko57 Nov 13, 2023
7127185
feat: add the info about tests to readme
koko57 Nov 14, 2023
f57f3f9
fix: minor fix
koko57 Nov 14, 2023
0dbd4b0
fix: remove unused directories
koko57 Nov 14, 2023
dd5dea9
fix: resolve conflicts
koko57 Nov 14, 2023
cdb2680
fix: remove unnecesary subscriber
koko57 Nov 15, 2023
833d39a
fix: resolve conflicts
koko57 Nov 15, 2023
d8a1e22
fix: resolve conflicts
koko57 Nov 21, 2023
c72152c
fix: apply requested changes
koko57 Nov 22, 2023
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
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,8 @@ dist/

# Decrypted private key we do not want to commit
.github/OSBotify-private-key.asc

## Playwright e2e setup
/test-results/
/playwright-report/
/playwright/.cache/
22 changes: 22 additions & 0 deletions lib/ActiveClientManager/index.d.ts
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};
23 changes: 23 additions & 0 deletions lib/ActiveClientManager/index.native.js
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,
};
99 changes: 99 additions & 0 deletions lib/ActiveClientManager/index.web.js
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
Copy link
Contributor

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.

* 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,
};
10 changes: 10 additions & 0 deletions lib/Onyx.d.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import {Component} from 'react';
import * as Logger from './Logger';
import * as ActiveClientManager from './ActiveClientManager';
import {CollectionKey, CollectionKeyBase, DeepRecord, KeyValueMapping, NullishDeep, OnyxCollection, OnyxEntry, OnyxKey} from './types';

/**
Expand Down Expand Up @@ -293,6 +294,11 @@ declare function hasPendingMergeForKey(key: OnyxKey): boolean;
*/
declare function setMemoryOnlyKeys(keyList: OnyxKey[]): void;

/**
* Sets the callback to be called when the clear finishes executing.
*/
declare function onClear(callback: () => void): void;

declare const Onyx: {
connect: typeof connect;
disconnect: typeof disconnect;
Expand All @@ -311,6 +317,10 @@ declare const Onyx: {
isSafeEvictionKey: typeof isSafeEvictionKey;
METHOD: typeof METHOD;
setMemoryOnlyKeys: typeof setMemoryOnlyKeys;
onClear: typeof onClear;
isClientManagerReady: typeof ActiveClientManager.isReady,
isClientTheLeader: typeof ActiveClientManager.isClientTheLeader,
subscribeToClientChange: typeof ActiveClientManager.subscribeToClientChange,
};

export default Onyx;
Expand Down
117 changes: 115 additions & 2 deletions lib/Onyx.js
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -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 = {};
Expand Down Expand Up @@ -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 = [];

Expand Down Expand Up @@ -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) {
Expand Down Expand Up @@ -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) => {
Expand Down Expand Up @@ -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)) {
Expand Down Expand Up @@ -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;
}

Expand Down Expand Up @@ -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 = [];
Expand Down Expand Up @@ -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);
});
});
}

Expand Down Expand Up @@ -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
*
Expand Down Expand Up @@ -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();
Copy link
Contributor

Choose a reason for hiding this comment

The 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

Copy link
Contributor

Choose a reason for hiding this comment

The 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
Expand Down Expand Up @@ -1587,6 +1696,10 @@ const Onyx = {
setMemoryOnlyKeys,
tryGetCachedValue,
hasPendingMergeForKey,
onClear,
isClientManagerReady: ActiveClientManager.isReady,
isClientTheLeader: ActiveClientManager.isClientTheLeader,
subscribeToClientChange: ActiveClientManager.subscribeToClientChange,
};

/**
Expand Down
Loading
Loading