Skip to main content

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