You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

282 line
8.2 KiB

  1. /*
  2. Copyright 2017 Google Inc.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. https://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. import CacheTimestampsModel from './models/CacheTimestampsModel.mjs';
  14. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  15. import {assert} from 'workbox-core/_private/assert.mjs';
  16. import {logger} from 'workbox-core/_private/logger.mjs';
  17. import './_version.mjs';
  18. /**
  19. * The `CacheExpiration` class allows you define an expiration and / or
  20. * limit on the number of responses stored in a
  21. * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
  22. *
  23. * @memberof workbox.expiration
  24. */
  25. class CacheExpiration {
  26. /**
  27. * To construct a new CacheExpiration instance you must provide at least
  28. * one of the `config` properties.
  29. *
  30. * @param {string} cacheName Name of the cache to apply restrictions to.
  31. * @param {Object} config
  32. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  33. * Entries used the least will be removed as the maximum is reached.
  34. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  35. * it's treated as stale and removed.
  36. */
  37. constructor(cacheName, config = {}) {
  38. if (process.env.NODE_ENV !== 'production') {
  39. assert.isType(cacheName, 'string', {
  40. moduleName: 'workbox-cache-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-cache-expiration',
  48. className: 'CacheExpiration',
  49. funcName: 'constructor',
  50. });
  51. }
  52. if (config.maxEntries) {
  53. assert.isType(config.maxEntries, 'number', {
  54. moduleName: 'workbox-cache-expiration',
  55. className: 'CacheExpiration',
  56. funcName: 'constructor',
  57. paramName: 'config.maxEntries',
  58. });
  59. // TODO: Assert is positive
  60. }
  61. if (config.maxAgeSeconds) {
  62. assert.isType(config.maxAgeSeconds, 'number', {
  63. moduleName: 'workbox-cache-expiration',
  64. className: 'CacheExpiration',
  65. funcName: 'constructor',
  66. paramName: 'config.maxAgeSeconds',
  67. });
  68. // TODO: Assert is positive
  69. }
  70. }
  71. this._isRunning = false;
  72. this._rerunRequested = false;
  73. this._maxEntries = config.maxEntries;
  74. this._maxAgeSeconds = config.maxAgeSeconds;
  75. this._cacheName = cacheName;
  76. this._timestampModel = new CacheTimestampsModel(cacheName);
  77. }
  78. /**
  79. * Expires entries for the given cache and given criteria.
  80. */
  81. async expireEntries() {
  82. if (this._isRunning) {
  83. this._rerunRequested = true;
  84. return;
  85. }
  86. this._isRunning = true;
  87. const now = Date.now();
  88. // First, expire old entries, if maxAgeSeconds is set.
  89. const oldEntries = await this._findOldEntries(now);
  90. // Once that's done, check for the maximum size.
  91. const extraEntries = await this._findExtraEntries();
  92. // Use a Set to remove any duplicates following the concatenation, then
  93. // convert back into an array.
  94. const allUrls = [...new Set(oldEntries.concat(extraEntries))];
  95. await Promise.all([
  96. this._deleteFromCache(allUrls),
  97. this._deleteFromIDB(allUrls),
  98. ]);
  99. if (process.env.NODE_ENV !== 'production') {
  100. // TODO: break apart entries deleted due to expiration vs size restraints
  101. if (allUrls.length > 0) {
  102. logger.groupCollapsed(
  103. `Expired ${allUrls.length} ` +
  104. `${allUrls.length === 1 ? 'entry' : 'entries'} and removed ` +
  105. `${allUrls.length === 1 ? 'it' : 'them'} from the ` +
  106. `'${this._cacheName}' cache.`);
  107. logger.log(
  108. `Expired the following ${allUrls.length === 1 ? 'URL' : 'URLs'}:`);
  109. allUrls.forEach((url) => logger.log(` ${url}`));
  110. logger.groupEnd();
  111. } else {
  112. logger.debug(`Cache expiration ran and found no entries to remove.`);
  113. }
  114. }
  115. this._isRunning = false;
  116. if (this._rerunRequested) {
  117. this._rerunRequested = false;
  118. this.expireEntries();
  119. }
  120. }
  121. /**
  122. * Expires entries based on the maximum age.
  123. *
  124. * @param {number} expireFromTimestamp A timestamp.
  125. * @return {Promise<Array<string>>} A list of the URLs that were expired.
  126. *
  127. * @private
  128. */
  129. async _findOldEntries(expireFromTimestamp) {
  130. if (process.env.NODE_ENV !== 'production') {
  131. assert.isType(expireFromTimestamp, 'number', {
  132. moduleName: 'workbox-cache-expiration',
  133. className: 'CacheExpiration',
  134. funcName: '_findOldEntries',
  135. paramName: 'expireFromTimestamp',
  136. });
  137. }
  138. if (!this._maxAgeSeconds) {
  139. return [];
  140. }
  141. const expireOlderThan = expireFromTimestamp - (this._maxAgeSeconds * 1000);
  142. const timestamps = await this._timestampModel.getAllTimestamps();
  143. const expiredUrls = [];
  144. timestamps.forEach((timestampDetails) => {
  145. if (timestampDetails.timestamp < expireOlderThan) {
  146. expiredUrls.push(timestampDetails.url);
  147. }
  148. });
  149. return expiredUrls;
  150. }
  151. /**
  152. * @return {Promise<Array>}
  153. *
  154. * @private
  155. */
  156. async _findExtraEntries() {
  157. const extraUrls = [];
  158. if (!this._maxEntries) {
  159. return [];
  160. }
  161. const timestamps = await this._timestampModel.getAllTimestamps();
  162. while (timestamps.length > this._maxEntries) {
  163. const lastUsed = timestamps.shift();
  164. extraUrls.push(lastUsed.url);
  165. }
  166. return extraUrls;
  167. }
  168. /**
  169. * @param {Array<string>} urls Array of URLs to delete from cache.
  170. *
  171. * @private
  172. */
  173. async _deleteFromCache(urls) {
  174. const cache = await caches.open(this._cacheName);
  175. for (const url of urls) {
  176. await cache.delete(url);
  177. }
  178. }
  179. /**
  180. * @param {Array<string>} urls Array of URLs to delete from IDB
  181. *
  182. * @private
  183. */
  184. async _deleteFromIDB(urls) {
  185. for (const url of urls) {
  186. await this._timestampModel.deleteUrl(url);
  187. }
  188. }
  189. /**
  190. * Update the timestamp for the given URL. This ensures the when
  191. * removing entries based on maximum entries, most recently used
  192. * is accurate or when expiring, the timestamp is up-to-date.
  193. *
  194. * @param {string} url
  195. */
  196. async updateTimestamp(url) {
  197. if (process.env.NODE_ENV !== 'production') {
  198. assert.isType(url, 'string', {
  199. moduleName: 'workbox-cache-expiration',
  200. className: 'CacheExpiration',
  201. funcName: 'updateTimestamp',
  202. paramName: 'url',
  203. });
  204. }
  205. const urlObject = new URL(url, location);
  206. urlObject.hash = '';
  207. await this._timestampModel.setTimestamp(urlObject.href, Date.now());
  208. }
  209. /**
  210. * Can be used to check if a URL has expired or not before it's used.
  211. *
  212. * This requires a look up from IndexedDB, so can be slow.
  213. *
  214. * Note: This method will not remove the cached entry, call
  215. * `expireEntries()` to remove indexedDB and Cache entries.
  216. *
  217. * @param {string} url
  218. * @return {boolean}
  219. */
  220. async isURLExpired(url) {
  221. if (!this._maxAgeSeconds) {
  222. throw new WorkboxError(`expired-test-without-max-age`, {
  223. methodName: 'isURLExpired',
  224. paramName: 'maxAgeSeconds',
  225. });
  226. }
  227. const urlObject = new URL(url, location);
  228. urlObject.hash = '';
  229. const timestamp = await this._timestampModel.getTimestamp(urlObject.href);
  230. const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000);
  231. return (timestamp < expireOlderThan);
  232. }
  233. /**
  234. * Removes the IndexedDB object store used to keep track of cache expiration
  235. * metadata.
  236. */
  237. async delete() {
  238. // Make sure we don't attempt another rerun if we're called in the middle of
  239. // a cache expiration.
  240. this._rerunRequested = false;
  241. await this._timestampModel.delete();
  242. }
  243. }
  244. export {CacheExpiration};