react-native-onyx 3.0.82 → 3.0.84

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.
package/dist/OnyxUtils.js CHANGED
@@ -665,8 +665,8 @@ function remove(key, isProcessingCollectionUpdate) {
665
665
  }
666
666
  function reportStorageQuota(error) {
667
667
  return storage_1.default.getDatabaseSize()
668
- .then(({ bytesUsed, bytesRemaining }) => {
669
- Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}. Original error: ${error}`);
668
+ .then(({ bytesUsed, bytesRemaining, usageDetails }) => {
669
+ Logger.logInfo(`Storage Quota Check -- bytesUsed: ${bytesUsed} bytesRemaining: ${bytesRemaining}${usageDetails ? ` usageDetails: ${JSON.stringify(usageDetails)}` : ''}. Original error: ${error}`);
670
670
  })
671
671
  .catch((dbSizeError) => {
672
672
  Logger.logAlert(`Unable to get database size. getDatabaseSize error: ${dbSizeError}. Original error: ${error}`);
@@ -14,6 +14,7 @@ declare const StorageMock: {
14
14
  getDatabaseSize: jest.Mock<Promise<{
15
15
  bytesUsed: number;
16
16
  bytesRemaining: number;
17
+ usageDetails?: Record<string, number>;
17
18
  }>, [], any>;
18
19
  keepInstancesSync: jest.Mock<any, any, any>;
19
20
  getMockStore: jest.Mock<{
@@ -35,12 +35,47 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  Object.defineProperty(exports, "__esModule", { value: true });
36
36
  const IDB = __importStar(require("idb-keyval"));
37
37
  const Logger = __importStar(require("../../../Logger"));
38
+ const HEAL_ATTEMPTS_MAX = 3;
39
+ /**
40
+ * Detects the Chromium-specific IDB backing store corruption error.
41
+ * Fires when LevelDB files backing IndexedDB are corrupted and Chrome's
42
+ * internal recovery (RepairDB -> delete -> recreate) also fails.
43
+ */
44
+ function isBackingStoreError(error) {
45
+ return (error instanceof Error || error instanceof DOMException) && error.message.includes('Internal error opening backing store');
46
+ }
47
+ /**
48
+ * Detects Safari/WebKit IDB connection termination errors.
49
+ * Fires when Safari kills the IDB server process for backgrounded tabs.
50
+ * WebKit bugs: https://bugs.webkit.org/show_bug.cgi?id=197050, https://bugs.webkit.org/show_bug.cgi?id=201483
51
+ */
52
+ function isConnectionLostError(error) {
53
+ if (!(error instanceof Error || error instanceof DOMException))
54
+ return false;
55
+ const msg = error.message.toLowerCase();
56
+ return msg.includes('connection to indexed database server lost') || msg.includes('connection is closing');
57
+ }
58
+ function isInvalidStateError(error) {
59
+ return (error instanceof Error || error instanceof DOMException) && error.name === 'InvalidStateError';
60
+ }
61
+ /** Errors that trigger a budgeted heal-and-retry in store(). */
62
+ function isBudgetedHealError(error) {
63
+ return isBackingStoreError(error) || isConnectionLostError(error);
64
+ }
65
+ function getBudgetedHealErrorLabel(error) {
66
+ if (isBackingStoreError(error))
67
+ return 'backing store';
68
+ if (isConnectionLostError(error))
69
+ return 'connection lost';
70
+ return 'unknown';
71
+ }
38
72
  // This is a copy of the createStore function from idb-keyval, we need a custom implementation
39
73
  // because we need to create the database manually in order to ensure that the store exists before we use it.
40
74
  // If the store does not exist, idb-keyval will throw an error
41
75
  // source: https://github.com/jakearchibald/idb-keyval/blob/9d19315b4a83897df1e0193dccdc29f78466a0f3/src/index.ts#L12
42
76
  function createStore(dbName, storeName) {
43
77
  let dbp;
78
+ let healAttemptsRemaining = HEAL_ATTEMPTS_MAX;
44
79
  const attachHandlers = (db) => {
45
80
  // Browsers may close idle IDB connections at any time, especially Safari.
46
81
  // We clear the cached promise so the next operation opens a fresh connection.
@@ -60,16 +95,27 @@ function createStore(dbName, storeName) {
60
95
  dbp = undefined;
61
96
  };
62
97
  };
98
+ // Cache the open promise and attach handlers + rejection cleanup.
99
+ // On rejection, clears dbp so the next operation retries with a fresh indexedDB.open()
100
+ // instead of returning the same rejected promise.
101
+ // Guard: only clear if dbp hasn't been replaced by a concurrent heal/retry.
102
+ function cacheOpenPromise(openPromise) {
103
+ dbp = openPromise;
104
+ const currentPromise = openPromise;
105
+ openPromise.then(attachHandlers, () => {
106
+ if (dbp !== currentPromise) {
107
+ return;
108
+ }
109
+ dbp = undefined;
110
+ });
111
+ return openPromise;
112
+ }
63
113
  const getDB = () => {
64
114
  if (dbp)
65
115
  return dbp;
66
116
  const request = indexedDB.open(dbName);
67
117
  request.onupgradeneeded = () => request.result.createObjectStore(storeName);
68
- dbp = IDB.promisifyRequest(request);
69
- dbp.then(attachHandlers,
70
- // eslint-disable-next-line @typescript-eslint/no-empty-function
71
- () => { });
72
- return dbp;
118
+ return cacheOpenPromise(IDB.promisifyRequest(request));
73
119
  };
74
120
  // Ensures the store exists in the DB. If missing, bumps the version to trigger
75
121
  // onupgradeneeded, recreates the store, and returns a promise to the new DB.
@@ -89,29 +135,65 @@ function createStore(dbName, storeName) {
89
135
  Logger.logInfo(`Creating store ${storeName} in database ${dbName}.`);
90
136
  updatedDatabase.createObjectStore(storeName);
91
137
  };
92
- dbp = IDB.promisifyRequest(request);
93
- // eslint-disable-next-line @typescript-eslint/no-empty-function
94
- dbp.then(attachHandlers, () => { });
95
- return dbp;
138
+ return cacheOpenPromise(IDB.promisifyRequest(request));
96
139
  };
97
140
  function executeTransaction(txMode, callback) {
98
141
  return getDB()
99
142
  .then(verifyStoreExists)
100
143
  .then((db) => callback(db.transaction(storeName, txMode).objectStore(storeName)));
101
144
  }
102
- // If the connection was closed between getDB() resolving and db.transaction() executing,
103
- // the transaction throws InvalidStateError. We catch it and retry once with a fresh connection.
104
- return (txMode, callback) => executeTransaction(txMode, callback).catch((error) => {
105
- if (error instanceof DOMException && error.name === 'InvalidStateError') {
106
- Logger.logAlert('IDB InvalidStateError, retrying with fresh connection', {
145
+ function resetHealBudget(result) {
146
+ healAttemptsRemaining = HEAL_ATTEMPTS_MAX;
147
+ return result;
148
+ }
149
+ // Handles three recoverable error classes:
150
+ // 1. InvalidStateError — connection closed between getDB() resolving and db.transaction().
151
+ // Retry once with a fresh connection. No budget limit (transient, always worth one reopen).
152
+ // 2. Backing store corruption (Chromium UnknownError) — drop cached connection and reopen.
153
+ // 3. Connection lost (Safari UnknownError) — IDB server terminated for backgrounded tabs.
154
+ // Both 2 and 3 share a heal budget (3 attempts, reset on success).
155
+ // Mirrors Dexie's PR1398_maxLoop pattern: https://github.com/dexie/Dexie.js/blob/master/src/functions/temp-transaction.ts
156
+ // Note: concurrent store() calls share the budget. Under overlapping failures each caller
157
+ // decrements independently, so the budget may drain faster than one-per-incident. This is
158
+ // acceptable — same as Dexie's approach — and the budget resets on any success.
159
+ return (txMode, callback) => executeTransaction(txMode, callback)
160
+ .then(resetHealBudget)
161
+ .catch((error) => {
162
+ if (isInvalidStateError(error)) {
163
+ Logger.logInfo('IDB InvalidStateError — dropping cached connection and retrying', {
107
164
  dbName,
108
165
  storeName,
109
166
  txMode,
110
- errorMessage: error.message,
167
+ errorMessage: error instanceof Error ? error.message : String(error),
111
168
  });
112
169
  dbp = undefined;
113
- // Retry only once — this call is not wrapped, so if it also fails the error propagates normally.
114
- return executeTransaction(txMode, callback);
170
+ return executeTransaction(txMode, callback).then(resetHealBudget);
171
+ }
172
+ if (isBudgetedHealError(error) && healAttemptsRemaining > 0) {
173
+ healAttemptsRemaining--;
174
+ const label = getBudgetedHealErrorLabel(error);
175
+ Logger.logInfo(`IDB heal: ${label} error detected — dropping cached connection and reopening (${healAttemptsRemaining} attempts left)`, {
176
+ dbName,
177
+ storeName,
178
+ });
179
+ dbp = undefined;
180
+ return executeTransaction(txMode, callback).then((result) => {
181
+ Logger.logInfo(`IDB heal: successfully recovered after ${label} error`, { dbName, storeName });
182
+ return resetHealBudget(result);
183
+ });
184
+ }
185
+ if (isBudgetedHealError(error)) {
186
+ Logger.logAlert(`IDB heal: ${getBudgetedHealErrorLabel(error)} error — heal budget exhausted, giving up`, {
187
+ dbName,
188
+ storeName,
189
+ });
190
+ }
191
+ else {
192
+ Logger.logAlert('IDB error is not recoverable, giving up', {
193
+ dbName,
194
+ storeName,
195
+ errorMessage: error instanceof Error ? error.message : String(error),
196
+ });
115
197
  }
116
198
  throw error;
117
199
  });
@@ -171,6 +171,7 @@ const provider = {
171
171
  return ({
172
172
  bytesUsed: (_a = value.usage) !== null && _a !== void 0 ? _a : 0,
173
173
  bytesRemaining: ((_b = value.quota) !== null && _b !== void 0 ? _b : 0) - ((_c = value.usage) !== null && _c !== void 0 ? _c : 0),
174
+ usageDetails: value.usageDetails,
174
175
  });
175
176
  })
176
177
  .catch((error) => {
@@ -5,6 +5,7 @@ type StorageKeyList = OnyxKey[];
5
5
  type DatabaseSize = {
6
6
  bytesUsed: number;
7
7
  bytesRemaining: number;
8
+ usageDetails?: Record<string, number>;
8
9
  };
9
10
  type OnStorageKeyChanged = <TKey extends OnyxKey>(key: TKey, value: OnyxValue<TKey>) => void;
10
11
  type StorageProvider<TStore> = {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "react-native-onyx",
3
- "version": "3.0.82",
3
+ "version": "3.0.84",
4
4
  "author": "Expensify, Inc.",
5
5
  "homepage": "https://expensify.com",
6
6
  "description": "State management for React Native",