Skip to main content

script/dom/stream/
readablestream.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::{Cell, RefCell};
8use std::collections::VecDeque;
9use std::ptr::{self};
10use std::rc::Rc;
11
12use dom_struct::dom_struct;
13use js::context::JSContext;
14use js::conversions::ToJSValConvertible;
15use js::jsapi::{Heap, JSObject};
16use js::jsval::{JSVal, ObjectValue, UndefinedValue};
17use js::realm::CurrentRealm;
18use js::rust::{
19    HandleObject as SafeHandleObject, HandleValue as SafeHandleValue,
20    MutableHandleValue as SafeMutableHandleValue,
21};
22use js::typedarray::{ArrayBufferViewU8, Uint8};
23use rustc_hash::FxHashMap;
24use servo_base::generic_channel::GenericSharedMemory;
25use servo_base::id::{MessagePortId, MessagePortIndex};
26use servo_constellation_traits::MessagePortImpl;
27
28use crate::dom::bindings::codegen::Bindings::QueuingStrategyBinding::QueuingStrategy;
29use crate::dom::bindings::codegen::Bindings::ReadableStreamBinding::{
30    ReadableStreamGetReaderOptions, ReadableStreamMethods, ReadableStreamReaderMode,
31    ReadableWritablePair, StreamPipeOptions,
32};
33use script_bindings::str::DOMString;
34use crate::dom::domexception::{DOMErrorName, DOMException};
35use crate::dom::encoding::textdecoderstream::TextDecoderStream;
36use script_bindings::codegen::GenericBindings::TextDecoderStreamBinding::TextDecoderStreamMethods;
37use script_bindings::conversions::{is_array_like, StringificationBehavior};
38use crate::dom::bindings::callback::RootedCallback;
39use crate::dom::bindings::codegen::Bindings::QueuingStrategyBinding::QueuingStrategySize;
40use crate::dom::abortsignal::{AbortAlgorithm, AbortSignal};
41use crate::dom::bindings::codegen::Bindings::ReadableStreamDefaultReaderBinding::ReadableStreamDefaultReaderMethods;
42use crate::dom::bindings::codegen::Bindings::ReadableStreamDefaultControllerBinding::ReadableStreamDefaultController_Binding::ReadableStreamDefaultControllerMethods;
43use crate::dom::bindings::codegen::Bindings::UnderlyingSourceBinding::UnderlyingSource as JsUnderlyingSource;
44use crate::dom::bindings::conversions::{ConversionBehavior, ConversionResult, get_property, get_property_jsval};
45use crate::dom::bindings::error::{Error, ErrorToJsval, Fallible};
46use crate::dom::bindings::codegen::GenericBindings::WritableStreamDefaultWriterBinding::WritableStreamDefaultWriter_Binding::WritableStreamDefaultWriterMethods;
47use crate::dom::stream::writablestream::WritableStream;
48use crate::dom::bindings::codegen::UnionTypes::ReadableStreamDefaultReaderOrReadableStreamBYOBReader as ReadableStreamReader;
49use crate::dom::bindings::reflector::DomGlobal;
50use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto};
51use crate::dom::bindings::root::{DomRoot, MutNullableDom, Dom};
52use crate::dom::bindings::trace::RootedTraceableBox;
53use crate::dom::stream::byteteeunderlyingsource::{ByteTeeCancelAlgorithm, ByteTeePullAlgorithm, ByteTeeUnderlyingSource};
54use crate::dom::stream::countqueuingstrategy::{extract_high_water_mark, extract_size_algorithm};
55use crate::dom::stream::readablestreamgenericreader::ReadableStreamGenericReader;
56use crate::dom::globalscope::GlobalScope;
57use crate::dom::promise::{wait_for_all_promise, Promise, RootedPromise, TracedPromise};
58use crate::dom::stream::readablebytestreamcontroller::ReadableByteStreamController;
59use crate::dom::stream::readablestreambyobreader::ReadableStreamBYOBReader;
60use crate::dom::stream::readablestreamdefaultcontroller::ReadableStreamDefaultController;
61use crate::dom::stream::readablestreamdefaultreader::{ReadRequest, ReadableStreamDefaultReader};
62use crate::dom::stream::defaultteeunderlyingsource::DefaultTeeCancelAlgorithm;
63use crate::dom::types::DefaultTeeUnderlyingSource;
64use crate::dom::stream::underlyingsourcecontainer::UnderlyingSourceType;
65use crate::dom::stream::writablestreamdefaultwriter::WritableStreamDefaultWriter;
66use script_bindings::codegen::GenericBindings::MessagePortBinding::MessagePortMethods;
67use crate::dom::messageport::MessagePort;
68use crate::realms::{enter_auto_realm};
69use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
70use crate::dom::bindings::transferable::Transferable;
71use script_bindings::structuredclone::StructuredData;
72
73use super::readablestreambyobreader::ReadIntoRequest;
74use crate::dom::bindings::buffer_source::{HeapBufferSource, create_buffer_source};
75
76/// State Machine for `PipeTo`.
77#[derive(Clone, Debug, Default, MallocSizeOf, PartialEq)]
78enum PipeToState {
79    /// The starting state
80    #[default]
81    Starting,
82    /// Waiting for the writer to be ready
83    PendingReady,
84    /// Waiting for a read to resolve.
85    PendingRead,
86    /// Waiting for all pending writes to finish,
87    /// as part of shutting down with an optional action.
88    ShuttingDownWithPendingWrites(Option<ShutdownAction>),
89    /// When shutting down with an action,
90    /// waiting for the action to complete,
91    /// at which point we can `finalize`.
92    ShuttingDownPendingAction,
93    /// The pipe has been finalized,
94    /// no further actions should be performed.
95    Finalized,
96}
97
98/// <https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action>
99#[derive(Clone, Debug, MallocSizeOf, PartialEq)]
100enum ShutdownAction {
101    /// <https://streams.spec.whatwg.org/#writable-stream-abort>
102    WritableStreamAbort,
103    /// <https://streams.spec.whatwg.org/#readable-stream-cancel>
104    ReadableStreamCancel,
105    /// <https://streams.spec.whatwg.org/#writable-stream-default-writer-close-with-error-propagation>
106    WritableStreamDefaultWriterCloseWithErrorPropagation,
107    /// <https://streams.spec.whatwg.org/#ref-for-rs-pipeTo-shutdown-with-action>
108    Abort,
109}
110
111impl js::gc::Rootable for PipeTo {}
112
113/// The "in parallel, but not really" part of
114/// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
115///
116/// Note: the spec is flexible about how this is done, but requires the following constraints to apply:
117/// - Public API must not be used: we'll only use Rust.
118/// - Backpressure must be enforced: we'll only read from source when dest is ready.
119/// - Shutdown must stop activity: we'll do this together with the below.
120/// - Error and close states must be propagated: we'll do this by checking these states at every step.
121#[derive(Clone, JSTraceable, MallocSizeOf)]
122#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
123pub(crate) struct PipeTo {
124    /// <https://streams.spec.whatwg.org/#ref-for-readablestream%E2%91%A7%E2%91%A0>
125    reader: Dom<ReadableStreamDefaultReader>,
126
127    /// <https://streams.spec.whatwg.org/#ref-for-acquire-writable-stream-default-writer>
128    writer: Dom<WritableStreamDefaultWriter>,
129
130    /// Pending writes are needed when shutting down(with an action),
131    /// because we can only finalize when all writes are finished.
132    #[ignore_malloc_size_of = "nested Rc"]
133    pending_writes: Rc<RefCell<VecDeque<TracedPromise>>>,
134
135    /// The state machine.
136    #[conditional_malloc_size_of]
137    #[no_trace]
138    state: Rc<RefCell<PipeToState>>,
139
140    /// <https://streams.spec.whatwg.org/#readablestream-pipe-to-preventabort>
141    prevent_abort: bool,
142
143    /// <https://streams.spec.whatwg.org/#readablestream-pipe-to-preventcancel>
144    prevent_cancel: bool,
145
146    /// <https://streams.spec.whatwg.org/#readablestream-pipe-to-preventclose>
147    prevent_close: bool,
148
149    /// The `shuttingDown` variable of
150    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
151    #[conditional_malloc_size_of]
152    shutting_down: Rc<Cell<bool>>,
153
154    /// The abort reason of the abort signal,
155    /// stored here because we must keep it across a microtask.
156    #[ignore_malloc_size_of = "mozjs"]
157    abort_reason: Rc<Heap<JSVal>>,
158
159    /// The error potentially passed to shutdown,
160    /// stored here because we must keep it across a microtask.
161    #[ignore_malloc_size_of = "mozjs"]
162    shutdown_error: Rc<RefCell<Option<Heap<JSVal>>>>,
163
164    /// The promise returned by a shutdown action.
165    /// We keep it to only continue when it is not pending anymore.
166    #[conditional_malloc_size_of]
167    shutdown_action_promise: Rc<RefCell<Option<TracedPromise>>>,
168
169    /// The promise resolved or rejected at
170    /// <https://streams.spec.whatwg.org/#rs-pipeTo-finalize>
171    result_promise: TracedPromise,
172}
173
174impl PipeTo {
175    /// Run the `abortAlgorithm` defined at
176    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
177    pub(crate) fn abort_with_reason(
178        &self,
179        cx: &mut CurrentRealm,
180        global: &GlobalScope,
181        reason: SafeHandleValue,
182    ) {
183        // Abort should do nothing if we are already shutting down.
184        if self.shutting_down.get() {
185            return;
186        }
187
188        // Let error be signal’s abort reason.
189        // Note: storing it because it may need to be kept across a microtask,
190        // and see the note below as to why it is kept separately from `shutdown_error`.
191        self.abort_reason.set(reason.get());
192
193        // Note: setting the error now,
194        // will result in a rejection of the pipe promise, with this error.
195        // Unless any shutdown action raise their own error,
196        // in which case this error will be overwritten by the shutdown action error.
197        self.set_shutdown_error(reason);
198
199        // Let actions be an empty ordered set.
200        // Note: the actions are defined, and performed, inside `shutdown_with_an_action`.
201
202        // Shutdown with an action consisting of getting a promise to wait for all of the actions in actions,
203        // and with error.
204        self.shutdown(cx, global, Some(ShutdownAction::Abort));
205    }
206}
207
208impl Callback for PipeTo {
209    /// The pipe makes progress one microtask at a time.
210    /// Note: we use one struct as the callback for all promises,
211    /// and for both of their reactions.
212    ///
213    /// The context of the callback is determined from:
214    /// - the current state.
215    /// - the type of `result`.
216    /// - the state of a stored promise(in some cases).
217    fn callback(&self, cx: &mut CurrentRealm, result: SafeHandleValue) {
218        let global = self.reader.global();
219
220        // Note: we only care about the result of writes when they are rejected,
221        // and the error is accessed not through handlers,
222        // but directly using `dest.get_stored_error`.
223        // So we must mark rejected promises as handled
224        // to prevent unhandled rejection errors.
225        self.pending_writes.borrow_mut().retain(|p| {
226            let pending = p.is_pending();
227            if !pending {
228                p.set_promise_is_handled(cx);
229            }
230            pending
231        });
232
233        // Note: cloning to prevent re-borrow in methods called below.
234        let state_before_checks = self.state.borrow().clone();
235
236        // Note: if we are in a `PendingRead` state,
237        // and the source is closed,
238        // we try to write chunks before doing any shutdown,
239        // which is necessary to implement the
240        // "If any chunks have been read but not yet written, write them to dest."
241        // part of shutdown.
242        if state_before_checks == PipeToState::PendingRead {
243            let source = self.reader.get_stream().expect("Source stream must be set");
244            if source.is_closed() {
245                let dest = self
246                    .writer
247                    .get_stream()
248                    .expect("Destination stream must be set");
249
250                // If dest.[[state]] is "writable",
251                // and ! WritableStreamCloseQueuedOrInFlight(dest) is false,
252                if dest.is_writable() && !dest.close_queued_or_in_flight() {
253                    let Ok(done) = get_read_promise_done(cx, &result) else {
254                        // This is the case that the microtask ran in reaction
255                        // to the closed promise of the reader,
256                        // so we should wait for subsequent chunks,
257                        // and skip the shutdown below
258                        // (reader is closed, but there are still pending reads).
259                        // Shutdown will happen when the last chunk has been received.
260                        return;
261                    };
262
263                    if !done {
264                        // If any chunks have been read but not yet written, write them to dest.
265                        self.write_chunk(cx, &global, result);
266                    }
267                }
268            }
269        }
270
271        self.check_and_propagate_errors_forward(cx, &global);
272        self.check_and_propagate_errors_backward(cx, &global);
273        self.check_and_propagate_closing_forward(cx, &global);
274        self.check_and_propagate_closing_backward(cx, &global);
275
276        // Note: cloning to prevent re-borrow in methods called below.
277        let state = self.state.borrow().clone();
278
279        // If we switched to a shutdown state,
280        // return.
281        // Progress will be made at the next tick.
282        if state != state_before_checks {
283            return;
284        }
285
286        match state {
287            PipeToState::Starting => unreachable!("PipeTo should not be in the Starting state."),
288            PipeToState::PendingReady => {
289                // Read a chunk.
290                self.read_chunk(cx, &global);
291            },
292            PipeToState::PendingRead => {
293                // Write the chunk.
294                self.write_chunk(cx, &global, result);
295
296                // An early return is necessary if the write algorithm aborted the pipe.
297                if self.shutting_down.get() {
298                    return;
299                }
300
301                // Wait for the writer to be ready again.
302                self.wait_for_writer_ready(cx, &global);
303            },
304            PipeToState::ShuttingDownWithPendingWrites(action) => {
305                // Wait until every chunk that has been read has been written
306                // (i.e. the corresponding promises have settled).
307                if let Some(write) = self.pending_writes.borrow().front() {
308                    self.wait_on_pending_write(cx, &global, write);
309                    return;
310                }
311
312                // Note: error is stored in `self.shutdown_error`.
313                if let Some(action) = action {
314                    // Let p be the result of performing action.
315                    self.perform_action(cx, &global, action);
316                } else {
317                    // Finalize, passing along error if it was given.
318                    self.finalize(cx, &global);
319                }
320            },
321            PipeToState::ShuttingDownPendingAction => {
322                let Some(ref promise) = *self.shutdown_action_promise.borrow() else {
323                    unreachable!();
324                };
325                if promise.is_pending() {
326                    // While waiting for the action to complete,
327                    // we may get callbacks for other promises(closed, ready),
328                    // and we should ignore those.
329                    return;
330                }
331
332                let is_array_like = {
333                    if !result.is_object() {
334                        false
335                    } else {
336                        is_array_like::<crate::DomTypeHolder>(cx, result)
337                    }
338                };
339
340                // Finalize, passing along error if it was given.
341                if !result.is_undefined() && !is_array_like {
342                    // Most actions either resolve with undefined,
343                    // or reject with an error,
344                    // and the error should be used when finalizing.
345                    // One exception is the `Abort` action,
346                    // which resolves with a list of undefined values.
347
348                    // If `result` isn't undefined or array-like,
349                    // then it is an error
350                    // and should overwrite the current shutdown error.
351                    self.set_shutdown_error(result);
352                }
353                self.finalize(cx, &global);
354            },
355            PipeToState::Finalized => {},
356        }
357    }
358}
359
360impl PipeTo {
361    /// Setting shutdown error in a way that ensures it isn't
362    /// moved after it has been set.
363    fn set_shutdown_error(&self, error: SafeHandleValue) {
364        *self.shutdown_error.borrow_mut() = Some(Heap::default());
365        let Some(ref heap) = *self.shutdown_error.borrow() else {
366            unreachable!("Option set to Some(heap) above.");
367        };
368        heap.set(error.get())
369    }
370
371    /// Wait for the writer to be ready,
372    /// which implements the constraint that backpressure must be enforced.
373    fn wait_for_writer_ready(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
374        {
375            let mut state = self.state.borrow_mut();
376            *state = PipeToState::PendingReady;
377        }
378
379        let ready_promise = self.writer.Ready(cx);
380        if ready_promise.is_fulfilled() {
381            self.read_chunk(cx, global);
382        } else {
383            let handler = PromiseNativeHandler::new(
384                cx,
385                global,
386                Some(Box::new(self.clone())),
387                Some(Box::new(self.clone())),
388            );
389            ready_promise.append_native_handler(cx, &handler);
390
391            // Note: if the writer is not ready,
392            // in order to ensure progress we must
393            // also react to the closure of the source(because source may close empty).
394            let closed_promise = self.reader.Closed(cx);
395            closed_promise.append_native_handler(cx, &handler);
396        }
397    }
398
399    /// Read a chunk
400    fn read_chunk(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
401        *self.state.borrow_mut() = PipeToState::PendingRead;
402        let chunk_promise = self.reader.Read(cx);
403        let handler = PromiseNativeHandler::new(
404            cx,
405            global,
406            Some(Box::new(self.clone())),
407            Some(Box::new(self.clone())),
408        );
409        chunk_promise.append_native_handler(cx, &handler);
410
411        // Note: in order to ensure progress we must
412        // also react to the closure of the destination.
413        let ready_promise = self.writer.Closed(cx);
414        ready_promise.append_native_handler(cx, &handler);
415    }
416
417    /// Try to write a chunk using the jsval, and returns wether it succeeded
418    // It will fail if it is the last `done` chunk, or if it is not a chunk at all.
419    fn write_chunk(
420        &self,
421        cx: &mut JSContext,
422        global: &GlobalScope,
423        chunk: SafeHandleValue,
424    ) -> bool {
425        if chunk.is_object() {
426            rooted!(&in(cx) let object = chunk.to_object());
427            rooted!(&in(cx) let mut bytes = UndefinedValue());
428            get_property_jsval(cx, object.handle(), c"value", bytes.handle_mut())
429                .expect("Chunk should have a value.");
430
431            // Write the chunk.
432            let write_promise = self.writer.write(cx, global, bytes.handle());
433            self.pending_writes
434                .borrow_mut()
435                .push_back(write_promise.to_traced());
436            return true;
437        }
438        false
439    }
440
441    /// Only as part of shutting-down do we wait on pending writes
442    /// (backpressure is communicated not through pending writes
443    /// but through the readiness of the writer).
444    fn wait_on_pending_write(
445        &self,
446        cx: &mut CurrentRealm,
447        global: &GlobalScope,
448        promise: &Promise,
449    ) {
450        let handler = PromiseNativeHandler::new(
451            cx,
452            global,
453            Some(Box::new(self.clone())),
454            Some(Box::new(self.clone())),
455        );
456        promise.append_native_handler(cx, &handler);
457    }
458
459    /// Errors must be propagated forward part of
460    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
461    fn check_and_propagate_errors_forward(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
462        // An early return is necessary if we are shutting down,
463        // because in that case the source can already have been set to none.
464        if self.shutting_down.get() {
465            return;
466        }
467
468        // if source.[[state]] is or becomes "errored", then
469        let source = self
470            .reader
471            .get_stream()
472            .expect("Reader should still have a stream");
473        if source.is_errored() {
474            rooted!(&in(cx) let mut source_error = UndefinedValue());
475            source.get_stored_error(source_error.handle_mut());
476            self.set_shutdown_error(source_error.handle());
477
478            // If preventAbort is false,
479            if !self.prevent_abort {
480                // shutdown with an action of ! WritableStreamAbort(dest, source.[[storedError]])
481                // and with source.[[storedError]].
482                self.shutdown(cx, global, Some(ShutdownAction::WritableStreamAbort))
483            } else {
484                // Otherwise, shutdown with source.[[storedError]].
485                self.shutdown(cx, global, None);
486            }
487        }
488    }
489
490    /// Errors must be propagated backward part of
491    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
492    fn check_and_propagate_errors_backward(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
493        // An early return is necessary if we are shutting down,
494        // because in that case the destination can already have been set to none.
495        if self.shutting_down.get() {
496            return;
497        }
498
499        // if dest.[[state]] is or becomes "errored", then
500        let dest = self
501            .writer
502            .get_stream()
503            .expect("Writer should still have a stream");
504        if dest.is_errored() {
505            rooted!(&in(cx) let mut dest_error = UndefinedValue());
506            dest.get_stored_error(dest_error.handle_mut());
507            self.set_shutdown_error(dest_error.handle());
508
509            // If preventCancel is false,
510            if !self.prevent_cancel {
511                // shutdown with an action of ! ReadableStreamCancel(source, dest.[[storedError]])
512                // and with dest.[[storedError]].
513                self.shutdown(cx, global, Some(ShutdownAction::ReadableStreamCancel))
514            } else {
515                // Otherwise, shutdown with dest.[[storedError]].
516                self.shutdown(cx, global, None);
517            }
518        }
519    }
520
521    /// Closing must be propagated forward part of
522    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
523    fn check_and_propagate_closing_forward(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
524        // An early return is necessary if we are shutting down,
525        // because in that case the source can already have been set to none.
526        if self.shutting_down.get() {
527            return;
528        }
529
530        // if source.[[state]] is or becomes "closed", then
531        let source = self
532            .reader
533            .get_stream()
534            .expect("Reader should still have a stream");
535        if source.is_closed() {
536            // If preventClose is false,
537            if !self.prevent_close {
538                // shutdown with an action of ! WritableStreamAbort(dest, source.[[storedError]])
539                // and with source.[[storedError]].
540                self.shutdown(
541                    cx,
542                    global,
543                    Some(ShutdownAction::WritableStreamDefaultWriterCloseWithErrorPropagation),
544                )
545            } else {
546                // Otherwise, shutdown.
547                self.shutdown(cx, global, None);
548            }
549        }
550    }
551
552    /// Closing must be propagated backward part of
553    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
554    fn check_and_propagate_closing_backward(&self, cx: &mut CurrentRealm, global: &GlobalScope) {
555        // An early return is necessary if we are shutting down,
556        // because in that case the destination can already have been set to none.
557        if self.shutting_down.get() {
558            return;
559        }
560
561        // if ! WritableStreamCloseQueuedOrInFlight(dest) is true
562        // or dest.[[state]] is "closed"
563        let dest = self
564            .writer
565            .get_stream()
566            .expect("Writer should still have a stream");
567        if dest.close_queued_or_in_flight() || dest.is_closed() {
568            // Assert: no chunks have been read or written.
569            // Note: unclear how to perform this assertion.
570
571            // Let destClosed be a new TypeError.
572            rooted!(&in(cx) let mut dest_closed = UndefinedValue());
573            let error =
574                Error::Type(c"Destination is closed or has closed queued or in flight".to_owned());
575            error.to_jsval(cx, global, dest_closed.handle_mut());
576            self.set_shutdown_error(dest_closed.handle());
577
578            // If preventCancel is false,
579            if !self.prevent_cancel {
580                // shutdown with an action of ! ReadableStreamCancel(source, destClosed)
581                // and with destClosed.
582                self.shutdown(cx, global, Some(ShutdownAction::ReadableStreamCancel))
583            } else {
584                // Otherwise, shutdown with destClosed.
585                self.shutdown(cx, global, None);
586            }
587        }
588    }
589
590    /// <https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action>
591    /// <https://streams.spec.whatwg.org/#rs-pipeTo-shutdown>
592    /// Combined into one method with an optional action.
593    fn shutdown(
594        &self,
595        cx: &mut CurrentRealm,
596        global: &GlobalScope,
597        action: Option<ShutdownAction>,
598    ) {
599        // If shuttingDown is true, abort these substeps.
600        // Set shuttingDown to true.
601        if !self.shutting_down.replace(true) {
602            let dest = self.writer.get_stream().expect("Stream must be set");
603            // If dest.[[state]] is "writable",
604            // and ! WritableStreamCloseQueuedOrInFlight(dest) is false,
605            if dest.is_writable() && !dest.close_queued_or_in_flight() {
606                // If any chunks have been read but not yet written, write them to dest.
607                // Done at the top of `Callback`.
608
609                // Wait until every chunk that has been read has been written
610                // (i.e. the corresponding promises have settled).
611                if let Some(write) = self.pending_writes.borrow().front() {
612                    *self.state.borrow_mut() = PipeToState::ShuttingDownWithPendingWrites(action);
613                    self.wait_on_pending_write(cx, global, write);
614                    return;
615                }
616            }
617
618            // Note: error is stored in `self.shutdown_error`.
619            if let Some(action) = action {
620                // Let p be the result of performing action.
621                self.perform_action(cx, global, action);
622            } else {
623                // Finalize, passing along error if it was given.
624                self.finalize(cx, global);
625            }
626        }
627    }
628
629    /// The perform action part of
630    /// <https://streams.spec.whatwg.org/#rs-pipeTo-shutdown-with-action>
631    fn perform_action(&self, cx: &mut CurrentRealm, global: &GlobalScope, action: ShutdownAction) {
632        rooted!(&in(cx) let mut error = UndefinedValue());
633        if let Some(shutdown_error) = self.shutdown_error.borrow().as_ref() {
634            error.set(shutdown_error.get());
635        }
636
637        *self.state.borrow_mut() = PipeToState::ShuttingDownPendingAction;
638
639        // Let p be the result of performing action.
640        let promise = match action {
641            ShutdownAction::WritableStreamAbort => {
642                let dest = self.writer.get_stream().expect("Stream must be set");
643                dest.abort(cx, global, error.handle())
644            },
645            ShutdownAction::ReadableStreamCancel => {
646                let source = self
647                    .reader
648                    .get_stream()
649                    .expect("Reader should have a stream.");
650                source.cancel(cx, global, error.handle())
651            },
652            ShutdownAction::WritableStreamDefaultWriterCloseWithErrorPropagation => {
653                self.writer.close_with_error_propagation(cx, global)
654            },
655            ShutdownAction::Abort => {
656                // Note: implementation of the `abortAlgorithm`
657                // of the signal associated with this piping operation.
658
659                // Let error be signal’s abort reason.
660                rooted!(&in(cx) let mut error = UndefinedValue());
661                error.set(self.abort_reason.get());
662
663                // Let actions be an empty ordered set.
664                let mut actions = vec![];
665
666                // If preventAbort is false, append the following action to actions:
667                if !self.prevent_abort {
668                    let dest = self
669                        .writer
670                        .get_stream()
671                        .expect("Destination stream must be set");
672
673                    // If dest.[[state]] is "writable",
674                    let promise = if dest.is_writable() {
675                        // return ! WritableStreamAbort(dest, error)
676                        dest.abort(cx, global, error.handle())
677                    } else {
678                        // Otherwise, return a promise resolved with undefined.
679                        Promise::new_resolved(cx, global, ())
680                    };
681                    actions.push(promise);
682                }
683
684                // If preventCancel is false, append the following action action to actions:
685                if !self.prevent_cancel {
686                    let source = self.reader.get_stream().expect("Source stream must be set");
687
688                    // If source.[[state]] is "readable",
689                    let promise = if source.is_readable() {
690                        // return ! ReadableStreamCancel(source, error).
691                        source.cancel(cx, global, error.handle())
692                    } else {
693                        // Otherwise, return a promise resolved with undefined.
694                        Promise::new_resolved(cx, global, ())
695                    };
696                    actions.push(promise);
697                }
698
699                // Shutdown with an action consisting
700                // of getting a promise to wait for all of the actions in actions,
701                // and with error.
702                wait_for_all_promise(cx, global, actions)
703            },
704        };
705
706        // Upon fulfillment of p, finalize, passing along originalError if it was given.
707        // Upon rejection of p with reason newError, finalize with newError.
708        let handler = PromiseNativeHandler::new(
709            cx,
710            global,
711            Some(Box::new(self.clone())),
712            Some(Box::new(self.clone())),
713        );
714        promise.append_native_handler(cx, &handler);
715        *self.shutdown_action_promise.borrow_mut() = Some(promise.to_traced());
716    }
717
718    /// <https://streams.spec.whatwg.org/#rs-pipeTo-finalize>
719    fn finalize(&self, cx: &mut JSContext, global: &GlobalScope) {
720        *self.state.borrow_mut() = PipeToState::Finalized;
721
722        // Perform ! WritableStreamDefaultWriterRelease(writer).
723        self.writer.release(cx, global);
724
725        // If reader implements ReadableStreamBYOBReader,
726        // perform ! ReadableStreamBYOBReaderRelease(reader).
727        // TODO.
728
729        // Otherwise, perform ! ReadableStreamDefaultReaderRelease(reader).
730        self.reader
731            .release(cx)
732            .expect("Releasing the reader should not fail");
733
734        // If signal is not undefined, remove abortAlgorithm from signal.
735        // Note: since `self.shutdown` is true at this point,
736        // the abort algorithm is a no-op,
737        // so for now not implementing this step.
738
739        if let Some(shutdown_error) = self.shutdown_error.borrow().as_ref() {
740            rooted!(&in(cx) let mut error = UndefinedValue());
741            error.set(shutdown_error.get());
742            // If error was given, reject promise with error.
743            self.result_promise.reject_native(cx, &error.handle());
744        } else {
745            // Otherwise, resolve promise with undefined.
746            self.result_promise.resolve_native(cx, &());
747        }
748    }
749}
750
751/// The fulfillment handler for the reacting to sourceCancelPromise part of
752/// <https://streams.spec.whatwg.org/#readable-stream-cancel>.
753#[derive(Clone, JSTraceable, MallocSizeOf)]
754#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
755struct SourceCancelPromiseFulfillmentHandler {
756    result: TracedPromise,
757}
758
759impl SourceCancelPromiseFulfillmentHandler {
760    fn new(promise: &RootedPromise) -> Box<Self> {
761        Box::new(Self {
762            result: promise.to_traced(),
763        })
764    }
765}
766
767impl Callback for SourceCancelPromiseFulfillmentHandler {
768    /// The fulfillment handler for the reacting to sourceCancelPromise part of
769    /// <https://streams.spec.whatwg.org/#readable-stream-cancel>.
770    /// An implementation of <https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled>
771    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
772        self.result.resolve_native(cx, &());
773    }
774}
775
776/// The rejection handler for the reacting to sourceCancelPromise part of
777/// <https://streams.spec.whatwg.org/#readable-stream-cancel>.
778#[derive(Clone, JSTraceable, MallocSizeOf)]
779#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
780struct SourceCancelPromiseRejectionHandler {
781    result: TracedPromise,
782}
783
784impl SourceCancelPromiseRejectionHandler {
785    fn new(promise: &RootedPromise) -> Box<Self> {
786        Box::new(Self {
787            result: promise.to_traced(),
788        })
789    }
790}
791
792impl Callback for SourceCancelPromiseRejectionHandler {
793    /// The rejection handler for the reacting to sourceCancelPromise part of
794    /// <https://streams.spec.whatwg.org/#readable-stream-cancel>.
795    /// An implementation of <https://webidl.spec.whatwg.org/#dfn-perform-steps-once-promise-is-settled>
796    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
797        self.result.reject_native(cx, &v);
798    }
799}
800
801/// <https://streams.spec.whatwg.org/#readablestream-state>
802#[derive(Clone, Copy, Debug, Default, JSTraceable, MallocSizeOf, PartialEq)]
803pub(crate) enum ReadableStreamState {
804    #[default]
805    Readable,
806    Closed,
807    Errored,
808}
809
810/// <https://streams.spec.whatwg.org/#readablestream-controller>
811#[derive(JSTraceable, MallocSizeOf)]
812#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
813pub(crate) enum ControllerType {
814    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller>
815    Byte(MutNullableDom<ReadableByteStreamController>),
816    /// <https://streams.spec.whatwg.org/#readablestreamdefaultcontroller>
817    Default(MutNullableDom<ReadableStreamDefaultController>),
818}
819
820/// <https://streams.spec.whatwg.org/#readablestream-readerr>
821#[derive(JSTraceable, MallocSizeOf)]
822#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
823pub(crate) enum ReaderType {
824    /// <https://streams.spec.whatwg.org/#readablestreambyobreader>
825    #[allow(clippy::upper_case_acronyms)]
826    BYOB(MutNullableDom<ReadableStreamBYOBReader>),
827    /// <https://streams.spec.whatwg.org/#readablestreamdefaultreader>
828    Default(MutNullableDom<ReadableStreamDefaultReader>),
829}
830
831impl js::gc::Rootable for ReaderType {}
832
833impl Eq for ReaderType {}
834impl PartialEq for ReaderType {
835    fn eq(&self, other: &Self) -> bool {
836        matches!(
837            (self, other),
838            (ReaderType::BYOB(_), ReaderType::BYOB(_)) |
839                (ReaderType::Default(_), ReaderType::Default(_))
840        )
841    }
842}
843
844/// <https://streams.spec.whatwg.org/#create-readable-stream>
845pub(crate) fn create_readable_stream(
846    cx: &mut JSContext,
847    global: &GlobalScope,
848    underlying_source_type: UnderlyingSourceType,
849    queuing_strategy: Option<RootedCallback<QueuingStrategySize>>,
850    high_water_mark: Option<f64>,
851) -> DomRoot<ReadableStream> {
852    // If highWaterMark was not passed, set it to 1.
853    let high_water_mark = high_water_mark.unwrap_or(1.0);
854
855    // If sizeAlgorithm was not passed, set it to an algorithm that returns 1.
856    let size_algorithm =
857        queuing_strategy.unwrap_or(extract_size_algorithm(cx, &QueuingStrategy::empty()));
858
859    // Assert: ! IsNonNegativeNumber(highWaterMark) is true.
860    assert!(high_water_mark >= 0.0);
861
862    // Let stream be a new ReadableStream.
863    // Perform ! InitializeReadableStream(stream).
864    let stream = ReadableStream::new_with_proto(cx, global, None);
865
866    // Let controller be a new ReadableStreamDefaultController.
867    let controller = ReadableStreamDefaultController::new(
868        cx,
869        global,
870        underlying_source_type,
871        high_water_mark,
872        size_algorithm,
873    );
874
875    // Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm,
876    // pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
877    controller
878        .setup(cx, &stream)
879        .expect("Setup of default controller cannot fail");
880
881    // Return stream.
882    stream
883}
884
885/// <https://streams.spec.whatwg.org/#abstract-opdef-createreadablebytestream>
886fn readable_byte_stream_tee(
887    cx: &mut JSContext,
888    global: &GlobalScope,
889    underlying_source_type: UnderlyingSourceType,
890) -> DomRoot<ReadableStream> {
891    // Let stream be a new ReadableStream.
892    // Perform ! InitializeReadableStream(stream).
893    let tee_stream = ReadableStream::new_with_proto(cx, global, None);
894
895    // Let controller be a new ReadableByteStreamController.
896    let controller = ReadableByteStreamController::new(cx, underlying_source_type, 0.0, global);
897
898    // Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, 0, undefined).
899    controller
900        .setup(cx, global, &tee_stream)
901        .expect("Setup of byte stream controller cannot fail");
902
903    // Return stream.
904    tee_stream
905}
906
907/// <https://streams.spec.whatwg.org/#rs-class>
908#[dom_struct]
909pub(crate) struct ReadableStream {
910    reflector_: Reflector,
911
912    /// <https://streams.spec.whatwg.org/#readablestream-controller>
913    /// Note: the inner `MutNullableDom` should really be an `Option<Dom>`,
914    /// because it is never unset once set.
915    controller: RefCell<Option<ControllerType>>,
916
917    /// <https://streams.spec.whatwg.org/#readablestream-storederror>
918    #[ignore_malloc_size_of = "mozjs"]
919    stored_error: Heap<JSVal>,
920
921    /// <https://streams.spec.whatwg.org/#readablestream-disturbed>
922    disturbed: Cell<bool>,
923
924    /// <https://streams.spec.whatwg.org/#readablestream-reader>
925    reader: RefCell<Option<ReaderType>>,
926
927    /// <https://streams.spec.whatwg.org/#readablestream-state>
928    state: Cell<ReadableStreamState>,
929}
930
931impl ReadableStream {
932    /// <https://streams.spec.whatwg.org/#initialize-readable-stream>
933    fn new_inherited() -> ReadableStream {
934        ReadableStream {
935            reflector_: Reflector::new(),
936            controller: RefCell::new(None),
937            stored_error: Heap::default(),
938            disturbed: Default::default(),
939            reader: RefCell::new(None),
940            state: Cell::new(Default::default()),
941        }
942    }
943
944    pub(crate) fn new_with_proto(
945        cx: &mut JSContext,
946        global: &GlobalScope,
947        proto: Option<SafeHandleObject>,
948    ) -> DomRoot<ReadableStream> {
949        reflect_dom_object_with_proto(cx, Box::new(ReadableStream::new_inherited()), global, proto)
950    }
951
952    /// Used as part of
953    /// <https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller>
954    pub(crate) fn set_default_controller(&self, controller: &ReadableStreamDefaultController) {
955        *self.controller.borrow_mut() = Some(ControllerType::Default(MutNullableDom::new(Some(
956            controller,
957        ))));
958    }
959
960    /// Used as part of
961    /// <https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller>
962    pub(crate) fn set_byte_controller(&self, controller: &ReadableByteStreamController) {
963        *self.controller.borrow_mut() =
964            Some(ControllerType::Byte(MutNullableDom::new(Some(controller))));
965    }
966
967    /// Used as part of
968    /// <https://streams.spec.whatwg.org/#set-up-readable-stream-default-controller>
969    pub(crate) fn assert_no_controller(&self) {
970        let has_no_controller = self.controller.borrow().is_none();
971        assert!(has_no_controller);
972    }
973
974    /// Build a stream backed by a Rust source that has already been read into memory.
975    pub(crate) fn new_from_bytes(
976        cx: &mut JSContext,
977        global: &GlobalScope,
978        bytes: Vec<u8>,
979    ) -> Fallible<DomRoot<ReadableStream>> {
980        let stream = ReadableStream::new_with_external_underlying_source(
981            cx,
982            global,
983            UnderlyingSourceType::Memory(bytes.len()),
984        )?;
985        stream.enqueue_native(cx, bytes);
986        stream.controller_close_native(cx);
987        Ok(stream)
988    }
989
990    /// Build an empty stream.
991    /// Used as step 2 of <https://fetch.spec.whatwg.org/#dom-body-textstream>
992    pub(crate) fn new_empty(
993        cx: &mut JSContext,
994        global: &GlobalScope,
995    ) -> Fallible<DomRoot<ReadableStream>> {
996        // Step 1. Let emptyStream be a new ReadableStream in this’s relevant realm.
997        // Step 2. Set up emptyStream.
998        let empty_stream = ReadableStream::new_with_external_underlying_source(
999            cx,
1000            global,
1001            UnderlyingSourceType::Memory(0),
1002        )?;
1003        // Step 3. Close emptyStream.
1004        empty_stream.controller_close_native(cx);
1005        // Step 4. Return emptyStream.
1006        Ok(empty_stream)
1007    }
1008
1009    /// <https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support>
1010    pub(crate) fn new_from_bytes_with_byte_reading_support(
1011        cx: &mut JSContext,
1012        global: &GlobalScope,
1013        bytes: Vec<u8>,
1014    ) -> Fallible<DomRoot<ReadableStream>> {
1015        let stream = ReadableStream::new_with_external_underlying_byte_source(
1016            cx,
1017            global,
1018            UnderlyingSourceType::Memory(bytes.len()),
1019        )?;
1020        stream.enqueue_native(cx, bytes);
1021        stream.controller_close_native(cx);
1022        Ok(stream)
1023    }
1024
1025    /// Build a stream backed by a Rust underlying source.
1026    /// Note: external sources are always paired with a default controller.
1027    pub(crate) fn new_with_external_underlying_source(
1028        cx: &mut JSContext,
1029        global: &GlobalScope,
1030        source: UnderlyingSourceType,
1031    ) -> Fallible<DomRoot<ReadableStream>> {
1032        assert!(source.is_native());
1033        let stream = ReadableStream::new_with_proto(cx, global, None);
1034        let strategy_size = extract_size_algorithm(cx, &QueuingStrategy::empty());
1035        let controller =
1036            ReadableStreamDefaultController::new(cx, global, source, 1.0, strategy_size);
1037        controller.setup(cx, &stream)?;
1038        Ok(stream)
1039    }
1040
1041    /// <https://streams.spec.whatwg.org/#readablestream-set-up-with-byte-reading-support>
1042    pub(crate) fn new_with_external_underlying_byte_source(
1043        cx: &mut JSContext,
1044        global: &GlobalScope,
1045        source: UnderlyingSourceType,
1046    ) -> Fallible<DomRoot<ReadableStream>> {
1047        assert!(source.is_native());
1048        let stream = ReadableStream::new_with_proto(cx, global, None);
1049        let controller = ReadableByteStreamController::new(cx, source, 0.0, global);
1050        controller.setup(cx, global, &stream)?;
1051        Ok(stream)
1052    }
1053
1054    /// Call into the release steps of the controller,
1055    pub(crate) fn perform_release_steps(&self) -> Fallible<()> {
1056        match self.controller.borrow().as_ref() {
1057            Some(ControllerType::Default(controller)) => {
1058                let controller = controller
1059                    .get()
1060                    .ok_or_else(|| Error::Type(c"Stream should have controller.".to_owned()))?;
1061                controller.perform_release_steps()
1062            },
1063            Some(ControllerType::Byte(controller)) => {
1064                let controller = controller
1065                    .get()
1066                    .ok_or_else(|| Error::Type(c"Stream should have controller.".to_owned()))?;
1067                controller.perform_release_steps()
1068            },
1069            None => Err(Error::Type(c"Stream should have controller.".to_owned())),
1070        }
1071    }
1072
1073    /// Call into the pull steps of the controller,
1074    /// as part of
1075    /// <https://streams.spec.whatwg.org/#readable-stream-default-reader-read>
1076    pub(crate) fn perform_pull_steps(&self, cx: &mut JSContext, read_request: &ReadRequest) {
1077        match self.controller.borrow().as_ref() {
1078            Some(ControllerType::Default(controller)) => controller
1079                .get()
1080                .expect("Stream should have controller.")
1081                .perform_pull_steps(cx, read_request),
1082            Some(ControllerType::Byte(controller)) => controller
1083                .get()
1084                .expect("Stream should have controller.")
1085                .perform_pull_steps(cx, read_request),
1086            None => {
1087                unreachable!("Stream does not have a controller.");
1088            },
1089        }
1090    }
1091
1092    /// Call into the pull steps of the controller,
1093    /// as part of
1094    /// <https://streams.spec.whatwg.org/#readable-stream-byob-reader-read>
1095    pub(crate) fn perform_pull_into(
1096        &self,
1097        cx: &mut JSContext,
1098        read_into_request: &ReadIntoRequest,
1099        view: &HeapBufferSource<ArrayBufferViewU8>,
1100        min: u64,
1101    ) {
1102        match self.controller.borrow().as_ref() {
1103            Some(ControllerType::Byte(controller)) => controller
1104                .get()
1105                .expect("Stream should have controller.")
1106                .perform_pull_into(cx, read_into_request, view, min),
1107            _ => {
1108                unreachable!(
1109                    "Pulling a chunk from a stream with a default controller using a BYOB reader"
1110                )
1111            },
1112        }
1113    }
1114
1115    /// <https://streams.spec.whatwg.org/#readable-stream-add-read-request>
1116    pub(crate) fn add_read_request(&self, read_request: &ReadRequest) {
1117        match self.reader.borrow().as_ref() {
1118            Some(ReaderType::Default(reader)) => {
1119                let Some(reader) = reader.get() else {
1120                    panic!("Attempt to add a read request without having first acquired a reader.");
1121                };
1122
1123                // Assert: stream.[[state]] is "readable".
1124                assert!(self.is_readable());
1125
1126                // Append readRequest to stream.[[reader]].[[readRequests]].
1127                reader.add_read_request(read_request);
1128            },
1129            _ => {
1130                unreachable!("Adding a read request can only be done on a default reader.")
1131            },
1132        }
1133    }
1134
1135    /// <https://streams.spec.whatwg.org/#readable-stream-add-read-into-request>
1136    pub(crate) fn add_read_into_request(&self, read_request: &ReadIntoRequest) {
1137        match self.reader.borrow().as_ref() {
1138            // Assert: stream.[[reader]] implements ReadableStreamBYOBReader.
1139            Some(ReaderType::BYOB(reader)) => {
1140                let Some(reader) = reader.get() else {
1141                    unreachable!(
1142                        "Attempt to add a read into request without having first acquired a reader."
1143                    );
1144                };
1145
1146                // Assert: stream.[[state]] is "readable" or "closed".
1147                assert!(self.is_readable() || self.is_closed());
1148
1149                // Append readRequest to stream.[[reader]].[[readIntoRequests]].
1150                reader.add_read_into_request(read_request);
1151            },
1152            _ => {
1153                unreachable!("Adding a read into request can only be done on a BYOB reader.")
1154            },
1155        }
1156    }
1157
1158    /// <https://streams.spec.whatwg.org/#readablestream-enqueue>
1159    pub(crate) fn enqueue_native(&self, cx: &mut JSContext, bytes: Vec<u8>) {
1160        match self.controller.borrow().as_ref() {
1161            Some(ControllerType::Default(controller)) => controller
1162                .get()
1163                .expect("Stream should have controller.")
1164                .enqueue_native(cx, bytes),
1165            Some(ControllerType::Byte(controller)) => {
1166                if bytes.is_empty() {
1167                    return;
1168                }
1169
1170                let controller = controller.get().expect("Stream should have controller.");
1171                rooted!(&in(cx) let mut chunk_object = ptr::null_mut::<JSObject>());
1172                create_buffer_source::<Uint8>(cx, &bytes, chunk_object.handle_mut())
1173                    .expect("failed to create buffer source for native byte chunk.");
1174
1175                let chunk = RootedTraceableBox::new(HeapBufferSource::<ArrayBufferViewU8>::new(
1176                    chunk_object.handle(),
1177                ));
1178                controller
1179                    .enqueue(cx, chunk)
1180                    .expect("Enqueuing a native byte chunk should not fail.");
1181            },
1182            _ => {
1183                unreachable!("Enqueueing chunk to a stream from Rust without a controller");
1184            },
1185        }
1186    }
1187
1188    /// <https://streams.spec.whatwg.org/#readable-stream-error>
1189    pub(crate) fn error(&self, cx: &mut JSContext, e: SafeHandleValue) {
1190        // Assert: stream.[[state]] is "readable".
1191        assert!(self.is_readable());
1192
1193        // Set stream.[[state]] to "errored".
1194        self.state.set(ReadableStreamState::Errored);
1195
1196        // Set stream.[[storedError]] to e.
1197        self.stored_error.set(e.get());
1198
1199        // Let reader be stream.[[reader]].
1200
1201        let default_reader = {
1202            let reader_ref = self.reader.borrow();
1203            match reader_ref.as_ref() {
1204                Some(ReaderType::Default(reader)) => reader.get(),
1205                _ => None,
1206            }
1207        };
1208
1209        if let Some(reader) = default_reader {
1210            // Perform ! ReadableStreamDefaultReaderErrorReadRequests(reader, e).
1211            reader.error(cx, e);
1212            return;
1213        }
1214
1215        let byob_reader = {
1216            let reader_ref = self.reader.borrow();
1217            match reader_ref.as_ref() {
1218                Some(ReaderType::BYOB(reader)) => reader.get(),
1219                _ => None,
1220            }
1221        };
1222
1223        if let Some(reader) = byob_reader {
1224            // Perform ! ReadableStreamBYOBReaderErrorReadIntoRequests(reader, e).
1225            reader.error_read_into_requests(cx, e);
1226        }
1227
1228        // If reader is undefined, return.
1229    }
1230
1231    /// <https://streams.spec.whatwg.org/#readablestream-storederror>
1232    pub(crate) fn get_stored_error(&self, mut handle_mut: SafeMutableHandleValue) {
1233        handle_mut.set(self.stored_error.get());
1234    }
1235
1236    /// <https://streams.spec.whatwg.org/#readable-stream-error>
1237    /// Note: in other use cases this call happens via the controller.
1238    pub(crate) fn error_native(&self, cx: &mut JSContext, error: Error) {
1239        rooted!(&in(cx) let mut error_val = UndefinedValue());
1240        error.to_jsval(cx, &self.global(), error_val.handle_mut());
1241        self.error(cx, error_val.handle());
1242    }
1243
1244    /// Call into the controller's `Close` method.
1245    /// <https://streams.spec.whatwg.org/#readablestream-close>
1246    pub(crate) fn controller_close_native(&self, cx: &mut JSContext) {
1247        match self.controller.borrow().as_ref() {
1248            Some(ControllerType::Default(controller)) => {
1249                let _ = controller
1250                    .get()
1251                    .expect("Stream should have controller.")
1252                    .Close(cx);
1253            },
1254            Some(ControllerType::Byte(controller)) => {
1255                let controller = controller.get().expect("Stream should have controller.");
1256                // Step 1.1. Perform ! ReadableByteStreamControllerClose(stream.[[controller]]).
1257                let _ = controller.close(cx);
1258                // Step 1.2. If stream.[[controller]].[[pendingPullIntos]] is not empty, perform !
1259                // ReadableByteStreamControllerRespond(stream.[[controller]], 0).
1260                if self.is_closed() && controller.get_pending_pull_intos_size() > 0 {
1261                    let _ = controller.respond(cx, 0);
1262                }
1263            },
1264            _ => {
1265                unreachable!("Native closing requires a stream controller.")
1266            },
1267        }
1268    }
1269
1270    /// Returns a boolean reflecting whether the stream has all data in memory.
1271    /// Useful for native source integration only.
1272    pub(crate) fn in_memory(&self) -> bool {
1273        match self.controller.borrow().as_ref() {
1274            Some(ControllerType::Default(controller)) => controller
1275                .get()
1276                .expect("Stream should have controller.")
1277                .in_memory(),
1278            Some(ControllerType::Byte(controller)) => controller
1279                .get()
1280                .expect("Stream should have controller.")
1281                .in_memory(),
1282            _ => unreachable!("Checking if source is in memory for a stream without a controller"),
1283        }
1284    }
1285
1286    /// Return bytes for synchronous use, if the stream has all data in memory.
1287    /// Useful for native source integration only.
1288    pub(crate) fn get_in_memory_bytes(&self, cx: &mut JSContext) -> Option<GenericSharedMemory> {
1289        match self.controller.borrow().as_ref() {
1290            Some(ControllerType::Default(controller)) => controller
1291                .get()
1292                .expect("Stream should have controller.")
1293                .get_in_memory_bytes()
1294                .map(GenericSharedMemory::from_vec),
1295            Some(ControllerType::Byte(controller)) => controller
1296                .get()
1297                .expect("Stream should have controller.")
1298                .get_in_memory_bytes(cx)
1299                .map(GenericSharedMemory::from_vec),
1300            _ => unreachable!("Getting in-memory bytes for a stream without a controller"),
1301        }
1302    }
1303
1304    /// Acquires a reader and locks the stream,
1305    /// must be done before `read_a_chunk`.
1306    /// Native call to
1307    /// <https://streams.spec.whatwg.org/#acquire-readable-stream-reader>
1308    pub(crate) fn acquire_default_reader(
1309        &self,
1310        cx: &mut JSContext,
1311    ) -> Fallible<DomRoot<ReadableStreamDefaultReader>> {
1312        // Let reader be a new ReadableStreamDefaultReader.
1313        let reader = ReadableStreamDefaultReader::new(cx, &self.global());
1314
1315        // Perform ? SetUpReadableStreamDefaultReader(reader, stream).
1316        reader.set_up(cx, self, &self.global())?;
1317
1318        // Return reader.
1319        Ok(reader)
1320    }
1321
1322    /// <https://streams.spec.whatwg.org/#acquire-readable-stream-byob-reader>
1323    pub(crate) fn acquire_byob_reader(
1324        &self,
1325        cx: &mut JSContext,
1326    ) -> Fallible<DomRoot<ReadableStreamBYOBReader>> {
1327        // Let reader be a new ReadableStreamBYOBReader.
1328        let reader = ReadableStreamBYOBReader::new(cx, &self.global());
1329        // Perform ? SetUpReadableStreamBYOBReader(reader, stream).
1330        reader.set_up(cx, self, &self.global())?;
1331
1332        // Return reader.
1333        Ok(reader)
1334    }
1335
1336    pub(crate) fn get_default_controller(&self) -> DomRoot<ReadableStreamDefaultController> {
1337        match self.controller.borrow().as_ref() {
1338            Some(ControllerType::Default(controller)) => {
1339                controller.get().expect("Stream should have controller.")
1340            },
1341            _ => {
1342                unreachable!(
1343                    "Getting default controller for a stream with a non-default controller"
1344                )
1345            },
1346        }
1347    }
1348
1349    pub(crate) fn get_byte_controller(&self) -> DomRoot<ReadableByteStreamController> {
1350        match self.controller.borrow().as_ref() {
1351            Some(ControllerType::Byte(controller)) => {
1352                controller.get().expect("Stream should have controller.")
1353            },
1354            _ => {
1355                unreachable!("Getting byte controller for a stream with a non-byte controller")
1356            },
1357        }
1358    }
1359
1360    pub(crate) fn get_default_reader(&self) -> DomRoot<ReadableStreamDefaultReader> {
1361        match self.reader.borrow().as_ref() {
1362            Some(ReaderType::Default(reader)) => reader.get().expect("Stream should have reader."),
1363            _ => {
1364                unreachable!("Getting default reader for a stream with a non-default reader")
1365            },
1366        }
1367    }
1368
1369    /// Read a chunk from the stream,
1370    /// must be called after `start_reading`,
1371    /// and before `stop_reading`.
1372    /// Native call to
1373    /// <https://streams.spec.whatwg.org/#readable-stream-default-reader-read>
1374    pub(crate) fn read_a_chunk(&self, cx: &mut JSContext) -> RootedPromise {
1375        match self.reader.borrow().as_ref() {
1376            Some(ReaderType::Default(reader)) => {
1377                let Some(reader) = reader.get() else {
1378                    unreachable!(
1379                        "Attempt to read stream chunk without having first acquired a reader."
1380                    );
1381                };
1382                reader.Read(cx)
1383            },
1384            _ => {
1385                unreachable!("Native reading of a chunk can only be done with a default reader.")
1386            },
1387        }
1388    }
1389
1390    /// Releases the lock on the reader,
1391    /// must be done after `start_reading`.
1392    /// Native call to
1393    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaultreaderrelease>
1394    pub(crate) fn stop_reading(&self, cx: &mut JSContext) {
1395        let reader_ref = self.reader.borrow();
1396
1397        match reader_ref.as_ref() {
1398            Some(ReaderType::Default(reader)) => {
1399                let Some(reader) = reader.get() else {
1400                    unreachable!("Attempt to stop reading without having first acquired a reader.");
1401                };
1402
1403                drop(reader_ref);
1404                reader.release(cx).expect("Reader release cannot fail.");
1405            },
1406            _ => {
1407                unreachable!("Native stop reading can only be done with a default reader.")
1408            },
1409        }
1410    }
1411
1412    /// <https://streams.spec.whatwg.org/#is-readable-stream-locked>
1413    pub(crate) fn is_locked(&self) -> bool {
1414        match self.reader.borrow().as_ref() {
1415            Some(ReaderType::Default(reader)) => reader.get().is_some(),
1416            Some(ReaderType::BYOB(reader)) => reader.get().is_some(),
1417            None => false,
1418        }
1419    }
1420
1421    pub(crate) fn is_disturbed(&self) -> bool {
1422        self.disturbed.get()
1423    }
1424
1425    pub(crate) fn set_is_disturbed(&self, disturbed: bool) {
1426        self.disturbed.set(disturbed);
1427    }
1428
1429    pub(crate) fn is_closed(&self) -> bool {
1430        self.state.get() == ReadableStreamState::Closed
1431    }
1432
1433    pub(crate) fn is_errored(&self) -> bool {
1434        self.state.get() == ReadableStreamState::Errored
1435    }
1436
1437    pub(crate) fn is_readable(&self) -> bool {
1438        self.state.get() == ReadableStreamState::Readable
1439    }
1440
1441    pub(crate) fn has_default_reader(&self) -> bool {
1442        match self.reader.borrow().as_ref() {
1443            Some(ReaderType::Default(reader)) => reader.get().is_some(),
1444            _ => false,
1445        }
1446    }
1447
1448    pub(crate) fn has_byob_reader(&self) -> bool {
1449        match self.reader.borrow().as_ref() {
1450            Some(ReaderType::BYOB(reader)) => reader.get().is_some(),
1451            _ => false,
1452        }
1453    }
1454
1455    pub(crate) fn has_byte_controller(&self) -> bool {
1456        match self.controller.borrow().as_ref() {
1457            Some(ControllerType::Byte(controller)) => controller.get().is_some(),
1458            _ => false,
1459        }
1460    }
1461
1462    /// <https://streams.spec.whatwg.org/#readable-stream-get-num-read-requests>
1463    pub(crate) fn get_num_read_requests(&self) -> usize {
1464        match self.reader.borrow().as_ref() {
1465            Some(ReaderType::Default(reader)) => {
1466                let reader = reader
1467                    .get()
1468                    .expect("Stream must have a reader when getting the number of read requests.");
1469                reader.get_num_read_requests()
1470            },
1471            _ => unreachable!(
1472                "Stream must have a default reader when get num read requests is called into."
1473            ),
1474        }
1475    }
1476
1477    /// <https://streams.spec.whatwg.org/#readable-stream-get-num-read-into-requests>
1478    pub(crate) fn get_num_read_into_requests(&self) -> usize {
1479        assert!(self.has_byob_reader());
1480
1481        match self.reader.borrow().as_ref() {
1482            Some(ReaderType::BYOB(reader)) => {
1483                let Some(reader) = reader.get() else {
1484                    unreachable!(
1485                        "Stream must have a reader when get num read into requests is called into."
1486                    );
1487                };
1488                reader.get_num_read_into_requests()
1489            },
1490            _ => {
1491                unreachable!(
1492                    "Stream must have a BYOB reader when get num read into requests is called into."
1493                );
1494            },
1495        }
1496    }
1497
1498    /// <https://streams.spec.whatwg.org/#readable-stream-fulfill-read-request>
1499    pub(crate) fn fulfill_read_request(
1500        &self,
1501        cx: &mut JSContext,
1502        chunk: SafeHandleValue,
1503        done: bool,
1504    ) {
1505        // step 1 - Assert: ! ReadableStreamHasDefaultReader(stream) is true.
1506        assert!(self.has_default_reader());
1507
1508        match self.reader.borrow().as_ref() {
1509            Some(ReaderType::Default(reader)) => {
1510                // step 2 - Let reader be stream.[[reader]].
1511                let reader = reader
1512                    .get()
1513                    .expect("Stream must have a reader when a read request is fulfilled.");
1514                // step 3 - Assert: reader.[[readRequests]] is not empty.
1515                assert_ne!(reader.get_num_read_requests(), 0);
1516                // step 4 & 5
1517                // Let readRequest be reader.[[readRequests]][0]. & Remove readRequest from reader.[[readRequests]].
1518                rooted!(&in(cx) let request = reader.remove_read_request());
1519
1520                if done {
1521                    // step 6 - If done is true, perform readRequest’s close steps.
1522                    request.close_steps(cx);
1523                } else {
1524                    // step 7 - Otherwise, perform readRequest’s chunk steps, given chunk.
1525                    let result = RootedTraceableBox::new(Heap::default());
1526                    result.set(*chunk);
1527                    request.chunk_steps(cx, result, &self.global());
1528                }
1529            },
1530            _ => {
1531                unreachable!(
1532                    "Stream must have a default reader when fulfill read requests is called into."
1533                );
1534            },
1535        }
1536    }
1537
1538    /// <https://streams.spec.whatwg.org/#readable-stream-fulfill-read-into-request>
1539    pub(crate) fn fulfill_read_into_request(
1540        &self,
1541        cx: &mut JSContext,
1542        chunk: SafeHandleValue,
1543        done: bool,
1544    ) {
1545        // Assert: ! ReadableStreamHasBYOBReader(stream) is true.
1546        assert!(self.has_byob_reader());
1547
1548        // Let reader be stream.[[reader]].
1549        match self.reader.borrow().as_ref() {
1550            Some(ReaderType::BYOB(reader)) => {
1551                let Some(reader) = reader.get() else {
1552                    unreachable!(
1553                        "Stream must have a reader when a read into request is fulfilled."
1554                    );
1555                };
1556
1557                // Assert: reader.[[readIntoRequests]] is not empty.
1558                assert!(reader.get_num_read_into_requests() > 0);
1559
1560                // Let readIntoRequest be reader.[[readIntoRequests]][0].
1561                // Remove readIntoRequest from reader.[[readIntoRequests]].
1562                rooted!(&in(cx) let read_into_request = reader.remove_read_into_request());
1563
1564                // If done is true, perform readIntoRequest’s close steps, given chunk.
1565                let result = RootedTraceableBox::new(Heap::default());
1566                if done {
1567                    result.set(*chunk);
1568                    read_into_request.close_steps(cx, Some(result));
1569                } else {
1570                    // Otherwise, perform readIntoRequest’s chunk steps, given chunk.
1571                    result.set(*chunk);
1572                    read_into_request.chunk_steps(cx, result);
1573                }
1574            },
1575            _ => {
1576                unreachable!(
1577                    "Stream must have a BYOB reader when fulfill read into requests is called into."
1578                );
1579            },
1580        };
1581    }
1582
1583    /// <https://streams.spec.whatwg.org/#readable-stream-close>
1584    pub(crate) fn close(&self, cx: &mut JSContext) {
1585        // Assert: stream.[[state]] is "readable".
1586        assert!(self.is_readable());
1587        // Set stream.[[state]] to "closed".
1588        self.state.set(ReadableStreamState::Closed);
1589        // Let reader be stream.[[reader]].
1590
1591        // NOTE: do not hold the RefCell borrow across reader.close(),
1592        // or release() will panic when it tries to mut-borrow stream.reader.
1593        // So we pull out the underlying DOM reader in a local, then drop the borrow.
1594        let default_reader = {
1595            let reader_ref = self.reader.borrow();
1596            match reader_ref.as_ref() {
1597                Some(ReaderType::Default(reader)) => reader.get(),
1598                _ => None,
1599            }
1600        };
1601
1602        if let Some(reader) = default_reader {
1603            // steps 5 & 6 for a default reader
1604            reader.close(cx);
1605            return;
1606        }
1607
1608        // Same for BYOB reader.
1609        let byob_reader = {
1610            let reader_ref = self.reader.borrow();
1611            match reader_ref.as_ref() {
1612                Some(ReaderType::BYOB(reader)) => reader.get(),
1613                _ => None,
1614            }
1615        };
1616
1617        if let Some(reader) = byob_reader {
1618            // steps 5 & 6 for a BYOB reader
1619            reader.close(cx);
1620        }
1621
1622        // If reader is undefined, return.
1623    }
1624
1625    /// <https://streams.spec.whatwg.org/#readable-stream-cancel>
1626    pub(crate) fn cancel(
1627        &self,
1628        cx: &mut JSContext,
1629        global: &GlobalScope,
1630        reason: SafeHandleValue,
1631    ) -> RootedPromise {
1632        // Set stream.[[disturbed]] to true.
1633        self.disturbed.set(true);
1634
1635        // If stream.[[state]] is "closed", return a promise resolved with undefined.
1636        if self.is_closed() {
1637            return Promise::new_resolved(cx, global, ());
1638        }
1639        // If stream.[[state]] is "errored", return a promise rejected with stream.[[storedError]].
1640        if self.is_errored() {
1641            let promise = Promise::new(cx, global);
1642            rooted!(&in(cx) let mut rval = UndefinedValue());
1643            self.stored_error.to_jsval(cx, rval.handle_mut());
1644            promise.reject_native(cx, &rval.handle());
1645            return promise;
1646        }
1647        // Perform ! ReadableStreamClose(stream).
1648        self.close(cx);
1649
1650        // If reader is not undefined and reader implements ReadableStreamBYOBReader,
1651        let byob_reader = {
1652            let reader_ref = self.reader.borrow();
1653            match reader_ref.as_ref() {
1654                Some(ReaderType::BYOB(reader)) => reader.get(),
1655                _ => None,
1656            }
1657        };
1658
1659        if let Some(reader) = byob_reader {
1660            // step 6.1, 6.2 & 6.3 of https://streams.spec.whatwg.org/#readable-stream-cancel
1661            reader.cancel(cx);
1662        }
1663
1664        // Let sourceCancelPromise be ! stream.[[controller]].[[CancelSteps]](reason).
1665
1666        let source_cancel_promise = match self.controller.borrow().as_ref() {
1667            Some(ControllerType::Default(controller)) => controller
1668                .get()
1669                .expect("Stream should have controller.")
1670                .perform_cancel_steps(cx, global, reason),
1671            Some(ControllerType::Byte(controller)) => controller
1672                .get()
1673                .expect("Stream should have controller.")
1674                .perform_cancel_steps(cx, global, reason),
1675            None => {
1676                panic!("Stream does not have a controller.");
1677            },
1678        };
1679
1680        // Create a new promise,
1681        // and setup a handler in order to react to the fulfillment of sourceCancelPromise.
1682        let global = self.global();
1683        let result_promise = Promise::new(cx, &global);
1684        rooted!(&in(cx) let mut fulfillment_handler = Some(SourceCancelPromiseFulfillmentHandler::new(&result_promise)));
1685        rooted!(&in(cx) let mut rejection_handler = Some(SourceCancelPromiseRejectionHandler::new(&result_promise)));
1686        let handler = PromiseNativeHandler::new(
1687            cx,
1688            &global,
1689            fulfillment_handler
1690                .take()
1691                .map(|handler| handler as Box<dyn Callback>),
1692            rejection_handler
1693                .take()
1694                .map(|handler| handler as Box<dyn Callback>),
1695        );
1696        let mut realm = enter_auto_realm(cx, &*global);
1697        let cx = &mut realm.current_realm();
1698        source_cancel_promise.append_native_handler(cx, &handler);
1699
1700        // Return the result of reacting to sourceCancelPromise
1701        // with a fulfillment step that returns undefined.
1702        result_promise
1703    }
1704
1705    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
1706    pub(crate) fn set_reader(&self, new_reader: Option<ReaderType>) {
1707        *self.reader.borrow_mut() = new_reader;
1708    }
1709
1710    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
1711    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamtee>
1712    fn byte_tee(&self, cx: &mut JSContext) -> Fallible<Vec<DomRoot<ReadableStream>>> {
1713        // Assert: stream implements ReadableStream.
1714        // Assert: stream.[[controller]] implements ReadableByteStreamController.
1715
1716        // Let reader be ? AcquireReadableStreamDefaultReader(stream).
1717        let reader = self.acquire_default_reader(cx)?;
1718        let reader = Rc::new(RefCell::new(ReaderType::Default(MutNullableDom::new(
1719            Some(&reader),
1720        ))));
1721
1722        // Let reading be false.
1723        let reading = Rc::new(Cell::new(false));
1724
1725        // Let readAgainForBranch1 be false.
1726        let read_again_for_branch_1 = Rc::new(Cell::new(false));
1727
1728        // Let readAgainForBranch2 be false.
1729        let read_again_for_branch_2 = Rc::new(Cell::new(false));
1730
1731        // Let canceled1 be false.
1732        let canceled_1 = Rc::new(Cell::new(false));
1733
1734        // Let canceled2 be false.
1735        let canceled_2 = Rc::new(Cell::new(false));
1736
1737        // Let reason1 be undefined.
1738        let reason_1 = Rc::new(Heap::default());
1739
1740        // Let reason2 be undefined.
1741        let reason_2 = Rc::new(Heap::default());
1742
1743        // Let cancelPromise be a new promise.
1744        let cancel_promise = Promise::new(cx, &self.global());
1745        let reader_version = Rc::new(Cell::new(0));
1746
1747        let byte_tee_source_1 = ByteTeeUnderlyingSource::new(
1748            cx,
1749            reader.clone(),
1750            self,
1751            reading.clone(),
1752            read_again_for_branch_1.clone(),
1753            read_again_for_branch_2.clone(),
1754            canceled_1.clone(),
1755            canceled_2.clone(),
1756            reason_1.clone(),
1757            reason_2.clone(),
1758            &cancel_promise,
1759            reader_version.clone(),
1760            ByteTeeCancelAlgorithm::Cancel1Algorithm,
1761            ByteTeePullAlgorithm::Pull1Algorithm,
1762        );
1763
1764        let byte_tee_source_2 = ByteTeeUnderlyingSource::new(
1765            cx,
1766            reader.clone(),
1767            self,
1768            reading,
1769            read_again_for_branch_1,
1770            read_again_for_branch_2,
1771            canceled_1,
1772            canceled_2,
1773            reason_1,
1774            reason_2,
1775            &cancel_promise,
1776            reader_version,
1777            ByteTeeCancelAlgorithm::Cancel2Algorithm,
1778            ByteTeePullAlgorithm::Pull2Algorithm,
1779        );
1780
1781        // Set branch1 to ! CreateReadableByteStream(startAlgorithm, pull1Algorithm, cancel1Algorithm).
1782        let branch_1 = readable_byte_stream_tee(
1783            cx,
1784            &self.global(),
1785            UnderlyingSourceType::TeeByte(&byte_tee_source_1),
1786        );
1787        byte_tee_source_1.set_branch_1(&branch_1);
1788        byte_tee_source_2.set_branch_1(&branch_1);
1789
1790        // Set branch2 to ! CreateReadableByteStream(startAlgorithm, pull2Algorithm, cancel2Algorithm).
1791        let branch_2 = readable_byte_stream_tee(
1792            cx,
1793            &self.global(),
1794            UnderlyingSourceType::TeeByte(&byte_tee_source_2),
1795        );
1796        byte_tee_source_1.set_branch_2(&branch_2);
1797        byte_tee_source_2.set_branch_2(&branch_2);
1798
1799        // Perform forwardReaderError, given reader.
1800        byte_tee_source_1.forward_reader_error(cx, reader.clone());
1801        byte_tee_source_2.forward_reader_error(cx, reader);
1802
1803        // Return « branch1, branch2 ».
1804        Ok(vec![branch_1, branch_2])
1805    }
1806
1807    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee>
1808    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
1809    fn default_tee(
1810        &self,
1811        cx: &mut JSContext,
1812        clone_for_branch_2: bool,
1813    ) -> Fallible<Vec<DomRoot<ReadableStream>>> {
1814        // Assert: stream implements ReadableStream.
1815
1816        // Assert: cloneForBranch2 is a boolean.
1817        let clone_for_branch_2 = Rc::new(Cell::new(clone_for_branch_2));
1818
1819        // Let reader be ? AcquireReadableStreamDefaultReader(stream).
1820        let reader = self.acquire_default_reader(cx)?;
1821
1822        // Let reading be false.
1823        let reading = Rc::new(Cell::new(false));
1824        // Let readAgain be false.
1825        let read_again = Rc::new(Cell::new(false));
1826        // Let canceled1 be false.
1827        let canceled_1 = Rc::new(Cell::new(false));
1828        // Let canceled2 be false.
1829        let canceled_2 = Rc::new(Cell::new(false));
1830
1831        // Let reason1 be undefined.
1832        let reason_1 = Rc::new(Heap::default());
1833        // Let reason2 be undefined.
1834        let reason_2 = Rc::new(Heap::default());
1835        // Let cancelPromise be a new promise.
1836        let cancel_promise = Promise::new(cx, &self.global());
1837
1838        let tee_source_1 = DefaultTeeUnderlyingSource::new(
1839            cx,
1840            &reader,
1841            self,
1842            reading.clone(),
1843            read_again.clone(),
1844            canceled_1.clone(),
1845            canceled_2.clone(),
1846            clone_for_branch_2.clone(),
1847            reason_1.clone(),
1848            reason_2.clone(),
1849            &cancel_promise,
1850            DefaultTeeCancelAlgorithm::Cancel1Algorithm,
1851        );
1852
1853        let underlying_source_type_branch_1 = UnderlyingSourceType::Tee(&tee_source_1);
1854
1855        let tee_source_2 = DefaultTeeUnderlyingSource::new(
1856            cx,
1857            &reader,
1858            self,
1859            reading,
1860            read_again,
1861            canceled_1.clone(),
1862            canceled_2.clone(),
1863            clone_for_branch_2,
1864            reason_1,
1865            reason_2,
1866            &cancel_promise,
1867            DefaultTeeCancelAlgorithm::Cancel2Algorithm,
1868        );
1869
1870        let underlying_source_type_branch_2 = UnderlyingSourceType::Tee(&tee_source_2);
1871
1872        // Set branch_1 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel1Algorithm).
1873        let branch_1 = create_readable_stream(
1874            cx,
1875            &self.global(),
1876            underlying_source_type_branch_1,
1877            None,
1878            None,
1879        );
1880        tee_source_1.set_branch_1(&branch_1);
1881        tee_source_2.set_branch_1(&branch_1);
1882
1883        // Set branch_2 to ! CreateReadableStream(startAlgorithm, pullAlgorithm, cancel2Algorithm).
1884        let branch_2 = create_readable_stream(
1885            cx,
1886            &self.global(),
1887            underlying_source_type_branch_2,
1888            None,
1889            None,
1890        );
1891        tee_source_1.set_branch_2(&branch_2);
1892        tee_source_2.set_branch_2(&branch_2);
1893
1894        // Upon rejection of reader.[[closedPromise]] with reason r,
1895        reader.default_tee_append_native_handler_to_closed_promise(
1896            cx,
1897            &branch_1,
1898            &branch_2,
1899            canceled_1,
1900            canceled_2,
1901            &cancel_promise,
1902        );
1903
1904        // Return « branch_1, branch_2 ».
1905        Ok(vec![branch_1, branch_2])
1906    }
1907
1908    /// <https://streams.spec.whatwg.org/#readable-stream-pipe-to>
1909    #[allow(clippy::too_many_arguments)]
1910    pub(crate) fn pipe_to(
1911        &self,
1912        cx: &mut CurrentRealm,
1913        global: &GlobalScope,
1914        dest: &WritableStream,
1915        prevent_close: bool,
1916        prevent_abort: bool,
1917        prevent_cancel: bool,
1918        signal: Option<&AbortSignal>,
1919    ) -> RootedPromise {
1920        // Assert: source implements ReadableStream.
1921        // Assert: dest implements WritableStream.
1922        // Assert: prevent_close, prevent_abort, and prevent_cancel are all booleans.
1923        // Done with method signature types.
1924
1925        // If signal was not given, let signal be undefined.
1926        // Assert: either signal is undefined, or signal implements AbortSignal.
1927        // Note: done with the `signal` argument.
1928
1929        // Assert: ! IsReadableStreamLocked(source) is false.
1930        assert!(!self.is_locked());
1931
1932        // Assert: ! IsWritableStreamLocked(dest) is false.
1933        assert!(!dest.is_locked());
1934
1935        // If source.[[controller]] implements ReadableByteStreamController,
1936        // let reader be either ! AcquireReadableStreamBYOBReader(source)
1937        // or ! AcquireReadableStreamDefaultReader(source),
1938        // at the user agent’s discretion.
1939        // Note: for now only using default readers.
1940
1941        // Otherwise, let reader be ! AcquireReadableStreamDefaultReader(source).
1942        let reader = self
1943            .acquire_default_reader(cx)
1944            .expect("Acquiring a default reader for pipe_to cannot fail");
1945
1946        // Let writer be ! AcquireWritableStreamDefaultWriter(dest).
1947        let writer = dest
1948            .aquire_default_writer(cx, global)
1949            .expect("Acquiring a default writer for pipe_to cannot fail");
1950
1951        // Set source.[[disturbed]] to true.
1952        self.disturbed.set(true);
1953
1954        // Let shuttingDown be false.
1955        // Done below with default.
1956
1957        // Let promise be a new promise.
1958        let promise = Promise::new(cx, global);
1959
1960        // In parallel, but not really, using reader and writer, read all chunks from source and write them to dest.
1961        rooted!(&in(cx) let pipe_to = PipeTo {
1962            reader: Dom::from_ref(&reader),
1963            writer: Dom::from_ref(&writer),
1964            pending_writes: Default::default(),
1965            state: Default::default(),
1966            prevent_abort,
1967            prevent_cancel,
1968            prevent_close,
1969            shutting_down: Default::default(),
1970            abort_reason: Default::default(),
1971            shutdown_error: Default::default(),
1972            shutdown_action_promise:  Default::default(),
1973            result_promise: promise.to_traced(),
1974        });
1975
1976        // If signal is not undefined,
1977        // Note: moving the steps to here, so that the `PipeTo` is available.
1978        if let Some(signal) = signal {
1979            // Let abortAlgorithm be the following steps:
1980            // Note: steps are implemented at call site.
1981            rooted!(&in(cx) let abort_algorithm = AbortAlgorithm::StreamPiping(pipe_to.clone()));
1982
1983            // If signal is aborted, perform abortAlgorithm and return promise.
1984            if signal.aborted() {
1985                signal.run_abort_algorithm(cx, global, &abort_algorithm);
1986                return promise;
1987            }
1988
1989            // Add abortAlgorithm to signal.
1990            signal.add(&abort_algorithm);
1991        }
1992
1993        // Note: perfom checks now, since streams can start as closed or errored.
1994        pipe_to.check_and_propagate_errors_forward(cx, global);
1995        pipe_to.check_and_propagate_errors_backward(cx, global);
1996        pipe_to.check_and_propagate_closing_forward(cx, global);
1997        pipe_to.check_and_propagate_closing_backward(cx, global);
1998
1999        // If we are not closed or errored,
2000        if *pipe_to.state.borrow() == PipeToState::Starting {
2001            // Start the pipe, by waiting on the writer being ready for a chunk.
2002            pipe_to.wait_for_writer_ready(cx, global);
2003        }
2004
2005        // Return promise.
2006        promise
2007    }
2008
2009    /// <https://streams.spec.whatwg.org/#readable-stream-tee>
2010    pub(crate) fn tee(
2011        &self,
2012        cx: &mut JSContext,
2013        clone_for_branch_2: bool,
2014    ) -> Fallible<Vec<DomRoot<ReadableStream>>> {
2015        // Assert: stream implements ReadableStream.
2016        // Assert: cloneForBranch2 is a boolean.
2017
2018        match self.controller.borrow().as_ref() {
2019            Some(ControllerType::Default(_)) => {
2020                // Return ? ReadableStreamDefaultTee(stream, cloneForBranch2).
2021                self.default_tee(cx, clone_for_branch_2)
2022            },
2023            Some(ControllerType::Byte(_)) => {
2024                // If stream.[[controller]] implements ReadableByteStreamController,
2025                // return ? ReadableByteStreamTee(stream).
2026                self.byte_tee(cx)
2027            },
2028            None => {
2029                unreachable!("Stream should have a controller.");
2030            },
2031        }
2032    }
2033
2034    /// <https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller-from-underlying-source>
2035    fn set_up_byte_controller(
2036        &self,
2037        cx: &mut JSContext,
2038        global: &GlobalScope,
2039        underlying_source_dict: &JsUnderlyingSource,
2040        underlying_source_handle: SafeHandleObject,
2041        stream: &ReadableStream,
2042        strategy_hwm: f64,
2043    ) -> Fallible<()> {
2044        // Let pullAlgorithm be an algorithm that returns a promise resolved with undefined.
2045        // Let cancelAlgorithm be an algorithm that returns a promise resolved with undefined.
2046        // If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result
2047        // of invoking underlyingSourceDict["start"] with argument list « controller »
2048        // and callback this value underlyingSource.
2049        // If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result
2050        // of invoking underlyingSourceDict["pull"] with argument list « controller »
2051        // and callback this value underlyingSource.
2052        // If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an
2053        // argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list
2054        // « reason » and callback this value underlyingSource.
2055
2056        // Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"],
2057        // if it exists, or undefined otherwise.
2058        // If autoAllocateChunkSize is 0, then throw a TypeError exception.
2059        if let Some(0) = underlying_source_dict.autoAllocateChunkSize {
2060            return Err(Error::Type(c"autoAllocateChunkSize cannot be 0".to_owned()));
2061        }
2062
2063        let controller = ReadableByteStreamController::new(
2064            cx,
2065            UnderlyingSourceType::Js(underlying_source_dict),
2066            strategy_hwm,
2067            global,
2068        );
2069
2070        // Note: this must be done before `setup`,
2071        // otherwise `thisOb` is null in the start callback.
2072        controller.set_underlying_source_this_object(underlying_source_handle);
2073
2074        // Perform ? SetUpReadableByteStreamController(stream, controller, startAlgorithm,
2075        // pullAlgorithm, cancelAlgorithm, highWaterMark, autoAllocateChunkSize).
2076        controller.setup(cx, global, stream)
2077    }
2078
2079    /// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
2080    pub(crate) fn setup_cross_realm_transform_readable(
2081        &self,
2082        cx: &mut JSContext,
2083        port: &MessagePort,
2084    ) {
2085        let port_id = port.message_port_id();
2086        let global = self.global();
2087
2088        // Perform ! InitializeReadableStream(stream).
2089        // Done in `new_inherited`.
2090
2091        // Let sizeAlgorithm be an algorithm that returns 1.
2092        let size_algorithm = extract_size_algorithm(cx, &QueuingStrategy::default());
2093
2094        // Note: other algorithms defined in the underlying source container.
2095
2096        // Let controller be a new ReadableStreamDefaultController.
2097        let controller = ReadableStreamDefaultController::new(
2098            cx,
2099            &self.global(),
2100            UnderlyingSourceType::Transfer(port),
2101            0.,
2102            size_algorithm,
2103        );
2104
2105        // Add a handler for port’s message event with the following steps:
2106        // Add a handler for port’s messageerror event with the following steps:
2107        rooted!(&in(cx) let cross_realm_transform_readable = CrossRealmTransformReadable {
2108            controller: Dom::from_ref(&controller),
2109        });
2110        global.note_cross_realm_transform_readable(&cross_realm_transform_readable, port_id);
2111
2112        // Enable port’s port message queue.
2113        port.Start(cx);
2114
2115        // Perform ! SetUpReadableStreamDefaultController
2116        controller
2117            .setup(cx, self)
2118            .expect("Setting up controller for transfer cannot fail.");
2119    }
2120}
2121
2122impl ReadableStreamMethods<crate::DomTypeHolder> for ReadableStream {
2123    /// <https://streams.spec.whatwg.org/#rs-constructor>
2124    fn Constructor(
2125        cx: &mut JSContext,
2126        global: &GlobalScope,
2127        proto: Option<SafeHandleObject>,
2128        underlying_source: Option<*mut JSObject>,
2129        strategy: &QueuingStrategy,
2130    ) -> Fallible<DomRoot<Self>> {
2131        // If underlyingSource is missing, set it to null.
2132        rooted!(&in(cx) let underlying_source_obj = underlying_source.unwrap_or(ptr::null_mut()));
2133        // Let underlyingSourceDict be underlyingSource,
2134        // converted to an IDL value of type UnderlyingSource.
2135        let underlying_source_dict = if !underlying_source_obj.is_null() {
2136            rooted!(&in(cx) let obj_val = ObjectValue(underlying_source_obj.get()));
2137            match JsUnderlyingSource::new(cx, obj_val.handle()) {
2138                Ok(ConversionResult::Success(val)) => val,
2139                Ok(ConversionResult::Failure(error)) => {
2140                    return Err(Error::Type(error.into_owned()));
2141                },
2142                _ => {
2143                    return Err(Error::JSFailed);
2144                },
2145            }
2146        } else {
2147            JsUnderlyingSource::empty()
2148        };
2149
2150        // Perform ! InitializeReadableStream(this).
2151        let stream = ReadableStream::new_with_proto(cx, global, proto);
2152
2153        if underlying_source_dict.type_.is_some() {
2154            // If strategy["size"] exists, throw a RangeError exception.
2155            if strategy.size.is_some() {
2156                return Err(Error::Range(
2157                    c"size is not supported for byte streams".to_owned(),
2158                ));
2159            }
2160
2161            // Let highWaterMark be ? ExtractHighWaterMark(strategy, 0).
2162            let strategy_hwm = extract_high_water_mark(strategy, 0.0)?;
2163
2164            // Perform ? SetUpReadableByteStreamControllerFromUnderlyingSource(this,
2165            // underlyingSource, underlyingSourceDict, highWaterMark).
2166            stream.set_up_byte_controller(
2167                cx,
2168                global,
2169                &underlying_source_dict,
2170                underlying_source_obj.handle(),
2171                &stream,
2172                strategy_hwm,
2173            )?;
2174        } else {
2175            // Let highWaterMark be ? ExtractHighWaterMark(strategy, 1).
2176            let high_water_mark = extract_high_water_mark(strategy, 1.0)?;
2177
2178            // Let sizeAlgorithm be ! ExtractSizeAlgorithm(strategy).
2179            let size_algorithm = extract_size_algorithm(cx, strategy);
2180
2181            let controller = ReadableStreamDefaultController::new(
2182                cx,
2183                global,
2184                UnderlyingSourceType::Js(&underlying_source_dict),
2185                high_water_mark,
2186                size_algorithm,
2187            );
2188
2189            // Note: this must be done before `setup`,
2190            // otherwise `thisOb` is null in the start callback.
2191            controller.set_underlying_source_this_object(underlying_source_obj.handle());
2192
2193            // Perform ? SetUpReadableStreamDefaultControllerFromUnderlyingSource
2194            controller.setup(cx, &stream)?;
2195        };
2196
2197        Ok(stream)
2198    }
2199
2200    /// <https://streams.spec.whatwg.org/#rs-locked>
2201    fn Locked(&self) -> bool {
2202        self.is_locked()
2203    }
2204
2205    /// <https://streams.spec.whatwg.org/#rs-cancel>
2206    fn Cancel(&self, cx: &mut JSContext, reason: SafeHandleValue) -> RootedPromise {
2207        let global = self.global();
2208        if self.is_locked() {
2209            // If ! IsReadableStreamLocked(this) is true,
2210            // return a promise rejected with a TypeError exception.
2211            let promise = Promise::new(cx, &global);
2212            promise.reject_error(cx, Error::Type(c"stream is locked".to_owned()));
2213            promise
2214        } else {
2215            // Return ! ReadableStreamCancel(this, reason).
2216            self.cancel(cx, &global, reason)
2217        }
2218    }
2219
2220    /// <https://streams.spec.whatwg.org/#rs-get-reader>
2221    fn GetReader(
2222        &self,
2223        cx: &mut JSContext,
2224        options: &ReadableStreamGetReaderOptions,
2225    ) -> Fallible<ReadableStreamReader> {
2226        // 1, If options["mode"] does not exist, return ? AcquireReadableStreamDefaultReader(this).
2227        if options.mode.is_none() {
2228            return Ok(ReadableStreamReader::ReadableStreamDefaultReader(
2229                self.acquire_default_reader(cx)?,
2230            ));
2231        }
2232        // 2. Assert: options["mode"] is "byob".
2233        assert!(options.mode.unwrap() == ReadableStreamReaderMode::Byob);
2234
2235        // 3. Return ? AcquireReadableStreamBYOBReader(this).
2236        Ok(ReadableStreamReader::ReadableStreamBYOBReader(
2237            self.acquire_byob_reader(cx)?,
2238        ))
2239    }
2240
2241    /// <https://streams.spec.whatwg.org/#rs-tee>
2242    fn Tee(&self, cx: &mut JSContext) -> Fallible<Vec<DomRoot<ReadableStream>>> {
2243        // Return ? ReadableStreamTee(this, false).
2244        self.tee(cx, false)
2245    }
2246
2247    /// <https://streams.spec.whatwg.org/#rs-pipe-to>
2248    fn PipeTo(
2249        &self,
2250        cx: &mut CurrentRealm,
2251        destination: &WritableStream,
2252        options: &StreamPipeOptions,
2253    ) -> RootedPromise {
2254        let global = self.global();
2255
2256        // If ! IsReadableStreamLocked(this) is true,
2257        if self.is_locked() {
2258            // return a promise rejected with a TypeError exception.
2259            let promise = Promise::new(cx, &global);
2260            promise.reject_error(cx, Error::Type(c"Source stream is locked".to_owned()));
2261            return promise;
2262        }
2263
2264        // If ! IsWritableStreamLocked(destination) is true,
2265        if destination.is_locked() {
2266            // return a promise rejected with a TypeError exception.
2267            let promise = Promise::new(cx, &global);
2268            promise.reject_error(cx, Error::Type(c"Destination stream is locked".to_owned()));
2269            return promise;
2270        }
2271
2272        // Let signal be options["signal"] if it exists, or undefined otherwise.
2273        let signal = options.signal.as_deref();
2274
2275        // Return ! ReadableStreamPipeTo.
2276        self.pipe_to(
2277            cx,
2278            &global,
2279            destination,
2280            options.preventClose,
2281            options.preventAbort,
2282            options.preventCancel,
2283            signal,
2284        )
2285    }
2286
2287    /// <https://streams.spec.whatwg.org/#rs-pipe-through>
2288    fn PipeThrough(
2289        &self,
2290        cx: &mut CurrentRealm,
2291        transform: &ReadableWritablePair,
2292        options: &StreamPipeOptions,
2293    ) -> Fallible<DomRoot<ReadableStream>> {
2294        let global = self.global();
2295
2296        // If ! IsReadableStreamLocked(this) is true, throw a TypeError exception.
2297        if self.is_locked() {
2298            return Err(Error::Type(c"Source stream is locked".to_owned()));
2299        }
2300
2301        // If ! IsWritableStreamLocked(transform["writable"]) is true, throw a TypeError exception.
2302        if transform.writable.is_locked() {
2303            return Err(Error::Type(c"Destination stream is locked".to_owned()));
2304        }
2305
2306        // Let signal be options["signal"] if it exists, or undefined otherwise.
2307        let signal = options.signal.as_deref();
2308
2309        // Let promise be ! ReadableStreamPipeTo(this, transform["writable"],
2310        // options["preventClose"], options["preventAbort"], options["preventCancel"], signal).
2311        let promise = self.pipe_to(
2312            cx,
2313            &global,
2314            &transform.writable,
2315            options.preventClose,
2316            options.preventAbort,
2317            options.preventCancel,
2318            signal,
2319        );
2320
2321        // Set promise.[[PromiseIsHandled]] to true.
2322        promise.set_promise_is_handled(cx);
2323
2324        // Return transform["readable"].
2325        Ok(transform.readable.as_rooted())
2326    }
2327}
2328
2329/// The initial steps for the message handler for both readable and writable cross realm transforms.
2330/// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
2331/// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
2332pub(crate) fn get_type_and_value_from_message(
2333    cx: &mut JSContext,
2334    data: SafeHandleValue,
2335    value: SafeMutableHandleValue,
2336) -> DOMString {
2337    // Let data be the data of the message.
2338    // Note: we are passed the data as argument,
2339    // which originates in the return value of `structuredclone::read`.
2340
2341    // Assert: data is an Object.
2342    assert!(data.is_object());
2343    rooted!(&in(cx) let data_object = data.to_object());
2344
2345    // Let type be ! Get(data, "type").
2346    let type_ = get_property::<DOMString>(
2347        cx,
2348        data_object.handle(),
2349        c"type",
2350        StringificationBehavior::Empty,
2351    );
2352
2353    // Let value be ! Get(data, "value").
2354    get_property_jsval(cx, data_object.handle(), c"value", value)
2355        .expect("Getting the value should not fail.");
2356
2357    // Assert: type is a String.
2358    type_
2359        .expect("The type of the message should be a string")
2360        .expect("Property should be present")
2361}
2362
2363impl js::gc::Rootable for CrossRealmTransformReadable {}
2364
2365/// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
2366/// A wrapper to handle `message` and `messageerror` events
2367/// for the port used by the transfered stream.
2368#[derive(Clone, JSTraceable, MallocSizeOf)]
2369#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
2370pub(crate) struct CrossRealmTransformReadable {
2371    /// The controller used in the algorithm.
2372    controller: Dom<ReadableStreamDefaultController>,
2373}
2374
2375impl CrossRealmTransformReadable {
2376    /// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformreadable>
2377    /// Add a handler for port’s message event with the following steps:
2378    pub(crate) fn handle_message(
2379        &self,
2380        cx: &mut CurrentRealm,
2381        global: &GlobalScope,
2382        port: &MessagePort,
2383        message: SafeHandleValue,
2384    ) {
2385        rooted!(&in(cx) let mut value = UndefinedValue());
2386        let type_string = get_type_and_value_from_message(cx, message, value.handle_mut());
2387
2388        // If type is "chunk",
2389        if type_string == "chunk" {
2390            // Perform ! ReadableStreamDefaultControllerEnqueue(controller, value).
2391            self.controller
2392                .enqueue(cx, value.handle())
2393                .expect("Enqueing a chunk should not fail.");
2394        }
2395
2396        // Otherwise, if type is "close",
2397        if type_string == "close" {
2398            // Perform ! ReadableStreamDefaultControllerClose(controller).
2399            self.controller.close(cx);
2400
2401            // Disentangle port.
2402            global.disentangle_port(cx, port);
2403        }
2404
2405        // Otherwise, if type is "error",
2406        if type_string == "error" {
2407            // Perform ! ReadableStreamDefaultControllerError(controller, value).
2408            self.controller.error(cx, value.handle());
2409
2410            // Disentangle port.
2411            global.disentangle_port(cx, port);
2412        }
2413    }
2414
2415    /// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
2416    /// Add a handler for port’s messageerror event with the following steps:
2417    pub(crate) fn handle_error(
2418        &self,
2419        cx: &mut CurrentRealm,
2420        global: &GlobalScope,
2421        port: &MessagePort,
2422    ) {
2423        // Let error be a new "DataCloneError" DOMException.
2424        let error = DOMException::new(cx, global, DOMErrorName::DataCloneError);
2425        rooted!(&in(cx) let mut rooted_error = UndefinedValue());
2426        error.to_jsval(cx, rooted_error.handle_mut());
2427
2428        // Perform ! CrossRealmTransformSendError(port, error).
2429        port.cross_realm_transform_send_error(cx, rooted_error.handle());
2430
2431        // Perform ! ReadableStreamDefaultControllerError(controller, error).
2432        self.controller.error(cx, rooted_error.handle());
2433
2434        // Disentangle port.
2435        global.disentangle_port(cx, port);
2436    }
2437}
2438
2439/// Get the `done` property of an object that a read promise resolved to.
2440pub(crate) fn get_read_promise_done(
2441    cx: &mut JSContext,
2442    v: &SafeHandleValue,
2443) -> Result<bool, Error> {
2444    if !v.is_object() {
2445        return Err(Error::Type(c"Unknown format for done property.".to_owned()));
2446    }
2447
2448    rooted!(&in(cx) let object = v.to_object());
2449    get_property::<bool>(cx, object.handle(), c"done", ())?
2450        .ok_or(Error::Type(c"Promise has no done property.".to_owned()))
2451}
2452
2453/// Get the `value` property of an object that a read promise resolved to.
2454pub(crate) fn get_read_promise_bytes(
2455    cx: &mut JSContext,
2456    v: &SafeHandleValue,
2457) -> Result<Vec<u8>, Error> {
2458    if !v.is_object() {
2459        return Err(Error::Type(
2460            c"Unknown format for for bytes read.".to_owned(),
2461        ));
2462    }
2463
2464    rooted!(&in(cx) let object = v.to_object());
2465    get_property::<Vec<u8>>(
2466        cx,
2467        object.handle(),
2468        c"value",
2469        ConversionBehavior::EnforceRange,
2470    )?
2471    .ok_or(Error::Type(c"Promise has no value property.".to_owned()))
2472}
2473
2474/// <https://streams.spec.whatwg.org/#rs-transfer>
2475impl Transferable for ReadableStream {
2476    type Index = MessagePortIndex;
2477    type Data = MessagePortImpl;
2478
2479    /// <https://streams.spec.whatwg.org/#ref-for-transfer-steps>
2480    fn transfer(&self, cx: &mut JSContext) -> Fallible<(MessagePortId, MessagePortImpl)> {
2481        // Step 1. If ! IsReadableStreamLocked(value) is true, throw a
2482        // "DataCloneError" DOMException.
2483        if self.is_locked() {
2484            return Err(Error::DataClone(None));
2485        }
2486
2487        let global = self.global();
2488        let mut realm = enter_auto_realm(cx, &*global);
2489        let mut realm = realm.current_realm();
2490        let cx = &mut realm;
2491
2492        // Step 2. Let port1 be a new MessagePort in the current Realm.
2493        let port_1 = MessagePort::new(cx, &global);
2494        global.track_message_port(&port_1, None);
2495
2496        // Step 3. Let port2 be a new MessagePort in the current Realm.
2497        let port_2 = MessagePort::new(cx, &global);
2498        global.track_message_port(&port_2, None);
2499
2500        // Step 4. Entangle port1 and port2.
2501        global.entangle_ports(*port_1.message_port_id(), *port_2.message_port_id());
2502
2503        // Step 5. Let writable be a new WritableStream in the current Realm.
2504        let writable = WritableStream::new_with_proto(cx, &global, None);
2505
2506        // Step 6. Perform ! SetUpCrossRealmTransformWritable(writable, port1).
2507        writable.setup_cross_realm_transform_writable(cx, &port_1);
2508
2509        // Step 7. Let promise be ! ReadableStreamPipeTo(value, writable, false, false, false).
2510        let promise = self.pipe_to(cx, &global, &writable, false, false, false, None);
2511
2512        // Step 8. Set promise.[[PromiseIsHandled]] to true.
2513        promise.set_promise_is_handled(cx);
2514
2515        // Step 9. Set dataHolder.[[port]] to ! StructuredSerializeWithTransfer(port2, « port2 »).
2516        port_2.transfer(cx)
2517    }
2518
2519    /// <https://streams.spec.whatwg.org/#ref-for-transfer-receiving-steps>
2520    fn transfer_receive(
2521        cx: &mut JSContext,
2522        owner: &GlobalScope,
2523        id: MessagePortId,
2524        port_impl: MessagePortImpl,
2525    ) -> Result<DomRoot<Self>, ()> {
2526        // Their transfer-receiving steps, given dataHolder and value, are:
2527        // Note: dataHolder is used in `structuredclone.rs`, and value is created here.
2528        let value = ReadableStream::new_with_proto(cx, owner, None);
2529
2530        // Step 1. Let deserializedRecord be !
2531        // StructuredDeserializeWithTransfer(dataHolder.[[port]], the current
2532        // Realm).
2533        // Done with the `Deserialize` derive of `MessagePortImpl`.
2534
2535        // Step 2. Let port be deserializedRecord.[[Deserialized]].
2536        let transferred_port = MessagePort::transfer_receive(cx, owner, id, port_impl)?;
2537
2538        // Step 3. Perform ! SetUpCrossRealmTransformReadable(value, port).
2539        value.setup_cross_realm_transform_readable(cx, &transferred_port);
2540        Ok(value)
2541    }
2542
2543    /// Note: we are relying on the port transfer, so the data returned here are related to the port.
2544    fn serialized_storage<'a>(
2545        data: StructuredData<'a, '_>,
2546    ) -> &'a mut Option<FxHashMap<MessagePortId, Self::Data>> {
2547        match data {
2548            StructuredData::Reader(r) => &mut r.port_impls,
2549            StructuredData::Writer(w) => &mut w.ports,
2550        }
2551    }
2552}
2553
2554/// <https://streams.spec.whatwg.org/#readablestream-pipe-through>
2555/// Pipe a ReadableStream through a transform and return the readable side.
2556/// Note: Unlike [`ReadableStream::PipeThrough`], this is not failliable.
2557///
2558/// Note: Spec says it takes same options as [`ReadableStream::PipeThrough`],
2559/// however all usages use default `false`.
2560pub(crate) fn pipe_through(
2561    source: &ReadableStream,
2562    cx: &mut JSContext,
2563    global: &GlobalScope,
2564    transform: &TextDecoderStream,
2565) -> DomRoot<ReadableStream> {
2566    // Step 1. Assert: `! IsReadableStreamLocked(readable)` is false.
2567
2568    // Step 2. Assert: `! IsWritableStreamLocked(transform.[[writable]])` is false.
2569
2570    // Above is done in `pipe_to` below.
2571    let mut realm = CurrentRealm::assert(cx);
2572    // Step 4. Let promise be ! ReadableStreamPipeTo(readable,
2573    // transform.[[writable]], preventClose, preventAbort, preventCancel, signalArg).
2574    let promise = source.pipe_to(
2575        &mut realm,
2576        global,
2577        &transform.Writable(),
2578        false, // preventClose
2579        false, // preventAbort
2580        false, // preventCancel
2581        None,  // signal
2582    );
2583
2584    // Step 5. Set promise.[[PromiseIsHandled]] to true.
2585    promise.set_promise_is_handled(cx);
2586    // Step 6. Return transform.[[readable]].
2587    transform.Readable()
2588}