ExpirationPlugin.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254
  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 { cacheNames } from 'workbox-core/_private/cacheNames.js';
  9. import { dontWaitFor } from 'workbox-core/_private/dontWaitFor.js';
  10. import { getFriendlyURL } from 'workbox-core/_private/getFriendlyURL.js';
  11. import { logger } from 'workbox-core/_private/logger.js';
  12. import { registerQuotaErrorCallback } from 'workbox-core/registerQuotaErrorCallback.js';
  13. import { WorkboxError } from 'workbox-core/_private/WorkboxError.js';
  14. import { CacheExpiration } from './CacheExpiration.js';
  15. import './_version.js';
  16. /**
  17. * This plugin can be used in a `workbox-strategy` to regularly enforce a
  18. * limit on the age and / or the number of cached requests.
  19. *
  20. * It can only be used with `workbox-strategy` instances that have a
  21. * [custom `cacheName` property set](/web/tools/workbox/guides/configure-workbox#custom_cache_names_in_strategies).
  22. * In other words, it can't be used to expire entries in strategy that uses the
  23. * default runtime cache name.
  24. *
  25. * Whenever a cached response is used or updated, this plugin will look
  26. * at the associated cache and remove any old or extra responses.
  27. *
  28. * When using `maxAgeSeconds`, responses may be used *once* after expiring
  29. * because the expiration clean up will not have occurred until *after* the
  30. * cached response has been used. If the response has a "Date" header, then
  31. * a light weight expiration check is performed and the response will not be
  32. * used immediately.
  33. *
  34. * When using `maxEntries`, the entry least-recently requested will be removed
  35. * from the cache first.
  36. *
  37. * @memberof workbox-expiration
  38. */
  39. class ExpirationPlugin {
  40. /**
  41. * @param {ExpirationPluginOptions} config
  42. * @param {number} [config.maxEntries] The maximum number of entries to cache.
  43. * Entries used the least will be removed as the maximum is reached.
  44. * @param {number} [config.maxAgeSeconds] The maximum age of an entry before
  45. * it's treated as stale and removed.
  46. * @param {Object} [config.matchOptions] The [`CacheQueryOptions`](https://developer.mozilla.org/en-US/docs/Web/API/Cache/delete#Parameters)
  47. * that will be used when calling `delete()` on the cache.
  48. * @param {boolean} [config.purgeOnQuotaError] Whether to opt this cache in to
  49. * automatic deletion if the available storage quota has been exceeded.
  50. */
  51. constructor(config = {}) {
  52. /**
  53. * A "lifecycle" callback that will be triggered automatically by the
  54. * `workbox-strategies` handlers when a `Response` is about to be returned
  55. * from a [Cache](https://developer.mozilla.org/en-US/docs/Web/API/Cache) to
  56. * the handler. It allows the `Response` to be inspected for freshness and
  57. * prevents it from being used if the `Response`'s `Date` header value is
  58. * older than the configured `maxAgeSeconds`.
  59. *
  60. * @param {Object} options
  61. * @param {string} options.cacheName Name of the cache the response is in.
  62. * @param {Response} options.cachedResponse The `Response` object that's been
  63. * read from a cache and whose freshness should be checked.
  64. * @return {Response} Either the `cachedResponse`, if it's
  65. * fresh, or `null` if the `Response` is older than `maxAgeSeconds`.
  66. *
  67. * @private
  68. */
  69. this.cachedResponseWillBeUsed = async ({ event, request, cacheName, cachedResponse, }) => {
  70. if (!cachedResponse) {
  71. return null;
  72. }
  73. const isFresh = this._isResponseDateFresh(cachedResponse);
  74. // Expire entries to ensure that even if the expiration date has
  75. // expired, it'll only be used once.
  76. const cacheExpiration = this._getCacheExpiration(cacheName);
  77. dontWaitFor(cacheExpiration.expireEntries());
  78. // Update the metadata for the request URL to the current timestamp,
  79. // but don't `await` it as we don't want to block the response.
  80. const updateTimestampDone = cacheExpiration.updateTimestamp(request.url);
  81. if (event) {
  82. try {
  83. event.waitUntil(updateTimestampDone);
  84. }
  85. catch (error) {
  86. if (process.env.NODE_ENV !== 'production') {
  87. // The event may not be a fetch event; only log the URL if it is.
  88. if ('request' in event) {
  89. logger.warn(`Unable to ensure service worker stays alive when ` +
  90. `updating cache entry for ` +
  91. `'${getFriendlyURL(event.request.url)}'.`);
  92. }
  93. }
  94. }
  95. }
  96. return isFresh ? cachedResponse : null;
  97. };
  98. /**
  99. * A "lifecycle" callback that will be triggered automatically by the
  100. * `workbox-strategies` handlers when an entry is added to a cache.
  101. *
  102. * @param {Object} options
  103. * @param {string} options.cacheName Name of the cache that was updated.
  104. * @param {string} options.request The Request for the cached entry.
  105. *
  106. * @private
  107. */
  108. this.cacheDidUpdate = async ({ cacheName, request, }) => {
  109. if (process.env.NODE_ENV !== 'production') {
  110. assert.isType(cacheName, 'string', {
  111. moduleName: 'workbox-expiration',
  112. className: 'Plugin',
  113. funcName: 'cacheDidUpdate',
  114. paramName: 'cacheName',
  115. });
  116. assert.isInstance(request, Request, {
  117. moduleName: 'workbox-expiration',
  118. className: 'Plugin',
  119. funcName: 'cacheDidUpdate',
  120. paramName: 'request',
  121. });
  122. }
  123. const cacheExpiration = this._getCacheExpiration(cacheName);
  124. await cacheExpiration.updateTimestamp(request.url);
  125. await cacheExpiration.expireEntries();
  126. };
  127. if (process.env.NODE_ENV !== 'production') {
  128. if (!(config.maxEntries || config.maxAgeSeconds)) {
  129. throw new WorkboxError('max-entries-or-age-required', {
  130. moduleName: 'workbox-expiration',
  131. className: 'Plugin',
  132. funcName: 'constructor',
  133. });
  134. }
  135. if (config.maxEntries) {
  136. assert.isType(config.maxEntries, 'number', {
  137. moduleName: 'workbox-expiration',
  138. className: 'Plugin',
  139. funcName: 'constructor',
  140. paramName: 'config.maxEntries',
  141. });
  142. }
  143. if (config.maxAgeSeconds) {
  144. assert.isType(config.maxAgeSeconds, 'number', {
  145. moduleName: 'workbox-expiration',
  146. className: 'Plugin',
  147. funcName: 'constructor',
  148. paramName: 'config.maxAgeSeconds',
  149. });
  150. }
  151. }
  152. this._config = config;
  153. this._maxAgeSeconds = config.maxAgeSeconds;
  154. this._cacheExpirations = new Map();
  155. if (config.purgeOnQuotaError) {
  156. registerQuotaErrorCallback(() => this.deleteCacheAndMetadata());
  157. }
  158. }
  159. /**
  160. * A simple helper method to return a CacheExpiration instance for a given
  161. * cache name.
  162. *
  163. * @param {string} cacheName
  164. * @return {CacheExpiration}
  165. *
  166. * @private
  167. */
  168. _getCacheExpiration(cacheName) {
  169. if (cacheName === cacheNames.getRuntimeName()) {
  170. throw new WorkboxError('expire-custom-caches-only');
  171. }
  172. let cacheExpiration = this._cacheExpirations.get(cacheName);
  173. if (!cacheExpiration) {
  174. cacheExpiration = new CacheExpiration(cacheName, this._config);
  175. this._cacheExpirations.set(cacheName, cacheExpiration);
  176. }
  177. return cacheExpiration;
  178. }
  179. /**
  180. * @param {Response} cachedResponse
  181. * @return {boolean}
  182. *
  183. * @private
  184. */
  185. _isResponseDateFresh(cachedResponse) {
  186. if (!this._maxAgeSeconds) {
  187. // We aren't expiring by age, so return true, it's fresh
  188. return true;
  189. }
  190. // Check if the 'date' header will suffice a quick expiration check.
  191. // See https://github.com/GoogleChromeLabs/sw-toolbox/issues/164 for
  192. // discussion.
  193. const dateHeaderTimestamp = this._getDateHeaderTimestamp(cachedResponse);
  194. if (dateHeaderTimestamp === null) {
  195. // Unable to parse date, so assume it's fresh.
  196. return true;
  197. }
  198. // If we have a valid headerTime, then our response is fresh iff the
  199. // headerTime plus maxAgeSeconds is greater than the current time.
  200. const now = Date.now();
  201. return dateHeaderTimestamp >= now - this._maxAgeSeconds * 1000;
  202. }
  203. /**
  204. * This method will extract the data header and parse it into a useful
  205. * value.
  206. *
  207. * @param {Response} cachedResponse
  208. * @return {number|null}
  209. *
  210. * @private
  211. */
  212. _getDateHeaderTimestamp(cachedResponse) {
  213. if (!cachedResponse.headers.has('date')) {
  214. return null;
  215. }
  216. const dateHeader = cachedResponse.headers.get('date');
  217. const parsedDate = new Date(dateHeader);
  218. const headerTime = parsedDate.getTime();
  219. // If the Date header was invalid for some reason, parsedDate.getTime()
  220. // will return NaN.
  221. if (isNaN(headerTime)) {
  222. return null;
  223. }
  224. return headerTime;
  225. }
  226. /**
  227. * This is a helper method that performs two operations:
  228. *
  229. * - Deletes *all* the underlying Cache instances associated with this plugin
  230. * instance, by calling caches.delete() on your behalf.
  231. * - Deletes the metadata from IndexedDB used to keep track of expiration
  232. * details for each Cache instance.
  233. *
  234. * When using cache expiration, calling this method is preferable to calling
  235. * `caches.delete()` directly, since this will ensure that the IndexedDB
  236. * metadata is also cleanly removed and open IndexedDB instances are deleted.
  237. *
  238. * Note that if you're *not* using cache expiration for a given cache, calling
  239. * `caches.delete()` and passing in the cache's name should be sufficient.
  240. * There is no Workbox-specific method needed for cleanup in that case.
  241. */
  242. async deleteCacheAndMetadata() {
  243. // Do this one at a time instead of all at once via `Promise.all()` to
  244. // reduce the chance of inconsistency if a promise rejects.
  245. for (const [cacheName, cacheExpiration] of this._cacheExpirations) {
  246. await self.caches.delete(cacheName);
  247. await cacheExpiration.delete();
  248. }
  249. // Reset this._cacheExpirations to its initial state.
  250. this._cacheExpirations = new Map();
  251. }
  252. }
  253. export { ExpirationPlugin };