react-native-onyx 1.0.118 → 1.0.120

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Determines when the client is ready. We need to wait till the init method is called and the leader message is sent.
3
+ */
4
+ declare function isReady(): Promise<void>;
5
+
6
+ /**
7
+ * Subscribes to the broadcast channel to listen for messages from other tabs, so that
8
+ * all tabs agree on who the leader is, which should always be the last tab to open.
9
+ */
10
+ declare function init(): void;
11
+
12
+ /**
13
+ * Returns a boolean indicating if the current client is the leader.
14
+ */
15
+ declare function isClientTheLeader(): boolean;
16
+
17
+ /**
18
+ * Subscribes to when the client changes.
19
+ */
20
+ declare function subscribeToClientChange(callback: () => {}): void;
21
+
22
+ export {isReady, init, isClientTheLeader, subscribeToClientChange};
@@ -0,0 +1,23 @@
1
+ /**
2
+ * For native devices, there will never be more than one
3
+ * client running at a time, so this lib is a big no-op
4
+ */
5
+
6
+ function isReady() {
7
+ return Promise.resolve();
8
+ }
9
+
10
+ function isClientTheLeader() {
11
+ return true;
12
+ }
13
+
14
+ function init() {}
15
+
16
+ function subscribeToClientChange() {}
17
+
18
+ export {
19
+ isClientTheLeader,
20
+ init,
21
+ isReady,
22
+ subscribeToClientChange,
23
+ };
@@ -0,0 +1,99 @@
1
+ /**
2
+ * 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
3
+ * only one tab is processing those saved requests or we would be duplicating data (or creating errors).
4
+ * 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".
5
+ */
6
+
7
+ import * as Str from '../Str';
8
+ import * as Broadcast from '../broadcast';
9
+
10
+ const NEW_LEADER_MESSAGE = 'NEW_LEADER';
11
+ const REMOVED_LEADER_MESSAGE = 'REMOVE_LEADER';
12
+
13
+ const clientID = Str.guid();
14
+ const subscribers = [];
15
+ let timestamp = null;
16
+
17
+ let activeClientID = null;
18
+ let setIsReady = () => {};
19
+ const isReadyPromise = new Promise((resolve) => {
20
+ setIsReady = resolve;
21
+ });
22
+
23
+ /**
24
+ * Determines when the client is ready. We need to wait both till we saved our ID in onyx AND the init method was called
25
+ * @returns {Promise}
26
+ */
27
+ function isReady() {
28
+ return isReadyPromise;
29
+ }
30
+
31
+ /**
32
+ * Returns a boolean indicating if the current client is the leader.
33
+ *
34
+ * @returns {Boolean}
35
+ */
36
+ function isClientTheLeader() {
37
+ return activeClientID === clientID;
38
+ }
39
+
40
+ /**
41
+ * Subscribes to when the client changes.
42
+ * @param {Function} callback
43
+ */
44
+ function subscribeToClientChange(callback) {
45
+ subscribers.push(callback);
46
+ }
47
+
48
+ /**
49
+ * Subscribe to the broadcast channel to listen for messages from other tabs, so that
50
+ * all tabs agree on who the leader is, which should always be the last tab to open.
51
+ */
52
+ function init() {
53
+ Broadcast.subscribe((message) => {
54
+ switch (message.data.type) {
55
+ case NEW_LEADER_MESSAGE: {
56
+ // Only update the active leader if the message received was from another
57
+ // tab that initialized after the current one; if the timestamps are the
58
+ // same, it uses the client ID to tie-break
59
+ const isTimestampEqual = timestamp === message.data.timestamp;
60
+ const isTimestampNewer = timestamp > message.data.timestamp;
61
+ if (isClientTheLeader() && (isTimestampNewer || (isTimestampEqual && clientID > message.data.clientID))) {
62
+ return;
63
+ }
64
+ activeClientID = message.data.clientID;
65
+
66
+ subscribers.forEach(callback => callback());
67
+ break;
68
+ }
69
+ case REMOVED_LEADER_MESSAGE:
70
+ activeClientID = clientID;
71
+ timestamp = Date.now();
72
+ Broadcast.sendMessage({type: NEW_LEADER_MESSAGE, clientID, timestamp});
73
+ subscribers.forEach(callback => callback());
74
+ break;
75
+ default:
76
+ break;
77
+ }
78
+ });
79
+
80
+ activeClientID = clientID;
81
+ timestamp = Date.now();
82
+
83
+ Broadcast.sendMessage({type: NEW_LEADER_MESSAGE, clientID, timestamp});
84
+ setIsReady();
85
+
86
+ window.addEventListener('beforeunload', () => {
87
+ if (!isClientTheLeader()) {
88
+ return;
89
+ }
90
+ Broadcast.sendMessage({type: REMOVED_LEADER_MESSAGE, clientID});
91
+ });
92
+ }
93
+
94
+ export {
95
+ isClientTheLeader,
96
+ init,
97
+ isReady,
98
+ subscribeToClientChange,
99
+ };
package/lib/Onyx.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import {Component} from 'react';
2
2
  import * as Logger from './Logger';
3
+ import * as ActiveClientManager from './ActiveClientManager';
3
4
  import {CollectionKey, CollectionKeyBase, DeepRecord, KeyValueMapping, NullishDeep, OnyxCollection, OnyxEntry, OnyxKey} from './types';
4
5
 
5
6
  /**
@@ -293,6 +294,11 @@ declare function hasPendingMergeForKey(key: OnyxKey): boolean;
293
294
  */
294
295
  declare function setMemoryOnlyKeys(keyList: OnyxKey[]): void;
295
296
 
297
+ /**
298
+ * Sets the callback to be called when the clear finishes executing.
299
+ */
300
+ declare function onClear(callback: () => void): void;
301
+
296
302
  declare const Onyx: {
297
303
  connect: typeof connect;
298
304
  disconnect: typeof disconnect;
@@ -311,6 +317,10 @@ declare const Onyx: {
311
317
  isSafeEvictionKey: typeof isSafeEvictionKey;
312
318
  METHOD: typeof METHOD;
313
319
  setMemoryOnlyKeys: typeof setMemoryOnlyKeys;
320
+ onClear: typeof onClear;
321
+ isClientManagerReady: typeof ActiveClientManager.isReady,
322
+ isClientTheLeader: typeof ActiveClientManager.isClientTheLeader,
323
+ subscribeToClientChange: typeof ActiveClientManager.subscribeToClientChange,
314
324
  };
315
325
 
316
326
  export default Onyx;
package/lib/Onyx.js CHANGED
@@ -7,6 +7,8 @@ import * as Str from './Str';
7
7
  import createDeferredTask from './createDeferredTask';
8
8
  import * as PerformanceUtils from './metrics/PerformanceUtils';
9
9
  import Storage from './storage';
10
+ import * as Broadcast from './broadcast';
11
+ import * as ActiveClientManager from './ActiveClientManager';
10
12
  import utils from './utils';
11
13
  import unstable_batchedUpdates from './batch';
12
14
 
@@ -19,6 +21,8 @@ const METHOD = {
19
21
  CLEAR: 'clear',
20
22
  };
21
23
 
24
+ const ON_CLEAR = 'on_clear';
25
+
22
26
  // Key/value store of Onyx key and arrays of values to merge
23
27
  const mergeQueue = {};
24
28
  const mergeQueuePromise = {};
@@ -49,6 +53,12 @@ let defaultKeyStates = {};
49
53
  // Connections can be made before `Onyx.init`. They would wait for this task before resolving
50
54
  const deferredInitTask = createDeferredTask();
51
55
 
56
+ // The promise of the clear function, saved so that no writes happen while it's executing
57
+ let isClearing = false;
58
+
59
+ // Callback to be executed after the clear execution ends
60
+ let onClearCallback = null;
61
+
52
62
  let batchUpdatesPromise = null;
53
63
  let batchUpdatesQueue = [];
54
64
 
@@ -1060,6 +1070,15 @@ function removeNullValues(key, value) {
1060
1070
  * @returns {Promise}
1061
1071
  */
1062
1072
  function set(key, value) {
1073
+ if (!ActiveClientManager.isClientTheLeader()) {
1074
+ Broadcast.sendMessage({type: METHOD.SET, key, value});
1075
+ return Promise.resolve();
1076
+ }
1077
+
1078
+ if (isClearing) {
1079
+ return Promise.resolve();
1080
+ }
1081
+
1063
1082
  const valueWithoutNull = removeNullValues(key, value);
1064
1083
 
1065
1084
  if (valueWithoutNull === null) {
@@ -1106,6 +1125,15 @@ function prepareKeyValuePairsForStorage(data) {
1106
1125
  * @returns {Promise}
1107
1126
  */
1108
1127
  function multiSet(data) {
1128
+ if (!ActiveClientManager.isClientTheLeader()) {
1129
+ Broadcast.sendMessage({type: METHOD.MULTI_SET, data});
1130
+ return Promise.resolve();
1131
+ }
1132
+
1133
+ if (isClearing) {
1134
+ return Promise.resolve();
1135
+ }
1136
+
1109
1137
  const keyValuePairs = prepareKeyValuePairsForStorage(data);
1110
1138
 
1111
1139
  const updatePromises = _.map(data, (val, key) => {
@@ -1176,6 +1204,15 @@ function applyMerge(existingValue, changes, shouldRemoveNullObjectValues) {
1176
1204
  * @returns {Promise}
1177
1205
  */
1178
1206
  function merge(key, changes) {
1207
+ if (!ActiveClientManager.isClientTheLeader()) {
1208
+ Broadcast.sendMessage({type: METHOD.MERGE, key, changes});
1209
+ return Promise.resolve();
1210
+ }
1211
+
1212
+ if (isClearing) {
1213
+ return Promise.resolve();
1214
+ }
1215
+
1179
1216
  // Top-level undefined values are ignored
1180
1217
  // Therefore we need to prevent adding them to the merge queue
1181
1218
  if (_.isUndefined(changes)) {
@@ -1230,7 +1267,7 @@ function merge(key, changes) {
1230
1267
  const updatePromise = broadcastUpdate(key, modifiedData, hasChanged, 'merge');
1231
1268
 
1232
1269
  // If the value has not changed, calling Storage.setItem() would be redundant and a waste of performance, so return early instead.
1233
- if (!hasChanged) {
1270
+ if (!hasChanged || isClearing) {
1234
1271
  return updatePromise;
1235
1272
  }
1236
1273
 
@@ -1284,6 +1321,17 @@ function initializeWithDefaultKeyStates() {
1284
1321
  * @returns {Promise<void>}
1285
1322
  */
1286
1323
  function clear(keysToPreserve = []) {
1324
+ if (!ActiveClientManager.isClientTheLeader()) {
1325
+ Broadcast.sendMessage({type: METHOD.CLEAR, keysToPreserve});
1326
+ return Promise.resolve();
1327
+ }
1328
+
1329
+ if (isClearing) {
1330
+ return Promise.resolve();
1331
+ }
1332
+
1333
+ isClearing = true;
1334
+
1287
1335
  return getAllKeys()
1288
1336
  .then((keys) => {
1289
1337
  const keysToBeClearedFromStorage = [];
@@ -1342,7 +1390,11 @@ function clear(keysToPreserve = []) {
1342
1390
 
1343
1391
  // Remove only the items that we want cleared from storage, and reset others to default
1344
1392
  _.each(keysToBeClearedFromStorage, key => cache.drop(key));
1345
- return Storage.removeItems(keysToBeClearedFromStorage).then(() => Storage.multiSet(defaultKeyValuePairs)).then(() => Promise.all(updatePromises));
1393
+ return Storage.removeItems(keysToBeClearedFromStorage).then(() => Storage.multiSet(defaultKeyValuePairs)).then(() => {
1394
+ isClearing = false;
1395
+ Broadcast.sendMessage({type: METHOD.CLEAR, keysToPreserve});
1396
+ return Promise.all(updatePromises);
1397
+ });
1346
1398
  });
1347
1399
  }
1348
1400
 
@@ -1492,6 +1544,48 @@ function setMemoryOnlyKeys(keyList) {
1492
1544
  cache.setRecentKeysLimit(Infinity);
1493
1545
  }
1494
1546
 
1547
+ /**
1548
+ * Sets the callback to be called when the clear finishes executing.
1549
+ * @param {Function} callback
1550
+ */
1551
+ function onClear(callback) {
1552
+ onClearCallback = callback;
1553
+ }
1554
+
1555
+ /**
1556
+ * Subscribes to the Broadcast channel and executes actions based on the
1557
+ * types of events.
1558
+ */
1559
+ function subscribeToEvents() {
1560
+ Broadcast.subscribe(({data}) => {
1561
+ if (!ActiveClientManager.isClientTheLeader()) {
1562
+ return;
1563
+ }
1564
+ switch (data.type) {
1565
+ case METHOD.CLEAR:
1566
+ clear(data.keysToPreserve);
1567
+ break;
1568
+ case METHOD.SET:
1569
+ set(data.key, data.value);
1570
+ break;
1571
+ case METHOD.MULTI_SET:
1572
+ multiSet(data.key, data.value);
1573
+ break;
1574
+ case METHOD.MERGE:
1575
+ merge(data.key, data.changes);
1576
+ break;
1577
+ case ON_CLEAR:
1578
+ if (!onClearCallback) {
1579
+ break;
1580
+ }
1581
+ onClearCallback();
1582
+ break;
1583
+ default:
1584
+ break;
1585
+ }
1586
+ });
1587
+ }
1588
+
1495
1589
  /**
1496
1590
  * Initialize the store with actions and listening for storage events
1497
1591
  *
@@ -1526,6 +1620,15 @@ function init({
1526
1620
  shouldSyncMultipleInstances = Boolean(global.localStorage),
1527
1621
  debugSetState = false,
1528
1622
  } = {}) {
1623
+ ActiveClientManager.init();
1624
+
1625
+ ActiveClientManager.isReady().then(() => {
1626
+ if (!ActiveClientManager.isClientTheLeader()) {
1627
+ return;
1628
+ }
1629
+ subscribeToEvents();
1630
+ });
1631
+
1529
1632
  if (captureMetrics) {
1530
1633
  // The code here is only bundled and applied when the captureMetrics is set
1531
1634
  // eslint-disable-next-line no-use-before-define
@@ -1588,6 +1691,10 @@ const Onyx = {
1588
1691
  setMemoryOnlyKeys,
1589
1692
  tryGetCachedValue,
1590
1693
  hasPendingMergeForKey,
1694
+ onClear,
1695
+ isClientManagerReady: ActiveClientManager.isReady,
1696
+ isClientTheLeader: ActiveClientManager.isClientTheLeader,
1697
+ subscribeToClientChange: ActiveClientManager.subscribeToClientChange,
1591
1698
  };
1592
1699
 
1593
1700
  /**
package/lib/Str.js CHANGED
@@ -26,4 +26,19 @@ function result(parameter, ...args) {
26
26
  return _.isFunction(parameter) ? parameter(...args) : parameter;
27
27
  }
28
28
 
29
- export {startsWith, result};
29
+ /**
30
+ * A simple GUID generator taken from https://stackoverflow.com/a/32760401/9114791
31
+ *
32
+ * @param {String} [prefix] an optional prefix to put in front of the guid
33
+ * @returns {String}
34
+ */
35
+ function guid(prefix = '') {
36
+ function s4() {
37
+ return Math.floor((1 + Math.random()) * 0x10000)
38
+ .toString(16)
39
+ .substring(1);
40
+ }
41
+ return `${prefix}${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
42
+ }
43
+
44
+ export {guid, startsWith, result};
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Sends a message to the broadcast channel.
3
+ */
4
+ declare function sendMessage(message: string): void;
5
+
6
+ /**
7
+ * Subscribes to the broadcast channel. Every time a new message
8
+ * is received, the callback is called.
9
+ */
10
+ declare function subscribe(callback: () => {}): void;
11
+
12
+ /**
13
+ * Disconnects from the broadcast channel.
14
+ */
15
+ declare function disconnect(): void;
16
+
17
+ export {sendMessage, subscribe, disconnect};
@@ -0,0 +1,14 @@
1
+ /**
2
+ * For native devices, there will never be more than one
3
+ * client running at a time, so this lib is a big no-op
4
+ */
5
+
6
+ function sendMessage() {}
7
+
8
+ function subscribe() {}
9
+
10
+ function disconnect() {}
11
+
12
+ export {
13
+ sendMessage, subscribe, disconnect,
14
+ };
@@ -0,0 +1,35 @@
1
+ const BROADCAST_ONYX = 'BROADCAST_ONYX';
2
+
3
+ const subscriptions = [];
4
+ const channel = new BroadcastChannel(BROADCAST_ONYX);
5
+
6
+ /**
7
+ * Sends a message to the broadcast channel.
8
+ * @param {String} message
9
+ */
10
+ function sendMessage(message) {
11
+ channel.postMessage(message);
12
+ }
13
+
14
+ /**
15
+ * Subscribes to the broadcast channel. Every time a new message
16
+ * is received, the callback is called.
17
+ * @param {Function} callback
18
+ */
19
+ function subscribe(callback) {
20
+ subscriptions.push(callback);
21
+ channel.onmessage = (message) => {
22
+ subscriptions.forEach(c => c(message));
23
+ };
24
+ }
25
+
26
+ /**
27
+ * Disconnects from the broadcast channel.
28
+ */
29
+ function disconnect() {
30
+ channel.close();
31
+ }
32
+
33
+ export {
34
+ sendMessage, subscribe, disconnect,
35
+ };
@@ -49,7 +49,7 @@ const webStorage = {
49
49
  this.clear = () => {
50
50
  let allKeys;
51
51
 
52
- // They keys must be retreived before storage is cleared or else the list of keys would be empty
52
+ // The keys must be retrieved before storage is cleared or else the list of keys would be empty
53
53
  return Storage.getAllKeys()
54
54
  .then((keys) => {
55
55
  allKeys = keys;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-onyx",
3
- "version": "1.0.118",
3
+ "version": "1.0.120",
4
4
  "author": "Expensify, Inc.",
5
5
  "homepage": "https://expensify.com",
6
6
  "description": "State management for React Native",
@@ -37,7 +37,10 @@
37
37
  "lint-tests": "eslint tests/**",
38
38
  "test": "jest",
39
39
  "build": "webpack --config webpack.config.js",
40
- "build:docs": "node buildDocs.js"
40
+ "build:docs": "node buildDocs.js",
41
+ "e2e": "playwright test",
42
+ "e2e-ui": "playwright test --ui",
43
+ "postinstall": "cd tests/e2e/app && npm install"
41
44
  },
42
45
  "dependencies": {
43
46
  "ascii-table": "0.0.9",
@@ -48,9 +51,11 @@
48
51
  "@babel/core": "7.20.12",
49
52
  "@babel/preset-env": "^7.20.2",
50
53
  "@babel/preset-react": "^7.18.6",
54
+ "@playwright/test": "^1.38.1",
51
55
  "@react-native-community/eslint-config": "^2.0.0",
52
56
  "@testing-library/jest-native": "^3.4.2",
53
57
  "@testing-library/react-native": "^7.0.2",
58
+ "@types/node": "^20.7.1",
54
59
  "@types/react": "^18.2.14",
55
60
  "babel-eslint": "^10.1.0",
56
61
  "babel-jest": "^26.2.2",
@@ -81,9 +86,9 @@
81
86
  "idb-keyval": "^6.2.1",
82
87
  "react": ">=18.1.0",
83
88
  "react-dom": ">=18.1.0",
89
+ "react-native-device-info": "^10.3.0",
84
90
  "react-native-performance": "^5.1.0",
85
- "react-native-quick-sqlite": "^8.0.0-beta.2",
86
- "react-native-device-info": "^10.3.0"
91
+ "react-native-quick-sqlite": "^8.0.0-beta.2"
87
92
  },
88
93
  "peerDependenciesMeta": {
89
94
  "idb-keyval": {
@@ -100,8 +105,8 @@
100
105
  }
101
106
  },
102
107
  "engines": {
103
- "node": ">=16.15.1 <=20.9.0",
104
- "npm": ">=8.11.0 <=10.1.0"
108
+ "node": "20.9.0",
109
+ "npm": "10.1.0"
105
110
  },
106
111
  "jest": {
107
112
  "preset": "react-native",
@@ -113,7 +118,8 @@
113
118
  ],
114
119
  "testPathIgnorePatterns": [
115
120
  "<rootDir>/node_modules/",
116
- "<rootDir>/tests/unit/mocks/"
121
+ "<rootDir>/tests/unit/mocks/",
122
+ "<rootDir>/tests/e2e/"
117
123
  ],
118
124
  "testMatch": [
119
125
  "**/tests/unit/**/*.[jt]s?(x)",