AbstractOperations.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023, Matthew Olsson <mattco@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <LibJS/Runtime/PromiseCapability.h>
  8. #include <LibJS/Runtime/PromiseConstructor.h>
  9. #include <LibWeb/Bindings/ExceptionOrUtils.h>
  10. #include <LibWeb/Streams/AbstractOperations.h>
  11. #include <LibWeb/Streams/ReadableStream.h>
  12. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  13. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  14. #include <LibWeb/Streams/ReadableStreamGenericReader.h>
  15. #include <LibWeb/Streams/UnderlyingSource.h>
  16. #include <LibWeb/WebIDL/AbstractOperations.h>
  17. #include <LibWeb/WebIDL/ExceptionOr.h>
  18. #include <LibWeb/WebIDL/Promise.h>
  19. namespace Web::Streams {
  20. // https://streams.spec.whatwg.org/#acquire-readable-stream-reader
  21. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStreamDefaultReader>> acquire_readable_stream_default_reader(ReadableStream& stream)
  22. {
  23. auto& realm = stream.realm();
  24. // 1. Let reader be a new ReadableStreamDefaultReader.
  25. auto reader = TRY(realm.heap().allocate<ReadableStreamDefaultReader>(realm, realm));
  26. // 2. Perform ? SetUpReadableStreamDefaultReader(reader, stream).
  27. TRY(set_up_readable_stream_default_reader(reader, stream));
  28. // 3. Return reader.
  29. return reader;
  30. }
  31. // https://streams.spec.whatwg.org/#is-readable-stream-locked
  32. bool is_readable_stream_locked(ReadableStream const& stream)
  33. {
  34. // 1. If stream.[[reader]] is undefined, return false.
  35. if (!stream.reader())
  36. return false;
  37. // 2. Return true.
  38. return true;
  39. }
  40. // https://streams.spec.whatwg.org/#readable-stream-cancel
  41. WebIDL::ExceptionOr<JS::NonnullGCPtr<WebIDL::Promise>> readable_stream_cancel(ReadableStream& stream, JS::Value reason)
  42. {
  43. auto& realm = stream.realm();
  44. // 1. Set stream.[[disturbed]] to true.
  45. stream.set_disturbed(true);
  46. // 2. If stream.[[state]] is "closed", return a promise resolved with undefined.
  47. if (stream.is_closed())
  48. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  49. // 3. If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
  50. if (stream.is_errored())
  51. return WebIDL::create_rejected_promise(realm, stream.stored_error());
  52. // 4. Perform ! ReadableStreamClose(stream).
  53. readable_stream_close(stream);
  54. // 5. Let reader be stream.[[reader]].
  55. auto reader = stream.reader();
  56. // FIXME:
  57. // 6. If reader is not undefined and reader implements ReadableStreamBYOBReader,
  58. // 1. Let readIntoRequests be reader.[[readIntoRequests]].
  59. // 2. Set reader.[[readIntoRequests]] to an empty list.
  60. // 3. For each readIntoRequest of readIntoRequests,
  61. // 1. Perform readIntoRequest’s close steps, given undefined.
  62. (void)reader;
  63. // 7. Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
  64. auto source_cancel_promise = MUST(stream.controller()->cancel_steps(reason));
  65. // 8. Return the result of reacting to sourceCancelPromise with a fulfillment step that returns undefined.
  66. auto react_result = WebIDL::react_to_promise(*source_cancel_promise,
  67. [](auto const&) -> WebIDL::ExceptionOr<JS::Value> { return JS::js_undefined(); },
  68. {});
  69. return WebIDL::create_resolved_promise(realm, react_result);
  70. }
  71. // https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request
  72. void readable_stream_fulfill_read_request(ReadableStream& stream, JS::Value chunk, bool done)
  73. {
  74. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  75. VERIFY(readable_stream_has_default_reader(stream));
  76. // 2. Let reader be stream.[[reader]].
  77. auto& reader = *stream.reader();
  78. // 3. Assert: reader.[[readRequests]] is not empty.
  79. VERIFY(!reader.read_requests().is_empty());
  80. // 4. Let readRequest be reader.[[readRequests]][0].
  81. // 5. Remove readRequest from reader.[[readRequests]].
  82. auto read_request = reader.read_requests().take_first();
  83. // 6. If done is true, perform readRequest’s close steps.
  84. if (done) {
  85. read_request->on_close();
  86. }
  87. // 7. Otherwise, perform readRequest’s chunk steps, given chunk.
  88. else {
  89. read_request->on_chunk(chunk);
  90. }
  91. }
  92. // https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests
  93. size_t readable_stream_get_num_read_requests(ReadableStream& stream)
  94. {
  95. // 1. Assert: ! ReadableStreamHasDefaultReader(stream) is true.
  96. VERIFY(readable_stream_has_default_reader(stream));
  97. // 2. Return stream.[[reader]].[[readRequests]]'s size.
  98. return stream.reader()->read_requests().size();
  99. }
  100. // https://streams.spec.whatwg.org/#readable-stream-has-default-reader
  101. bool readable_stream_has_default_reader(ReadableStream& stream)
  102. {
  103. // 1. Let reader be stream.[[reader]].
  104. auto reader = stream.reader();
  105. // 2. If reader is undefined, return false.
  106. if (!reader)
  107. return false;
  108. // 3. If reader implements ReadableStreamDefaultReader, return true.
  109. if (reader->is_default_reader())
  110. return true;
  111. // 4. Return false.
  112. return false;
  113. }
  114. // https://streams.spec.whatwg.org/#readable-stream-close
  115. void readable_stream_close(ReadableStream& stream)
  116. {
  117. auto& realm = stream.realm();
  118. // 1. Assert: stream.[[state]] is "readable".
  119. VERIFY(stream.is_readable());
  120. // 2. Set stream.[[state]] to "closed".
  121. stream.set_stream_state(ReadableStream::State::Closed);
  122. // 3. Let reader be stream.[[reader]].
  123. auto reader = stream.reader();
  124. // 4. If reader is undefined, return.
  125. if (!reader)
  126. return;
  127. // 5. Resolve reader.[[closedPromise]] with undefined.
  128. WebIDL::resolve_promise(realm, *reader->closed_promise_capability());
  129. // 6. If reader implements ReadableStreamDefaultReader,
  130. if (reader->is_default_reader()) {
  131. // 1. Let readRequests be reader.[[readRequests]].
  132. // 2. Set reader.[[readRequests]] to an empty list.
  133. auto read_requests = move(reader->read_requests());
  134. // 3. For each readRequest of readRequests,
  135. for (auto& read_request : read_requests) {
  136. // 1. Perform readRequest’s close steps.
  137. read_request->on_close();
  138. }
  139. }
  140. }
  141. // https://streams.spec.whatwg.org/#readable-stream-error
  142. void readable_stream_error(ReadableStream& stream, JS::Value error)
  143. {
  144. auto& realm = stream.realm();
  145. // 1. Assert: stream.[[state]] is "readable".
  146. VERIFY(stream.is_readable());
  147. // 2. Set stream.[[state]] to "errored".
  148. stream.set_stream_state(ReadableStream::State::Errored);
  149. // 3. Set stream.[[storedError]] to e.
  150. stream.set_stored_error(error);
  151. // 4. Let reader be stream.[[reader]].
  152. auto reader = stream.reader();
  153. // 5. If reader is undefined, return.
  154. if (!reader)
  155. return;
  156. // 6. Reject reader.[[closedPromise]] with e.
  157. WebIDL::reject_promise(realm, *reader->closed_promise_capability(), error);
  158. // 7. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  159. WebIDL::mark_promise_as_handled(*reader->closed_promise_capability());
  160. // 8. If reader implements ReadableStreamDefaultReader,
  161. if (reader->is_default_reader()) {
  162. // 1. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  163. readable_stream_default_reader_error_read_requests(*reader, error);
  164. }
  165. // 9. Otherwise,
  166. else {
  167. // 1. Assert: reader implements ReadableStreamBYOBReader.
  168. // 2. Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
  169. // FIXME: Handle BYOBReader
  170. TODO();
  171. }
  172. }
  173. // https://streams.spec.whatwg.org/#readable-stream-add-read-request
  174. void readable_stream_add_read_request(ReadableStream& stream, ReadRequest const& read_request)
  175. {
  176. // FIXME: Check implementation type
  177. // 1. Assert: stream.[[reader]] implements ReadableStreamDefaultReader.
  178. VERIFY(stream.reader());
  179. // 2. Assert: stream.[[state]] is "readable".
  180. VERIFY(stream.is_readable());
  181. // 3. Append readRequest to stream.[[reader]].[[readRequests]].
  182. stream.reader()->read_requests().append(read_request);
  183. }
  184. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-cancel
  185. JS::NonnullGCPtr<WebIDL::Promise> readable_stream_reader_generic_cancel(ReadableStreamGenericReaderMixin& reader, JS::Value reason)
  186. {
  187. // 1. Let stream be reader.[[stream]]
  188. auto stream = reader.stream();
  189. // 2. Assert: stream is not undefined
  190. VERIFY(stream);
  191. // 3. Return ! ReadableStreamCancel(stream, reason)
  192. return MUST(readable_stream_cancel(*stream, reason));
  193. }
  194. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-initialize
  195. void readable_stream_reader_generic_initialize(ReadableStreamGenericReaderMixin& reader, ReadableStream& stream)
  196. {
  197. auto& realm = stream.realm();
  198. // 1. Set reader.[[stream]] to stream.
  199. reader.set_stream(stream);
  200. // 2. Set stream.[[reader]] to reader.
  201. if (reader.is_default_reader()) {
  202. stream.set_reader(static_cast<ReadableStreamDefaultReader&>(reader));
  203. } else {
  204. // FIXME: Handle other descendents of ReadableStreamGenericReaderMixin (i.e. BYOBReader)
  205. TODO();
  206. }
  207. // 3. If stream.[[state]] is "readable",
  208. if (stream.is_readable()) {
  209. // 1. Set reader.[[closedPromise]] to a new promise.
  210. reader.set_closed_promise_capability(WebIDL::create_promise(realm));
  211. }
  212. // 4. Otherwise, if stream.[[state]] is "closed",
  213. else if (stream.is_closed()) {
  214. // 1. Set reader.[[closedPromise]] to a promise resolved with undefined.
  215. reader.set_closed_promise_capability(WebIDL::create_resolved_promise(realm, JS::js_undefined()));
  216. }
  217. // 5. Otherwise,
  218. else {
  219. // 1. Assert: stream.[[state]] is "errored".
  220. VERIFY(stream.is_errored());
  221. // 2. Set reader.[[closedPromise]] to a promise rejected with stream.[[storedError]].
  222. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(realm, stream.stored_error()));
  223. // 3. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  224. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  225. }
  226. }
  227. // https://streams.spec.whatwg.org/#readable-stream-reader-generic-release
  228. WebIDL::ExceptionOr<void> readable_stream_reader_generic_release(ReadableStreamGenericReaderMixin& reader)
  229. {
  230. // 1. Let stream be reader.[[stream]].
  231. auto stream = reader.stream();
  232. // 2. Assert: stream is not undefined.
  233. VERIFY(stream);
  234. // 3. Assert: stream.[[reader]] is reader.
  235. VERIFY(stream->reader().ptr() == &reader);
  236. // 4. If stream.[[state]] is "readable", reject reader.[[closedPromise]] with a TypeError exception.
  237. auto exception = TRY(JS::TypeError::create(stream->realm(), "Released readable stream"sv));
  238. if (stream->is_readable()) {
  239. WebIDL::reject_promise(stream->realm(), *reader.closed_promise_capability(), exception);
  240. }
  241. // 5. Otherwise, set reader.[[closedPromise]] to a promise rejected with a TypeError exception.
  242. else {
  243. reader.set_closed_promise_capability(WebIDL::create_rejected_promise(stream->realm(), exception));
  244. }
  245. // 6. Set reader.[[closedPromise]].[[PromiseIsHandled]] to true.
  246. WebIDL::mark_promise_as_handled(*reader.closed_promise_capability());
  247. // 7. Perform ! stream.[[controller]].[[ReleaseSteps]]().
  248. stream->controller()->release_steps();
  249. // 8. Set stream.[[reader]] to undefined.
  250. stream->set_reader({});
  251. // 9. Set reader.[[stream]] to undefined.
  252. reader.set_stream({});
  253. return {};
  254. }
  255. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreadererrorreadrequests
  256. void readable_stream_default_reader_error_read_requests(ReadableStreamDefaultReader& reader, JS::Value error)
  257. {
  258. // 1. Let readRequests be reader.[[readRequests]].
  259. // 2. Set reader.[[readRequests]] to a new empty list.
  260. auto read_requests = move(reader.read_requests());
  261. // 3. For each readRequest of readRequests,
  262. for (auto& read_request : read_requests) {
  263. // 1. Perform readRequest’s error steps, given e.
  264. read_request->on_error(error);
  265. }
  266. }
  267. // https://streams.spec.whatwg.org/#readable-stream-default-reader-read
  268. void readable_stream_default_reader_read(ReadableStreamDefaultReader& reader, ReadRequest& read_request)
  269. {
  270. // 1. Let stream be reader.[[stream]].
  271. auto stream = reader.stream();
  272. // 2. Assert: stream is not undefined.
  273. VERIFY(stream);
  274. // 3. Set stream.[[disturbed]] to true.
  275. stream->set_disturbed(true);
  276. // 4. If stream.[[state]] is "closed", perform readRequest’s close steps.
  277. if (stream->is_closed()) {
  278. read_request.on_close();
  279. }
  280. // 5. Otherwise, if stream.[[state]] is "errored", perform readRequest’s error steps given stream.[[storedError]].
  281. else if (stream->is_errored()) {
  282. read_request.on_error(stream->stored_error());
  283. }
  284. // 6. Otherwise,
  285. else {
  286. // 1. Assert: stream.[[state]] is "readable".
  287. VERIFY(stream->is_readable());
  288. // 2. Perform ! stream.[[controller]].[[PullSteps]](readRequest).
  289. MUST(stream->controller()->pull_steps(read_request));
  290. }
  291. }
  292. // https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease
  293. WebIDL::ExceptionOr<void> readable_stream_default_reader_release(ReadableStreamDefaultReader& reader)
  294. {
  295. // 1. Perform ! ReadableStreamReaderGenericRelease(reader).
  296. TRY(readable_stream_reader_generic_release(reader));
  297. // 2. Let e be a new TypeError exception.
  298. auto e = TRY(JS::TypeError::create(reader.realm(), "Reader has been released"sv));
  299. // 3. Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
  300. readable_stream_default_reader_error_read_requests(reader, e);
  301. return {};
  302. }
  303. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-reader
  304. WebIDL::ExceptionOr<void> set_up_readable_stream_default_reader(ReadableStreamDefaultReader& reader, ReadableStream& stream)
  305. {
  306. // 1. If ! IsReadableStreamLocked(stream) is true, throw a TypeError exception.
  307. if (is_readable_stream_locked(stream))
  308. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Cannot create stream reader for a locked stream"sv };
  309. // 2. Perform ! ReadableStreamReaderGenericInitialize(reader, stream).
  310. // 3. Set reader.[[readRequests]] to a new empty list.
  311. readable_stream_reader_generic_initialize(reader, stream);
  312. return {};
  313. }
  314. // https://streams.spec.whatwg.org/#readable-stream-default-controller-close
  315. void readable_stream_default_controller_close(ReadableStreamDefaultController& controller)
  316. {
  317. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  318. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  319. return;
  320. // 2. Let stream be controller.[[stream]].
  321. auto stream = controller.stream();
  322. // 3. Set controller.[[closeRequested]] to true.
  323. controller.set_close_requested(true);
  324. // 4. If controller.[[queue]] is empty,
  325. if (controller.queue().is_empty()) {
  326. // 1. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  327. readable_stream_default_controller_clear_algorithms(controller);
  328. // 2. Perform ! ReadableStreamClose(stream).
  329. readable_stream_close(*stream);
  330. }
  331. }
  332. // https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue
  333. WebIDL::ExceptionOr<void> readable_stream_default_controller_enqueue(ReadableStreamDefaultController& controller, JS::Value chunk)
  334. {
  335. auto& vm = controller.vm();
  336. // 1. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
  337. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  338. return {};
  339. // 2. Let stream be controller.[[stream]].
  340. auto stream = controller.stream();
  341. // 3. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
  342. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0) {
  343. readable_stream_fulfill_read_request(*stream, chunk, false);
  344. }
  345. // 4. Otherwise,
  346. else {
  347. // 1. Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
  348. auto result = (*controller.strategy_size_algorithm())(chunk);
  349. // 2. If result is an abrupt completion,
  350. if (result.is_abrupt()) {
  351. // 1. Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
  352. readable_stream_default_controller_error(controller, result.value().value());
  353. // 2. Return result.
  354. return result;
  355. }
  356. // 3. Let chunkSize be result.[[Value]].
  357. auto chunk_size = TRY(result.release_value().release_value().to_double(vm));
  358. // 4. Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
  359. auto enqueue_result = enqueue_value_with_size(controller, chunk, chunk_size);
  360. // 5. If enqueueResult is an abrupt completion,
  361. if (enqueue_result.is_error()) {
  362. auto throw_completion = Bindings::throw_dom_exception_if_needed(vm, [&] { return enqueue_result; }).throw_completion();
  363. // 1. Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
  364. readable_stream_default_controller_error(controller, throw_completion.value().value());
  365. // 2. Return enqueueResult.
  366. return enqueue_result;
  367. }
  368. }
  369. // 5. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  370. return readable_stream_default_controller_can_pull_if_needed(controller);
  371. }
  372. // https://streams.spec.whatwg.org/#readable-stream-default-controller-call-pull-if-needed
  373. WebIDL::ExceptionOr<void> readable_stream_default_controller_can_pull_if_needed(ReadableStreamDefaultController& controller)
  374. {
  375. // 1. Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
  376. auto should_pull = readable_stream_default_controller_should_call_pull(controller);
  377. // 2. If shouldPull is false, return.
  378. if (!should_pull)
  379. return {};
  380. // 3. If controller.[[pulling]] is true,
  381. if (controller.pulling()) {
  382. // 1. Set controller.[[pullAgain]] to true.
  383. controller.set_pull_again(true);
  384. // 2. Return.
  385. return {};
  386. }
  387. // 4. Assert: controller.[[pullAgain]] is false.
  388. VERIFY(!controller.pull_again());
  389. // 5. Set controller.[[pulling]] to true.
  390. controller.set_pulling(true);
  391. // 6. Let pullPromise be the result of performing controller.[[pullAlgorithm]].
  392. auto pull_promise = TRY((*controller.pull_algorithm())());
  393. // 7. Upon fulfillment of pullPromise,
  394. WebIDL::upon_fulfillment(*pull_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  395. // 1. Set controller.[[pulling]] to false.
  396. controller.set_pulling(false);
  397. // 2. If controller.[[pullAgain]] is true,
  398. if (controller.pull_again()) {
  399. // 1. Set controller.[[pullAgain]] to false.
  400. controller.set_pull_again(false);
  401. // 2. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  402. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  403. }
  404. return JS::js_undefined();
  405. });
  406. // 8. Upon rejection of pullPromise with reason e,
  407. WebIDL::upon_rejection(*pull_promise, [&](auto const& e) -> WebIDL::ExceptionOr<JS::Value> {
  408. // 1. Perform ! ReadableStreamDefaultControllerError(controller, e).
  409. readable_stream_default_controller_error(controller, e);
  410. return JS::js_undefined();
  411. });
  412. return {};
  413. }
  414. // https://streams.spec.whatwg.org/#readable-stream-default-controller-should-call-pull
  415. bool readable_stream_default_controller_should_call_pull(ReadableStreamDefaultController& controller)
  416. {
  417. // 1. Let stream be controller.[[stream]].
  418. auto stream = controller.stream();
  419. // 2. If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
  420. if (!readable_stream_default_controller_can_close_or_enqueue(controller))
  421. return false;
  422. // 3. If controller.[[started]] is false, return false.
  423. if (!controller.started())
  424. return false;
  425. // 4. If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
  426. if (is_readable_stream_locked(*stream) && readable_stream_get_num_read_requests(*stream) > 0)
  427. return true;
  428. // 5. Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
  429. auto desired_size = readable_stream_default_controller_get_desired_size(controller);
  430. // 6. Assert: desiredSize is not null.
  431. VERIFY(desired_size.has_value());
  432. // 7. If desiredSize > 0, return true.
  433. if (desired_size.release_value() > 0)
  434. return true;
  435. // 8. Return false.
  436. return false;
  437. }
  438. // https://streams.spec.whatwg.org/#readable-stream-default-controller-clear-algorithms
  439. void readable_stream_default_controller_clear_algorithms(ReadableStreamDefaultController& controller)
  440. {
  441. // 1. Set controller.[[pullAlgorithm]] to undefined.
  442. controller.set_pull_algorithm({});
  443. // 2. Set controller.[[cancelAlgorithm]] to undefined.
  444. controller.set_cancel_algorithm({});
  445. // 3. Set controller.[[strategySizeAlgorithm]] to undefined.
  446. controller.set_strategy_size_algorithm({});
  447. }
  448. // https://streams.spec.whatwg.org/#readable-stream-default-controller-error
  449. void readable_stream_default_controller_error(ReadableStreamDefaultController& controller, JS::Value error)
  450. {
  451. // 1. Let stream be controller.[[stream]].
  452. auto stream = controller.stream();
  453. // 2. If stream.[[state]] is not "readable", return.
  454. if (!stream->is_readable())
  455. return;
  456. // 3. Perform ! ResetQueue(controller).
  457. reset_queue(controller);
  458. // 4. Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
  459. readable_stream_default_controller_clear_algorithms(controller);
  460. // 5. Perform ! ReadableStreamError(stream, e).
  461. readable_stream_error(*stream, error);
  462. }
  463. // https://streams.spec.whatwg.org/#readable-stream-default-controller-get-desired-size
  464. Optional<float> readable_stream_default_controller_get_desired_size(ReadableStreamDefaultController& controller)
  465. {
  466. auto stream = controller.stream();
  467. // 1. Let state be controller.[[stream]].[[state]].
  468. // 2. If state is "errored", return null.
  469. if (stream->is_errored())
  470. return {};
  471. // 3. If state is "closed", return 0.
  472. if (stream->is_closed())
  473. return 0.0f;
  474. // 4. Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
  475. return controller.strategy_hwm() - controller.queue_total_size();
  476. }
  477. // https://streams.spec.whatwg.org/#readable-stream-default-controller-can-close-or-enqueue
  478. bool readable_stream_default_controller_can_close_or_enqueue(ReadableStreamDefaultController& controller)
  479. {
  480. // 1. Let state be controller.[[stream]].[[state]].
  481. // 2. If controller.[[closeRequested]] is false and state is "readable", return true.
  482. // 3. Otherwise, return false.
  483. return !controller.close_requested() && controller.stream()->is_readable();
  484. }
  485. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller
  486. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller(ReadableStream& stream, ReadableStreamDefaultController& controller, StartAlgorithm&& start_algorithm, PullAlgorithm&& pull_algorithm, CancelAlgorithm&& cancel_algorithm, double high_water_mark, SizeAlgorithm&& size_algorithm)
  487. {
  488. auto& realm = stream.realm();
  489. // 1. Assert: stream.[[controller]] is undefined.
  490. VERIFY(!stream.controller());
  491. // 2. Set controller.[[stream]] to stream.
  492. controller.set_stream(stream);
  493. // 3. Perform ! ResetQueue(controller).
  494. reset_queue(controller);
  495. // 4. Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
  496. controller.set_started(false);
  497. controller.set_close_requested(false);
  498. controller.set_pull_again(false);
  499. controller.set_pulling(false);
  500. // 5. Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
  501. controller.set_strategy_size_algorithm(move(size_algorithm));
  502. controller.set_strategy_hwm(high_water_mark);
  503. // 6. Set controller.[[pullAlgorithm]] to pullAlgorithm.
  504. controller.set_pull_algorithm(move(pull_algorithm));
  505. // 7. Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
  506. controller.set_cancel_algorithm(move(cancel_algorithm));
  507. // 8. Set stream.[[controller]] to controller.
  508. stream.set_controller(controller);
  509. // 9. Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
  510. auto start_result = TRY(start_algorithm());
  511. // 10. Let startPromise be a promise resolved with startResult.
  512. auto start_promise = WebIDL::create_resolved_promise(realm, start_result ? start_result->promise() : JS::js_undefined());
  513. // 11. Upon fulfillment of startPromise,
  514. WebIDL::upon_fulfillment(start_promise, [&](auto const&) -> WebIDL::ExceptionOr<JS::Value> {
  515. // 1. Set controller.[[started]] to true.
  516. controller.set_started(true);
  517. // 2. Assert: controller.[[pulling]] is false.
  518. VERIFY(!controller.pulling());
  519. // 3. Assert: controller.[[pullAgain]] is false.
  520. VERIFY(!controller.pull_again());
  521. // 4. Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
  522. TRY(readable_stream_default_controller_can_pull_if_needed(controller));
  523. return JS::js_undefined();
  524. });
  525. // 12. Upon rejection of startPromise with reason r,
  526. WebIDL::upon_rejection(start_promise, [&](auto const& r) -> WebIDL::ExceptionOr<JS::Value> {
  527. // 1. Perform ! ReadableStreamDefaultControllerError(controller, r).
  528. readable_stream_default_controller_error(controller, r);
  529. return JS::js_undefined();
  530. });
  531. return {};
  532. }
  533. // https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller-from-underlying-source
  534. WebIDL::ExceptionOr<void> set_up_readable_stream_default_controller_from_underlying_source(ReadableStream& stream, JS::Value underlying_source_value, UnderlyingSource underlying_source, double high_water_mark, SizeAlgorithm&& size_algorithm)
  535. {
  536. auto& realm = stream.realm();
  537. // 1. Let controller be a new ReadableStreamDefaultController.
  538. auto controller = MUST_OR_THROW_OOM(stream.heap().allocate<ReadableStreamDefaultController>(realm, realm));
  539. // 2. Let startAlgorithm be an algorithm that returns undefined.
  540. StartAlgorithm start_algorithm = [] { return JS::GCPtr<WebIDL::Promise> {}; };
  541. // 3. Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
  542. PullAlgorithm pull_algorithm = [&realm]() {
  543. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  544. };
  545. // 4. Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
  546. CancelAlgorithm cancel_algorithm = [&realm](auto const&) {
  547. return WebIDL::create_resolved_promise(realm, JS::js_undefined());
  548. };
  549. // 5. If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list « controller » and callback this value underlyingSource.
  550. if (underlying_source.start) {
  551. start_algorithm = [&, start = underlying_source.start]() -> WebIDL::ExceptionOr<JS::GCPtr<WebIDL::Promise>> {
  552. auto result = TRY(WebIDL::invoke_callback(*start, underlying_source_value, controller)).release_value();
  553. return WebIDL::create_resolved_promise(realm, result);
  554. };
  555. }
  556. // 6. If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list « controller » and callback this value underlyingSource.
  557. if (underlying_source.pull) {
  558. pull_algorithm = [&, pull = underlying_source.pull]() -> WebIDL::ExceptionOr<JS::GCPtr<WebIDL::Promise>> {
  559. auto result = TRY(WebIDL::invoke_callback(*pull, underlying_source_value, controller)).release_value();
  560. return WebIDL::create_resolved_promise(realm, result);
  561. };
  562. }
  563. // 7. If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list « reason » and callback this value underlyingSource.
  564. if (underlying_source.cancel) {
  565. cancel_algorithm = [&, cancel = underlying_source.cancel](auto const& reason) -> WebIDL::ExceptionOr<JS::GCPtr<WebIDL::Promise>> {
  566. auto result = TRY(WebIDL::invoke_callback(*cancel, underlying_source_value, reason)).release_value();
  567. return WebIDL::create_resolved_promise(realm, result);
  568. };
  569. }
  570. // 8. Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
  571. return set_up_readable_stream_default_controller(stream, controller, move(start_algorithm), move(pull_algorithm), move(cancel_algorithm), high_water_mark, move(size_algorithm));
  572. }
  573. }