Debian Codegraph @

resources/src/mediawiki.storage/SafeStorage.js

raw symbols SCIP
1 'use strict';
2 const EXPIRY_PREFIX = '_EXPIRY_';
3
4 /**
5 * @classdesc
6 * A wrapper for the HTML5 Storage interface (`localStorage` or `sessionStorage`)
7 * that is safe to call in all browsers.
8 *
9 * The constructor is not publicly accessible. An instance can be accessed from
10 * {@link mw.storage} or {@link module:mediawiki.storage}.
11 *
12 * @class
13 * @param {Object|undefined} store The Storage instance to wrap around
14 * @hideconstructor
15 * @memberof module:mediawiki.storage
16 * @inner
17 */
18 function SafeStorage( store ) {
19 this.store = store;
20
21 // Purge expired items once per page session
22 if ( !window.QUnit ) {
23 const storage = this;
24 setTimeout( () => {
25 storage.clearExpired();
26 }, 2000 );
27 }
28 }
29
30 /**
31 * Retrieve value from device storage.
32 *
33 * @param {string} key Key of item to retrieve
34 * @return {string|null|boolean} String value, null if no value exists, or false
35 * if storage is not available.
36 */
37 SafeStorage.prototype.get = function ( key ) {
38 if ( this.isExpired( key ) ) {
39 return null;
40 }
41 try {
42 return this.store.getItem( key );
43 } catch ( e ) {}
44 return false;
45 };
46
47 /**
48 * Set a value in device storage.
49 *
50 * @param {string} key Key name to store under
51 * @param {string} value Value to be stored
52 * @param {number} [expiry] Number of seconds after which this item can be deleted
53 * @return {boolean} The value was set
54 */
55 SafeStorage.prototype.set = function ( key, value, expiry ) {
56 if ( key.slice( 0, EXPIRY_PREFIX.length ) === EXPIRY_PREFIX ) {
57 throw new Error( 'Key can\'t have a prefix of ' + EXPIRY_PREFIX );
58 }
59 // Compare to `false` instead of checking falsiness to tolerate subclasses and mocks in
60 // extensions that weren't updated to add a return value to setExpires().
61 if ( this.setExpires( key, expiry ) === false ) {
62 // If we failed to set the expiration time, don't try to set the value,
63 // otherwise it might end up set with no expiration.
64 return false;
65 }
66 try {
67 this.store.setItem( key, value );
68 return true;
69 } catch ( e ) {}
70 return false;
71 };
72
73 /**
74 * Remove a value from device storage.
75 *
76 * @param {string} key Key of item to remove
77 * @return {boolean} Whether the key was removed
78 */
79 SafeStorage.prototype.remove = function ( key ) {
80 try {
81 this.store.removeItem( key );
82 this.setExpires( key );
83 return true;
84 } catch ( e ) {}
85 return false;
86 };
87
88 /**
89 * Retrieve JSON object from device storage.
90 *
91 * @param {string} key Key of item to retrieve
92 * @return {Object|null|boolean} Object, null if no value exists or value
93 * is not JSON-parseable, or false if storage is not available.
94 */
95 SafeStorage.prototype.getObject = function ( key ) {
96 const json = this.get( key );
97
98 if ( json === false ) {
99 return false;
100 }
101
102 try {
103 return JSON.parse( json );
104 } catch ( e ) {}
105
106 return null;
107 };
108
109 /**
110 * Set an object value in device storage by JSON encoding.
111 *
112 * @param {string} key Key name to store under
113 * @param {Object} value Object value to be stored
114 * @param {number} [expiry] Number of seconds after which this item can be deleted
115 * @return {boolean} The value was set
116 */
117 SafeStorage.prototype.setObject = function ( key, value, expiry ) {
118 let json;
119 try {
120 json = JSON.stringify( value );
121 return this.set( key, json, expiry );
122 } catch ( e ) {}
123 return false;
124 };
125
126 /**
127 * Set the expiry time for an item in the store.
128 *
129 * @param {string} key Key name
130 * @param {number} [expiry] Number of seconds after which this item can be deleted,
131 * omit to clear the expiry (either making the item never expire, or to clean up
132 * when deleting a key).
133 * @return {boolean} The expiry was set (or cleared) [since 1.41]
134 */
135 SafeStorage.prototype.setExpires = function ( key, expiry ) {
136 if ( expiry ) {
137 try {
138 this.store.setItem(
139 EXPIRY_PREFIX + key,
140 Math.floor( Date.now() / 1000 ) + expiry
141 );
142 return true;
143 } catch ( e ) {}
144 } else {
145 try {
146 this.store.removeItem( EXPIRY_PREFIX + key );
147 return true;
148 } catch ( e ) {}
149 }
150 return false;
151 };
152
153 // Minimum amount of time (in milliseconds) for an iteration involving localStorage access.
154 const MIN_WORK_TIME = 3;
155
156 /**
157 * Clear any expired items from the store
158 *
159 * @private
160 * @return {jQuery.Promise} Resolves when items have been expired
161 */
162 SafeStorage.prototype.clearExpired = function () {
163 const storage = this;
164 return this.getExpiryKeys().then( ( keys ) => $.Deferred( ( d ) => {
165 mw.requestIdleCallback( function iterate( deadline ) {
166 while ( keys[ 0 ] !== undefined && deadline.timeRemaining() > MIN_WORK_TIME ) {
167 const key = keys.shift();
168 if ( storage.isExpired( key ) ) {
169 storage.remove( key );
170 }
171 }
172 if ( keys[ 0 ] !== undefined ) {
173 // Ran out of time with keys still to remove, continue later
174 mw.requestIdleCallback( iterate );
175 } else {
176 return d.resolve();
177 }
178 } );
179 } ) );
180 };
181
182 /**
183 * Get all keys with expiry values
184 *
185 * @private
186 * @return {jQuery.Promise} Promise resolving with all the keys which have
187 * expiry values (unprefixed), or as many could be retrieved in the allocated time.
188 */
189 SafeStorage.prototype.getExpiryKeys = function () {
190 const store = this.store;
191 return $.Deferred( ( d ) => {
192 mw.requestIdleCallback( ( deadline ) => {
193 const prefixLength = EXPIRY_PREFIX.length;
194 const keys = [];
195 let length = 0;
196 try {
197 length = store.length;
198 } catch ( e ) {}
199
200 // Optimization: If time runs out, degrade to checking fewer keys.
201 // We will get another chance during a future page view. Iterate forward
202 // so that older keys are checked first and increase likelihood of recovering
203 // from key exhaustion.
204 //
205 // We don't expect to have more keys than we can handle in 50ms long-task window.
206 // But, we might still run out of time when other tasks run before this,
207 // or when the device receives UI events (especially on low-end devices).
208 for ( let i = 0; ( i < length && deadline.timeRemaining() > MIN_WORK_TIME ); i++ ) {
209 let key = null;
210 try {
211 key = store.key( i );
212 } catch ( e ) {}
213 if ( key !== null && key.slice( 0, prefixLength ) === EXPIRY_PREFIX ) {
214 keys.push( key.slice( prefixLength ) );
215 }
216 }
217 d.resolve( keys );
218 } );
219 } ).promise();
220 };
221
222 /**
223 * Check if a given key has expired
224 *
225 * @private
226 * @param {string} key Key name
227 * @return {boolean} Whether key is expired
228 */
229 SafeStorage.prototype.isExpired = function ( key ) {
230 let expiry;
231 try {
232 expiry = this.store.getItem( EXPIRY_PREFIX + key );
233 } catch ( e ) {
234 return false;
235 }
236 return !!expiry && expiry < Math.floor( Date.now() / 1000 );
237 };
238
239 module.exports = SafeStorage;