Skip to main content

script/dom/stream/
defaultteeunderlyingsource.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::conversions::ToJSValConvertible;
11use js::jsapi::{Heap, Value};
12use js::jsval::UndefinedValue;
13use js::rust::HandleValue as SafeHandleValue;
14use script_bindings::reflector::{Reflector, reflect_dom_object};
15
16use crate::dom::bindings::error::Error;
17use crate::dom::bindings::reflector::DomGlobal;
18use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
19use crate::dom::globalscope::GlobalScope;
20use crate::dom::promise::{Promise, RootedPromise, TracedPromise};
21use crate::dom::stream::defaultteereadrequest::DefaultTeeReadRequest;
22use crate::dom::stream::readablestreamdefaultreader::ReadRequest;
23use crate::dom::types::{ReadableStream, ReadableStreamDefaultReader};
24
25#[derive(JSTraceable, MallocSizeOf)]
26pub(crate) enum DefaultTeeCancelAlgorithm {
27    Cancel1Algorithm,
28    Cancel2Algorithm,
29}
30
31#[dom_struct]
32/// <https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee>
33pub(crate) struct DefaultTeeUnderlyingSource {
34    reflector_: Reflector,
35    reader: Dom<ReadableStreamDefaultReader>,
36    stream: Dom<ReadableStream>,
37    branch_1: MutNullableDom<ReadableStream>,
38    branch_2: MutNullableDom<ReadableStream>,
39    #[conditional_malloc_size_of]
40    reading: Rc<Cell<bool>>,
41    #[conditional_malloc_size_of]
42    read_again: Rc<Cell<bool>>,
43    #[conditional_malloc_size_of]
44    canceled_1: Rc<Cell<bool>>,
45    #[conditional_malloc_size_of]
46    canceled_2: Rc<Cell<bool>>,
47    #[conditional_malloc_size_of]
48    clone_for_branch_2: Rc<Cell<bool>>,
49    #[ignore_malloc_size_of = "mozjs"]
50    reason_1: Rc<Heap<Value>>,
51    #[ignore_malloc_size_of = "mozjs"]
52    reason_2: Rc<Heap<Value>>,
53    cancel_promise: TracedPromise,
54    tee_cancel_algorithm: DefaultTeeCancelAlgorithm,
55}
56
57impl DefaultTeeUnderlyingSource {
58    #[expect(clippy::too_many_arguments)]
59    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
60    pub(crate) fn new(
61        cx: &mut JSContext,
62        reader: &ReadableStreamDefaultReader,
63        stream: &ReadableStream,
64        reading: Rc<Cell<bool>>,
65        read_again: Rc<Cell<bool>>,
66        canceled_1: Rc<Cell<bool>>,
67        canceled_2: Rc<Cell<bool>>,
68        clone_for_branch_2: Rc<Cell<bool>>,
69        reason_1: Rc<Heap<Value>>,
70        reason_2: Rc<Heap<Value>>,
71        cancel_promise: &RootedPromise,
72        tee_cancel_algorithm: DefaultTeeCancelAlgorithm,
73    ) -> DomRoot<DefaultTeeUnderlyingSource> {
74        reflect_dom_object(
75            cx,
76            Box::new(DefaultTeeUnderlyingSource {
77                reflector_: Reflector::new(),
78                reader: Dom::from_ref(reader),
79                stream: Dom::from_ref(stream),
80                branch_1: MutNullableDom::new(None),
81                branch_2: MutNullableDom::new(None),
82                reading,
83                read_again,
84                canceled_1,
85                canceled_2,
86                clone_for_branch_2,
87                reason_1,
88                reason_2,
89                cancel_promise: cancel_promise.to_traced(),
90                tee_cancel_algorithm,
91            }),
92            &*stream.global(),
93        )
94    }
95
96    pub(crate) fn set_branch_1(&self, stream: &ReadableStream) {
97        self.branch_1.set(Some(stream));
98    }
99
100    pub(crate) fn set_branch_2(&self, stream: &ReadableStream) {
101        self.branch_2.set(Some(stream));
102    }
103
104    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee>
105    /// Let pullAlgorithm be the following steps:
106    pub(crate) fn pull_algorithm(&self, cx: &mut js::context::JSContext) -> RootedPromise {
107        // If reading is true,
108        if self.reading.get() {
109            // Set readAgain to true.
110            self.read_again.set(true);
111            // Return a promise resolved with undefined.
112            return Promise::new_resolved_rooted(cx, &self.stream.global(), ());
113        }
114
115        // Set reading to true.
116        self.reading.set(true);
117
118        // Let readRequest be a read request with the following items:
119        let tee_read_request = DefaultTeeReadRequest::new(
120            cx,
121            &self.stream,
122            &self.branch_1.get().expect("Branch 1 should be set."),
123            &self.branch_2.get().expect("Branch 2 should be set."),
124            self.reading.clone(),
125            self.read_again.clone(),
126            self.canceled_1.clone(),
127            self.canceled_2.clone(),
128            self.clone_for_branch_2.clone(),
129            &self.cancel_promise.root(cx),
130            self,
131        );
132
133        // Rooting: the tee read request is rooted above.
134        rooted!(&in(cx) let read_request = ReadRequest::DefaultTee {
135            tee_read_request: Dom::from_ref(&tee_read_request),
136        });
137
138        // Perform ! ReadableStreamDefaultReaderRead(reader, readRequest).
139        self.reader.read(cx, &read_request);
140
141        // Return a promise resolved with undefined.
142        Promise::new_resolved_rooted(cx, &self.stream.global(), ())
143    }
144
145    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablestreamdefaulttee>
146    /// Let cancel1Algorithm be the following steps, taking a reason argument
147    /// and
148    /// Let cancel2Algorithm be the following steps, taking a reason argument
149    pub(crate) fn cancel_algorithm(
150        &self,
151        cx: &mut js::context::JSContext,
152        global: &GlobalScope,
153        reason: SafeHandleValue,
154    ) -> Option<Result<RootedPromise, Error>> {
155        match self.tee_cancel_algorithm {
156            DefaultTeeCancelAlgorithm::Cancel1Algorithm => {
157                // Set canceled_1 to true.
158                self.canceled_1.set(true);
159
160                // Set reason_1 to reason.
161                self.reason_1.set(reason.get());
162
163                // If canceled_2 is true,
164                if self.canceled_2.get() {
165                    self.resolve_cancel_promise(cx, global);
166                }
167                // Return cancelPromise.
168                Some(Ok(self.cancel_promise.root(cx)))
169            },
170            DefaultTeeCancelAlgorithm::Cancel2Algorithm => {
171                // Set canceled_2 to true.
172                self.canceled_2.set(true);
173
174                // Set reason_2 to reason.
175                self.reason_2.set(reason.get());
176
177                // If canceled_1 is true,
178                if self.canceled_1.get() {
179                    self.resolve_cancel_promise(cx, global);
180                }
181                // Return cancelPromise.
182                Some(Ok(self.cancel_promise.root(cx)))
183            },
184        }
185    }
186
187    fn resolve_cancel_promise(&self, cx: &mut js::context::JSContext, global: &GlobalScope) {
188        // Let compositeReason be ! CreateArrayFromList(« reason_1, reason_2 »).
189        rooted_vec!(let mut reasons_values);
190        reasons_values.push(self.reason_1.get());
191        reasons_values.push(self.reason_2.get());
192
193        rooted!(&in(cx) let mut reasons_value = UndefinedValue());
194        reasons_values.to_jsval(cx, reasons_value.handle_mut());
195
196        // Let cancelResult be ! ReadableStreamCancel(stream, compositeReason).
197        let cancel_result = self.stream.cancel(cx, global, reasons_value.handle());
198
199        // Resolve cancelPromise with cancelResult.
200        self.cancel_promise.resolve_native(cx, &cancel_result);
201    }
202}