File size: 10,393 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import config from '@automattic/calypso-config';
import debugFactory from 'debug';
import { kebabCase } from 'lodash';
import { bumpStat } from 'calypso/lib/analytics/mc';
import { once } from 'calypso/lib/memoize-last';
import {
	getStoredItem as bypassGet,
	getAllStoredItems as bypassGetAll,
	setStoredItem as bypassSet,
	clearStorage as bypassClear,
	activate as activateBypass,
} from './bypass';
import { StoredItems } from './types';

const debug = debugFactory( 'calypso:browser-storage' );

let shouldBypass = false;
let shouldDisableIDB = false;

const DB_NAME = 'calypso';
const DB_VERSION = 2; // Match versioning of the previous localforage-based implementation.
const STORE_NAME = 'calypso_store';

const SANITY_TEST_KEY = 'browser-storage-sanity-test';

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const isAffectedSafari =
	config.isEnabled( 'safari-idb-mitigation' ) &&
	typeof window !== 'undefined' &&
	!! window.IDBKeyRange?.lowerBound( 0 ).includes &&
	!! ( window as any ).webkitAudioContext &&
	!! window.PointerEvent;

debug( 'Safari IDB mitigation active: %s', isAffectedSafari );

export const supportsIDB = once( async () => {
	if ( typeof window === 'undefined' || ! window.indexedDB ) {
		debug( 'IDB not found in host' );
		return false;
	}

	if ( shouldDisableIDB ) {
		debug( 'IDB disabled' );
		return false;
	}

	try {
		const testValue = Date.now().toString();
		await idbSet( SANITY_TEST_KEY, testValue );
		await idbGet( SANITY_TEST_KEY );
		return true;
	} catch ( error ) {
		// IDB sanity test failed. Fall back to alternative method.
		return false;
	}
} );

const getDB = once( () => {
	const request = window.indexedDB.open( DB_NAME, DB_VERSION );
	return new Promise< IDBDatabase >( ( resolve, reject ) => {
		try {
			if ( request ) {
				request.onerror = ( event ) => {
					// InvalidStateError is special in Firefox.
					// We need to `preventDefault` to stop it from reaching the console.
					if ( request.error && request.error.name === 'InvalidStateError' ) {
						event.preventDefault();
					}
					reject( request.error );
				};
				request.onsuccess = () => {
					const db = request.result;

					// Add a general error handler for any future requests made against this db handle.
					// See https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB#Handling_Errors for
					// more information on how error events bubble with IndexedDB
					db.onerror = function ( errorEvent: any ) {
						debug( 'IDB Error', errorEvent );
						if ( errorEvent.target?.error?.name ) {
							bumpStat( 'calypso-browser-storage', kebabCase( errorEvent.target.error.name ) );

							if ( errorEvent.target.error.name === 'QuotaExceededError' ) {
								// we've blown through the quota. Turn off IDB for this page load
								shouldDisableIDB = true;
								supportsIDB.clear();
								debug( 'disabling IDB because we saw a QuotaExceededError' );
							}
						}
					};
					db.onversionchange = () => {
						// This fires when the database gets upgraded or when it gets deleted.
						// We need to close our handle to allow the change to proceed
						db.close();
					};
					resolve( db );
				};
				request.onupgradeneeded = () => request.result.createObjectStore( STORE_NAME );
			}
		} catch ( error ) {
			reject( error );
		}
	} );
} );

function idbGet< T >( key: string ): Promise< T | undefined > {
	return new Promise( ( resolve, reject ) => {
		getDB()
			.then( ( db ) => {
				const transaction = db.transaction( STORE_NAME, 'readonly' );
				const get = transaction.objectStore( STORE_NAME ).get( key );

				const success = () => resolve( get.result );
				const error = () => reject( transaction.error );

				transaction.oncomplete = success;
				transaction.onabort = error;
				transaction.onerror = error;
			} )
			.catch( ( err ) => reject( err ) );
	} );
}

type EventTargetWithCursorResult = EventTarget & { result: IDBCursorWithValue | null };

function idbGetAll( pattern?: RegExp ): Promise< StoredItems > {
	return getDB().then(
		( db ) =>
			new Promise( ( resolve, reject ) => {
				const results: StoredItems = {};
				const transaction = db.transaction( STORE_NAME, 'readonly' );
				const getAll = transaction.objectStore( STORE_NAME ).openCursor();

				const success = ( event: Event ) => {
					const cursor = ( event.target as EventTargetWithCursorResult ).result;
					if ( cursor ) {
						const { primaryKey: key, value } = cursor;
						if (
							key &&
							typeof key === 'string' &&
							key !== SANITY_TEST_KEY &&
							( ! pattern || pattern.test( key ) )
						) {
							results[ key ] = value;
						}
						cursor.continue();
					} else {
						// No more results.
						resolve( results );
					}
				};
				const error = () => reject( transaction.error );

				getAll.onsuccess = success;
				transaction.onabort = error;
				transaction.onerror = error;
			} )
	);
}

let idbWriteCount = 0;
let idbWriteBlock: Promise< void > | null = null;
async function idbSet< T >( key: string, value: T ): Promise< void > {
	// if there's a write lock, wait on it
	if ( idbWriteBlock ) {
		await idbWriteBlock;
	}
	// if we're on safari 13, we need to clear out the object store every
	// so many writes to make sure we don't chew up the transaction log
	if ( isAffectedSafari && ++idbWriteCount % 20 === 0 ) {
		await idbSafariReset();
	}

	return new Promise( ( resolve, reject ) => {
		getDB()
			.then( async ( db ) => {
				const transaction = db.transaction( STORE_NAME, 'readwrite' );
				transaction.objectStore( STORE_NAME ).put( value, key );

				const success = () => resolve();
				const error = () => reject( transaction.error );

				transaction.oncomplete = success;
				transaction.onabort = error;
				transaction.onerror = error;
			} )
			.catch( ( err ) => reject( err ) );
	} );
}

function idbClear(): Promise< void > {
	return new Promise( ( resolve, reject ) => {
		getDB()
			.then( ( db ) => {
				const transaction = db.transaction( STORE_NAME, 'readwrite' );
				transaction.objectStore( STORE_NAME ).clear();

				const success = () => resolve();
				const error = () => reject( transaction.error );

				transaction.oncomplete = success;
				transaction.onabort = error;
				transaction.onerror = error;
			} )
			.catch( ( err ) => reject( err ) );
	} );
}

function idbRemove(): Promise< void > {
	return new Promise( ( resolve, reject ) => {
		const deleteRequest = window.indexedDB.deleteDatabase( DB_NAME );
		deleteRequest.onsuccess = () => {
			getDB.clear();
			resolve();
		};
		deleteRequest.onerror = ( event ) => reject( event );
	} );
}

async function idbSafariReset() {
	if ( idbWriteBlock ) {
		return idbWriteBlock;
	}
	debug( 'performing safari idb mitigation' );
	idbWriteBlock = _idbSafariReset();
	idbWriteBlock.finally( () => {
		idbWriteBlock = null;
		debug( 'idb mitigation complete' );
	} );
	return idbWriteBlock;
}

async function _idbSafariReset(): Promise< void > {
	const items = await idbGetAll();

	await idbRemove();

	return new Promise( ( resolve, reject ) => {
		getDB().then(
			( db ) => {
				const transaction = db.transaction( STORE_NAME, 'readwrite' );
				const oStore = transaction.objectStore( STORE_NAME );
				// eslint-disable-next-line prefer-const
				for ( let [ key, value ] of Object.entries( items ) ) {
					oStore.put( value, key );
				}
				const success = () => resolve();
				const error = () => reject( transaction.error );

				transaction.oncomplete = success;
				transaction.onabort = error;
				transaction.onerror = error;
			},
			( err ) => reject( err )
		);
	} );
}

/**
 * Whether persistent storage should be bypassed, using a memory store instead.
 * @param shouldBypassPersistentStorage Whether persistent storage should be bypassed.
 */
export function bypassPersistentStorage( shouldBypassPersistentStorage: boolean ) {
	shouldBypass = shouldBypassPersistentStorage;

	if ( shouldBypass ) {
		activateBypass();
	}
}

/**
 * Get a stored item.
 * @param key The stored item key.
 * @returns A promise with the stored value. `undefined` if missing.
 */
export async function getStoredItem< T >( key: string ): Promise< T | undefined > {
	if ( shouldBypass ) {
		return await bypassGet( key );
	}

	const idbSupported = await supportsIDB();
	if ( ! idbSupported ) {
		try {
			const valueString = window.localStorage.getItem( key );
			if ( valueString === undefined || valueString === null ) {
				return undefined;
			}

			return JSON.parse( valueString );
		} catch {
			return undefined;
		}
	}

	return await idbGet( key );
}

/**
 * Get all stored items.
 * @param pattern The pattern to match on returned item keys.
 * @returns A promise with the stored key/value pairs as an object. Empty if none.
 */
export async function getAllStoredItems( pattern?: RegExp ): Promise< StoredItems > {
	if ( shouldBypass ) {
		return await bypassGetAll( pattern );
	}

	const idbSupported = await supportsIDB();
	if ( ! idbSupported ) {
		try {
			const entries = Object.entries( window.localStorage ).map( ( [ key, value ] ) => [
				key,
				value !== undefined ? JSON.parse( value ) : undefined,
			] );

			if ( ! pattern ) {
				return Object.fromEntries( entries );
			}

			return Object.fromEntries( entries.filter( ( [ key ] ) => pattern.test( key ) ) );
		} catch {
			return {};
		}
	}

	return await idbGetAll( pattern );
}

/**
 * Set an item in storage.
 * @param key The key to store the item under.
 * @param value The value of the item to be stored.
 * @returns A promise that gets resolved when the item is successfully stored.
 */
export async function setStoredItem< T >( key: string, value: T ): Promise< void > {
	if ( shouldBypass ) {
		return await bypassSet( key, value );
	}

	const idbSupported = await supportsIDB();
	if ( ! idbSupported ) {
		try {
			window.localStorage.setItem( key, JSON.stringify( value ) );
		} catch {
			// Do nothing.
		}
		return;
	}

	return await idbSet( key, value );
}

/**
 * Clear all stored items.
 * @returns A promise that gets resolved when all items are successfully cleared.
 */
export async function clearStorage(): Promise< void > {
	if ( shouldBypass ) {
		return await bypassClear();
	}

	const idbSupported = await supportsIDB();
	if ( ! idbSupported ) {
		try {
			window.localStorage.clear();
		} catch {
			// Do nothing.
		}
		return;
	}

	return await idbClear();
}