| 1 | /*
|
|---|
| 2 | Copyright 2018 Google LLC
|
|---|
| 3 |
|
|---|
| 4 | Use of this source code is governed by an MIT-style
|
|---|
| 5 | license that can be found in the LICENSE file or at
|
|---|
| 6 | https://opensource.org/licenses/MIT.
|
|---|
| 7 | */
|
|---|
| 8 | import { assert } from 'workbox-core/_private/assert.js';
|
|---|
| 9 | import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';
|
|---|
| 10 | import { logger } from 'workbox-core/_private/logger.js';
|
|---|
| 11 | import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
|
|---|
| 12 | import { CacheTimestampsModel } from './models/CacheTimestampsModel.js';
|
|---|
| 13 | import './_version.js';
|
|---|
| 14 | /**
|
|---|
| 15 | * The `CacheExpiration` class allows you define an expiration and / or
|
|---|
| 16 | * limit on the number of responses stored in a
|
|---|
| 17 | * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
|
|---|
| 18 | *
|
|---|
| 19 | * @memberof workbox-expiration
|
|---|
| 20 | */
|
|---|
| 21 | class CacheExpiration {
|
|---|
| 22 | /**
|
|---|
| 23 | * To construct a new CacheExpiration instance you must provide at least
|
|---|
| 24 | * one of the `config` properties.
|
|---|
| 25 | *
|
|---|
| 26 | * @param {string} cacheName Name of the cache to apply restrictions to.
|
|---|
| 27 | * @param {Object} config
|
|---|
| 28 | * @param {number} [config.maxEntries] The maximum number of entries to cache.
|
|---|
| 29 | * Entries used the least will be removed as the maximum is reached.
|
|---|
| 30 | * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
|
|---|
| 31 | * it's treated as stale and removed.
|
|---|
| 32 | * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
|
|---|
| 33 | * that will be used when calling `delete()` on the cache.
|
|---|
| 34 | */
|
|---|
| 35 | constructor(cacheName, config = {}) {
|
|---|
| 36 | this._isRunning = false;
|
|---|
| 37 | this._rerunRequested = false;
|
|---|
| 38 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 39 | assert.isType(cacheName, 'string', {
|
|---|
| 40 | moduleName: 'workbox-expiration',
|
|---|
| 41 | className: 'CacheExpiration',
|
|---|
| 42 | funcName: 'constructor',
|
|---|
| 43 | paramName: 'cacheName',
|
|---|
| 44 | });
|
|---|
| 45 | if (!(config.maxEntries || config.maxAgeSeconds)) {
|
|---|
| 46 | throw new WorkboxError('max-entries-or-age-required', {
|
|---|
| 47 | moduleName: 'workbox-expiration',
|
|---|
| 48 | className: 'CacheExpiration',
|
|---|
| 49 | funcName: 'constructor',
|
|---|
| 50 | });
|
|---|
| 51 | }
|
|---|
| 52 | if (config.maxEntries) {
|
|---|
| 53 | assert.isType(config.maxEntries, 'number', {
|
|---|
| 54 | moduleName: 'workbox-expiration',
|
|---|
| 55 | className: 'CacheExpiration',
|
|---|
| 56 | funcName: 'constructor',
|
|---|
| 57 | paramName: 'config.maxEntries',
|
|---|
| 58 | });
|
|---|
| 59 | }
|
|---|
| 60 | if (config.maxAgeSeconds) {
|
|---|
| 61 | assert.isType(config.maxAgeSeconds, 'number', {
|
|---|
| 62 | moduleName: 'workbox-expiration',
|
|---|
| 63 | className: 'CacheExpiration',
|
|---|
| 64 | funcName: 'constructor',
|
|---|
| 65 | paramName: 'config.maxAgeSeconds',
|
|---|
| 66 | });
|
|---|
| 67 | }
|
|---|
| 68 | }
|
|---|
| 69 | this._maxEntries = config.maxEntries;
|
|---|
| 70 | this._maxAgeSeconds = config.maxAgeSeconds;
|
|---|
| 71 | this._matchOptions = config.matchOptions;
|
|---|
| 72 | this._cacheName = cacheName;
|
|---|
| 73 | this._timestampModel = new CacheTimestampsModel(cacheName);
|
|---|
| 74 | }
|
|---|
| 75 | /**
|
|---|
| 76 | * Expires entries for the given cache and given criteria.
|
|---|
| 77 | */
|
|---|
| 78 | async expireEntries() {
|
|---|
| 79 | if (this._isRunning) {
|
|---|
| 80 | this._rerunRequested = true;
|
|---|
| 81 | return;
|
|---|
| 82 | }
|
|---|
| 83 | this._isRunning = true;
|
|---|
| 84 | const minTimestamp = this._maxAgeSeconds
|
|---|
| 85 | ? Date.now() - this._maxAgeSeconds * 1000
|
|---|
| 86 | : 0;
|
|---|
| 87 | const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
|
|---|
| 88 | // Delete URLs from the cache
|
|---|
| 89 | const cache = await self.caches.open(this._cacheName);
|
|---|
| 90 | for (const url of urlsExpired) {
|
|---|
| 91 | await cache.delete(url, this._matchOptions);
|
|---|
| 92 | }
|
|---|
| 93 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 94 | if (urlsExpired.length > 0) {
|
|---|
| 95 | logger.groupCollapsed(`Expired ${urlsExpired.length} ` +
|
|---|
| 96 | `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +
|
|---|
| 97 | `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +
|
|---|
| 98 | `'${this._cacheName}' cache.`);
|
|---|
| 99 | logger.log(`Expired the following ${urlsExpired.length === 1 ? 'URL' : 'URLs'}:`);
|
|---|
| 100 | urlsExpired.forEach((url) => logger.log(` ${url}`));
|
|---|
| 101 | logger.groupEnd();
|
|---|
| 102 | }
|
|---|
| 103 | else {
|
|---|
| 104 | logger.debug(`Cache expiration ran and found no entries to remove.`);
|
|---|
| 105 | }
|
|---|
| 106 | }
|
|---|
| 107 | this._isRunning = false;
|
|---|
| 108 | if (this._rerunRequested) {
|
|---|
| 109 | this._rerunRequested = false;
|
|---|
| 110 | dontWaitFor(this.expireEntries());
|
|---|
| 111 | }
|
|---|
| 112 | }
|
|---|
| 113 | /**
|
|---|
| 114 | * Update the timestamp for the given URL. This ensures the when
|
|---|
| 115 | * removing entries based on maximum entries, most recently used
|
|---|
| 116 | * is accurate or when expiring, the timestamp is up-to-date.
|
|---|
| 117 | *
|
|---|
| 118 | * @param {string} url
|
|---|
| 119 | */
|
|---|
| 120 | async updateTimestamp(url) {
|
|---|
| 121 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 122 | assert.isType(url, 'string', {
|
|---|
| 123 | moduleName: 'workbox-expiration',
|
|---|
| 124 | className: 'CacheExpiration',
|
|---|
| 125 | funcName: 'updateTimestamp',
|
|---|
| 126 | paramName: 'url',
|
|---|
| 127 | });
|
|---|
| 128 | }
|
|---|
| 129 | await this._timestampModel.setTimestamp(url, Date.now());
|
|---|
| 130 | }
|
|---|
| 131 | /**
|
|---|
| 132 | * Can be used to check if a URL has expired or not before it's used.
|
|---|
| 133 | *
|
|---|
| 134 | * This requires a look up from IndexedDB, so can be slow.
|
|---|
| 135 | *
|
|---|
| 136 | * Note: This method will not remove the cached entry, call
|
|---|
| 137 | * `expireEntries()` to remove indexedDB and Cache entries.
|
|---|
| 138 | *
|
|---|
| 139 | * @param {string} url
|
|---|
| 140 | * @return {boolean}
|
|---|
| 141 | */
|
|---|
| 142 | async isURLExpired(url) {
|
|---|
| 143 | if (!this._maxAgeSeconds) {
|
|---|
| 144 | if (process.env.NODE_ENV !== 'production') {
|
|---|
| 145 | throw new WorkboxError(`expired-test-without-max-age`, {
|
|---|
| 146 | methodName: 'isURLExpired',
|
|---|
| 147 | paramName: 'maxAgeSeconds',
|
|---|
| 148 | });
|
|---|
| 149 | }
|
|---|
| 150 | return false;
|
|---|
| 151 | }
|
|---|
| 152 | else {
|
|---|
| 153 | const timestamp = await this._timestampModel.getTimestamp(url);
|
|---|
| 154 | const expireOlderThan = Date.now() - this._maxAgeSeconds * 1000;
|
|---|
| 155 | return timestamp !== undefined ? timestamp < expireOlderThan : true;
|
|---|
| 156 | }
|
|---|
| 157 | }
|
|---|
| 158 | /**
|
|---|
| 159 | * Removes the IndexedDB object store used to keep track of cache expiration
|
|---|
| 160 | * metadata.
|
|---|
| 161 | */
|
|---|
| 162 | async delete() {
|
|---|
| 163 | // Make sure we don't attempt another rerun if we're called in the middle of
|
|---|
| 164 | // a cache expiration.
|
|---|
| 165 | this._rerunRequested = false;
|
|---|
| 166 | await this._timestampModel.expireEntries(Infinity); // Expires all.
|
|---|
| 167 | }
|
|---|
| 168 | }
|
|---|
| 169 | export { CacheExpiration };
|
|---|