script/dom/stream/
defaultteereadrequest.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
5use std::cell::Cell;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use js::jsapi::Heap;
10use js::jsval::{JSVal, UndefinedValue};
11use js::realm::AutoRealm;
12use js::rust::HandleValue as SafeHandleValue;
13
14use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
15use crate::dom::bindings::root::{Dom, DomRoot};
16use crate::dom::bindings::structuredclone;
17use crate::dom::bindings::trace::RootedTraceableBox;
18use crate::dom::globalscope::GlobalScope;
19use crate::dom::promise::Promise;
20use crate::dom::stream::defaultteeunderlyingsource::DefaultTeeUnderlyingSource;
21use crate::dom::stream::readablestream::ReadableStream;
22use crate::microtask::{Microtask, MicrotaskRunnable};
23use crate::realms::enter_auto_realm;
24use crate::script_runtime::CanGc;
25
26#[derive(JSTraceable, MallocSizeOf)]
27#[cfg_attr(crown, expect(crown::unrooted_must_root))]
28pub(crate) struct DefaultTeeReadRequestMicrotask {
29    #[ignore_malloc_size_of = "mozjs"]
30    chunk: Box<Heap<JSVal>>,
31    tee_read_request: Dom<DefaultTeeReadRequest>,
32}
33
34impl MicrotaskRunnable for DefaultTeeReadRequestMicrotask {
35    fn handler(&self, cx: &mut js::context::JSContext) {
36        self.tee_read_request.chunk_steps(cx, &self.chunk);
37    }
38
39    fn enter_realm<'cx>(&self, cx: &'cx mut js::context::JSContext) -> AutoRealm<'cx> {
40        enter_auto_realm(cx, &*self.tee_read_request)
41    }
42}
43
44#[dom_struct]
45/// <https://streams.spec.whatwg.org/#ref-for-read-request%E2%91%A2>
46pub(crate) struct DefaultTeeReadRequest {
47    reflector_: Reflector,
48    stream: Dom<ReadableStream>,
49    branch_1: Dom<ReadableStream>,
50    branch_2: Dom<ReadableStream>,
51    #[conditional_malloc_size_of]
52    reading: Rc<Cell<bool>>,
53    #[conditional_malloc_size_of]
54    read_again: Rc<Cell<bool>>,
55    #[conditional_malloc_size_of]
56    canceled_1: Rc<Cell<bool>>,
57    #[conditional_malloc_size_of]
58    canceled_2: Rc<Cell<bool>>,
59    #[conditional_malloc_size_of]
60    clone_for_branch_2: Rc<Cell<bool>>,
61    #[conditional_malloc_size_of]
62    cancel_promise: Rc<Promise>,
63    tee_underlying_source: Dom<DefaultTeeUnderlyingSource>,
64}
65impl DefaultTeeReadRequest {
66    #[expect(clippy::too_many_arguments)]
67    pub(crate) fn new(
68        stream: &ReadableStream,
69        branch_1: &ReadableStream,
70        branch_2: &ReadableStream,
71        reading: Rc<Cell<bool>>,
72        read_again: Rc<Cell<bool>>,
73        canceled_1: Rc<Cell<bool>>,
74        canceled_2: Rc<Cell<bool>>,
75        clone_for_branch_2: Rc<Cell<bool>>,
76        cancel_promise: Rc<Promise>,
77        tee_underlying_source: &DefaultTeeUnderlyingSource,
78        can_gc: CanGc,
79    ) -> DomRoot<Self> {
80        reflect_dom_object(
81            Box::new(DefaultTeeReadRequest {
82                reflector_: Reflector::new(),
83                stream: Dom::from_ref(stream),
84                branch_1: Dom::from_ref(branch_1),
85                branch_2: Dom::from_ref(branch_2),
86                reading,
87                read_again,
88                canceled_1,
89                canceled_2,
90                clone_for_branch_2,
91                cancel_promise,
92                tee_underlying_source: Dom::from_ref(tee_underlying_source),
93            }),
94            &*stream.global(),
95            can_gc,
96        )
97    }
98    /// Call into cancel of the stream,
99    /// <https://streams.spec.whatwg.org/#readable-stream-cancel>
100    pub(crate) fn stream_cancel(
101        &self,
102        cx: &mut js::context::JSContext,
103        global: &GlobalScope,
104        reason: SafeHandleValue,
105    ) {
106        self.stream.cancel(cx, global, reason);
107    }
108    /// Enqueue a microtask to perform the chunk steps
109    /// <https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps%E2%91%A2>
110    pub(crate) fn enqueue_chunk_steps(&self, chunk: RootedTraceableBox<Heap<JSVal>>) {
111        // Queue a microtask to perform the following steps:
112        let tee_read_request_chunk = DefaultTeeReadRequestMicrotask {
113            chunk: Heap::boxed(*chunk.handle()),
114            tee_read_request: Dom::from_ref(self),
115        };
116        self.stream
117            .global()
118            .enqueue_microtask(Microtask::ReadableStreamTeeReadRequest(
119                tee_read_request_chunk,
120            ));
121    }
122    /// <https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps%E2%91%A2>
123    #[expect(clippy::borrowed_box)]
124    pub(crate) fn chunk_steps(&self, cx: &mut js::context::JSContext, chunk: &Box<Heap<JSVal>>) {
125        let global = &self.stream.global();
126        // Set readAgain to false.
127        self.read_again.set(false);
128        // Let chunk1 and chunk2 be chunk.
129        let chunk1 = chunk;
130        let chunk2 = chunk;
131
132        rooted!(&in(cx) let chunk1_value = chunk1.get());
133        rooted!(&in(cx) let chunk2_value = chunk2.get());
134        // If canceled_2 is false and cloneForBranch2 is true,
135        if !self.canceled_2.get() && self.clone_for_branch_2.get() {
136            // Let cloneResult be StructuredClone(chunk2).
137            rooted!(&in(cx) let mut clone_result = UndefinedValue());
138            let data = structuredclone::write(cx.into(), chunk2_value.handle(), None).unwrap();
139            // If cloneResult is an abrupt completion,
140            if structuredclone::read(global, data, clone_result.handle_mut(), CanGc::from_cx(cx))
141                .is_err()
142            {
143                // Perform ! ReadableStreamDefaultControllerError(branch_1.[[controller]], cloneResult.[[Value]]).
144                self.readable_stream_default_controller_error(
145                    &self.branch_1,
146                    clone_result.handle(),
147                    CanGc::from_cx(cx),
148                );
149
150                // Perform ! ReadableStreamDefaultControllerError(branch_2.[[controller]], cloneResult.[[Value]]).
151                self.readable_stream_default_controller_error(
152                    &self.branch_2,
153                    clone_result.handle(),
154                    CanGc::from_cx(cx),
155                );
156                // Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
157                self.stream_cancel(cx, global, clone_result.handle());
158                // Return.
159                return;
160            } else {
161                // Otherwise, set chunk2 to cloneResult.[[Value]].
162                chunk2.set(*clone_result);
163            }
164        }
165        // If canceled_1 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch_1.[[controller]], chunk1).
166        if !self.canceled_1.get() {
167            self.readable_stream_default_controller_enqueue(
168                cx,
169                &self.branch_1,
170                chunk1_value.handle(),
171            );
172        }
173        // If canceled_2 is false, perform ! ReadableStreamDefaultControllerEnqueue(branch_2.[[controller]], chunk2).
174        if !self.canceled_2.get() {
175            self.readable_stream_default_controller_enqueue(
176                cx,
177                &self.branch_2,
178                chunk2_value.handle(),
179            );
180        }
181        // Set reading to false.
182        self.reading.set(false);
183        // If readAgain is true, perform pullAlgorithm.
184        if self.read_again.get() {
185            self.pull_algorithm(cx);
186        }
187    }
188    /// <https://streams.spec.whatwg.org/#read-request-close-steps>
189    pub(crate) fn close_steps(&self, can_gc: CanGc) {
190        // Set reading to false.
191        self.reading.set(false);
192        // If canceled_1 is false, perform ! ReadableStreamDefaultControllerClose(branch_1.[[controller]]).
193        if !self.canceled_1.get() {
194            self.readable_stream_default_controller_close(&self.branch_1, can_gc);
195        }
196        // If canceled_2 is false, perform ! ReadableStreamDefaultControllerClose(branch_2.[[controller]]).
197        if !self.canceled_2.get() {
198            self.readable_stream_default_controller_close(&self.branch_2, can_gc);
199        }
200        // If canceled_1 is false or canceled_2 is false, resolve cancelPromise with undefined.
201        if !self.canceled_1.get() || !self.canceled_2.get() {
202            self.cancel_promise.resolve_native(&(), can_gc);
203        }
204    }
205    /// <https://streams.spec.whatwg.org/#read-request-error-steps>
206    pub(crate) fn error_steps(&self) {
207        // Set reading to false.
208        self.reading.set(false);
209    }
210    /// Call into enqueue of the default controller of a stream,
211    /// <https://streams.spec.whatwg.org/#readable-stream-default-controller-enqueue>
212    fn readable_stream_default_controller_enqueue(
213        &self,
214        cx: &mut js::context::JSContext,
215        stream: &ReadableStream,
216        chunk: SafeHandleValue,
217    ) {
218        stream
219            .get_default_controller()
220            .enqueue(cx, chunk)
221            .expect("enqueue failed for stream controller in DefaultTeeReadRequest");
222    }
223
224    /// Call into close of the default controller of a stream,
225    /// <https://streams.spec.whatwg.org/#readable-stream-default-controller-close>
226    fn readable_stream_default_controller_close(&self, stream: &ReadableStream, can_gc: CanGc) {
227        stream.get_default_controller().close(can_gc);
228    }
229
230    /// Call into error of the default controller of stream,
231    /// <https://streams.spec.whatwg.org/#readable-stream-default-controller-error>
232    fn readable_stream_default_controller_error(
233        &self,
234        stream: &ReadableStream,
235        error: SafeHandleValue,
236        can_gc: CanGc,
237    ) {
238        stream.get_default_controller().error(error, can_gc);
239    }
240
241    pub(crate) fn pull_algorithm(&self, cx: &mut js::context::JSContext) {
242        self.tee_underlying_source
243            .pull_algorithm(CanGc::from_cx(cx));
244    }
245}