NetworkFirst.mjs 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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 {cacheWrapper} from 'workbox-core/_private/cacheWrapper.mjs';
  10. import {fetchWrapper} from 'workbox-core/_private/fetchWrapper.mjs';
  11. import {getFriendlyURL} from 'workbox-core/_private/getFriendlyURL.mjs';
  12. import {logger} from 'workbox-core/_private/logger.mjs';
  13. import {WorkboxError} from 'workbox-core/_private/WorkboxError.mjs';
  14. import {messages} from './utils/messages.mjs';
  15. import {cacheOkAndOpaquePlugin} from './plugins/cacheOkAndOpaquePlugin.mjs';
  16. import './_version.mjs';
  17. /**
  18. * An implementation of a
  19. * [network first]{@link https://developers.google.com/web/fundamentals/instant-and-offline/offline-cookbook/#network-falling-back-to-cache}
  20. * request strategy.
  21. *
  22. * By default, this strategy will cache responses with a 200 status code as
  23. * well as [opaque responses]{@link https://developers.google.com/web/tools/workbox/guides/handle-third-party-requests}.
  24. * Opaque responses are are cross-origin requests where the response doesn't
  25. * support [CORS]{@link https://enable-cors.org/}.
  26. *
  27. * If the network request fails, and there is no cache match, this will throw
  28. * a `WorkboxError` exception.
  29. *
  30. * @memberof workbox.strategies
  31. */
  32. class NetworkFirst {
  33. /**
  34. * @param {Object} options
  35. * @param {string} options.cacheName Cache name to store and retrieve
  36. * requests. Defaults to cache names provided by
  37. * [workbox-core]{@link workbox.core.cacheNames}.
  38. * @param {Array<Object>} options.plugins [Plugins]{@link https://developers.google.com/web/tools/workbox/guides/using-plugins}
  39. * to use in conjunction with this caching strategy.
  40. * @param {Object} options.fetchOptions Values passed along to the
  41. * [`init`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Parameters)
  42. * of all fetch() requests made by this strategy.
  43. * @param {Object} options.matchOptions [`CacheQueryOptions`](https://w3c.github.io/ServiceWorker/#dictdef-cachequeryoptions)
  44. * @param {number} options.networkTimeoutSeconds If set, any network requests
  45. * that fail to respond within the timeout will fallback to the cache.
  46. *
  47. * This option can be used to combat
  48. * "[lie-fi]{@link https://developers.google.com/web/fundamentals/performance/poor-connectivity/#lie-fi}"
  49. * scenarios.
  50. */
  51. constructor(options = {}) {
  52. this._cacheName = cacheNames.getRuntimeName(options.cacheName);
  53. if (options.plugins) {
  54. let isUsingCacheWillUpdate =
  55. options.plugins.some((plugin) => !!plugin.cacheWillUpdate);
  56. this._plugins = isUsingCacheWillUpdate ?
  57. options.plugins : [cacheOkAndOpaquePlugin, ...options.plugins];
  58. } else {
  59. // No plugins passed in, use the default plugin.
  60. this._plugins = [cacheOkAndOpaquePlugin];
  61. }
  62. this._networkTimeoutSeconds = options.networkTimeoutSeconds;
  63. if (process.env.NODE_ENV !== 'production') {
  64. if (this._networkTimeoutSeconds) {
  65. assert.isType(this._networkTimeoutSeconds, 'number', {
  66. moduleName: 'workbox-strategies',
  67. className: 'NetworkFirst',
  68. funcName: 'constructor',
  69. paramName: 'networkTimeoutSeconds',
  70. });
  71. }
  72. }
  73. this._fetchOptions = options.fetchOptions || null;
  74. this._matchOptions = options.matchOptions || null;
  75. }
  76. /**
  77. * This method will perform a request strategy and follows an API that
  78. * will work with the
  79. * [Workbox Router]{@link workbox.routing.Router}.
  80. *
  81. * @param {Object} options
  82. * @param {Request} options.request The request to run this strategy for.
  83. * @param {Event} [options.event] The event that triggered the request.
  84. * @return {Promise<Response>}
  85. */
  86. async handle({event, request}) {
  87. return this.makeRequest({
  88. event,
  89. request: request || event.request,
  90. });
  91. }
  92. /**
  93. * This method can be used to perform a make a standalone request outside the
  94. * context of the [Workbox Router]{@link workbox.routing.Router}.
  95. *
  96. * See "[Advanced Recipes](https://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests)"
  97. * for more usage information.
  98. *
  99. * @param {Object} options
  100. * @param {Request|string} options.request Either a
  101. * [`Request`]{@link https://developer.mozilla.org/en-US/docs/Web/API/Request}
  102. * object, or a string URL, corresponding to the request to be made.
  103. * @param {FetchEvent} [options.event] If provided, `event.waitUntil()` will
  104. * be called automatically to extend the service worker's lifetime.
  105. * @return {Promise<Response>}
  106. */
  107. async makeRequest({event, request}) {
  108. const logs = [];
  109. if (typeof request === 'string') {
  110. request = new Request(request);
  111. }
  112. if (process.env.NODE_ENV !== 'production') {
  113. assert.isInstance(request, Request, {
  114. moduleName: 'workbox-strategies',
  115. className: 'NetworkFirst',
  116. funcName: 'handle',
  117. paramName: 'makeRequest',
  118. });
  119. }
  120. const promises = [];
  121. let timeoutId;
  122. if (this._networkTimeoutSeconds) {
  123. const {id, promise} = this._getTimeoutPromise({request, event, logs});
  124. timeoutId = id;
  125. promises.push(promise);
  126. }
  127. const networkPromise =
  128. this._getNetworkPromise({timeoutId, request, event, logs});
  129. promises.push(networkPromise);
  130. // Promise.race() will resolve as soon as the first promise resolves.
  131. let response = await Promise.race(promises);
  132. // If Promise.race() resolved with null, it might be due to a network
  133. // timeout + a cache miss. If that were to happen, we'd rather wait until
  134. // the networkPromise resolves instead of returning null.
  135. // Note that it's fine to await an already-resolved promise, so we don't
  136. // have to check to see if it's still "in flight".
  137. if (!response) {
  138. response = await networkPromise;
  139. }
  140. if (process.env.NODE_ENV !== 'production') {
  141. logger.groupCollapsed(
  142. messages.strategyStart('NetworkFirst', request));
  143. for (let log of logs) {
  144. logger.log(log);
  145. }
  146. messages.printFinalResponse(response);
  147. logger.groupEnd();
  148. }
  149. if (!response) {
  150. throw new WorkboxError('no-response', {url: request.url});
  151. }
  152. return response;
  153. }
  154. /**
  155. * @param {Object} options
  156. * @param {Request} options.request
  157. * @param {Array} options.logs A reference to the logs array
  158. * @param {Event} [options.event]
  159. * @return {Promise<Response>}
  160. *
  161. * @private
  162. */
  163. _getTimeoutPromise({request, logs, event}) {
  164. let timeoutId;
  165. const timeoutPromise = new Promise((resolve) => {
  166. const onNetworkTimeout = async () => {
  167. if (process.env.NODE_ENV !== 'production') {
  168. logs.push(`Timing out the network response at ` +
  169. `${this._networkTimeoutSeconds} seconds.`);
  170. }
  171. resolve(await this._respondFromCache({request, event}));
  172. };
  173. timeoutId = setTimeout(
  174. onNetworkTimeout,
  175. this._networkTimeoutSeconds * 1000,
  176. );
  177. });
  178. return {
  179. promise: timeoutPromise,
  180. id: timeoutId,
  181. };
  182. }
  183. /**
  184. * @param {Object} options
  185. * @param {number|undefined} options.timeoutId
  186. * @param {Request} options.request
  187. * @param {Array} options.logs A reference to the logs Array.
  188. * @param {Event} [options.event]
  189. * @return {Promise<Response>}
  190. *
  191. * @private
  192. */
  193. async _getNetworkPromise({timeoutId, request, logs, event}) {
  194. let error;
  195. let response;
  196. try {
  197. response = await fetchWrapper.fetch({
  198. request,
  199. event,
  200. fetchOptions: this._fetchOptions,
  201. plugins: this._plugins,
  202. });
  203. } catch (err) {
  204. error = err;
  205. }
  206. if (timeoutId) {
  207. clearTimeout(timeoutId);
  208. }
  209. if (process.env.NODE_ENV !== 'production') {
  210. if (response) {
  211. logs.push(`Got response from network.`);
  212. } else {
  213. logs.push(`Unable to get a response from the network. Will respond ` +
  214. `with a cached response.`);
  215. }
  216. }
  217. if (error || !response) {
  218. response = await this._respondFromCache({request, event});
  219. if (process.env.NODE_ENV !== 'production') {
  220. if (response) {
  221. logs.push(`Found a cached response in the '${this._cacheName}'` +
  222. ` cache.`);
  223. } else {
  224. logs.push(`No response found in the '${this._cacheName}' cache.`);
  225. }
  226. }
  227. } else {
  228. // Keep the service worker alive while we put the request in the cache
  229. const responseClone = response.clone();
  230. const cachePut = cacheWrapper.put({
  231. cacheName: this._cacheName,
  232. request,
  233. response: responseClone,
  234. event,
  235. plugins: this._plugins,
  236. });
  237. if (event) {
  238. try {
  239. // The event has been responded to so we can keep the SW alive to
  240. // respond to the request
  241. event.waitUntil(cachePut);
  242. } catch (err) {
  243. if (process.env.NODE_ENV !== 'production') {
  244. logger.warn(`Unable to ensure service worker stays alive when ` +
  245. `updating cache for '${getFriendlyURL(request.url)}'.`);
  246. }
  247. }
  248. }
  249. }
  250. return response;
  251. }
  252. /**
  253. * Used if the network timeouts or fails to make the request.
  254. *
  255. * @param {Object} options
  256. * @param {Request} request The request to match in the cache
  257. * @param {Event} [options.event]
  258. * @return {Promise<Object>}
  259. *
  260. * @private
  261. */
  262. _respondFromCache({event, request}) {
  263. return cacheWrapper.match({
  264. cacheName: this._cacheName,
  265. request,
  266. event,
  267. matchOptions: this._matchOptions,
  268. plugins: this._plugins,
  269. });
  270. }
  271. }
  272. export {NetworkFirst};