CacheExpiration.mjs 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  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 {CacheTimestampsModel} from './models/CacheTimestampsModel.mjs';
  8. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  9. import {assert} from 'workbox-core/_private/assert.mjs';
  10. import {logger} from 'workbox-core/_private/logger.mjs';
  11. import './_version.mjs';
  12. /**
  13. * The `CacheExpiration` class allows you define an expiration and / or
  14. * limit on the number of responses stored in a
  15. * [`Cache`](https://developer.mozilla.org/en-US/docs/Web/API/Cache).
  16. *
  17. * @memberof workbox.expiration
  18. */
  19. class CacheExpiration {
  20. /**
  21. * To construct a new CacheExpiration instance you must provide at least
  22. * one of the `config` properties.
  23. *
  24. * @param {string} cacheName Name of the cache to apply restrictions to.
  25. * @param {Object} config
  26. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  27. * Entries used the least will be removed as the maximum is reached.
  28. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  29. * it's treated as stale and removed.
  30. */
  31. constructor(cacheName, config = {}) {
  32. if (process.env.NODE_ENV !== 'production') {
  33. assert.isType(cacheName, 'string', {
  34. moduleName: 'workbox-expiration',
  35. className: 'CacheExpiration',
  36. funcName: 'constructor',
  37. paramName: 'cacheName',
  38. });
  39. if (!(config.maxEntries || config.maxAgeSeconds)) {
  40. throw new WorkboxError('max-entries-or-age-required', {
  41. moduleName: 'workbox-expiration',
  42. className: 'CacheExpiration',
  43. funcName: 'constructor',
  44. });
  45. }
  46. if (config.maxEntries) {
  47. assert.isType(config.maxEntries, 'number', {
  48. moduleName: 'workbox-expiration',
  49. className: 'CacheExpiration',
  50. funcName: 'constructor',
  51. paramName: 'config.maxEntries',
  52. });
  53. // TODO: Assert is positive
  54. }
  55. if (config.maxAgeSeconds) {
  56. assert.isType(config.maxAgeSeconds, 'number', {
  57. moduleName: 'workbox-expiration',
  58. className: 'CacheExpiration',
  59. funcName: 'constructor',
  60. paramName: 'config.maxAgeSeconds',
  61. });
  62. // TODO: Assert is positive
  63. }
  64. }
  65. this._isRunning = false;
  66. this._rerunRequested = false;
  67. this._maxEntries = config.maxEntries;
  68. this._maxAgeSeconds = config.maxAgeSeconds;
  69. this._cacheName = cacheName;
  70. this._timestampModel = new CacheTimestampsModel(cacheName);
  71. }
  72. /**
  73. * Expires entries for the given cache and given criteria.
  74. */
  75. async expireEntries() {
  76. if (this._isRunning) {
  77. this._rerunRequested = true;
  78. return;
  79. }
  80. this._isRunning = true;
  81. const minTimestamp = this._maxAgeSeconds ?
  82. Date.now() - (this._maxAgeSeconds * 1000) : undefined;
  83. const urlsExpired = await this._timestampModel.expireEntries(
  84. minTimestamp, this._maxEntries);
  85. // Delete URLs from the cache
  86. const cache = await 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(
  93. `Expired ${urlsExpired.length} ` +
  94. `${urlsExpired.length === 1 ? 'entry' : 'entries'} and removed ` +
  95. `${urlsExpired.length === 1 ? 'it' : 'them'} from the ` +
  96. `'${this._cacheName}' cache.`);
  97. logger.log(`Expired the following ${urlsExpired.length === 1 ?
  98. 'URL' : 'URLs'}:`);
  99. urlsExpired.forEach((url) => logger.log(` ${url}`));
  100. logger.groupEnd();
  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. 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 (process.env.NODE_ENV !== 'production') {
  142. if (!this._maxAgeSeconds) {
  143. throw new WorkboxError(`expired-test-without-max-age`, {
  144. methodName: 'isURLExpired',
  145. paramName: 'maxAgeSeconds',
  146. });
  147. }
  148. }
  149. const timestamp = await this._timestampModel.getTimestamp(url);
  150. const expireOlderThan = Date.now() - (this._maxAgeSeconds * 1000);
  151. return (timestamp < expireOlderThan);
  152. }
  153. /**
  154. * Removes the IndexedDB object store used to keep track of cache expiration
  155. * metadata.
  156. */
  157. async delete() {
  158. // Make sure we don't attempt another rerun if we're called in the middle of
  159. // a cache expiration.
  160. this._rerunRequested = false;
  161. await this._timestampModel.expireEntries(Infinity); // Expires all.
  162. }
  163. }
  164. export {CacheExpiration};