ReadableStream.cpp 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. /*
  2. * Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
  3. * Copyright (c) 2023-2024, Shannon Booth <shannon@serenityos.org>
  4. * Copyright (c) 2024, Kenneth Myhra <kennethmyhra@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibJS/Runtime/PromiseCapability.h>
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/Bindings/ReadableStreamPrototype.h>
  11. #include <LibWeb/DOM/AbortSignal.h>
  12. #include <LibWeb/Streams/AbstractOperations.h>
  13. #include <LibWeb/Streams/ReadableByteStreamController.h>
  14. #include <LibWeb/Streams/ReadableStream.h>
  15. #include <LibWeb/Streams/ReadableStreamBYOBReader.h>
  16. #include <LibWeb/Streams/ReadableStreamDefaultController.h>
  17. #include <LibWeb/Streams/ReadableStreamDefaultReader.h>
  18. #include <LibWeb/Streams/UnderlyingSource.h>
  19. #include <LibWeb/WebIDL/ExceptionOr.h>
  20. namespace Web::Streams {
  21. JS_DEFINE_ALLOCATOR(ReadableStream);
  22. // https://streams.spec.whatwg.org/#rs-constructor
  23. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> ReadableStream::construct_impl(JS::Realm& realm, Optional<JS::Handle<JS::Object>> const& underlying_source_object, QueuingStrategy const& strategy)
  24. {
  25. auto& vm = realm.vm();
  26. auto readable_stream = realm.heap().allocate<ReadableStream>(realm, realm);
  27. // 1. If underlyingSource is missing, set it to null.
  28. auto underlying_source = underlying_source_object.has_value() ? JS::Value(underlying_source_object.value()) : JS::js_null();
  29. // 2. Let underlyingSourceDict be underlyingSource, converted to an IDL value of type UnderlyingSource.
  30. auto underlying_source_dict = TRY(UnderlyingSource::from_value(vm, underlying_source));
  31. // 3. Perform ! InitializeReadableStream(this).
  32. // 4. If underlyingSourceDict["type"] is "bytes":
  33. if (underlying_source_dict.type.has_value() && underlying_source_dict.type.value() == ReadableStreamType::Bytes) {
  34. // 1. If strategy["size"] exists, throw a RangeError exception.
  35. if (strategy.size)
  36. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::RangeError, "Size strategy not allowed for byte stream"sv };
  37. // 2. Let highWaterMark be ? ExtractHighWaterMark(strategy, 0).
  38. auto high_water_mark = TRY(extract_high_water_mark(strategy, 0));
  39. // 3. Perform ? SetUpReadableByteStreamControllerFromUnderlyingSource(this, underlyingSource, underlyingSourceDict, highWaterMark).
  40. TRY(set_up_readable_byte_stream_controller_from_underlying_source(*readable_stream, underlying_source, underlying_source_dict, high_water_mark));
  41. }
  42. // 5. Otherwise,
  43. else {
  44. // 1. Assert: underlyingSourceDict["type"] does not exist.
  45. VERIFY(!underlying_source_dict.type.has_value());
  46. // 2. Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).
  47. auto size_algorithm = extract_size_algorithm(vm, strategy);
  48. // 3. Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).
  49. auto high_water_mark = TRY(extract_high_water_mark(strategy, 1));
  50. // 4. Perform ? SetUpReadableStreamDefaultControllerFromUnderlyingSource(this, underlyingSource, underlyingSourceDict, highWaterMark, sizeAlgorithm).
  51. TRY(set_up_readable_stream_default_controller_from_underlying_source(*readable_stream, underlying_source, underlying_source_dict, high_water_mark, size_algorithm));
  52. }
  53. return readable_stream;
  54. }
  55. ReadableStream::ReadableStream(JS::Realm& realm)
  56. : PlatformObject(realm)
  57. {
  58. }
  59. ReadableStream::~ReadableStream() = default;
  60. // https://streams.spec.whatwg.org/#rs-locked
  61. bool ReadableStream::locked() const
  62. {
  63. // 1. Return ! IsReadableStreamLocked(this).
  64. return is_readable_stream_locked(*this);
  65. }
  66. // https://streams.spec.whatwg.org/#rs-cancel
  67. JS::NonnullGCPtr<JS::Object> ReadableStream::cancel(JS::Value reason)
  68. {
  69. auto& realm = this->realm();
  70. // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.
  71. if (is_readable_stream_locked(*this)) {
  72. auto exception = JS::TypeError::create(realm, "Cannot cancel a locked stream"sv);
  73. return WebIDL::create_rejected_promise(realm, JS::Value { exception })->promise();
  74. }
  75. // 2. Return ! ReadableStreamCancel(this, reason).
  76. return readable_stream_cancel(*this, reason)->promise();
  77. }
  78. // https://streams.spec.whatwg.org/#rs-get-reader
  79. WebIDL::ExceptionOr<ReadableStreamReader> ReadableStream::get_reader(ReadableStreamGetReaderOptions const& options)
  80. {
  81. // 1. If options["mode"] does not exist, return ? AcquireReadableStreamDefaultReader(this).
  82. if (!options.mode.has_value())
  83. return ReadableStreamReader { TRY(acquire_readable_stream_default_reader(*this)) };
  84. // 2. Assert: options["mode"] is "byob".
  85. VERIFY(*options.mode == Bindings::ReadableStreamReaderMode::Byob);
  86. // 3. Return ? AcquireReadableStreamBYOBReader(this).
  87. return ReadableStreamReader { TRY(acquire_readable_stream_byob_reader(*this)) };
  88. }
  89. WebIDL::ExceptionOr<JS::NonnullGCPtr<ReadableStream>> ReadableStream::pipe_through(ReadableWritablePair transform, StreamPipeOptions const& options)
  90. {
  91. // 1. If ! IsReadableStreamLocked(this) is true, throw a TypeError exception.
  92. if (is_readable_stream_locked(*this))
  93. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Failed to execute 'pipeThrough' on 'ReadableStream': Cannot pipe a locked stream"sv };
  94. // 2. If ! IsWritableStreamLocked(transform["writable"]) is true, throw a TypeError exception.
  95. if (is_writable_stream_locked(*transform.writable))
  96. return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Failed to execute 'pipeThrough' on 'ReadableStream': parameter 1's 'writable' is locked"sv };
  97. // 3. Let signal be options["signal"] if it exists, or undefined otherwise.
  98. auto signal = options.signal ? JS::Value(options.signal) : JS::js_undefined();
  99. // 4. Let promise be ! ReadableStreamPipeTo(this, transform["writable"], options["preventClose"], options["preventAbort"], options["preventCancel"], signal).
  100. auto promise = readable_stream_pipe_to(*this, *transform.writable, options.prevent_close, options.prevent_abort, options.prevent_cancel, signal);
  101. // 5. Set promise.[[PromiseIsHandled]] to true.
  102. WebIDL::mark_promise_as_handled(*promise);
  103. // 6. Return transform["readable"].
  104. return JS::NonnullGCPtr { *transform.readable };
  105. }
  106. JS::NonnullGCPtr<JS::Object> ReadableStream::pipe_to(WritableStream& destination, StreamPipeOptions const& options)
  107. {
  108. auto& realm = this->realm();
  109. // 1. If ! IsReadableStreamLocked(this) is true, return a promise rejected with a TypeError exception.
  110. if (is_readable_stream_locked(*this)) {
  111. auto promise = WebIDL::create_promise(realm);
  112. WebIDL::reject_promise(realm, promise, JS::TypeError::create(realm, "Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe a locked stream"sv));
  113. return promise->promise();
  114. }
  115. // 2. If ! IsWritableStreamLocked(destination) is true, return a promise rejected with a TypeError exception.
  116. if (is_writable_stream_locked(destination)) {
  117. auto promise = WebIDL::create_promise(realm);
  118. WebIDL::reject_promise(realm, promise, JS::TypeError::create(realm, "Failed to execute 'pipeTo' on 'ReadableStream': Cannot pipe to a locked stream"sv));
  119. return promise->promise();
  120. }
  121. // 3. Let signal be options["signal"] if it exists, or undefined otherwise.
  122. auto signal = options.signal ? JS::Value(options.signal) : JS::js_undefined();
  123. // 4. Return ! ReadableStreamPipeTo(this, destination, options["preventClose"], options["preventAbort"], options["preventCancel"], signal).
  124. return readable_stream_pipe_to(*this, destination, options.prevent_close, options.prevent_abort, options.prevent_cancel, signal)->promise();
  125. }
  126. // https://streams.spec.whatwg.org/#readablestream-tee
  127. WebIDL::ExceptionOr<ReadableStreamPair> ReadableStream::tee()
  128. {
  129. // To tee a ReadableStream stream, return ? ReadableStreamTee(stream, true).
  130. return TRY(readable_stream_tee(realm(), *this, true));
  131. }
  132. void ReadableStream::initialize(JS::Realm& realm)
  133. {
  134. Base::initialize(realm);
  135. WEB_SET_PROTOTYPE_FOR_INTERFACE(ReadableStream);
  136. }
  137. void ReadableStream::visit_edges(Cell::Visitor& visitor)
  138. {
  139. Base::visit_edges(visitor);
  140. if (m_controller.has_value())
  141. m_controller->visit([&](auto& controller) { visitor.visit(controller); });
  142. visitor.visit(m_stored_error);
  143. if (m_reader.has_value())
  144. m_reader->visit([&](auto& reader) { visitor.visit(reader); });
  145. }
  146. // https://streams.spec.whatwg.org/#readablestream-locked
  147. bool ReadableStream::is_readable() const
  148. {
  149. // A ReadableStream stream is readable if stream.[[state]] is "readable".
  150. return m_state == State::Readable;
  151. }
  152. // https://streams.spec.whatwg.org/#readablestream-closed
  153. bool ReadableStream::is_closed() const
  154. {
  155. // A ReadableStream stream is closed if stream.[[state]] is "closed".
  156. return m_state == State::Closed;
  157. }
  158. // https://streams.spec.whatwg.org/#readablestream-errored
  159. bool ReadableStream::is_errored() const
  160. {
  161. // A ReadableStream stream is errored if stream.[[state]] is "errored".
  162. return m_state == State::Errored;
  163. }
  164. // https://streams.spec.whatwg.org/#readablestream-locked
  165. bool ReadableStream::is_locked() const
  166. {
  167. // A ReadableStream stream is locked if ! IsReadableStreamLocked(stream) returns true.
  168. return is_readable_stream_locked(*this);
  169. }
  170. // https://streams.spec.whatwg.org/#is-readable-stream-disturbed
  171. bool ReadableStream::is_disturbed() const
  172. {
  173. // A ReadableStream stream is disturbed if stream.[[disturbed]] is true.
  174. return m_disturbed;
  175. }
  176. }