CacheExpiration.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168
  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 module: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. */
  32. constructor(cacheName, config = {}) {
  33. this._isRunning = false;
  34. this._rerunRequested = false;
  35. if (process.env.NODE_ENV !== 'production') {
  36. assert.isType(cacheName, 'string', {
  37. moduleName: 'workbox-expiration',
  38. className: 'CacheExpiration',
  39. funcName: 'constructor',
  40. paramName: 'cacheName',
  41. });
  42. if (!(config.maxEntries || config.maxAgeSeconds)) {
  43. throw new WorkboxError('max-entries-or-age-required', {
  44. moduleName: 'workbox-expiration',
  45. className: 'CacheExpiration',
  46. funcName: 'constructor',
  47. });
  48. }
  49. if (config.maxEntries) {
  50. assert.isType(config.maxEntries, 'number', {
  51. moduleName: 'workbox-expiration',
  52. className: 'CacheExpiration',
  53. funcName: 'constructor',
  54. paramName: 'config.maxEntries',
  55. });
  56. // TODO: Assert is positive
  57. }
  58. if (config.maxAgeSeconds) {
  59. assert.isType(config.maxAgeSeconds, 'number', {
  60. moduleName: 'workbox-expiration',
  61. className: 'CacheExpiration',
  62. funcName: 'constructor',
  63. paramName: 'config.maxAgeSeconds',
  64. });
  65. // TODO: Assert is positive
  66. }
  67. }
  68. this._maxEntries = config.maxEntries;
  69. this._maxAgeSeconds = config.maxAgeSeconds;
  70. this._cacheName = cacheName;
  71. this._timestampModel = new CacheTimestampsModel(cacheName);
  72. }
  73. /**
  74. * Expires entries for the given cache and given criteria.
  75. */
  76. async expireEntries() {
  77. if (this._isRunning) {
  78. this._rerunRequested = true;
  79. return;
  80. }
  81. this._isRunning = true;
  82. const minTimestamp = this._maxAgeSeconds ?
  83. Date.now() - (this._maxAgeSeconds * 1000) : 0;
  84. const urlsExpired = await this._timestampModel.expireEntries(minTimestamp, this._maxEntries);
  85. // Delete URLs from the cache
  86. const cache = await self.caches.open(this._cacheName);
  87. for (const url of urlsExpired) {
  88. await cache.delete(url);
  89. }
  90. if (process.env.NODE_ENV !== 'production') {
  91. if (urlsExpired.length > 0) {
  92. logger.groupCollapsed(`Expired ${urlsExpired.length} ` +
  93. `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +
  94. `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +
  95. `'${this._cacheName}' cache.`);
  96. logger.log(`Expired the following ${urlsExpired.length === 1 ?
  97. 'URL' : 'URLs'}:`);
  98. urlsExpired.forEach((url) => logger.log(` ${url}`));
  99. logger.groupEnd();
  100. }
  101. else {
  102. logger.debug(`Cache expiration ran and found no entries to remove.`);
  103. }
  104. }
  105. this._isRunning = false;
  106. if (this._rerunRequested) {
  107. this._rerunRequested = false;
  108. dontWaitFor(this.expireEntries());
  109. }
  110. }
  111. /**
  112. * Update the timestamp for the given URL. This ensures the when
  113. * removing entries based on maximum entries, most recently used
  114. * is accurate or when expiring, the timestamp is up-to-date.
  115. *
  116. * @param {string} url
  117. */
  118. async updateTimestamp(url) {
  119. if (process.env.NODE_ENV !== 'production') {
  120. assert.isType(url, 'string', {
  121. moduleName: 'workbox-expiration',
  122. className: 'CacheExpiration',
  123. funcName: 'updateTimestamp',
  124. paramName: 'url',
  125. });
  126. }
  127. await this._timestampModel.setTimestamp(url, Date.now());
  128. }
  129. /**
  130. * Can be used to check if a URL has expired or not before it's used.
  131. *
  132. * This requires a look up from IndexedDB, so can be slow.
  133. *
  134. * Note: This method will not remove the cached entry, call
  135. * `expireEntries()` to remove indexedDB and Cache entries.
  136. *
  137. * @param {string} url
  138. * @return {boolean}
  139. */
  140. async isURLExpired(url) {
  141. if (!this._maxAgeSeconds) {
  142. if (process.env.NODE_ENV !== 'production') {
  143. throw new WorkboxError(`expired-test-without-max-age`, {
  144. methodName: 'isURLExpired',
  145. paramName: 'maxAgeSeconds',
  146. });
  147. }
  148. return false;
  149. }
  150. else {
  151. const timestamp = await this._timestampModel.getTimestamp(url);
  152. const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000);
  153. return (timestamp < expireOlderThan);
  154. }
  155. }
  156. /**
  157. * Removes the IndexedDB object store used to keep track of cache expiration
  158. * metadata.
  159. */
  160. async delete() {
  161. // Make sure we don't attempt another rerun if we're called in the middle of
  162. // a cache expiration.
  163. this._rerunRequested = false;
  164. await this._timestampModel.expireEntries(Infinity); // Expires all.
  165. }
  166. }
  167. export { CacheExpiration };