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