Plugin.mjs 9.0 KB

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