@serwist/expiration 8.0.0

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/index.js ADDED
@@ -0,0 +1,521 @@
1
+ import { assert, SerwistError, logger, dontWaitFor, privateCacheNames, getFriendlyURL } from '@serwist/core/internal';
2
+ import { deleteDB, openDB } from 'idb';
3
+ import { registerQuotaErrorCallback } from '@serwist/core';
4
+
5
+ const DB_NAME = "serwist-expiration";
6
+ const CACHE_OBJECT_STORE = "cache-entries";
7
+ const normalizeURL = (unNormalizedUrl)=>{
8
+ const url = new URL(unNormalizedUrl, location.href);
9
+ url.hash = "";
10
+ return url.href;
11
+ };
12
+ /**
13
+ * Returns the timestamp model.
14
+ *
15
+ * @private
16
+ */ class CacheTimestampsModel {
17
+ _cacheName;
18
+ _db = null;
19
+ /**
20
+ *
21
+ * @param cacheName
22
+ *
23
+ * @private
24
+ */ constructor(cacheName){
25
+ this._cacheName = cacheName;
26
+ }
27
+ /**
28
+ * Performs an upgrade of indexedDB.
29
+ *
30
+ * @param db
31
+ *
32
+ * @private
33
+ */ _upgradeDb(db) {
34
+ // TODO(philipwalton): EdgeHTML doesn't support arrays as a keyPath, so we
35
+ // have to use the `id` keyPath here and create our own values (a
36
+ // concatenation of `url + cacheName`) instead of simply using
37
+ // `keyPath: ['url', 'cacheName']`, which is supported in other browsers.
38
+ const objStore = db.createObjectStore(CACHE_OBJECT_STORE, {
39
+ keyPath: "id"
40
+ });
41
+ // TODO(philipwalton): once we don't have to support EdgeHTML, we can
42
+ // create a single index with the keyPath `['cacheName', 'timestamp']`
43
+ // instead of doing both these indexes.
44
+ objStore.createIndex("cacheName", "cacheName", {
45
+ unique: false
46
+ });
47
+ objStore.createIndex("timestamp", "timestamp", {
48
+ unique: false
49
+ });
50
+ }
51
+ /**
52
+ * Performs an upgrade of indexedDB and deletes deprecated DBs.
53
+ *
54
+ * @param db
55
+ *
56
+ * @private
57
+ */ _upgradeDbAndDeleteOldDbs(db) {
58
+ this._upgradeDb(db);
59
+ if (this._cacheName) {
60
+ void deleteDB(this._cacheName);
61
+ }
62
+ }
63
+ /**
64
+ * @param url
65
+ * @param timestamp
66
+ *
67
+ * @private
68
+ */ async setTimestamp(url, timestamp) {
69
+ url = normalizeURL(url);
70
+ const entry = {
71
+ url,
72
+ timestamp,
73
+ cacheName: this._cacheName,
74
+ // Creating an ID from the URL and cache name won't be necessary once
75
+ // Edge switches to Chromium and all browsers we support work with
76
+ // array keyPaths.
77
+ id: this._getId(url)
78
+ };
79
+ const db = await this.getDb();
80
+ const tx = db.transaction(CACHE_OBJECT_STORE, "readwrite", {
81
+ durability: "relaxed"
82
+ });
83
+ await tx.store.put(entry);
84
+ await tx.done;
85
+ }
86
+ /**
87
+ * Returns the timestamp stored for a given URL.
88
+ *
89
+ * @param url
90
+ * @returns
91
+ * @private
92
+ */ async getTimestamp(url) {
93
+ const db = await this.getDb();
94
+ const entry = await db.get(CACHE_OBJECT_STORE, this._getId(url));
95
+ return entry?.timestamp;
96
+ }
97
+ /**
98
+ * Iterates through all the entries in the object store (from newest to
99
+ * oldest) and removes entries once either `maxCount` is reached or the
100
+ * entry's timestamp is less than `minTimestamp`.
101
+ *
102
+ * @param minTimestamp
103
+ * @param maxCount
104
+ * @returns
105
+ * @private
106
+ */ async expireEntries(minTimestamp, maxCount) {
107
+ const db = await this.getDb();
108
+ let cursor = await db.transaction(CACHE_OBJECT_STORE).store.index("timestamp").openCursor(null, "prev");
109
+ const entriesToDelete = [];
110
+ let entriesNotDeletedCount = 0;
111
+ while(cursor){
112
+ const result = cursor.value;
113
+ // TODO(philipwalton): once we can use a multi-key index, we
114
+ // won't have to check `cacheName` here.
115
+ if (result.cacheName === this._cacheName) {
116
+ // Delete an entry if it's older than the max age or
117
+ // if we already have the max number allowed.
118
+ if (minTimestamp && result.timestamp < minTimestamp || maxCount && entriesNotDeletedCount >= maxCount) {
119
+ // TODO(philipwalton): we should be able to delete the
120
+ // entry right here, but doing so causes an iteration
121
+ // bug in Safari stable (fixed in TP). Instead we can
122
+ // store the keys of the entries to delete, and then
123
+ // delete the separate transactions.
124
+ // https://github.com/GoogleChrome/workbox/issues/1978
125
+ // cursor.delete();
126
+ // We only need to return the URL, not the whole entry.
127
+ entriesToDelete.push(cursor.value);
128
+ } else {
129
+ entriesNotDeletedCount++;
130
+ }
131
+ }
132
+ cursor = await cursor.continue();
133
+ }
134
+ // TODO(philipwalton): once the Safari bug in the following issue is fixed,
135
+ // we should be able to remove this loop and do the entry deletion in the
136
+ // cursor loop above:
137
+ // https://github.com/GoogleChrome/workbox/issues/1978
138
+ const urlsDeleted = [];
139
+ for (const entry of entriesToDelete){
140
+ await db.delete(CACHE_OBJECT_STORE, entry.id);
141
+ urlsDeleted.push(entry.url);
142
+ }
143
+ return urlsDeleted;
144
+ }
145
+ /**
146
+ * Takes a URL and returns an ID that will be unique in the object store.
147
+ *
148
+ * @param url
149
+ * @returns
150
+ * @private
151
+ */ _getId(url) {
152
+ // Creating an ID from the URL and cache name won't be necessary once
153
+ // Edge switches to Chromium and all browsers we support work with
154
+ // array keyPaths.
155
+ return this._cacheName + "|" + normalizeURL(url);
156
+ }
157
+ /**
158
+ * Returns an open connection to the database.
159
+ *
160
+ * @private
161
+ */ async getDb() {
162
+ if (!this._db) {
163
+ this._db = await openDB(DB_NAME, 1, {
164
+ upgrade: this._upgradeDbAndDeleteOldDbs.bind(this)
165
+ });
166
+ }
167
+ return this._db;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * The `CacheExpiration` class allows you define an expiration and / or
173
+ * limit on the number of responses stored in a
174
+ * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
175
+ */ class CacheExpiration {
176
+ _isRunning = false;
177
+ _rerunRequested = false;
178
+ _maxEntries;
179
+ _maxAgeSeconds;
180
+ _matchOptions;
181
+ _cacheName;
182
+ _timestampModel;
183
+ /**
184
+ * To construct a new CacheExpiration instance you must provide at least
185
+ * one of the `config` properties.
186
+ *
187
+ * @param cacheName Name of the cache to apply restrictions to.
188
+ * @param config
189
+ */ constructor(cacheName, config = {}){
190
+ if (process.env.NODE_ENV !== "production") {
191
+ assert.isType(cacheName, "string", {
192
+ moduleName: "@serwist/expiration",
193
+ className: "CacheExpiration",
194
+ funcName: "constructor",
195
+ paramName: "cacheName"
196
+ });
197
+ if (!(config.maxEntries || config.maxAgeSeconds)) {
198
+ throw new SerwistError("max-entries-or-age-required", {
199
+ moduleName: "@serwist/expiration",
200
+ className: "CacheExpiration",
201
+ funcName: "constructor"
202
+ });
203
+ }
204
+ if (config.maxEntries) {
205
+ assert.isType(config.maxEntries, "number", {
206
+ moduleName: "@serwist/expiration",
207
+ className: "CacheExpiration",
208
+ funcName: "constructor",
209
+ paramName: "config.maxEntries"
210
+ });
211
+ }
212
+ if (config.maxAgeSeconds) {
213
+ assert.isType(config.maxAgeSeconds, "number", {
214
+ moduleName: "@serwist/expiration",
215
+ className: "CacheExpiration",
216
+ funcName: "constructor",
217
+ paramName: "config.maxAgeSeconds"
218
+ });
219
+ }
220
+ }
221
+ this._maxEntries = config.maxEntries;
222
+ this._maxAgeSeconds = config.maxAgeSeconds;
223
+ this._matchOptions = config.matchOptions;
224
+ this._cacheName = cacheName;
225
+ this._timestampModel = new CacheTimestampsModel(cacheName);
226
+ }
227
+ /**
228
+ * Expires entries for the given cache and given criteria.
229
+ */ async expireEntries() {
230
+ if (this._isRunning) {
231
+ this._rerunRequested = true;
232
+ return;
233
+ }
234
+ this._isRunning = true;
235
+ const minTimestamp = this._maxAgeSeconds ? Date.now() - this._maxAgeSeconds * 1000 : 0;
236
+ const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
237
+ // Delete URLs from the cache
238
+ const cache = await self.caches.open(this._cacheName);
239
+ for (const url of urlsExpired){
240
+ await cache.delete(url, this._matchOptions);
241
+ }
242
+ if (process.env.NODE_ENV !== "production") {
243
+ if (urlsExpired.length > 0) {
244
+ logger.groupCollapsed(`Expired ${urlsExpired.length} ` + `${urlsExpired.length === 1 ? "entry" : "entries"} and removed ` + `${urlsExpired.length === 1 ? "it" : "them"} from the ` + `'${this._cacheName}' cache.`);
245
+ logger.log(`Expired the following ${urlsExpired.length === 1 ? "URL" : "URLs"}:`);
246
+ urlsExpired.forEach((url)=>logger.log(` ${url}`));
247
+ logger.groupEnd();
248
+ } else {
249
+ logger.debug(`Cache expiration ran and found no entries to remove.`);
250
+ }
251
+ }
252
+ this._isRunning = false;
253
+ if (this._rerunRequested) {
254
+ this._rerunRequested = false;
255
+ dontWaitFor(this.expireEntries());
256
+ }
257
+ }
258
+ /**
259
+ * Update the timestamp for the given URL. This ensures the when
260
+ * removing entries based on maximum entries, most recently used
261
+ * is accurate or when expiring, the timestamp is up-to-date.
262
+ *
263
+ * @param url
264
+ */ async updateTimestamp(url) {
265
+ if (process.env.NODE_ENV !== "production") {
266
+ assert.isType(url, "string", {
267
+ moduleName: "@serwist/expiration",
268
+ className: "CacheExpiration",
269
+ funcName: "updateTimestamp",
270
+ paramName: "url"
271
+ });
272
+ }
273
+ await this._timestampModel.setTimestamp(url, Date.now());
274
+ }
275
+ /**
276
+ * Can be used to check if a URL has expired or not before it's used.
277
+ *
278
+ * This requires a look up from IndexedDB, so can be slow.
279
+ *
280
+ * Note: This method will not remove the cached entry, call
281
+ * `expireEntries()` to remove indexedDB and Cache entries.
282
+ *
283
+ * @param url
284
+ * @returns
285
+ */ async isURLExpired(url) {
286
+ if (!this._maxAgeSeconds) {
287
+ if (process.env.NODE_ENV !== "production") {
288
+ throw new SerwistError(`expired-test-without-max-age`, {
289
+ methodName: "isURLExpired",
290
+ paramName: "maxAgeSeconds"
291
+ });
292
+ }
293
+ return false;
294
+ } else {
295
+ const timestamp = await this._timestampModel.getTimestamp(url);
296
+ const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
297
+ return timestamp !== undefined ? timestamp < expireOlderThan : true;
298
+ }
299
+ }
300
+ /**
301
+ * Removes the IndexedDB object store used to keep track of cache expiration
302
+ * metadata.
303
+ */ async delete() {
304
+ // Make sure we don't attempt another rerun if we're called in the middle of
305
+ // a cache expiration.
306
+ this._rerunRequested = false;
307
+ await this._timestampModel.expireEntries(Infinity); // Expires all.
308
+ }
309
+ }
310
+
311
+ /**
312
+ * This plugin can be used in a `@serwist/strategies` Strategy to regularly enforce a
313
+ * limit on the age and / or the number of cached requests.
314
+ *
315
+ * It can only be used with Strategy instances that have a
316
+ * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).
317
+ * In other words, it can't be used to expire entries in strategy that uses the
318
+ * default runtime cache name.
319
+ *
320
+ * Whenever a cached response is used or updated, this plugin will look
321
+ * at the associated cache and remove any old or extra responses.
322
+ *
323
+ * When using `maxAgeSeconds`, responses may be used *once* after expiring
324
+ * because the expiration clean up will not have occurred until *after* the
325
+ * cached response has been used. If the response has a "Date" header, then
326
+ * a light weight expiration check is performed and the response will not be
327
+ * used immediately.
328
+ *
329
+ * When using `maxEntries`, the entry least-recently requested will be removed
330
+ * from the cache first.
331
+ */ class ExpirationPlugin {
332
+ _config;
333
+ _maxAgeSeconds;
334
+ _cacheExpirations;
335
+ /**
336
+ * @param config
337
+ */ constructor(config = {}){
338
+ if (process.env.NODE_ENV !== "production") {
339
+ if (!(config.maxEntries || config.maxAgeSeconds)) {
340
+ throw new SerwistError("max-entries-or-age-required", {
341
+ moduleName: "@serwist/expiration",
342
+ className: "Plugin",
343
+ funcName: "constructor"
344
+ });
345
+ }
346
+ if (config.maxEntries) {
347
+ assert.isType(config.maxEntries, "number", {
348
+ moduleName: "@serwist/expiration",
349
+ className: "Plugin",
350
+ funcName: "constructor",
351
+ paramName: "config.maxEntries"
352
+ });
353
+ }
354
+ if (config.maxAgeSeconds) {
355
+ assert.isType(config.maxAgeSeconds, "number", {
356
+ moduleName: "@serwist/expiration",
357
+ className: "Plugin",
358
+ funcName: "constructor",
359
+ paramName: "config.maxAgeSeconds"
360
+ });
361
+ }
362
+ }
363
+ this._config = config;
364
+ this._maxAgeSeconds = config.maxAgeSeconds;
365
+ this._cacheExpirations = new Map();
366
+ if (config.purgeOnQuotaError) {
367
+ registerQuotaErrorCallback(()=>this.deleteCacheAndMetadata());
368
+ }
369
+ }
370
+ /**
371
+ * A simple helper method to return a CacheExpiration instance for a given
372
+ * cache name.
373
+ *
374
+ * @param cacheName
375
+ * @returns
376
+ * @private
377
+ */ _getCacheExpiration(cacheName) {
378
+ if (cacheName === privateCacheNames.getRuntimeName()) {
379
+ throw new SerwistError("expire-custom-caches-only");
380
+ }
381
+ let cacheExpiration = this._cacheExpirations.get(cacheName);
382
+ if (!cacheExpiration) {
383
+ cacheExpiration = new CacheExpiration(cacheName, this._config);
384
+ this._cacheExpirations.set(cacheName, cacheExpiration);
385
+ }
386
+ return cacheExpiration;
387
+ }
388
+ /**
389
+ * A "lifecycle" callback that will be triggered automatically by the
390
+ * `@serwist/strategies` handlers when a `Response` is about to be returned
391
+ * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
392
+ * the handler. It allows the `Response` to be inspected for freshness and
393
+ * prevents it from being used if the `Response`'s `Date` header value is
394
+ * older than the configured `maxAgeSeconds`.
395
+ *
396
+ * @param options
397
+ * @returns Either the `cachedResponse`, if it's fresh, or `null` if the `Response`
398
+ * is older than `maxAgeSeconds`.
399
+ * @private
400
+ */ cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse })=>{
401
+ if (!cachedResponse) {
402
+ return null;
403
+ }
404
+ const isFresh = this._isResponseDateFresh(cachedResponse);
405
+ // Expire entries to ensure that even if the expiration date has
406
+ // expired, it'll only be used once.
407
+ const cacheExpiration = this._getCacheExpiration(cacheName);
408
+ dontWaitFor(cacheExpiration.expireEntries());
409
+ // Update the metadata for the request URL to the current timestamp,
410
+ // but don't `await` it as we don't want to block the response.
411
+ const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
412
+ if (event) {
413
+ try {
414
+ event.waitUntil(updateTimestampDone);
415
+ } catch (error) {
416
+ if (process.env.NODE_ENV !== "production") {
417
+ // The event may not be a fetch event; only log the URL if it is.
418
+ if ("request" in event) {
419
+ logger.warn(`Unable to ensure service worker stays alive when ` + `updating cache entry for ` + `'${getFriendlyURL(event.request.url)}'.`);
420
+ }
421
+ }
422
+ }
423
+ }
424
+ return isFresh ? cachedResponse : null;
425
+ };
426
+ /**
427
+ * @param cachedResponse
428
+ * @returns
429
+ * @private
430
+ */ _isResponseDateFresh(cachedResponse) {
431
+ if (!this._maxAgeSeconds) {
432
+ // We aren't expiring by age, so return true, it's fresh
433
+ return true;
434
+ }
435
+ // Check if the 'date' header will suffice a quick expiration check.
436
+ // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
437
+ // discussion.
438
+ const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
439
+ if (dateHeaderTimestamp === null) {
440
+ // Unable to parse date, so assume it's fresh.
441
+ return true;
442
+ }
443
+ // If we have a valid headerTime, then our response is fresh iff the
444
+ // headerTime plus maxAgeSeconds is greater than the current time.
445
+ const now = Date.now();
446
+ return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
447
+ }
448
+ /**
449
+ * This method will extract the data header and parse it into a useful
450
+ * value.
451
+ *
452
+ * @param cachedResponse
453
+ * @returns
454
+ * @private
455
+ */ _getDateHeaderTimestamp(cachedResponse) {
456
+ if (!cachedResponse.headers.has("date")) {
457
+ return null;
458
+ }
459
+ const dateHeader = cachedResponse.headers.get("date");
460
+ const parsedDate = new Date(dateHeader);
461
+ const headerTime = parsedDate.getTime();
462
+ // If the Date header was invalid for some reason, parsedDate.getTime()
463
+ // will return NaN.
464
+ if (isNaN(headerTime)) {
465
+ return null;
466
+ }
467
+ return headerTime;
468
+ }
469
+ /**
470
+ * A "lifecycle" callback that will be triggered automatically by the
471
+ * `@serwist/strategies` handlers when an entry is added to a cache.
472
+ *
473
+ * @param options
474
+ * @private
475
+ */ cacheDidUpdate = async ({ cacheName, request })=>{
476
+ if (process.env.NODE_ENV !== "production") {
477
+ assert.isType(cacheName, "string", {
478
+ moduleName: "@serwist/expiration",
479
+ className: "Plugin",
480
+ funcName: "cacheDidUpdate",
481
+ paramName: "cacheName"
482
+ });
483
+ assert.isInstance(request, Request, {
484
+ moduleName: "@serwist/expiration",
485
+ className: "Plugin",
486
+ funcName: "cacheDidUpdate",
487
+ paramName: "request"
488
+ });
489
+ }
490
+ const cacheExpiration = this._getCacheExpiration(cacheName);
491
+ await cacheExpiration.updateTimestamp(request.url);
492
+ await cacheExpiration.expireEntries();
493
+ };
494
+ /**
495
+ * This is a helper method that performs two operations:
496
+ *
497
+ * - Deletes *all* the underlying Cache instances associated with this plugin
498
+ * instance, by calling caches.delete() on your behalf.
499
+ * - Deletes the metadata from IndexedDB used to keep track of expiration
500
+ * details for each Cache instance.
501
+ *
502
+ * When using cache expiration, calling this method is preferable to calling
503
+ * `caches.delete()` directly, since this will ensure that the IndexedDB
504
+ * metadata is also cleanly removed and open IndexedDB instances are deleted.
505
+ *
506
+ * Note that if you're *not* using cache expiration for a given cache, calling
507
+ * `caches.delete()` and passing in the cache's name should be sufficient.
508
+ * There is no Serwist-specific method needed for cleanup in that case.
509
+ */ async deleteCacheAndMetadata() {
510
+ // Do this one at a time instead of all at once via `Promise.all()` to
511
+ // reduce the chance of inconsistency if a promise rejects.
512
+ for (const [cacheName, cacheExpiration] of this._cacheExpirations){
513
+ await self.caches.delete(cacheName);
514
+ await cacheExpiration.delete();
515
+ }
516
+ // Reset this._cacheExpirations to its initial state.
517
+ this._cacheExpirations = new Map();
518
+ }
519
+ }
520
+
521
+ export { CacheExpiration, ExpirationPlugin };