ExpirationPlugin.js 10 KB

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