Source: lib/net/http_fetch_plugin.js

  1. /*! @license
  2. * Shaka Player
  3. * Copyright 2016 Google LLC
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. goog.provide('shaka.net.HttpFetchPlugin');
  7. goog.require('goog.asserts');
  8. goog.require('shaka.log');
  9. goog.require('shaka.net.HttpPluginUtils');
  10. goog.require('shaka.net.NetworkingEngine');
  11. goog.require('shaka.util.AbortableOperation');
  12. goog.require('shaka.util.Error');
  13. goog.require('shaka.util.MapUtils');
  14. goog.require('shaka.util.Timer');
  15. /**
  16. * @summary A networking plugin to handle http and https URIs via the Fetch API.
  17. * @export
  18. */
  19. shaka.net.HttpFetchPlugin = class {
  20. /**
  21. * @param {string} uri
  22. * @param {shaka.extern.Request} request
  23. * @param {shaka.net.NetworkingEngine.RequestType} requestType
  24. * @param {shaka.extern.ProgressUpdated} progressUpdated Called when a
  25. * progress event happened.
  26. * @param {shaka.extern.HeadersReceived} headersReceived Called when the
  27. * headers for the download are received, but before the body is.
  28. * @param {shaka.extern.SchemePluginConfig} config
  29. * @return {!shaka.extern.IAbortableOperation.<shaka.extern.Response>}
  30. * @export
  31. */
  32. static parse(uri, request, requestType, progressUpdated, headersReceived,
  33. config) {
  34. const headers = new shaka.net.HttpFetchPlugin.Headers_();
  35. shaka.util.MapUtils.asMap(request.headers).forEach((value, key) => {
  36. headers.append(key, value);
  37. });
  38. const controller = new shaka.net.HttpFetchPlugin.AbortController_();
  39. /** @type {!RequestInit} */
  40. const init = {
  41. // Edge does not treat null as undefined for body; https://bit.ly/2luyE6x
  42. body: request.body || undefined,
  43. headers: headers,
  44. method: request.method,
  45. signal: controller.signal,
  46. credentials: request.allowCrossSiteCredentials ? 'include' : undefined,
  47. };
  48. /** @type {shaka.net.HttpFetchPlugin.AbortStatus} */
  49. const abortStatus = {
  50. canceled: false,
  51. timedOut: false,
  52. };
  53. const minBytes = config.minBytesForProgressEvents || 0;
  54. const pendingRequest = shaka.net.HttpFetchPlugin.request_(
  55. uri, request, requestType, init, abortStatus, progressUpdated,
  56. headersReceived, request.streamDataCallback, minBytes);
  57. /** @type {!shaka.util.AbortableOperation} */
  58. const op = new shaka.util.AbortableOperation(pendingRequest, () => {
  59. abortStatus.canceled = true;
  60. controller.abort();
  61. return Promise.resolve();
  62. });
  63. // The fetch API does not timeout natively, so do a timeout manually using
  64. // the AbortController.
  65. const timeoutMs = request.retryParameters.timeout;
  66. if (timeoutMs) {
  67. const timer = new shaka.util.Timer(() => {
  68. abortStatus.timedOut = true;
  69. controller.abort();
  70. });
  71. timer.tickAfter(timeoutMs / 1000);
  72. // To avoid calling |abort| on the network request after it finished, we
  73. // will stop the timer when the requests resolves/rejects.
  74. op.finally(() => {
  75. timer.stop();
  76. });
  77. }
  78. return op;
  79. }
  80. /**
  81. * @param {string} uri
  82. * @param {shaka.extern.Request} request
  83. * @param {shaka.net.NetworkingEngine.RequestType} requestType
  84. * @param {!RequestInit} init
  85. * @param {shaka.net.HttpFetchPlugin.AbortStatus} abortStatus
  86. * @param {shaka.extern.ProgressUpdated} progressUpdated
  87. * @param {shaka.extern.HeadersReceived} headersReceived
  88. * @param {?function(BufferSource):!Promise} streamDataCallback
  89. * @param {number} minBytes
  90. * @return {!Promise<!shaka.extern.Response>}
  91. * @private
  92. */
  93. static async request_(uri, request, requestType, init, abortStatus,
  94. progressUpdated, headersReceived, streamDataCallback, minBytes) {
  95. const fetch = shaka.net.HttpFetchPlugin.fetch_;
  96. const ReadableStream = shaka.net.HttpFetchPlugin.ReadableStream_;
  97. let response;
  98. let arrayBuffer = new ArrayBuffer(0);
  99. let loaded = 0;
  100. let lastLoaded = 0;
  101. // Last time stamp when we got a progress event.
  102. let lastTime = Date.now();
  103. try {
  104. // The promise returned by fetch resolves as soon as the HTTP response
  105. // headers are available. The download itself isn't done until the promise
  106. // for retrieving the data (arrayBuffer, blob, etc) has resolved.
  107. response = await fetch(uri, init);
  108. // At this point in the process, we have the headers of the response, but
  109. // not the body yet.
  110. headersReceived(shaka.net.HttpFetchPlugin.headersToGenericObject_(
  111. response.headers));
  112. // In new versions of Chromium, HEAD requests now have a response body
  113. // that is null.
  114. // So just don't try to download the body at all, if it's a HEAD request,
  115. // to avoid null reference errors.
  116. // See: https://crbug.com/1297060
  117. if (init.method != 'HEAD') {
  118. goog.asserts.assert(response.body,
  119. 'non-HEAD responses should have a body');
  120. const contentLengthRaw = response.headers.get('Content-Length');
  121. const contentLength =
  122. contentLengthRaw ? parseInt(contentLengthRaw, 10) : 0;
  123. // Fetch returning a ReadableStream response body is not currently
  124. // supported by all browsers.
  125. // Browser compatibility:
  126. // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API
  127. // If it is not supported, returning the whole segment when
  128. // it's ready (as xhr)
  129. if (!response.body) {
  130. arrayBuffer = await response.arrayBuffer();
  131. const currentTime = Date.now();
  132. // If the time between last time and this time we got progress event
  133. // is long enough, or if a whole segment is downloaded, call
  134. // progressUpdated().
  135. progressUpdated(currentTime - lastTime, arrayBuffer.byteLength, 0);
  136. } else {
  137. // Getting the reader in this way allows us to observe the process of
  138. // downloading the body, instead of just waiting for an opaque
  139. // promise to resolve.
  140. // We first clone the response because calling getReader lock the body
  141. // stream; if we didn't clone it here, we would be unable to get the
  142. // response's arrayBuffer later.
  143. const reader = response.clone().body.getReader();
  144. const start = (controller) => {
  145. const push = async () => {
  146. let readObj;
  147. try {
  148. readObj = await reader.read();
  149. } catch (e) {
  150. // If we abort the request, we'll get an error here.
  151. // Just ignore it
  152. // since real errors will be reported when we read
  153. // the buffer below.
  154. shaka.log.v1('error reading from stream', e.message);
  155. return;
  156. }
  157. if (!readObj.done) {
  158. loaded += readObj.value.byteLength;
  159. if (streamDataCallback) {
  160. await streamDataCallback(readObj.value);
  161. }
  162. }
  163. const currentTime = Date.now();
  164. const chunkSize = loaded - lastLoaded;
  165. // If the time between last time and this time we got
  166. // progress event is long enough, or if a whole segment
  167. // is downloaded, call progressUpdated().
  168. if ((currentTime - lastTime > 100 && chunkSize >= minBytes) ||
  169. readObj.done) {
  170. const numBytesRemaining =
  171. readObj.done ? 0 : contentLength - loaded;
  172. progressUpdated(currentTime - lastTime, chunkSize,
  173. numBytesRemaining);
  174. lastLoaded = loaded;
  175. lastTime = currentTime;
  176. }
  177. if (readObj.done) {
  178. goog.asserts.assert(!readObj.value,
  179. 'readObj should be unset when "done" is true.');
  180. controller.close();
  181. } else {
  182. controller.enqueue(readObj.value);
  183. push();
  184. }
  185. };
  186. push();
  187. };
  188. // Create a ReadableStream to use the reader. We don't need to use the
  189. // actual stream for anything, though, as we are using the response's
  190. // arrayBuffer method to get the body, so we don't store the
  191. // ReadableStream.
  192. new ReadableStream({start}); // eslint-disable-line no-new
  193. arrayBuffer = await response.arrayBuffer();
  194. }
  195. }
  196. } catch (error) {
  197. if (abortStatus.canceled) {
  198. throw new shaka.util.Error(
  199. shaka.util.Error.Severity.RECOVERABLE,
  200. shaka.util.Error.Category.NETWORK,
  201. shaka.util.Error.Code.OPERATION_ABORTED,
  202. uri, requestType);
  203. } else if (abortStatus.timedOut) {
  204. throw new shaka.util.Error(
  205. shaka.util.Error.Severity.RECOVERABLE,
  206. shaka.util.Error.Category.NETWORK,
  207. shaka.util.Error.Code.TIMEOUT,
  208. uri, requestType);
  209. } else {
  210. throw new shaka.util.Error(
  211. shaka.util.Error.Severity.RECOVERABLE,
  212. shaka.util.Error.Category.NETWORK,
  213. shaka.util.Error.Code.HTTP_ERROR,
  214. uri, error, requestType);
  215. }
  216. }
  217. const headers = shaka.net.HttpFetchPlugin.headersToGenericObject_(
  218. response.headers);
  219. return shaka.net.HttpPluginUtils.makeResponse(headers, arrayBuffer,
  220. response.status, uri, response.url, request, requestType);
  221. }
  222. /**
  223. * @param {!Headers} headers
  224. * @return {!Object<string, string>}
  225. * @private
  226. */
  227. static headersToGenericObject_(headers) {
  228. const headersObj = {};
  229. headers.forEach((value, key) => {
  230. // Since Edge incorrectly return the header with a leading new line
  231. // character ('\n'), we trim the header here.
  232. headersObj[key.trim()] = value;
  233. });
  234. return headersObj;
  235. }
  236. /**
  237. * Determine if the Fetch API is supported in the browser. Note: this is
  238. * deliberately exposed as a method to allow the client app to use the same
  239. * logic as Shaka when determining support.
  240. * @return {boolean}
  241. * @export
  242. */
  243. static isSupported() {
  244. // On Edge, ReadableStream exists, but attempting to construct it results in
  245. // an error. See https://bit.ly/2zwaFLL
  246. // So this has to check that ReadableStream is present AND usable.
  247. if (window.ReadableStream) {
  248. try {
  249. new ReadableStream({}); // eslint-disable-line no-new
  250. } catch (e) {
  251. return false;
  252. }
  253. } else {
  254. return false;
  255. }
  256. // Old fetch implementations hasn't body and ReadableStream implementation
  257. // See: https://github.com/shaka-project/shaka-player/issues/5088
  258. if (window.Response) {
  259. const response = new Response('');
  260. if (!response.body) {
  261. return false;
  262. }
  263. } else {
  264. return false;
  265. }
  266. return !!(window.fetch && !('polyfill' in window.fetch) &&
  267. window.AbortController);
  268. }
  269. };
  270. /**
  271. * @typedef {{
  272. * canceled: boolean,
  273. * timedOut: boolean
  274. * }}
  275. * @property {boolean} canceled
  276. * Indicates if the request was canceled.
  277. * @property {boolean} timedOut
  278. * Indicates if the request timed out.
  279. */
  280. shaka.net.HttpFetchPlugin.AbortStatus;
  281. /**
  282. * Overridden in unit tests, but compiled out in production.
  283. *
  284. * @const {function(string, !RequestInit)}
  285. * @private
  286. */
  287. shaka.net.HttpFetchPlugin.fetch_ = window.fetch;
  288. /**
  289. * Overridden in unit tests, but compiled out in production.
  290. *
  291. * @const {function(new: AbortController)}
  292. * @private
  293. */
  294. shaka.net.HttpFetchPlugin.AbortController_ = window.AbortController;
  295. /**
  296. * Overridden in unit tests, but compiled out in production.
  297. *
  298. * @const {function(new: ReadableStream, !Object)}
  299. * @private
  300. */
  301. shaka.net.HttpFetchPlugin.ReadableStream_ = window.ReadableStream;
  302. /**
  303. * Overridden in unit tests, but compiled out in production.
  304. *
  305. * @const {function(new: Headers)}
  306. * @private
  307. */
  308. shaka.net.HttpFetchPlugin.Headers_ = window.Headers;
  309. if (shaka.net.HttpFetchPlugin.isSupported()) {
  310. shaka.net.NetworkingEngine.registerScheme(
  311. 'http', shaka.net.HttpFetchPlugin.parse,
  312. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  313. /* progressSupport= */ true);
  314. shaka.net.NetworkingEngine.registerScheme(
  315. 'https', shaka.net.HttpFetchPlugin.parse,
  316. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  317. /* progressSupport= */ true);
  318. shaka.net.NetworkingEngine.registerScheme(
  319. 'blob', shaka.net.HttpFetchPlugin.parse,
  320. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  321. /* progressSupport= */ true);
  322. }