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. // Getting the reader in this way allows us to observe the process of
  121. // downloading the body, instead of just waiting for an opaque promise
  122. // to resolve.
  123. // We first clone the response because calling getReader locks the body
  124. // stream; if we didn't clone it here, we would be unable to get the
  125. // response's arrayBuffer later.
  126. const reader = response.clone().body.getReader();
  127. const contentLengthRaw = response.headers.get('Content-Length');
  128. const contentLength =
  129. contentLengthRaw ? parseInt(contentLengthRaw, 10) : 0;
  130. const start = (controller) => {
  131. const push = async () => {
  132. let readObj;
  133. try {
  134. readObj = await reader.read();
  135. } catch (e) {
  136. // If we abort the request, we'll get an error here. Just ignore
  137. // it since real errors will be reported when we read the buffer
  138. // below.
  139. shaka.log.v1('error reading from stream', e.message);
  140. return;
  141. }
  142. if (!readObj.done) {
  143. loaded += readObj.value.byteLength;
  144. if (streamDataCallback) {
  145. await streamDataCallback(readObj.value);
  146. }
  147. }
  148. const currentTime = Date.now();
  149. const chunkSize = loaded - lastLoaded;
  150. // If the time between last time and this time we got progress event
  151. // is long enough, or if a whole segment is downloaded, call
  152. // progressUpdated().
  153. if ((currentTime - lastTime > 100 && chunkSize >= minBytes) ||
  154. readObj.done) {
  155. const numBytesRemaining =
  156. readObj.done ? 0 : contentLength - loaded;
  157. progressUpdated(currentTime - lastTime, chunkSize,
  158. numBytesRemaining);
  159. lastLoaded = loaded;
  160. lastTime = currentTime;
  161. }
  162. if (readObj.done) {
  163. goog.asserts.assert(!readObj.value,
  164. 'readObj should be unset when "done" is true.');
  165. controller.close();
  166. } else {
  167. controller.enqueue(readObj.value);
  168. push();
  169. }
  170. };
  171. push();
  172. };
  173. // Create a ReadableStream to use the reader. We don't need to use the
  174. // actual stream for anything, though, as we are using the response's
  175. // arrayBuffer method to get the body, so we don't store the
  176. // ReadableStream.
  177. new ReadableStream({start}); // eslint-disable-line no-new
  178. arrayBuffer = await response.arrayBuffer();
  179. }
  180. } catch (error) {
  181. if (abortStatus.canceled) {
  182. throw new shaka.util.Error(
  183. shaka.util.Error.Severity.RECOVERABLE,
  184. shaka.util.Error.Category.NETWORK,
  185. shaka.util.Error.Code.OPERATION_ABORTED,
  186. uri, requestType);
  187. } else if (abortStatus.timedOut) {
  188. throw new shaka.util.Error(
  189. shaka.util.Error.Severity.RECOVERABLE,
  190. shaka.util.Error.Category.NETWORK,
  191. shaka.util.Error.Code.TIMEOUT,
  192. uri, requestType);
  193. } else {
  194. throw new shaka.util.Error(
  195. shaka.util.Error.Severity.RECOVERABLE,
  196. shaka.util.Error.Category.NETWORK,
  197. shaka.util.Error.Code.HTTP_ERROR,
  198. uri, error, requestType);
  199. }
  200. }
  201. const headers = shaka.net.HttpFetchPlugin.headersToGenericObject_(
  202. response.headers);
  203. return shaka.net.HttpPluginUtils.makeResponse(headers, arrayBuffer,
  204. response.status, uri, response.url, request, requestType);
  205. }
  206. /**
  207. * @param {!Headers} headers
  208. * @return {!Object<string, string>}
  209. * @private
  210. */
  211. static headersToGenericObject_(headers) {
  212. const headersObj = {};
  213. headers.forEach((value, key) => {
  214. // Since Edge incorrectly return the header with a leading new line
  215. // character ('\n'), we trim the header here.
  216. headersObj[key.trim()] = value;
  217. });
  218. return headersObj;
  219. }
  220. /**
  221. * Determine if the Fetch API is supported in the browser. Note: this is
  222. * deliberately exposed as a method to allow the client app to use the same
  223. * logic as Shaka when determining support.
  224. * @return {boolean}
  225. * @export
  226. */
  227. static isSupported() {
  228. // On Edge, ReadableStream exists, but attempting to construct it results in
  229. // an error. See https://bit.ly/2zwaFLL
  230. // So this has to check that ReadableStream is present AND usable.
  231. if (window.ReadableStream) {
  232. try {
  233. new ReadableStream({}); // eslint-disable-line no-new
  234. } catch (e) {
  235. return false;
  236. }
  237. } else {
  238. return false;
  239. }
  240. // Old fetch implementations hasn't body and ReadableStream implementation
  241. // See: https://github.com/shaka-project/shaka-player/issues/5088
  242. if (window.Response) {
  243. const response = new Response('');
  244. if (!response.body) {
  245. return false;
  246. }
  247. } else {
  248. return false;
  249. }
  250. return !!(window.fetch && !('polyfill' in window.fetch) &&
  251. window.AbortController);
  252. }
  253. };
  254. /**
  255. * @typedef {{
  256. * canceled: boolean,
  257. * timedOut: boolean
  258. * }}
  259. * @property {boolean} canceled
  260. * Indicates if the request was canceled.
  261. * @property {boolean} timedOut
  262. * Indicates if the request timed out.
  263. */
  264. shaka.net.HttpFetchPlugin.AbortStatus;
  265. /**
  266. * Overridden in unit tests, but compiled out in production.
  267. *
  268. * @const {function(string, !RequestInit)}
  269. * @private
  270. */
  271. shaka.net.HttpFetchPlugin.fetch_ = window.fetch;
  272. /**
  273. * Overridden in unit tests, but compiled out in production.
  274. *
  275. * @const {function(new: AbortController)}
  276. * @private
  277. */
  278. shaka.net.HttpFetchPlugin.AbortController_ = window.AbortController;
  279. /**
  280. * Overridden in unit tests, but compiled out in production.
  281. *
  282. * @const {function(new: ReadableStream, !Object)}
  283. * @private
  284. */
  285. shaka.net.HttpFetchPlugin.ReadableStream_ = window.ReadableStream;
  286. /**
  287. * Overridden in unit tests, but compiled out in production.
  288. *
  289. * @const {function(new: Headers)}
  290. * @private
  291. */
  292. shaka.net.HttpFetchPlugin.Headers_ = window.Headers;
  293. if (shaka.net.HttpFetchPlugin.isSupported()) {
  294. shaka.net.NetworkingEngine.registerScheme(
  295. 'http', shaka.net.HttpFetchPlugin.parse,
  296. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  297. /* progressSupport= */ true);
  298. shaka.net.NetworkingEngine.registerScheme(
  299. 'https', shaka.net.HttpFetchPlugin.parse,
  300. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  301. /* progressSupport= */ true);
  302. shaka.net.NetworkingEngine.registerScheme(
  303. 'blob', shaka.net.HttpFetchPlugin.parse,
  304. shaka.net.NetworkingEngine.PluginPriority.PREFERRED,
  305. /* progressSupport= */ true);
  306. }