Skip to main content

script/dom/stream/
byteteereadintorequest.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;
8use std::rc::Rc;
9
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use js::jsval::UndefinedValue;
13use js::typedarray::ArrayBufferViewU8;
14use script_bindings::reflector::{Reflector, reflect_dom_object};
15use script_bindings::trace::RootedTraceableBox;
16
17use super::byteteeunderlyingsource::ByteTeePullAlgorithm;
18use crate::dom::bindings::buffer_source::HeapBufferSource;
19use crate::dom::bindings::error::{ErrorToJsval, Fallible};
20use crate::dom::bindings::refcounted::Trusted;
21use crate::dom::bindings::reflector::DomGlobal;
22use crate::dom::bindings::root::{Dom, DomRoot};
23use crate::dom::globalscope::GlobalScope;
24use crate::dom::promise::{RootedPromise, TracedPromise};
25use crate::dom::stream::byteteeunderlyingsource::ByteTeeUnderlyingSource;
26use crate::dom::stream::readablestream::ReadableStream;
27use crate::realms::enter_auto_realm;
28use crate::runtime::job_queue::MicrotaskRunnable;
29
30#[derive(JSTraceable, MallocSizeOf)]
31pub(crate) struct ByteTeeReadIntoRequestMicrotask {
32    #[ignore_malloc_size_of = "mozjs"]
33    chunk: RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>,
34    tee_read_request: Trusted<ByteTeeReadIntoRequest>,
35}
36
37impl MicrotaskRunnable for ByteTeeReadIntoRequestMicrotask {
38    fn handler(&self, cx: &mut JSContext) {
39        let tee_read_request = self.tee_read_request.root();
40        let mut realm = enter_auto_realm(cx, &*tee_read_request);
41        let cx = &mut realm;
42        tee_read_request
43            .chunk_steps(&self.chunk, cx)
44            .expect("Failed to enqueue chunk");
45    }
46}
47
48#[dom_struct]
49pub(crate) struct ByteTeeReadIntoRequest {
50    reflector_: Reflector,
51    for_branch2: bool,
52    byob_branch: Dom<ReadableStream>,
53    other_branch: Dom<ReadableStream>,
54    stream: Dom<ReadableStream>,
55    #[conditional_malloc_size_of]
56    read_again_for_branch_1: Rc<Cell<bool>>,
57    #[conditional_malloc_size_of]
58    read_again_for_branch_2: Rc<Cell<bool>>,
59    #[conditional_malloc_size_of]
60    reading: Rc<Cell<bool>>,
61    #[conditional_malloc_size_of]
62    canceled_1: Rc<Cell<bool>>,
63    #[conditional_malloc_size_of]
64    canceled_2: Rc<Cell<bool>>,
65    cancel_promise: TracedPromise,
66    tee_underlying_source: Dom<ByteTeeUnderlyingSource>,
67}
68impl ByteTeeReadIntoRequest {
69    #[allow(clippy::too_many_arguments)]
70    pub(crate) fn new(
71        cx: &mut JSContext,
72        for_branch2: bool,
73        byob_branch: &ReadableStream,
74        other_branch: &ReadableStream,
75        stream: &ReadableStream,
76        read_again_for_branch_1: Rc<Cell<bool>>,
77        read_again_for_branch_2: Rc<Cell<bool>>,
78        reading: Rc<Cell<bool>>,
79        canceled_1: Rc<Cell<bool>>,
80        canceled_2: Rc<Cell<bool>>,
81        cancel_promise: &RootedPromise,
82        tee_underlying_source: &ByteTeeUnderlyingSource,
83        global: &GlobalScope,
84    ) -> DomRoot<Self> {
85        reflect_dom_object(
86            cx,
87            Box::new(ByteTeeReadIntoRequest {
88                reflector_: Reflector::new(),
89                for_branch2,
90                byob_branch: Dom::from_ref(byob_branch),
91                other_branch: Dom::from_ref(other_branch),
92                stream: Dom::from_ref(stream),
93                read_again_for_branch_1,
94                read_again_for_branch_2,
95                reading,
96                canceled_1,
97                canceled_2,
98                cancel_promise: cancel_promise.to_traced(),
99                tee_underlying_source: Dom::from_ref(tee_underlying_source),
100            }),
101            global,
102        )
103    }
104
105    pub(crate) fn enqueue_chunk_steps(
106        &self,
107        cx: &mut JSContext,
108        chunk: RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>,
109    ) {
110        // Queue a microtask to perform the following steps:
111        let byte_tee_read_request_chunk = ByteTeeReadIntoRequestMicrotask {
112            chunk,
113            tee_read_request: Trusted::new(self),
114        };
115
116        self.global()
117            .enqueue_microtask(cx, Box::new(byte_tee_read_request_chunk));
118    }
119
120    /// <https://streams.spec.whatwg.org/#ref-for-read-into-request-chunk-steps%E2%91%A0>
121    #[allow(clippy::borrowed_box)]
122    pub(crate) fn chunk_steps(
123        &self,
124        chunk: &HeapBufferSource<ArrayBufferViewU8>,
125        cx: &mut JSContext,
126    ) -> Fallible<()> {
127        // Set readAgainForBranch1 to false.
128        self.read_again_for_branch_1.set(false);
129
130        // Set readAgainForBranch2 to false.
131        self.read_again_for_branch_2.set(false);
132
133        // Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.
134        let byob_canceled = if self.for_branch2 {
135            self.canceled_2.get()
136        } else {
137            self.canceled_1.get()
138        };
139
140        // Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.
141        let other_canceled = if self.for_branch2 {
142            self.canceled_1.get()
143        } else {
144            self.canceled_2.get()
145        };
146
147        // If otherCanceled is false,
148        if !other_canceled {
149            // Let cloneResult be CloneAsUint8Array(chunk).
150            let clone_result = chunk.clone_as_uint8_array(cx);
151
152            // If cloneResult is an abrupt completion,
153            if let Err(error) = clone_result {
154                rooted!(&in(cx) let mut error_value = UndefinedValue());
155                error.to_jsval(cx, &self.global(), error_value.handle_mut());
156
157                // Perform ! ReadableByteStreamControllerError(byobBranch.[[controller]], cloneResult.[[Value]]).
158                let byob_branch_controller = self.byob_branch.get_byte_controller();
159                byob_branch_controller.error(cx, error_value.handle());
160
161                // Perform ! ReadableByteStreamControllerError(otherBranch.[[controller]], cloneResult.[[Value]]).
162                let other_branch_controller = self.other_branch.get_byte_controller();
163                other_branch_controller.error(cx, error_value.handle());
164
165                // Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
166                let cancel_result =
167                    self.stream
168                        .cancel(cx, &self.stream.global(), error_value.handle());
169                self.cancel_promise.resolve_native(cx, &cancel_result);
170
171                // Return.
172                return Ok(());
173            } else {
174                // Otherwise, let clonedChunk be cloneResult.[[Value]].
175                let cloned_chunk = clone_result.unwrap();
176
177                // If byobCanceled is false, perform !
178                // ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
179                if !byob_canceled {
180                    let byob_branch_controller = self.byob_branch.get_byte_controller();
181                    byob_branch_controller.respond_with_new_view(cx, chunk)?;
182                }
183
184                // Perform ! ReadableByteStreamControllerEnqueue(otherBranch.[[controller]], clonedChunk).
185                let other_branch_controller = self.other_branch.get_byte_controller();
186                other_branch_controller.enqueue(cx, cloned_chunk)?;
187            }
188        } else if !byob_canceled {
189            // Otherwise, if byobCanceled is false, perform
190            // ! ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
191
192            let byob_branch_controller = self.byob_branch.get_byte_controller();
193            byob_branch_controller.respond_with_new_view(cx, chunk)?;
194        }
195
196        // Set reading to false.
197        self.reading.set(false);
198
199        // If readAgainForBranch1 is true, perform pull1Algorithm.
200        if self.read_again_for_branch_1.get() {
201            self.pull_algorithm(cx, Some(ByteTeePullAlgorithm::Pull1Algorithm));
202        } else if self.read_again_for_branch_2.get() {
203            // Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.
204            self.pull_algorithm(cx, Some(ByteTeePullAlgorithm::Pull2Algorithm));
205        }
206
207        Ok(())
208    }
209
210    /// <https://streams.spec.whatwg.org/#ref-for-read-into-request-close-steps%E2%91%A1>
211    pub(crate) fn close_steps(
212        &self,
213        cx: &mut JSContext,
214        chunk: Option<RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>>,
215    ) -> Fallible<()> {
216        // Set reading to false.
217        self.reading.set(false);
218
219        // Let byobCanceled be canceled2 if forBranch2 is true, and canceled1 otherwise.
220        let byob_canceled = if self.for_branch2 {
221            self.canceled_2.get()
222        } else {
223            self.canceled_1.get()
224        };
225
226        // Let otherCanceled be canceled2 if forBranch2 is false, and canceled1 otherwise.
227        let other_canceled = if self.for_branch2 {
228            self.canceled_1.get()
229        } else {
230            self.canceled_2.get()
231        };
232
233        // If byobCanceled is false, perform ! ReadableByteStreamControllerClose(byobBranch.[[controller]]).
234        if !byob_canceled {
235            let byob_branch_controller = self.byob_branch.get_byte_controller();
236            byob_branch_controller.close(cx)?;
237        }
238
239        // If otherCanceled is false, perform ! ReadableByteStreamControllerClose(otherBranch.[[controller]]).
240        if !other_canceled {
241            let other_branch_controller = self.other_branch.get_byte_controller();
242            other_branch_controller.close(cx)?;
243        }
244
245        // If chunk is not undefined,
246        if let Some(chunk_value) = chunk {
247            if chunk_value.is_undefined() {
248                // Nothing to respond with if the provided chunk is undefined.
249                // Continue with the remaining close steps.
250            } else {
251                let chunk = chunk_value;
252                // Assert: chunk.[[ByteLength]] is 0.
253                assert_eq!(chunk.byte_length(), 0);
254
255                // If byobCanceled is false, perform !
256                // ReadableByteStreamControllerRespondWithNewView(byobBranch.[[controller]], chunk).
257                if !byob_canceled {
258                    let byob_branch_controller = self.byob_branch.get_byte_controller();
259                    byob_branch_controller.respond_with_new_view(cx, &chunk)?;
260                }
261
262                // If otherCanceled is false and otherBranch.[[controller]].[[pendingPullIntos]] is not empty,
263                // perform ! ReadableByteStreamControllerRespond(otherBranch.[[controller]], 0).
264                if !other_canceled {
265                    let other_branch_controller = self.other_branch.get_byte_controller();
266                    if other_branch_controller.get_pending_pull_intos_size() > 0 {
267                        other_branch_controller.respond(cx, 0)?;
268                    }
269                }
270            }
271        }
272
273        // If byobCanceled is false or otherCanceled is false, resolve cancelPromise with undefined.
274        if !byob_canceled || !other_canceled {
275            self.cancel_promise.resolve_native(cx, &());
276        }
277
278        Ok(())
279    }
280    /// <https://streams.spec.whatwg.org/#ref-for-read-into-request-error-steps%E2%91%A0>
281    pub(crate) fn error_steps(&self) {
282        // Set reading to false.
283        self.reading.set(false);
284    }
285
286    pub(crate) fn pull_algorithm(
287        &self,
288        cx: &mut JSContext,
289        byte_tee_pull_algorithm: Option<ByteTeePullAlgorithm>,
290    ) {
291        self.tee_underlying_source
292            .pull_algorithm(cx, byte_tee_pull_algorithm);
293    }
294}