-
Notifications
You must be signed in to change notification settings - Fork 94
Expand file tree
/
Copy pathOnyxUtils.ts
More file actions
1817 lines (1562 loc) · 76.7 KB
/
OnyxUtils.ts
File metadata and controls
1817 lines (1562 loc) · 76.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import {deepEqual} from 'fast-equals';
import type {ValueOf} from 'type-fest';
import lodashPick from 'lodash/pick';
import _ from 'underscore';
import DevTools from './DevTools';
import * as Logger from './Logger';
import type Onyx from './Onyx';
import cache, {TASK} from './OnyxCache';
import * as Str from './Str';
import Storage from './storage';
import type {
CollectionKey,
CollectionKeyBase,
ConnectOptions,
DeepRecord,
DefaultConnectCallback,
DefaultConnectOptions,
KeyValueMapping,
CallbackToStateMapping,
MultiMergeReplaceNullPatches,
OnyxCollection,
OnyxEntry,
OnyxInput,
OnyxInputKeyValueMapping,
OnyxKey,
OnyxMergeCollectionInput,
OnyxUpdate,
OnyxValue,
Selector,
MergeCollectionWithPatchesParams,
SetCollectionParams,
SetParams,
OnyxMultiSetInput,
RetriableOnyxOperation,
} from './types';
import type {FastMergeOptions, FastMergeResult} from './utils';
import utils from './utils';
import type {DeferredTask} from './createDeferredTask';
import createDeferredTask from './createDeferredTask';
import * as GlobalSettings from './GlobalSettings';
import decorateWithMetrics from './metrics';
import type {StorageKeyValuePair} from './storage/providers/types';
import logMessages from './logMessages';
// Method constants
const METHOD = {
SET: 'set',
MERGE: 'merge',
MERGE_COLLECTION: 'mergecollection',
SET_COLLECTION: 'setcollection',
MULTI_SET: 'multiset',
CLEAR: 'clear',
} as const;
// IndexedDB errors that indicate storage capacity issues where eviction can help
const IDB_STORAGE_ERRORS = [
'quotaexceedederror', // Browser storage quota exceeded
] as const;
// SQLite errors that indicate storage capacity issues where eviction can help
const SQLITE_STORAGE_ERRORS = [
'database or disk is full', // Device storage is full
'disk I/O error', // File system I/O failure, often due to insufficient space or corrupted storage
'out of memory', // Insufficient RAM or storage space to complete the operation
] as const;
const STORAGE_ERRORS = [...IDB_STORAGE_ERRORS, ...SQLITE_STORAGE_ERRORS];
// Max number of retries for failed storage operations
const MAX_STORAGE_OPERATION_RETRY_ATTEMPTS = 5;
type OnyxMethod = ValueOf<typeof METHOD>;
// Key/value store of Onyx key and arrays of values to merge
let mergeQueue: Record<OnyxKey, Array<OnyxValue<OnyxKey>>> = {};
let mergeQueuePromise: Record<OnyxKey, Promise<void>> = {};
// Holds a mapping of all the React components that want their state subscribed to a store key
let callbackToStateMapping: Record<string, CallbackToStateMapping<OnyxKey>> = {};
// Keeps a copy of the values of the onyx collection keys as a map for faster lookups
let onyxCollectionKeySet = new Set<OnyxKey>();
// Holds a mapping of the connected key to the subscriptionID for faster lookups
let onyxKeyToSubscriptionIDs = new Map();
// Optional user-provided key value states set when Onyx initializes or clears
let defaultKeyStates: Record<OnyxKey, OnyxValue<OnyxKey>> = {};
let batchUpdatesPromise: Promise<void> | null = null;
let batchUpdatesTimeoutID: number | null = null;
let batchUpdatesQueue: Array<() => void> = [];
// Used for comparison with a new update to avoid invoking the Onyx.connect callback with the same data.
let lastConnectionCallbackData = new Map<number, OnyxValue<OnyxKey>>();
let snapshotKey: OnyxKey | null = null;
// Keeps track of the last subscriptionID that was used so we can keep incrementing it
let lastSubscriptionID = 0;
// Connections can be made before `Onyx.init`. They would wait for this task before resolving
const deferredInitTask = createDeferredTask();
// Holds a set of collection member IDs which updates will be ignored when using Onyx methods.
let skippableCollectionMemberIDs = new Set<string>();
function getSnapshotKey(): OnyxKey | null {
return snapshotKey;
}
/**
* Getter - returns the merge queue.
*/
function getMergeQueue(): Record<OnyxKey, Array<OnyxValue<OnyxKey>>> {
return mergeQueue;
}
/**
* Getter - returns the merge queue promise.
*/
function getMergeQueuePromise(): Record<OnyxKey, Promise<void>> {
return mergeQueuePromise;
}
/**
* Getter - returns the default key states.
*/
function getDefaultKeyStates(): Record<OnyxKey, OnyxValue<OnyxKey>> {
return defaultKeyStates;
}
/**
* Getter - returns the deffered init task.
*/
function getDeferredInitTask(): DeferredTask {
return deferredInitTask;
}
/**
* Getter - returns the skippable collection member IDs.
*/
function getSkippableCollectionMemberIDs(): Set<string> {
return skippableCollectionMemberIDs;
}
/**
* Setter - sets the skippable collection member IDs.
*/
function setSkippableCollectionMemberIDs(ids: Set<string>): void {
skippableCollectionMemberIDs = ids;
}
/**
* Sets the initial values for the Onyx store
*
* @param keys - `ONYXKEYS` constants object from Onyx.init()
* @param initialKeyStates - initial data to set when `init()` and `clear()` are called
* @param evictableKeys - This is an array of keys (individual or collection patterns) that when provided to Onyx are flagged as "safe" for removal.
*/
function initStoreValues(keys: DeepRecord<string, OnyxKey>, initialKeyStates: Partial<KeyValueMapping>, evictableKeys: OnyxKey[]): void {
// We need the value of the collection keys later for checking if a
// key is a collection. We store it in a map for faster lookup.
const collectionValues = Object.values(keys.COLLECTION ?? {}) as string[];
onyxCollectionKeySet = collectionValues.reduce((acc, val) => {
acc.add(val);
return acc;
}, new Set<OnyxKey>());
// Set our default key states to use when initializing and clearing Onyx data
defaultKeyStates = initialKeyStates;
DevTools.initState(initialKeyStates);
// Let Onyx know about which keys are safe to evict
cache.setEvictionAllowList(evictableKeys);
// Set collection keys in cache for optimized storage
cache.setCollectionKeys(onyxCollectionKeySet);
if (typeof keys.COLLECTION === 'object' && typeof keys.COLLECTION.SNAPSHOT === 'string') {
snapshotKey = keys.COLLECTION.SNAPSHOT;
}
}
/**
* Sends an action to DevTools extension
*
* @param method - Onyx method from METHOD
* @param key - Onyx key that was changed
* @param value - contains the change that was made by the method
* @param mergedValue - (optional) value that was written in the storage after a merge method was executed.
*/
function sendActionToDevTools(
method: typeof METHOD.MERGE_COLLECTION | typeof METHOD.MULTI_SET | typeof METHOD.SET_COLLECTION,
key: undefined,
value: OnyxCollection<KeyValueMapping[OnyxKey]>,
mergedValue?: undefined,
): void;
function sendActionToDevTools(
method: Exclude<OnyxMethod, typeof METHOD.MERGE_COLLECTION | typeof METHOD.MULTI_SET | typeof METHOD.SET_COLLECTION>,
key: OnyxKey,
value: OnyxEntry<KeyValueMapping[OnyxKey]>,
mergedValue?: OnyxEntry<KeyValueMapping[OnyxKey]>,
): void;
function sendActionToDevTools(
method: OnyxMethod,
key: OnyxKey | undefined,
value: OnyxCollection<KeyValueMapping[OnyxKey]> | OnyxEntry<KeyValueMapping[OnyxKey]>,
mergedValue: OnyxEntry<KeyValueMapping[OnyxKey]> = undefined,
): void {
DevTools.registerAction(utils.formatActionName(method, key), value, key ? {[key]: mergedValue || value} : (value as OnyxCollection<KeyValueMapping[OnyxKey]>));
}
/**
* We are batching together onyx updates. This helps with use cases where we schedule onyx updates after each other.
* This happens for example in the Onyx.update function, where we process API responses that might contain a lot of
* update operations. Instead of calling the subscribers for each update operation, we batch them together which will
* cause react to schedule the updates at once instead of after each other. This is mainly a performance optimization.
*/
function maybeFlushBatchUpdates(): Promise<void> {
if (batchUpdatesPromise) {
return batchUpdatesPromise;
}
batchUpdatesPromise = new Promise((resolve) => {
/* We use (setTimeout, 0) here which should be called once native module calls are flushed (usually at the end of the frame)
* We may investigate if (setTimeout, 1) (which in React Native is equal to requestAnimationFrame) works even better
* then the batch will be flushed on next frame.
*/
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
batchUpdatesTimeoutID = setTimeout(() => {
const updatesCopy = batchUpdatesQueue;
batchUpdatesQueue = [];
batchUpdatesPromise = null;
for (const applyUpdates of updatesCopy) {
applyUpdates();
}
resolve();
}, 0);
});
return batchUpdatesPromise;
}
function batchUpdates(updates: () => void): Promise<void> {
batchUpdatesQueue.push(updates);
return maybeFlushBatchUpdates();
}
/**
* Takes a collection of items (eg. {testKey_1:{a:'a'}, testKey_2:{b:'b'}})
* and runs it through a reducer function to return a subset of the data according to a selector.
* The resulting collection will only contain items that are returned by the selector.
*/
function reduceCollectionWithSelector<TKey extends CollectionKeyBase, TReturn>(
collection: OnyxCollection<KeyValueMapping[TKey]>,
selector: Selector<TKey, TReturn>,
): Record<string, TReturn> {
return Object.entries(collection ?? {}).reduce((finalCollection: Record<string, TReturn>, [key, item]) => {
// eslint-disable-next-line no-param-reassign
finalCollection[key] = selector(item);
return finalCollection;
}, {});
}
/** Get some data from the store */
function get<TKey extends OnyxKey, TValue extends OnyxValue<TKey>>(key: TKey): Promise<TValue> {
// When we already have the value in cache - resolve right away
if (cache.hasCacheForKey(key)) {
return Promise.resolve(cache.get(key) as TValue);
}
const taskName = `${TASK.GET}:${key}` as const;
// When a value retrieving task for this key is still running hook to it
if (cache.hasPendingTask(taskName)) {
return cache.getTaskPromise(taskName) as Promise<TValue>;
}
// Otherwise retrieve the value from storage and capture a promise to aid concurrent usages
const promise = Storage.getItem(key)
.then((val) => {
if (skippableCollectionMemberIDs.size) {
try {
const [, collectionMemberID] = splitCollectionMemberKey(key);
if (skippableCollectionMemberIDs.has(collectionMemberID)) {
// The key is a skippable one, so we set the value to undefined.
// eslint-disable-next-line no-param-reassign
val = undefined as OnyxValue<TKey>;
}
} catch (e) {
// The key is not a collection one or something went wrong during split, so we proceed with the function's logic.
}
}
if (val === undefined) {
cache.addNullishStorageKey(key);
return undefined;
}
cache.set(key, val);
return val;
})
.catch((err) => Logger.logInfo(`Unable to get item from persistent storage. Key: ${key} Error: ${err}`));
return cache.captureTask(taskName, promise) as Promise<TValue>;
}
// multiGet the data first from the cache and then from the storage for the missing keys.
function multiGet<TKey extends OnyxKey>(keys: CollectionKeyBase[]): Promise<Map<OnyxKey, OnyxValue<TKey>>> {
// Keys that are not in the cache
const missingKeys: OnyxKey[] = [];
// Tasks that are pending
const pendingTasks: Array<Promise<OnyxValue<TKey>>> = [];
// Keys for the tasks that are pending
const pendingKeys: OnyxKey[] = [];
// Data to be sent back to the invoker
const dataMap = new Map<OnyxKey, OnyxValue<TKey>>();
/**
* We are going to iterate over all the matching keys and check if we have the data in the cache.
* If we do then we add it to the data object. If we do not have them, then we check if there is a pending task
* for the key. If there is such task, then we add the promise to the pendingTasks array and the key to the pendingKeys
* array. If there is no pending task then we add the key to the missingKeys array.
*
* These missingKeys will be later used to multiGet the data from the storage.
*/
for (const key of keys) {
const cacheValue = cache.get(key) as OnyxValue<TKey>;
if (cacheValue) {
dataMap.set(key, cacheValue);
continue;
}
const pendingKey = `${TASK.GET}:${key}` as const;
if (cache.hasPendingTask(pendingKey)) {
pendingTasks.push(cache.getTaskPromise(pendingKey) as Promise<OnyxValue<TKey>>);
pendingKeys.push(key);
} else {
missingKeys.push(key);
}
}
return (
Promise.all(pendingTasks)
// Wait for all the pending tasks to resolve and then add the data to the data map.
.then((values) => {
for (const [index, value] of values.entries()) {
dataMap.set(pendingKeys[index], value);
}
return Promise.resolve();
})
// Get the missing keys using multiGet from the storage.
.then(() => {
if (missingKeys.length === 0) {
return Promise.resolve(undefined);
}
return Storage.multiGet(missingKeys);
})
// Add the data from the missing keys to the data map and also merge it to the cache.
.then((values) => {
if (!values || values.length === 0) {
return dataMap;
}
// temp object is used to merge the missing data into the cache
const temp: OnyxCollection<KeyValueMapping[TKey]> = {};
for (const [key, value] of values) {
if (skippableCollectionMemberIDs.size) {
try {
const [, collectionMemberID] = splitCollectionMemberKey(key);
if (skippableCollectionMemberIDs.has(collectionMemberID)) {
// The key is a skippable one, so we skip this iteration.
continue;
}
} catch (e) {
// The key is not a collection one or something went wrong during split, so we proceed with the function's logic.
}
}
dataMap.set(key, value as OnyxValue<TKey>);
temp[key] = value as OnyxValue<TKey>;
}
cache.merge(temp);
return dataMap;
})
);
}
/**
* This helper exists to map an array of Onyx keys such as `['report_', 'conciergeReportID']`
* to the values for those keys (correctly typed) such as `[OnyxCollection<Report>, OnyxEntry<string>]`
*
* Note: just using `.map`, you'd end up with `Array<OnyxCollection<Report>|OnyxEntry<string>>`, which is not what we want. This preserves the order of the keys provided.
*/
function tupleGet<Keys extends readonly OnyxKey[]>(keys: Keys): Promise<{[Index in keyof Keys]: OnyxValue<Keys[Index]>}> {
return Promise.all(keys.map((key) => get(key))) as Promise<{[Index in keyof Keys]: OnyxValue<Keys[Index]>}>;
}
/**
* Stores a subscription ID associated with a given key.
*
* @param subscriptionID - A subscription ID of the subscriber.
* @param key - A key that the subscriber is subscribed to.
*/
function storeKeyBySubscriptions(key: OnyxKey, subscriptionID: number) {
if (!onyxKeyToSubscriptionIDs.has(key)) {
onyxKeyToSubscriptionIDs.set(key, []);
}
onyxKeyToSubscriptionIDs.get(key).push(subscriptionID);
}
/**
* Deletes a subscription ID associated with its corresponding key.
*
* @param subscriptionID - The subscription ID to be deleted.
*/
function deleteKeyBySubscriptions(subscriptionID: number) {
const subscriber = callbackToStateMapping[subscriptionID];
if (subscriber && onyxKeyToSubscriptionIDs.has(subscriber.key)) {
const updatedSubscriptionsIDs = onyxKeyToSubscriptionIDs.get(subscriber.key).filter((id: number) => id !== subscriptionID);
onyxKeyToSubscriptionIDs.set(subscriber.key, updatedSubscriptionsIDs);
}
lastConnectionCallbackData.delete(subscriptionID);
}
/** Returns current key names stored in persisted storage */
function getAllKeys(): Promise<Set<OnyxKey>> {
// When we've already read stored keys, resolve right away
const cachedKeys = cache.getAllKeys();
if (cachedKeys.size > 0) {
return Promise.resolve(cachedKeys);
}
// When a value retrieving task for all keys is still running hook to it
if (cache.hasPendingTask(TASK.GET_ALL_KEYS)) {
return cache.getTaskPromise(TASK.GET_ALL_KEYS) as Promise<Set<OnyxKey>>;
}
// Otherwise retrieve the keys from storage and capture a promise to aid concurrent usages
const promise = Storage.getAllKeys().then((keys) => {
cache.setAllKeys(keys);
// return the updated set of keys
return cache.getAllKeys();
});
return cache.captureTask(TASK.GET_ALL_KEYS, promise) as Promise<Set<OnyxKey>>;
}
/**
* Returns set of all registered collection keys
*/
function getCollectionKeys(): Set<OnyxKey> {
return onyxCollectionKeySet;
}
/**
* Checks to see if the subscriber's supplied key
* is associated with a collection of keys.
*/
function isCollectionKey(key: OnyxKey): key is CollectionKeyBase {
return onyxCollectionKeySet.has(key);
}
function isCollectionMemberKey<TCollectionKey extends CollectionKeyBase>(collectionKey: TCollectionKey, key: string): key is `${TCollectionKey}${string}` {
return key.startsWith(collectionKey) && key.length > collectionKey.length;
}
/**
* Checks if a given key is a collection member key (not just a collection key).
* @param key - The key to check
* @returns true if the key is a collection member, false otherwise
*/
function isCollectionMember(key: OnyxKey): boolean {
try {
const collectionKey = getCollectionKey(key);
// If the key is longer than the collection key, it's a collection member
return key.length > collectionKey.length;
} catch (e) {
// If getCollectionKey throws, the key is not a collection member
return false;
}
}
/**
* Splits a collection member key into the collection key part and the ID part.
* @param key - The collection member key to split.
* @param collectionKey - The collection key of the `key` param that can be passed in advance to optimize the function.
* @returns A tuple where the first element is the collection part and the second element is the ID part,
* or throws an Error if the key is not a collection one.
*/
function splitCollectionMemberKey<TKey extends CollectionKey, CollectionKeyType = TKey extends `${infer Prefix}_${string}` ? `${Prefix}_` : never>(
key: TKey,
collectionKey?: string,
): [CollectionKeyType, string] {
if (collectionKey && !isCollectionMemberKey(collectionKey, key)) {
throw new Error(`Invalid '${collectionKey}' collection key provided, it isn't compatible with '${key}' key.`);
}
if (!collectionKey) {
// eslint-disable-next-line no-param-reassign
collectionKey = getCollectionKey(key);
}
return [collectionKey as CollectionKeyType, key.slice(collectionKey.length)];
}
/**
* Checks to see if a provided key is the exact configured key of our connected subscriber
* or if the provided key is a collection member key (in case our configured key is a "collection key")
*/
function isKeyMatch(configKey: OnyxKey, key: OnyxKey): boolean {
return isCollectionKey(configKey) ? Str.startsWith(key, configKey) : configKey === key;
}
/**
* Extracts the collection identifier of a given collection member key.
*
* For example:
* - `getCollectionKey("report_123")` would return "report_"
* - `getCollectionKey("report_")` would return "report_"
* - `getCollectionKey("report_-1_something")` would return "report_"
* - `getCollectionKey("sharedNVP_user_-1_something")` would return "sharedNVP_user_"
*
* @param key - The collection key to process.
* @returns The plain collection key or throws an Error if the key is not a collection one.
*/
function getCollectionKey(key: CollectionKey): string {
// Start by finding the position of the last underscore in the string
let lastUnderscoreIndex = key.lastIndexOf('_');
// Iterate backwards to find the longest key that ends with '_'
while (lastUnderscoreIndex > 0) {
const possibleKey = key.slice(0, lastUnderscoreIndex + 1);
// Check if the substring is a key in the Set
if (isCollectionKey(possibleKey)) {
// Return the matching key and the rest of the string
return possibleKey;
}
// Move to the next underscore to check smaller possible keys
lastUnderscoreIndex = key.lastIndexOf('_', lastUnderscoreIndex - 1);
}
throw new Error(`Invalid '${key}' key provided, only collection keys are allowed.`);
}
/**
* Tries to get a value from the cache. If the value is not present in cache it will return the default value or undefined.
* If the requested key is a collection, it will return an object with all the collection members.
*/
function tryGetCachedValue<TKey extends OnyxKey>(key: TKey): OnyxValue<OnyxKey> {
let val = cache.get(key);
if (isCollectionKey(key)) {
const collectionData = cache.getCollectionData(key);
if (collectionData !== undefined) {
val = collectionData;
} else {
// If we haven't loaded all keys yet, we can't determine if the collection exists
if (cache.getAllKeys().size === 0) {
return;
}
// Set an empty collection object for collections that exist but have no data
val = {};
}
}
return val;
}
function getCachedCollection<TKey extends CollectionKeyBase>(collectionKey: TKey, collectionMemberKeys?: string[]): NonNullable<OnyxCollection<KeyValueMapping[TKey]>> {
// Use optimized collection data retrieval when cache is populated
const collectionData = cache.getCollectionData(collectionKey);
const allKeys = collectionMemberKeys || cache.getAllKeys();
if (collectionData !== undefined && (Array.isArray(allKeys) ? allKeys.length > 0 : allKeys.size > 0)) {
// If we have specific member keys, filter the collection
if (collectionMemberKeys) {
const filteredCollection: OnyxCollection<KeyValueMapping[TKey]> = {};
for (const key of collectionMemberKeys) {
if (collectionData[key] !== undefined) {
filteredCollection[key] = collectionData[key];
} else if (cache.hasNullishStorageKey(key)) {
filteredCollection[key] = cache.get(key);
}
}
return filteredCollection;
}
// Return a copy to avoid mutations affecting the cache
return {...collectionData};
}
// Fallback to original implementation if collection data not available
const collection: OnyxCollection<KeyValueMapping[TKey]> = {};
// forEach exists on both Set and Array
for (const key of allKeys) {
// If we don't have collectionMemberKeys array then we have to check whether a key is a collection member key.
// Because in that case the keys will be coming from `cache.getAllKeys()` and we need to filter out the keys that
// are not part of the collection.
if (!collectionMemberKeys && !isCollectionMemberKey(collectionKey, key)) {
continue;
}
const cachedValue = cache.get(key);
if (cachedValue === undefined && !cache.hasNullishStorageKey(key)) {
continue;
}
collection[key] = cache.get(key);
}
return collection;
}
/**
* When a collection of keys change, search for any callbacks matching the collection key and trigger those callbacks
*/
function keysChanged<TKey extends CollectionKeyBase>(
collectionKey: TKey,
partialCollection: OnyxCollection<KeyValueMapping[TKey]>,
partialPreviousCollection: OnyxCollection<KeyValueMapping[TKey]> | undefined,
notifyConnectSubscribers = true,
): void {
// We prepare the "cached collection" which is the entire collection + the new partial data that
// was merged in via mergeCollection().
const cachedCollection = getCachedCollection(collectionKey);
const previousCollection = partialPreviousCollection ?? {};
// We are iterating over all subscribers similar to keyChanged(). However, we are looking for subscribers who are subscribing to either a collection key or
// individual collection key member for the collection that is being updated. It is important to note that the collection parameter cane be a PARTIAL collection
// and does not represent all of the combined keys and values for a collection key. It is just the "new" data that was merged in via mergeCollection().
const stateMappingKeys = Object.keys(callbackToStateMapping);
for (const stateMappingKey of stateMappingKeys) {
const subscriber = callbackToStateMapping[stateMappingKey];
if (!subscriber) {
continue;
}
// Skip iteration if we do not have a collection key or a collection member key on this subscriber
if (!Str.startsWith(subscriber.key, collectionKey)) {
continue;
}
/**
* e.g. Onyx.connect({key: ONYXKEYS.COLLECTION.REPORT, callback: ...});
*/
const isSubscribedToCollectionKey = subscriber.key === collectionKey;
/**
* e.g. Onyx.connect({key: `${ONYXKEYS.COLLECTION.REPORT}{reportID}`, callback: ...});
*/
const isSubscribedToCollectionMemberKey = isCollectionMemberKey(collectionKey, subscriber.key);
// Regular Onyx.connect() subscriber found.
if (typeof subscriber.callback === 'function') {
if (!notifyConnectSubscribers) {
continue;
}
// If they are subscribed to the collection key and using waitForCollectionCallback then we'll
// send the whole cached collection.
if (isSubscribedToCollectionKey) {
if (subscriber.waitForCollectionCallback) {
subscriber.callback(cachedCollection, subscriber.key, partialCollection);
continue;
}
// If they are not using waitForCollectionCallback then we notify the subscriber with
// the new merged data but only for any keys in the partial collection.
const dataKeys = Object.keys(partialCollection ?? {});
for (const dataKey of dataKeys) {
if (deepEqual(cachedCollection[dataKey], previousCollection[dataKey])) {
continue;
}
subscriber.callback(cachedCollection[dataKey], dataKey);
}
continue;
}
// And if the subscriber is specifically only tracking a particular collection member key then we will
// notify them with the cached data for that key only.
if (isSubscribedToCollectionMemberKey) {
if (deepEqual(cachedCollection[subscriber.key], previousCollection[subscriber.key])) {
continue;
}
const subscriberCallback = subscriber.callback as DefaultConnectCallback<TKey>;
subscriberCallback(cachedCollection[subscriber.key], subscriber.key as TKey);
lastConnectionCallbackData.set(subscriber.subscriptionID, cachedCollection[subscriber.key]);
continue;
}
continue;
}
}
}
/**
* When a key change happens, search for any callbacks matching the key or collection key and trigger those callbacks
*
* @example
* keyChanged(key, value, subscriber => subscriber.initWithStoredValues === false)
*/
function keyChanged<TKey extends OnyxKey>(
key: TKey,
value: OnyxValue<TKey>,
canUpdateSubscriber: (subscriber?: CallbackToStateMapping<OnyxKey>) => boolean = () => true,
notifyConnectSubscribers = true,
isProcessingCollectionUpdate = false,
): void {
// Add or remove this key from the recentlyAccessedKeys lists
if (value !== null) {
cache.addLastAccessedKey(key, isCollectionKey(key));
} else {
cache.removeLastAccessedKey(key);
}
// We get the subscribers interested in the key that has just changed. If the subscriber's key is a collection key then we will
// notify them if the key that changed is a collection member. Or if it is a regular key notify them when there is an exact match.
// Given the amount of times this function is called we need to make sure we are not iterating over all subscribers every time. On the other hand, we don't need to
// do the same in keysChanged, because we only call that function when a collection key changes, and it doesn't happen that often.
// For performance reason, we look for the given key and later if don't find it we look for the collection key, instead of checking if it is a collection key first.
let stateMappingKeys = onyxKeyToSubscriptionIDs.get(key) ?? [];
let collectionKey: string | undefined;
try {
collectionKey = getCollectionKey(key);
} catch (e) {
// If getCollectionKey() throws an error it means the key is not a collection key.
collectionKey = undefined;
}
if (collectionKey) {
// Getting the collection key from the specific key because only collection keys were stored in the mapping.
stateMappingKeys = [...stateMappingKeys, ...(onyxKeyToSubscriptionIDs.get(collectionKey) ?? [])];
if (stateMappingKeys.length === 0) {
return;
}
}
const cachedCollections: Record<string, ReturnType<typeof getCachedCollection>> = {};
for (const stateMappingKey of stateMappingKeys) {
const subscriber = callbackToStateMapping[stateMappingKey];
if (!subscriber || !isKeyMatch(subscriber.key, key) || !canUpdateSubscriber(subscriber)) {
continue;
}
// Subscriber is a regular call to connect() and provided a callback
if (typeof subscriber.callback === 'function') {
if (!notifyConnectSubscribers) {
continue;
}
if (lastConnectionCallbackData.has(subscriber.subscriptionID) && lastConnectionCallbackData.get(subscriber.subscriptionID) === value) {
continue;
}
if (isCollectionKey(subscriber.key) && subscriber.waitForCollectionCallback) {
// Skip individual key changes for collection callbacks during collection updates
// to prevent duplicate callbacks - the collection update will handle this properly
if (isProcessingCollectionUpdate) {
continue;
}
let cachedCollection = cachedCollections[subscriber.key];
if (!cachedCollection) {
cachedCollection = getCachedCollection(subscriber.key);
cachedCollections[subscriber.key] = cachedCollection;
}
cachedCollection[key] = value;
subscriber.callback(cachedCollection, subscriber.key, {[key]: value});
continue;
}
const subscriberCallback = subscriber.callback as DefaultConnectCallback<TKey>;
subscriberCallback(value, key);
lastConnectionCallbackData.set(subscriber.subscriptionID, value);
continue;
}
console.error('Warning: Found a matching subscriber to a key that changed, but no callback could be found.');
}
}
/**
* Sends the data obtained from the keys to the connection.
*/
function sendDataToConnection<TKey extends OnyxKey>(mapping: CallbackToStateMapping<TKey>, value: OnyxValue<TKey> | null, matchedKey: TKey | undefined): void {
// If the mapping no longer exists then we should not send any data.
// This means our subscriber was disconnected.
if (!callbackToStateMapping[mapping.subscriptionID]) {
return;
}
// For regular callbacks, we never want to pass null values, but always just undefined if a value is not set in cache or storage.
const valueToPass = value === null ? undefined : value;
const lastValue = lastConnectionCallbackData.get(mapping.subscriptionID);
lastConnectionCallbackData.get(mapping.subscriptionID);
// If the value has not changed we do not need to trigger the callback
if (lastConnectionCallbackData.has(mapping.subscriptionID) && valueToPass === lastValue) {
return;
}
(mapping as DefaultConnectOptions<TKey>).callback?.(valueToPass, matchedKey as TKey);
}
/**
* We check to see if this key is flagged as safe for eviction and add it to the recentlyAccessedKeys list so that when we
* run out of storage the least recently accessed key can be removed.
*/
function addKeyToRecentlyAccessedIfNeeded<TKey extends OnyxKey>(key: TKey): void {
if (!cache.isEvictableKey(key)) {
return;
}
// Add the key to recentKeys first (this makes it the most recent key)
cache.addToAccessedKeys(key);
// Try to free some cache whenever we connect to a safe eviction key
cache.removeLeastRecentlyUsedKeys();
}
/**
* Gets the data for a given an array of matching keys, combines them into an object, and sends the result back to the subscriber.
*/
function getCollectionDataAndSendAsObject<TKey extends OnyxKey>(matchingKeys: CollectionKeyBase[], mapping: CallbackToStateMapping<TKey>): void {
multiGet(matchingKeys).then((dataMap) => {
const data = Object.fromEntries(dataMap.entries()) as OnyxValue<TKey>;
sendDataToConnection(mapping, data, mapping.key);
});
}
/**
* Schedules an update that will be appended to the macro task queue (so it doesn't update the subscribers immediately).
*
* @example
* scheduleSubscriberUpdate(key, value, subscriber => subscriber.initWithStoredValues === false)
*/
function scheduleSubscriberUpdate<TKey extends OnyxKey>(
key: TKey,
value: OnyxValue<TKey>,
canUpdateSubscriber: (subscriber?: CallbackToStateMapping<OnyxKey>) => boolean = () => true,
isProcessingCollectionUpdate = false,
): Promise<void> {
const promise = Promise.resolve().then(() => keyChanged(key, value, canUpdateSubscriber, true, isProcessingCollectionUpdate));
// batchUpdates(() => keyChanged(key, value, canUpdateSubscriber, false, isProcessingCollectionUpdate));
return Promise.all([maybeFlushBatchUpdates(), promise]).then(() => undefined);
}
/**
* This method is similar to notifySubscribersOnNextTick but it is built for working specifically with collections
* so that keysChanged() is triggered for the collection and not keyChanged(). If this was not done, then the
* subscriber callbacks receive the data in a different format than they normally expect and it breaks code.
*/
function scheduleNotifyCollectionSubscribers<TKey extends OnyxKey>(
key: TKey,
value: OnyxCollection<KeyValueMapping[TKey]>,
previousValue?: OnyxCollection<KeyValueMapping[TKey]>,
): Promise<void> {
const promise = Promise.resolve().then(() => keysChanged(key, value, previousValue, true));
// batchUpdates(() => keysChanged(key, value, previousValue, false));
return Promise.all([maybeFlushBatchUpdates(), promise]).then(() => undefined);
}
/**
* Remove a key from Onyx and update the subscribers
*/
function remove<TKey extends OnyxKey>(key: TKey, isProcessingCollectionUpdate?: boolean): Promise<void> {
cache.drop(key);
scheduleSubscriberUpdate(key, undefined as OnyxValue<TKey>, undefined, isProcessingCollectionUpdate);
return Storage.removeItem(key).then(() => undefined);
}
function reportStorageQuota(): Promise<void> {
return Storage.getDatabaseSize()
.then(({bytesUsed, bytesRemaining}) => {
Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}`);
})
.catch((dbSizeError) => {
Logger.logAlert(`Unable to get database size. Error: ${dbSizeError}`);
});
}
/**
* Handles storage operation failures based on the error type:
* - Storage capacity errors: evicts data and retries the operation
* - Invalid data errors: logs an alert and throws an error
* - Other errors: retries the operation
*/
function retryOperation<TMethod extends RetriableOnyxOperation>(error: Error, onyxMethod: TMethod, defaultParams: Parameters<TMethod>[0], retryAttempt: number | undefined): Promise<void> {
const currentRetryAttempt = retryAttempt ?? 0;
const nextRetryAttempt = currentRetryAttempt + 1;
Logger.logInfo(`Failed to save to storage. Error: ${error}. onyxMethod: ${onyxMethod.name}. retryAttempt: ${currentRetryAttempt}/${MAX_STORAGE_OPERATION_RETRY_ATTEMPTS}`);
if (error && Str.startsWith(error.message, "Failed to execute 'put' on 'IDBObjectStore'")) {
Logger.logAlert('Attempted to set invalid data set in Onyx. Please ensure all data is serializable.');
throw error;
}
const errorMessage = error?.message?.toLowerCase?.();
const errorName = error?.name?.toLowerCase?.();
const isStorageCapacityError = STORAGE_ERRORS.some((storageError) => errorName?.includes(storageError) || errorMessage?.includes(storageError));
if (nextRetryAttempt > MAX_STORAGE_OPERATION_RETRY_ATTEMPTS) {
Logger.logAlert(`Storage operation failed after 5 retries. Error: ${error}. onyxMethod: ${onyxMethod.name}.`);
return Promise.resolve();
}
if (!isStorageCapacityError) {
// @ts-expect-error No overload matches this call.
return onyxMethod(defaultParams, nextRetryAttempt);
}
// Find the first key that we can remove that has no subscribers in our blocklist
const keyForRemoval = cache.getKeyForEviction();
if (!keyForRemoval) {
// If we have no acceptable keys to remove then we are possibly trying to save mission critical data. If this is the case,
// then we should stop retrying as there is not much the user can do to fix this. Instead of getting them stuck in an infinite loop we
// will allow this write to be skipped.
Logger.logAlert('Out of storage. But found no acceptable keys to remove.');
return reportStorageQuota();
}
// Remove the least recently viewed key that is not currently being accessed and retry.
Logger.logInfo(`Out of storage. Evicting least recently accessed key (${keyForRemoval}) and retrying.`);
reportStorageQuota();
// @ts-expect-error No overload matches this call.
return remove(keyForRemoval).then(() => onyxMethod(defaultParams, nextRetryAttempt));
}
/**
* Notifies subscribers and writes current value to cache
*/
function broadcastUpdate<TKey extends OnyxKey>(key: TKey, value: OnyxValue<TKey>, hasChanged?: boolean): Promise<void> {
// Update subscribers if the cached value has changed, or when the subscriber specifically requires
// all updates regardless of value changes (indicated by initWithStoredValues set to false).
if (hasChanged) {
cache.set(key, value);
} else {
cache.addToAccessedKeys(key);
}
return scheduleSubscriberUpdate(key, value, (subscriber) => hasChanged || subscriber?.initWithStoredValues === false).then(() => undefined);
}
function hasPendingMergeForKey(key: OnyxKey): boolean {
return !!mergeQueue[key];
}
/**
* Storage expects array like: [["@MyApp_user", value_1], ["@MyApp_key", value_2]]
* This method transforms an object like {'@MyApp_user': myUserValue, '@MyApp_key': myKeyValue}
* to an array of key-value pairs in the above format and removes key-value pairs that are being set to null
*
* @return an array of key - value pairs <[key, value]>
*/
function prepareKeyValuePairsForStorage(
data: Record<OnyxKey, OnyxInput<OnyxKey>>,
shouldRemoveNestedNulls?: boolean,
replaceNullPatches?: MultiMergeReplaceNullPatches,
isProcessingCollectionUpdate?: boolean,
): StorageKeyValuePair[] {
const pairs: StorageKeyValuePair[] = [];
for (const [key, value] of Object.entries(data)) {
if (value === null) {
remove(key, isProcessingCollectionUpdate);
continue;
}
const valueWithoutNestedNullValues = shouldRemoveNestedNulls ?? true ? utils.removeNestedNullValues(value) : value;
if (valueWithoutNestedNullValues !== undefined) {
pairs.push([key, valueWithoutNestedNullValues, replaceNullPatches?.[key]]);
}
}
return pairs;