script/dom/stream/
writablestreamdefaultcontroller.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 https://mozilla.org/MPL/2.0/. */
4
5use std::cell::{Cell, RefCell};
6use std::ptr;
7use std::rc::Rc;
8
9use dom_struct::dom_struct;
10use js::jsapi::{Heap, IsPromiseObject, JSObject};
11use js::jsval::{JSVal, UndefinedValue};
12use js::realm::CurrentRealm;
13use js::rust::{HandleObject as SafeHandleObject, HandleValue as SafeHandleValue, IntoHandle};
14
15use crate::dom::bindings::callback::ExceptionHandling;
16use crate::dom::bindings::codegen::Bindings::QueuingStrategyBinding::QueuingStrategySize;
17use crate::dom::bindings::codegen::Bindings::UnderlyingSinkBinding::{
18    UnderlyingSinkAbortCallback, UnderlyingSinkCloseCallback, UnderlyingSinkStartCallback,
19    UnderlyingSinkWriteCallback,
20};
21use crate::dom::bindings::codegen::Bindings::WritableStreamDefaultControllerBinding::WritableStreamDefaultControllerMethods;
22use crate::dom::bindings::error::{Error, ErrorToJsval, Fallible};
23use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object};
24use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
25use crate::dom::globalscope::GlobalScope;
26use crate::dom::messageport::MessagePort;
27use crate::dom::promise::Promise;
28use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
29use crate::dom::readablestreamdefaultcontroller::{EnqueuedValue, QueueWithSizes, ValueWithSize};
30use crate::dom::stream::writablestream::WritableStream;
31use crate::dom::types::{AbortController, AbortSignal, TransformStream};
32use crate::realms::{InRealm, enter_auto_realm, enter_realm};
33use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
34
35impl js::gc::Rootable for CloseAlgorithmFulfillmentHandler {}
36
37/// The fulfillment handler for
38/// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close>
39#[derive(Clone, JSTraceable, MallocSizeOf)]
40#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
41struct CloseAlgorithmFulfillmentHandler {
42    stream: Dom<WritableStream>,
43}
44
45impl Callback for CloseAlgorithmFulfillmentHandler {
46    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
47        let can_gc = CanGc::from_cx(cx);
48        let stream = self.stream.as_rooted();
49
50        // Perform ! WritableStreamFinishInFlightClose(stream).
51        stream.finish_in_flight_close(cx.into(), can_gc);
52    }
53}
54
55impl js::gc::Rootable for CloseAlgorithmRejectionHandler {}
56
57/// The rejection handler for
58/// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close>
59#[derive(Clone, JSTraceable, MallocSizeOf)]
60#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
61struct CloseAlgorithmRejectionHandler {
62    stream: Dom<WritableStream>,
63}
64
65impl Callback for CloseAlgorithmRejectionHandler {
66    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
67        let stream = self.stream.as_rooted();
68
69        let global = GlobalScope::from_current_realm(cx);
70
71        // Perform ! WritableStreamFinishInFlightCloseWithError(stream, reason).
72        stream.finish_in_flight_close_with_error(cx, &global, v);
73    }
74}
75
76impl js::gc::Rootable for StartAlgorithmFulfillmentHandler {}
77
78/// The fulfillment handler for
79/// <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller>
80#[derive(Clone, JSTraceable, MallocSizeOf)]
81#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
82struct StartAlgorithmFulfillmentHandler {
83    controller: Dom<WritableStreamDefaultController>,
84}
85
86impl Callback for StartAlgorithmFulfillmentHandler {
87    /// Continuation of <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller>
88    /// Upon fulfillment of startPromise,
89    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
90        let controller = self.controller.as_rooted();
91        let stream = controller
92            .stream
93            .get()
94            .expect("Controller should have a stream.");
95
96        // Assert: stream.[[state]] is "writable" or "erroring".
97        assert!(stream.is_erroring() || stream.is_writable());
98
99        // Set controller.[[started]] to true.
100        controller.started.set(true);
101
102        let global = GlobalScope::from_current_realm(cx);
103
104        // Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
105        controller.advance_queue_if_needed(cx, &global)
106    }
107}
108
109impl js::gc::Rootable for StartAlgorithmRejectionHandler {}
110
111/// The rejection handler for
112/// <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller>
113#[derive(Clone, JSTraceable, MallocSizeOf)]
114#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
115struct StartAlgorithmRejectionHandler {
116    controller: Dom<WritableStreamDefaultController>,
117}
118
119impl Callback for StartAlgorithmRejectionHandler {
120    /// Continuation of <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller>
121    /// Upon rejection of startPromise with reason r,
122    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
123        let controller = self.controller.as_rooted();
124        let stream = controller
125            .stream
126            .get()
127            .expect("Controller should have a stream.");
128
129        // Assert: stream.[[state]] is "writable" or "erroring".
130        assert!(stream.is_erroring() || stream.is_writable());
131
132        // Set controller.[[started]] to true.
133        controller.started.set(true);
134
135        let global = GlobalScope::from_current_realm(cx);
136
137        // Perform ! WritableStreamDealWithRejection(stream, r).
138        stream.deal_with_rejection(cx, &global, v);
139    }
140}
141
142impl js::gc::Rootable for TransferBackPressurePromiseReaction {}
143
144/// Reacting to backpressurePromise as part of the `writeAlgorithm` of
145/// <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
146#[derive(JSTraceable, MallocSizeOf)]
147#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
148struct TransferBackPressurePromiseReaction {
149    /// The result of reacting to backpressurePromise.
150    #[conditional_malloc_size_of]
151    result_promise: Rc<Promise>,
152
153    /// The backpressurePromise.
154    #[ignore_malloc_size_of = "nested Rc"]
155    backpressure_promise: Rc<RefCell<Option<Rc<Promise>>>>,
156
157    /// The chunk received by the `writeAlgorithm`.
158    #[ignore_malloc_size_of = "mozjs"]
159    chunk: Box<Heap<JSVal>>,
160
161    /// The port used in the algorithm.
162    port: Dom<MessagePort>,
163}
164
165impl Callback for TransferBackPressurePromiseReaction {
166    /// Reacting to backpressurePromise with the following fulfillment steps:
167    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
168        let can_gc = CanGc::from_cx(cx);
169        let global = self.result_promise.global();
170        // Set backpressurePromise to a new promise.
171        let promise = Promise::new2(cx, &global);
172        *self.backpressure_promise.borrow_mut() = Some(promise);
173
174        // Let result be PackAndPostMessageHandlingError(port, "chunk", chunk).
175        rooted!(&in(cx) let mut chunk = UndefinedValue());
176        chunk.set(self.chunk.get());
177        let result =
178            self.port
179                .pack_and_post_message_handling_error("chunk", chunk.handle(), can_gc);
180
181        // If result is an abrupt completion,
182        if let Err(error) = result {
183            // Disentangle port.
184            global.disentangle_port(&self.port, can_gc);
185
186            // Return a promise rejected with result.[[Value]].
187            self.result_promise.reject_error(error, can_gc);
188        } else {
189            // Otherwise, return a promise resolved with undefined.
190            self.result_promise.resolve_native(&(), can_gc);
191        }
192    }
193}
194
195impl js::gc::Rootable for WriteAlgorithmFulfillmentHandler {}
196
197/// The fulfillment handler for
198/// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write>
199#[derive(Clone, JSTraceable, MallocSizeOf)]
200#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
201struct WriteAlgorithmFulfillmentHandler {
202    controller: Dom<WritableStreamDefaultController>,
203}
204
205impl Callback for WriteAlgorithmFulfillmentHandler {
206    fn callback(&self, cx: &mut CurrentRealm, _v: SafeHandleValue) {
207        let can_gc = CanGc::from_cx(cx);
208        let controller = self.controller.as_rooted();
209        let stream = controller
210            .stream
211            .get()
212            .expect("Controller should have a stream.");
213
214        // Perform ! WritableStreamFinishInFlightWrite(stream).
215        stream.finish_in_flight_write(can_gc);
216
217        // Let state be stream.[[state]].
218        // Assert: state is "writable" or "erroring".
219        assert!(stream.is_erroring() || stream.is_writable());
220
221        // Perform ! DequeueValue(controller).
222        rooted!(&in(cx) let mut rval = UndefinedValue());
223        controller
224            .queue
225            .dequeue_value(cx.into(), Some(rval.handle_mut()), can_gc);
226
227        let global = GlobalScope::from_current_realm(cx);
228
229        // If ! WritableStreamCloseQueuedOrInFlight(stream) is false and state is "writable",
230        if !stream.close_queued_or_in_flight() && stream.is_writable() {
231            // Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
232            let backpressure = controller.get_backpressure();
233
234            // Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
235            stream.update_backpressure(backpressure, &global, can_gc);
236        }
237
238        // Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
239        controller.advance_queue_if_needed(cx, &global)
240    }
241}
242
243impl js::gc::Rootable for WriteAlgorithmRejectionHandler {}
244
245/// The rejection handler for
246/// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write>
247#[derive(Clone, JSTraceable, MallocSizeOf)]
248#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
249struct WriteAlgorithmRejectionHandler {
250    controller: Dom<WritableStreamDefaultController>,
251}
252
253impl Callback for WriteAlgorithmRejectionHandler {
254    fn callback(&self, cx: &mut CurrentRealm, v: SafeHandleValue) {
255        let controller = self.controller.as_rooted();
256        let stream = controller
257            .stream
258            .get()
259            .expect("Controller should have a stream.");
260
261        // If stream.[[state]] is "writable",
262        if stream.is_writable() {
263            // perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
264            controller.clear_algorithms();
265        }
266
267        let global = GlobalScope::from_current_realm(cx);
268
269        // Perform ! WritableStreamFinishInFlightWriteWithError(stream, reason).
270        stream.finish_in_flight_write_with_error(cx, &global, v);
271    }
272}
273
274/// The type of sink algorithms we are using.
275#[derive(JSTraceable, PartialEq)]
276#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
277pub enum UnderlyingSinkType {
278    /// Algorithms are provided by Js callbacks.
279    Js {
280        /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortalgorithm>
281        abort: RefCell<Option<Rc<UnderlyingSinkAbortCallback>>>,
282
283        start: RefCell<Option<Rc<UnderlyingSinkStartCallback>>>,
284
285        /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm>
286        close: RefCell<Option<Rc<UnderlyingSinkCloseCallback>>>,
287
288        /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm>
289        write: RefCell<Option<Rc<UnderlyingSinkWriteCallback>>>,
290    },
291    /// Algorithms supporting streams transfer are implemented in Rust.
292    /// The promise and port used in those algorithms are stored here.
293    Transfer {
294        backpressure_promise: Rc<RefCell<Option<Rc<Promise>>>>,
295        port: Dom<MessagePort>,
296    },
297    /// Algorithms supporting transform streams are implemented in Rust.
298    Transform(Dom<TransformStream>, Rc<Promise>),
299}
300
301impl UnderlyingSinkType {
302    pub(crate) fn new_js(
303        abort: Option<Rc<UnderlyingSinkAbortCallback>>,
304        start: Option<Rc<UnderlyingSinkStartCallback>>,
305        close: Option<Rc<UnderlyingSinkCloseCallback>>,
306        write: Option<Rc<UnderlyingSinkWriteCallback>>,
307    ) -> Self {
308        UnderlyingSinkType::Js {
309            abort: RefCell::new(abort),
310            start: RefCell::new(start),
311            close: RefCell::new(close),
312            write: RefCell::new(write),
313        }
314    }
315}
316
317/// <https://streams.spec.whatwg.org/#ws-default-controller-class>
318#[dom_struct]
319pub struct WritableStreamDefaultController {
320    reflector_: Reflector,
321
322    /// The type of underlying sink used. Besides the default JS one,
323    /// there will be others for stream transfer, and for transform stream.
324    #[ignore_malloc_size_of = "underlying_sink_type"]
325    underlying_sink_type: UnderlyingSinkType,
326
327    /// The JS object used as `this` when invoking sink algorithms.
328    #[ignore_malloc_size_of = "mozjs"]
329    underlying_sink_obj: Heap<*mut JSObject>,
330
331    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-queue>
332    queue: QueueWithSizes,
333
334    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-started>
335    started: Cell<bool>,
336
337    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategyhwm>
338    strategy_hwm: f64,
339
340    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-strategysizealgorithm>
341    #[ignore_malloc_size_of = "QueuingStrategySize"]
342    strategy_size: RefCell<Option<Rc<QueuingStrategySize>>>,
343
344    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-stream>
345    stream: MutNullableDom<WritableStream>,
346
347    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-abortcontroller>
348    abort_controller: Dom<AbortController>,
349}
350
351impl WritableStreamDefaultController {
352    /// <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller-from-underlying-sink>
353    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
354    fn new_inherited(
355        global: &GlobalScope,
356        underlying_sink_type: UnderlyingSinkType,
357        strategy_hwm: f64,
358        strategy_size: Rc<QueuingStrategySize>,
359        can_gc: CanGc,
360    ) -> WritableStreamDefaultController {
361        WritableStreamDefaultController {
362            reflector_: Reflector::new(),
363            underlying_sink_type,
364            queue: Default::default(),
365            stream: Default::default(),
366            underlying_sink_obj: Default::default(),
367            strategy_hwm,
368            strategy_size: RefCell::new(Some(strategy_size)),
369            started: Default::default(),
370            abort_controller: Dom::from_ref(&AbortController::new_with_proto(global, None, can_gc)),
371        }
372    }
373
374    #[cfg_attr(crown, expect(crown::unrooted_must_root))]
375    pub(crate) fn new(
376        global: &GlobalScope,
377        underlying_sink_type: UnderlyingSinkType,
378        strategy_hwm: f64,
379        strategy_size: Rc<QueuingStrategySize>,
380        can_gc: CanGc,
381    ) -> DomRoot<WritableStreamDefaultController> {
382        reflect_dom_object(
383            Box::new(WritableStreamDefaultController::new_inherited(
384                global,
385                underlying_sink_type,
386                strategy_hwm,
387                strategy_size,
388                can_gc,
389            )),
390            global,
391            can_gc,
392        )
393    }
394
395    pub(crate) fn started(&self) -> bool {
396        self.started.get()
397    }
398
399    /// Setting the JS object after the heap has settled down.
400    pub(crate) fn set_underlying_sink_this_object(&self, this_object: SafeHandleObject) {
401        self.underlying_sink_obj.set(*this_object);
402    }
403
404    /// "Signal abort" call from <https://streams.spec.whatwg.org/#writable-stream-abort>
405    pub(crate) fn signal_abort(&self, cx: &mut CurrentRealm, reason: SafeHandleValue) {
406        self.abort_controller.signal_abort(cx, reason);
407    }
408
409    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-clear-algorithms>
410    fn clear_algorithms(&self) {
411        match &self.underlying_sink_type {
412            UnderlyingSinkType::Js {
413                abort,
414                start: _,
415                close,
416                write,
417            } => {
418                // Set controller.[[writeAlgorithm]] to undefined.
419                write.borrow_mut().take();
420
421                // Set controller.[[closeAlgorithm]] to undefined.
422                close.borrow_mut().take();
423
424                // Set controller.[[abortAlgorithm]] to undefined.
425                abort.borrow_mut().take();
426            },
427            UnderlyingSinkType::Transfer {
428                backpressure_promise,
429                ..
430            } => {
431                backpressure_promise.borrow_mut().take();
432            },
433            UnderlyingSinkType::Transform(_, _) => {
434                return;
435            },
436        }
437
438        // Set controller.[[strategySizeAlgorithm]] to undefined.
439        self.strategy_size.borrow_mut().take();
440    }
441
442    /// <https://streams.spec.whatwg.org/#set-up-writable-stream-default-controller>
443    pub(crate) fn setup(
444        &self,
445        cx: SafeJSContext,
446        global: &GlobalScope,
447        stream: &WritableStream,
448        can_gc: CanGc,
449    ) -> Result<(), Error> {
450        // Assert: stream implements WritableStream.
451        // Implied by stream type.
452
453        // Assert: stream.[[controller]] is undefined.
454        stream.assert_no_controller();
455
456        // Set controller.[[stream]] to stream.
457        self.stream.set(Some(stream));
458
459        // Set stream.[[controller]] to controller.
460        stream.set_default_controller(self);
461
462        // Perform ! ResetQueue(controller).
463
464        // Set controller.[[abortController]] to a new AbortController.
465
466        // Set controller.[[started]] to false.
467
468        // Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm.
469
470        // Set controller.[[strategyHWM]] to highWaterMark.
471
472        // Set controller.[[writeAlgorithm]] to writeAlgorithm.
473
474        // Set controller.[[closeAlgorithm]] to closeAlgorithm.
475
476        // Set controller.[[abortAlgorithm]] to abortAlgorithm.
477
478        // Note: above steps are done in `new_inherited`.
479
480        // Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
481        let backpressure = self.get_backpressure();
482
483        // Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
484        stream.update_backpressure(backpressure, global, can_gc);
485
486        // Let startResult be the result of performing startAlgorithm. (This may throw an exception.)
487        // Let startPromise be a promise resolved with startResult.
488        let start_promise = self.start_algorithm(cx, global, can_gc)?;
489
490        let rooted_default_controller = DomRoot::from_ref(self);
491
492        // Upon fulfillment of startPromise,
493        rooted!(in(*cx) let mut fulfillment_handler = Some(StartAlgorithmFulfillmentHandler {
494            controller: Dom::from_ref(&rooted_default_controller),
495        }));
496
497        // Upon rejection of startPromise with reason r,
498        rooted!(in(*cx) let mut rejection_handler = Some(StartAlgorithmRejectionHandler {
499            controller: Dom::from_ref(&rooted_default_controller),
500        }));
501
502        let handler = PromiseNativeHandler::new(
503            global,
504            fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
505            rejection_handler.take().map(|h| Box::new(h) as Box<_>),
506            can_gc,
507        );
508        let realm = enter_realm(global);
509        let comp = InRealm::Entered(&realm);
510        start_promise.append_native_handler(&handler, comp, can_gc);
511
512        Ok(())
513    }
514
515    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-close>
516    pub(crate) fn close(&self, cx: &mut js::context::JSContext, global: &GlobalScope) {
517        // Perform ! EnqueueValueWithSize(controller, close sentinel, 0).
518        self.queue
519            .enqueue_value_with_size(EnqueuedValue::CloseSentinel)
520            .expect("Enqueuing the close sentinel should not fail.");
521        // Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
522        self.advance_queue_if_needed(cx, global);
523    }
524
525    #[expect(unsafe_code)]
526    fn start_algorithm(
527        &self,
528        cx: SafeJSContext,
529        global: &GlobalScope,
530        can_gc: CanGc,
531    ) -> Fallible<Rc<Promise>> {
532        match &self.underlying_sink_type {
533            UnderlyingSinkType::Js {
534                start,
535                abort: _,
536                close: _,
537                write: _,
538            } => {
539                let algo = start.borrow().clone();
540                let start_promise = if let Some(start) = algo {
541                    rooted!(in(*cx) let mut result_object = ptr::null_mut::<JSObject>());
542                    rooted!(in(*cx) let mut result: JSVal);
543                    rooted!(in(*cx) let this_object = self.underlying_sink_obj.get());
544                    start.Call_(
545                        &this_object.handle(),
546                        self,
547                        result.handle_mut(),
548                        ExceptionHandling::Rethrow,
549                        can_gc,
550                    )?;
551                    let is_promise = unsafe {
552                        if result.is_object() {
553                            result_object.set(result.to_object());
554                            IsPromiseObject(result_object.handle().into_handle())
555                        } else {
556                            false
557                        }
558                    };
559                    if is_promise {
560                        Promise::new_with_js_promise(result_object.handle(), cx)
561                    } else {
562                        Promise::new_resolved(global, cx, result.get(), can_gc)
563                    }
564                } else {
565                    // Let startAlgorithm be an algorithm that returns undefined.
566                    Promise::new_resolved(global, cx, (), can_gc)
567                };
568
569                Ok(start_promise)
570            },
571            UnderlyingSinkType::Transfer { .. } => {
572                // Let startAlgorithm be an algorithm that returns undefined.
573                Ok(Promise::new_resolved(global, cx, (), can_gc))
574            },
575            UnderlyingSinkType::Transform(_, start_promise) => {
576                // Let startAlgorithm be an algorithm that returns startPromise.
577                Ok(start_promise.clone())
578            },
579        }
580    }
581
582    /// <https://streams.spec.whatwg.org/#ref-for-abstract-opdef-writablestreamcontroller-abortsteps>
583    pub(crate) fn abort_steps(
584        &self,
585        cx: &mut js::context::JSContext,
586        global: &GlobalScope,
587        reason: SafeHandleValue,
588    ) -> Rc<Promise> {
589        let result = match &self.underlying_sink_type {
590            UnderlyingSinkType::Js {
591                abort,
592                start: _,
593                close: _,
594                write: _,
595            } => {
596                rooted!(&in(cx) let this_object = self.underlying_sink_obj.get());
597                let algo = abort.borrow().clone();
598                // Let result be the result of performing this.[[abortAlgorithm]], passing reason.
599                let result = if let Some(algo) = algo {
600                    algo.Call_(
601                        &this_object.handle(),
602                        Some(reason),
603                        ExceptionHandling::Rethrow,
604                        CanGc::from_cx(cx),
605                    )
606                } else {
607                    Ok(Promise::new_resolved(
608                        global,
609                        cx.into(),
610                        (),
611                        CanGc::from_cx(cx),
612                    ))
613                };
614                result.unwrap_or_else(|e| {
615                    let promise = Promise::new(global, CanGc::from_cx(cx));
616                    promise.reject_error(e, CanGc::from_cx(cx));
617                    promise
618                })
619            },
620            UnderlyingSinkType::Transfer { port, .. } => {
621                // The steps from the `abortAlgorithm` at
622                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
623
624                // Let result be PackAndPostMessageHandlingError(port, "error", reason).
625                let result =
626                    port.pack_and_post_message_handling_error("error", reason, CanGc::from_cx(cx));
627
628                // Disentangle port.
629                global.disentangle_port(port, CanGc::from_cx(cx));
630
631                let promise = Promise::new(global, CanGc::from_cx(cx));
632
633                // If result is an abrupt completion, return a promise rejected with result.[[Value]]
634                if let Err(error) = result {
635                    promise.reject_error(error, CanGc::from_cx(cx));
636                } else {
637                    // Otherwise, return a promise resolved with undefined.
638                    promise.resolve_native(&(), CanGc::from_cx(cx));
639                }
640                promise
641            },
642            UnderlyingSinkType::Transform(stream, _) => {
643                // Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
644                stream
645                    .transform_stream_default_sink_abort_algorithm(
646                        cx.into(),
647                        global,
648                        reason,
649                        CanGc::from_cx(cx),
650                    )
651                    .expect("Transform stream default sink abort algorithm should not fail.")
652            },
653        };
654
655        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
656        self.clear_algorithms();
657
658        result
659    }
660
661    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm>
662    fn call_write_algorithm(
663        &self,
664        cx: &mut js::context::JSContext,
665        chunk: SafeHandleValue,
666        global: &GlobalScope,
667    ) -> Rc<Promise> {
668        match &self.underlying_sink_type {
669            UnderlyingSinkType::Js {
670                abort: _,
671                start: _,
672                close: _,
673                write,
674            } => {
675                rooted!(&in(cx) let this_object = self.underlying_sink_obj.get());
676                let algo = write.borrow().clone();
677                let result = if let Some(algo) = algo {
678                    algo.Call_(
679                        &this_object.handle(),
680                        chunk,
681                        self,
682                        ExceptionHandling::Rethrow,
683                        CanGc::from_cx(cx),
684                    )
685                } else {
686                    Ok(Promise::new_resolved(
687                        global,
688                        cx.into(),
689                        (),
690                        CanGc::from_cx(cx),
691                    ))
692                };
693                result.unwrap_or_else(|e| {
694                    let promise = Promise::new2(cx, global);
695                    promise.reject_error(e, CanGc::from_cx(cx));
696                    promise
697                })
698            },
699            UnderlyingSinkType::Transfer {
700                backpressure_promise,
701                port,
702            } => {
703                // The steps from the `writeAlgorithm` at
704                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
705
706                // If backpressurePromise is undefined,
707                // set backpressurePromise to a promise resolved with undefined.
708                if backpressure_promise.borrow().is_none() {
709                    let promise = Promise::new_resolved(global, cx.into(), (), CanGc::from_cx(cx));
710                    *backpressure_promise.borrow_mut() = Some(promise);
711                }
712
713                // Return the result of reacting to backpressurePromise with the following fulfillment steps:
714                let result_promise = Promise::new2(cx, global);
715                rooted!(&in(cx) let mut fulfillment_handler = Some(TransferBackPressurePromiseReaction {
716                    port: port.clone(),
717                    backpressure_promise: backpressure_promise.clone(),
718                    chunk: Heap::boxed(chunk.get()),
719                    result_promise: result_promise.clone(),
720                }));
721                let handler = PromiseNativeHandler::new(
722                    global,
723                    fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
724                    None,
725                    CanGc::from_cx(cx),
726                );
727                let mut realm = enter_auto_realm(cx, global);
728                let realm = &mut realm.current_realm();
729                let in_realm_proof = realm.into();
730                let comp = InRealm::Already(&in_realm_proof);
731                backpressure_promise
732                    .borrow()
733                    .as_ref()
734                    .expect("Promise must be some by now.")
735                    .append_native_handler(&handler, comp, CanGc::from_cx(realm));
736                result_promise
737            },
738            UnderlyingSinkType::Transform(stream, _) => {
739                // Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
740                stream
741                    .transform_stream_default_sink_write_algorithm(cx, global, chunk)
742                    .expect("Transform stream default sink write algorithm should not fail.")
743            },
744        }
745    }
746
747    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm>
748    fn call_close_algorithm(
749        &self,
750        cx: &mut js::context::JSContext,
751        global: &GlobalScope,
752    ) -> Rc<Promise> {
753        match &self.underlying_sink_type {
754            UnderlyingSinkType::Js {
755                abort: _,
756                start: _,
757                close,
758                write: _,
759            } => {
760                rooted!(&in(cx) let mut this_object = ptr::null_mut::<JSObject>());
761                this_object.set(self.underlying_sink_obj.get());
762                let algo = close.borrow().clone();
763                let result = if let Some(algo) = algo {
764                    algo.Call_(
765                        &this_object.handle(),
766                        ExceptionHandling::Rethrow,
767                        CanGc::from_cx(cx),
768                    )
769                } else {
770                    Ok(Promise::new_resolved(
771                        global,
772                        cx.into(),
773                        (),
774                        CanGc::from_cx(cx),
775                    ))
776                };
777                result.unwrap_or_else(|e| {
778                    let promise = Promise::new2(cx, global);
779                    promise.reject_error(e, CanGc::from_cx(cx));
780                    promise
781                })
782            },
783            UnderlyingSinkType::Transfer { port, .. } => {
784                // The steps from the `closeAlgorithm` at
785                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
786
787                // Perform ! PackAndPostMessage(port, "close", undefined).
788                rooted!(&in(cx) let mut value = UndefinedValue());
789                port.pack_and_post_message("close", value.handle(), CanGc::from_cx(cx))
790                    .expect("Sending close should not fail.");
791
792                // Disentangle port.
793                global.disentangle_port(port, CanGc::from_cx(cx));
794
795                // Return a promise resolved with undefined.
796                Promise::new_resolved(global, cx.into(), (), CanGc::from_cx(cx))
797            },
798            UnderlyingSinkType::Transform(stream, _) => {
799                // Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
800                stream
801                    .transform_stream_default_sink_close_algorithm(cx, global)
802                    .expect("Transform stream default sink close algorithm should not fail.")
803            },
804        }
805    }
806
807    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close>
808    pub(crate) fn process_close(&self, cx: &mut js::context::JSContext, global: &GlobalScope) {
809        // Let stream be controller.[[stream]].
810        let Some(stream) = self.stream.get() else {
811            unreachable!("Controller should have a stream");
812        };
813
814        // Perform ! WritableStreamMarkCloseRequestInFlight(stream).
815        stream.mark_close_request_in_flight();
816
817        // Perform ! DequeueValue(controller).
818        self.queue
819            .dequeue_value(cx.into(), None, CanGc::from_cx(cx));
820
821        // Assert: controller.[[queue]] is empty.
822        assert!(self.queue.is_empty());
823
824        // Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
825        let sink_close_promise = self.call_close_algorithm(cx, global);
826
827        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
828        self.clear_algorithms();
829
830        // Upon fulfillment of sinkClosePromise,
831        rooted!(&in(cx) let mut fulfillment_handler = Some(CloseAlgorithmFulfillmentHandler {
832            stream: Dom::from_ref(&stream),
833        }));
834
835        // Upon rejection of sinkClosePromise with reason reason,
836        rooted!(&in(cx) let mut rejection_handler = Some(CloseAlgorithmRejectionHandler {
837            stream: Dom::from_ref(&stream),
838        }));
839
840        // Attach handlers to the promise.
841        let handler = PromiseNativeHandler::new(
842            global,
843            fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
844            rejection_handler.take().map(|h| Box::new(h) as Box<_>),
845            CanGc::from_cx(cx),
846        );
847        let mut realm = enter_auto_realm(cx, global);
848        let realm = &mut realm.current_realm();
849        let in_realm_proof = realm.into();
850        let comp = InRealm::Already(&in_realm_proof);
851        sink_close_promise.append_native_handler(&handler, comp, CanGc::from_cx(realm));
852    }
853
854    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed>
855    fn advance_queue_if_needed(&self, cx: &mut js::context::JSContext, global: &GlobalScope) {
856        // Let stream be controller.[[stream]].
857        let Some(stream) = self.stream.get() else {
858            unreachable!("Controller should have a stream");
859        };
860
861        // If controller.[[started]] is false, return.
862        if !self.started.get() {
863            return;
864        }
865
866        // If stream.[[inFlightWriteRequest]] is not undefined, return.
867        if stream.has_in_flight_write_request() {
868            return;
869        }
870
871        // Let state be stream.[[state]].
872
873        // Assert: state is not "closed" or "errored".
874        assert!(!(stream.is_errored() || stream.is_closed()));
875
876        // If state is "erroring",
877        if stream.is_erroring() {
878            // Perform ! WritableStreamFinishErroring(stream).
879            stream.finish_erroring(cx, global);
880
881            // Return.
882            return;
883        }
884
885        // Let value be ! PeekQueueValue(controller).
886        rooted!(&in(cx) let mut value = UndefinedValue());
887        let is_closed = {
888            // If controller.[[queue]] is empty, return.
889            if self.queue.is_empty() {
890                return;
891            }
892            self.queue
893                .peek_queue_value(cx.into(), value.handle_mut(), CanGc::from_cx(cx))
894        };
895
896        if is_closed {
897            // If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
898            self.process_close(cx, global);
899        } else {
900            // Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
901            self.process_write(cx, value.handle(), global);
902        };
903    }
904
905    /// <https://streams.spec.whatwg.org/#ws-default-controller-private-error>
906    pub(crate) fn perform_error_steps(&self) {
907        // Perform ! ResetQueue(this).
908        self.queue.reset();
909    }
910
911    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write>
912    fn process_write(
913        &self,
914        cx: &mut js::context::JSContext,
915        chunk: SafeHandleValue,
916        global: &GlobalScope,
917    ) {
918        // Let stream be controller.[[stream]].
919        let Some(stream) = self.stream.get() else {
920            unreachable!("Controller should have a stream");
921        };
922
923        // Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
924        stream.mark_first_write_request_in_flight();
925
926        // Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
927        let sink_write_promise = self.call_write_algorithm(cx, chunk, global);
928
929        // Upon fulfillment of sinkWritePromise,
930        rooted!(&in(cx) let mut fulfillment_handler = Some(WriteAlgorithmFulfillmentHandler {
931            controller: Dom::from_ref(self),
932        }));
933
934        // Upon rejection of sinkWritePromise with reason,
935        rooted!(&in(cx) let mut rejection_handler = Some(WriteAlgorithmRejectionHandler {
936            controller: Dom::from_ref(self),
937        }));
938
939        // Attach handlers to the promise.
940        let handler = PromiseNativeHandler::new(
941            global,
942            fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
943            rejection_handler.take().map(|h| Box::new(h) as Box<_>),
944            CanGc::from_cx(cx),
945        );
946        let mut realm = enter_auto_realm(cx, global);
947        let realm = &mut realm.current_realm();
948        let in_realm_proof = realm.into();
949        let comp = InRealm::Already(&in_realm_proof);
950        sink_write_promise.append_native_handler(&handler, comp, CanGc::from_cx(realm));
951    }
952
953    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size>
954    pub(crate) fn get_desired_size(&self) -> f64 {
955        // Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
956        let desired_size = self.strategy_hwm - self.queue.total_size.get().clamp(0.0, f64::MAX);
957        desired_size.clamp(desired_size, self.strategy_hwm)
958    }
959
960    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure>
961    fn get_backpressure(&self) -> bool {
962        // Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
963        let desired_size = self.get_desired_size();
964
965        // Return true if desiredSize ≤ 0, or false otherwise.
966        desired_size == 0.0 || desired_size.is_sign_negative()
967    }
968
969    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size>
970    pub(crate) fn get_chunk_size(
971        &self,
972        cx: &mut js::context::JSContext,
973        global: &GlobalScope,
974        chunk: SafeHandleValue,
975    ) -> f64 {
976        // If controller.[[strategySizeAlgorithm]] is undefined, then:
977        let Some(strategy_size) = self.strategy_size.borrow().clone() else {
978            // Assert: controller.[[stream]].[[state]] is not "writable".
979            let Some(stream) = self.stream.get() else {
980                unreachable!("Controller should have a stream");
981            };
982            assert!(!stream.is_writable());
983
984            // Return 1.
985            return 1.0;
986        };
987
988        // Let returnValue be the result of performing controller.[[strategySizeAlgorithm]],
989        // passing in chunk, and interpreting the result as a completion record.
990        let result = strategy_size.Call__(chunk, ExceptionHandling::Rethrow, CanGc::from_cx(cx));
991
992        match result {
993            // Let chunkSize be result.[[Value]].
994            Ok(size) => size,
995            Err(error) => {
996                // If result is an abrupt completion,
997
998                // Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
999                // Create a rooted value for the error.
1000                rooted!(&in(cx) let mut rooted_error = UndefinedValue());
1001                error.to_jsval(
1002                    cx.into(),
1003                    global,
1004                    rooted_error.handle_mut(),
1005                    CanGc::from_cx(cx),
1006                );
1007                self.error_if_needed(cx, rooted_error.handle(), global);
1008
1009                // Return 1.
1010                1.0
1011            },
1012        }
1013    }
1014
1015    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-write>
1016    pub(crate) fn write(
1017        &self,
1018        cx: &mut js::context::JSContext,
1019        global: &GlobalScope,
1020        chunk: SafeHandleValue,
1021        chunk_size: f64,
1022    ) {
1023        // Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
1024        let enqueue_result = self
1025            .queue
1026            .enqueue_value_with_size(EnqueuedValue::Js(ValueWithSize {
1027                value: Heap::boxed(chunk.get()),
1028                size: chunk_size,
1029            }));
1030
1031        // If enqueueResult is an abrupt completion,
1032        if let Err(error) = enqueue_result {
1033            // Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
1034            // Create a rooted value for the error.
1035            rooted!(&in(cx) let mut rooted_error = UndefinedValue());
1036            error.to_jsval(
1037                cx.into(),
1038                global,
1039                rooted_error.handle_mut(),
1040                CanGc::from_cx(cx),
1041            );
1042            self.error_if_needed(cx, rooted_error.handle(), global);
1043
1044            // Return.
1045            return;
1046        }
1047
1048        // Let stream be controller.[[stream]].
1049        let Some(stream) = self.stream.get() else {
1050            unreachable!("Controller should have a stream");
1051        };
1052
1053        // If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
1054        if !stream.close_queued_or_in_flight() && stream.is_writable() {
1055            // Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
1056            let backpressure = self.get_backpressure();
1057
1058            // Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
1059            stream.update_backpressure(backpressure, global, CanGc::from_cx(cx));
1060        }
1061
1062        // Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
1063        self.advance_queue_if_needed(cx, global);
1064    }
1065
1066    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed>
1067    pub(crate) fn error_if_needed(
1068        &self,
1069        cx: &mut js::context::JSContext,
1070        error: SafeHandleValue,
1071        global: &GlobalScope,
1072    ) {
1073        // Let stream be controller.[[stream]].
1074        let Some(stream) = self.stream.get() else {
1075            unreachable!("Controller should have a stream");
1076        };
1077
1078        // If stream.[[state]] is "writable",
1079        if stream.is_writable() {
1080            // Perform ! WritableStreamDefaultControllerError(controller, e).
1081            self.error(cx, &stream, error, global);
1082        }
1083    }
1084
1085    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-error>
1086    fn error(
1087        &self,
1088        cx: &mut js::context::JSContext,
1089        stream: &WritableStream,
1090        e: SafeHandleValue,
1091        global: &GlobalScope,
1092    ) {
1093        // Let stream be controller.[[stream]].
1094        // Done above with the argument.
1095
1096        // Assert: stream.[[state]] is "writable".
1097        assert!(stream.is_writable());
1098
1099        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
1100        self.clear_algorithms();
1101
1102        // Perform ! WritableStreamStartErroring(stream, error).
1103        stream.start_erroring(cx, global, e);
1104    }
1105}
1106
1107impl WritableStreamDefaultControllerMethods<crate::DomTypeHolder>
1108    for WritableStreamDefaultController
1109{
1110    /// <https://streams.spec.whatwg.org/#ws-default-controller-error>
1111    fn Error(&self, cx: &mut CurrentRealm, e: SafeHandleValue) {
1112        // Let state be this.[[stream]].[[state]].
1113        let Some(stream) = self.stream.get() else {
1114            unreachable!("Controller should have a stream");
1115        };
1116
1117        // If state is not "writable", return.
1118        if !stream.is_writable() {
1119            return;
1120        }
1121
1122        let global = GlobalScope::from_current_realm(cx);
1123
1124        // Perform ! WritableStreamDefaultControllerError(this, e).
1125        self.error(cx, &stream, e, &global);
1126    }
1127
1128    /// <https://streams.spec.whatwg.org/#ws-default-controller-signal>
1129    fn Signal(&self) -> DomRoot<AbortSignal> {
1130        // Return this.[[abortController]]’s signal.
1131        self.abort_controller.signal()
1132    }
1133}