CacheExpiration.js 6.7 KB

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