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_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.into(), &global, v, CanGc::from_cx(cx));
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.into(), &global, CanGc::from_cx(cx))
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.into(), &global, v, CanGc::from_cx(cx));
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.into(), &global, can_gc)
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.into(), &global, v, CanGc::from_cx(cx));
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: SafeJSContext, global: &GlobalScope, can_gc: CanGc) {
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, can_gc);
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: SafeJSContext,
586        global: &GlobalScope,
587        reason: SafeHandleValue,
588        can_gc: CanGc,
589    ) -> Rc<Promise> {
590        let result = match &self.underlying_sink_type {
591            UnderlyingSinkType::Js {
592                abort,
593                start: _,
594                close: _,
595                write: _,
596            } => {
597                rooted!(in(*cx) let this_object = self.underlying_sink_obj.get());
598                let algo = abort.borrow().clone();
599                // Let result be the result of performing this.[[abortAlgorithm]], passing reason.
600                let result = if let Some(algo) = algo {
601                    algo.Call_(
602                        &this_object.handle(),
603                        Some(reason),
604                        ExceptionHandling::Rethrow,
605                        can_gc,
606                    )
607                } else {
608                    Ok(Promise::new_resolved(global, cx, (), can_gc))
609                };
610                result.unwrap_or_else(|e| {
611                    let promise = Promise::new(global, can_gc);
612                    promise.reject_error(e, can_gc);
613                    promise
614                })
615            },
616            UnderlyingSinkType::Transfer { port, .. } => {
617                // The steps from the `abortAlgorithm` at
618                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
619
620                // Let result be PackAndPostMessageHandlingError(port, "error", reason).
621                let result = port.pack_and_post_message_handling_error("error", reason, can_gc);
622
623                // Disentangle port.
624                global.disentangle_port(port, can_gc);
625
626                let promise = Promise::new(global, can_gc);
627
628                // If result is an abrupt completion, return a promise rejected with result.[[Value]]
629                if let Err(error) = result {
630                    promise.reject_error(error, can_gc);
631                } else {
632                    // Otherwise, return a promise resolved with undefined.
633                    promise.resolve_native(&(), can_gc);
634                }
635                promise
636            },
637            UnderlyingSinkType::Transform(stream, _) => {
638                // Return ! TransformStreamDefaultSinkAbortAlgorithm(stream, reason).
639                stream
640                    .transform_stream_default_sink_abort_algorithm(cx, global, reason, can_gc)
641                    .expect("Transform stream default sink abort algorithm should not fail.")
642            },
643        };
644
645        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
646        self.clear_algorithms();
647
648        result
649    }
650
651    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-writealgorithm>
652    fn call_write_algorithm(
653        &self,
654        cx: SafeJSContext,
655        chunk: SafeHandleValue,
656        global: &GlobalScope,
657        can_gc: CanGc,
658    ) -> Rc<Promise> {
659        match &self.underlying_sink_type {
660            UnderlyingSinkType::Js {
661                abort: _,
662                start: _,
663                close: _,
664                write,
665            } => {
666                rooted!(in(*cx) let this_object = self.underlying_sink_obj.get());
667                let algo = write.borrow().clone();
668                let result = if let Some(algo) = algo {
669                    algo.Call_(
670                        &this_object.handle(),
671                        chunk,
672                        self,
673                        ExceptionHandling::Rethrow,
674                        can_gc,
675                    )
676                } else {
677                    Ok(Promise::new_resolved(global, cx, (), can_gc))
678                };
679                result.unwrap_or_else(|e| {
680                    let promise = Promise::new(global, can_gc);
681                    promise.reject_error(e, can_gc);
682                    promise
683                })
684            },
685            UnderlyingSinkType::Transfer {
686                backpressure_promise,
687                port,
688            } => {
689                // The steps from the `writeAlgorithm` at
690                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
691
692                // If backpressurePromise is undefined,
693                // set backpressurePromise to a promise resolved with undefined.
694                if backpressure_promise.borrow().is_none() {
695                    let promise = Promise::new_resolved(global, cx, (), can_gc);
696                    *backpressure_promise.borrow_mut() = Some(promise);
697                }
698
699                // Return the result of reacting to backpressurePromise with the following fulfillment steps:
700                let result_promise = Promise::new(global, can_gc);
701                rooted!(in(*cx) let mut fulfillment_handler = Some(TransferBackPressurePromiseReaction {
702                    port: port.clone(),
703                    backpressure_promise: backpressure_promise.clone(),
704                    chunk: Heap::boxed(chunk.get()),
705                    result_promise: result_promise.clone(),
706                }));
707                let handler = PromiseNativeHandler::new(
708                    global,
709                    fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
710                    None,
711                    can_gc,
712                );
713                let realm = enter_realm(global);
714                let comp = InRealm::Entered(&realm);
715                backpressure_promise
716                    .borrow()
717                    .as_ref()
718                    .expect("Promise must be some by now.")
719                    .append_native_handler(&handler, comp, can_gc);
720                result_promise
721            },
722            UnderlyingSinkType::Transform(stream, _) => {
723                // Return ! TransformStreamDefaultSinkWriteAlgorithm(stream, chunk).
724                stream
725                    .transform_stream_default_sink_write_algorithm(cx, global, chunk, can_gc)
726                    .expect("Transform stream default sink write algorithm should not fail.")
727            },
728        }
729    }
730
731    /// <https://streams.spec.whatwg.org/#writablestreamdefaultcontroller-closealgorithm>
732    fn call_close_algorithm(
733        &self,
734        cx: SafeJSContext,
735        global: &GlobalScope,
736        can_gc: CanGc,
737    ) -> Rc<Promise> {
738        match &self.underlying_sink_type {
739            UnderlyingSinkType::Js {
740                abort: _,
741                start: _,
742                close,
743                write: _,
744            } => {
745                rooted!(in(*cx) let mut this_object = ptr::null_mut::<JSObject>());
746                this_object.set(self.underlying_sink_obj.get());
747                let algo = close.borrow().clone();
748                let result = if let Some(algo) = algo {
749                    algo.Call_(&this_object.handle(), ExceptionHandling::Rethrow, can_gc)
750                } else {
751                    Ok(Promise::new_resolved(global, cx, (), can_gc))
752                };
753                result.unwrap_or_else(|e| {
754                    let promise = Promise::new(global, can_gc);
755                    promise.reject_error(e, can_gc);
756                    promise
757                })
758            },
759            UnderlyingSinkType::Transfer { port, .. } => {
760                // The steps from the `closeAlgorithm` at
761                // <https://streams.spec.whatwg.org/#abstract-opdef-setupcrossrealmtransformwritable>
762
763                // Perform ! PackAndPostMessage(port, "close", undefined).
764                rooted!(in(*cx) let mut value = UndefinedValue());
765                port.pack_and_post_message("close", value.handle(), can_gc)
766                    .expect("Sending close should not fail.");
767
768                // Disentangle port.
769                global.disentangle_port(port, can_gc);
770
771                // Return a promise resolved with undefined.
772                Promise::new_resolved(global, cx, (), can_gc)
773            },
774            UnderlyingSinkType::Transform(stream, _) => {
775                // Return ! TransformStreamDefaultSinkCloseAlgorithm(stream).
776                stream
777                    .transform_stream_default_sink_close_algorithm(cx, global, can_gc)
778                    .expect("Transform stream default sink close algorithm should not fail.")
779            },
780        }
781    }
782
783    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-close>
784    pub(crate) fn process_close(&self, cx: SafeJSContext, global: &GlobalScope, can_gc: CanGc) {
785        // Let stream be controller.[[stream]].
786        let Some(stream) = self.stream.get() else {
787            unreachable!("Controller should have a stream");
788        };
789
790        // Perform ! WritableStreamMarkCloseRequestInFlight(stream).
791        stream.mark_close_request_in_flight();
792
793        // Perform ! DequeueValue(controller).
794        self.queue.dequeue_value(cx, None, can_gc);
795
796        // Assert: controller.[[queue]] is empty.
797        assert!(self.queue.is_empty());
798
799        // Let sinkClosePromise be the result of performing controller.[[closeAlgorithm]].
800        let sink_close_promise = self.call_close_algorithm(cx, global, can_gc);
801
802        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
803        self.clear_algorithms();
804
805        // Upon fulfillment of sinkClosePromise,
806        rooted!(in(*cx) let mut fulfillment_handler = Some(CloseAlgorithmFulfillmentHandler {
807            stream: Dom::from_ref(&stream),
808        }));
809
810        // Upon rejection of sinkClosePromise with reason reason,
811        rooted!(in(*cx) let mut rejection_handler = Some(CloseAlgorithmRejectionHandler {
812            stream: Dom::from_ref(&stream),
813        }));
814
815        // Attach handlers to the promise.
816        let handler = PromiseNativeHandler::new(
817            global,
818            fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
819            rejection_handler.take().map(|h| Box::new(h) as Box<_>),
820            can_gc,
821        );
822        let realm = enter_realm(global);
823        let comp = InRealm::Entered(&realm);
824        sink_close_promise.append_native_handler(&handler, comp, can_gc);
825    }
826
827    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-advance-queue-if-needed>
828    fn advance_queue_if_needed(&self, cx: SafeJSContext, global: &GlobalScope, can_gc: CanGc) {
829        // Let stream be controller.[[stream]].
830        let Some(stream) = self.stream.get() else {
831            unreachable!("Controller should have a stream");
832        };
833
834        // If controller.[[started]] is false, return.
835        if !self.started.get() {
836            return;
837        }
838
839        // If stream.[[inFlightWriteRequest]] is not undefined, return.
840        if stream.has_in_flight_write_request() {
841            return;
842        }
843
844        // Let state be stream.[[state]].
845
846        // Assert: state is not "closed" or "errored".
847        assert!(!(stream.is_errored() || stream.is_closed()));
848
849        // If state is "erroring",
850        if stream.is_erroring() {
851            // Perform ! WritableStreamFinishErroring(stream).
852            stream.finish_erroring(cx, global, can_gc);
853
854            // Return.
855            return;
856        }
857
858        // Let value be ! PeekQueueValue(controller).
859        rooted!(in(*cx) let mut value = UndefinedValue());
860        let is_closed = {
861            // If controller.[[queue]] is empty, return.
862            if self.queue.is_empty() {
863                return;
864            }
865            self.queue.peek_queue_value(cx, value.handle_mut(), can_gc)
866        };
867
868        if is_closed {
869            // If value is the close sentinel, perform ! WritableStreamDefaultControllerProcessClose(controller).
870            self.process_close(cx, global, can_gc);
871        } else {
872            // Otherwise, perform ! WritableStreamDefaultControllerProcessWrite(controller, value).
873            self.process_write(cx, value.handle(), global, can_gc);
874        };
875    }
876
877    /// <https://streams.spec.whatwg.org/#ws-default-controller-private-error>
878    pub(crate) fn perform_error_steps(&self) {
879        // Perform ! ResetQueue(this).
880        self.queue.reset();
881    }
882
883    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-process-write>
884    fn process_write(
885        &self,
886        cx: SafeJSContext,
887        chunk: SafeHandleValue,
888        global: &GlobalScope,
889        can_gc: CanGc,
890    ) {
891        // Let stream be controller.[[stream]].
892        let Some(stream) = self.stream.get() else {
893            unreachable!("Controller should have a stream");
894        };
895
896        // Perform ! WritableStreamMarkFirstWriteRequestInFlight(stream).
897        stream.mark_first_write_request_in_flight();
898
899        // Let sinkWritePromise be the result of performing controller.[[writeAlgorithm]], passing in chunk.
900        let sink_write_promise = self.call_write_algorithm(cx, chunk, global, can_gc);
901
902        // Upon fulfillment of sinkWritePromise,
903        rooted!(in(*cx) let mut fulfillment_handler = Some(WriteAlgorithmFulfillmentHandler {
904            controller: Dom::from_ref(self),
905        }));
906
907        // Upon rejection of sinkWritePromise with reason,
908        rooted!(in(*cx) let mut rejection_handler = Some(WriteAlgorithmRejectionHandler {
909            controller: Dom::from_ref(self),
910        }));
911
912        // Attach handlers to the promise.
913        let handler = PromiseNativeHandler::new(
914            global,
915            fulfillment_handler.take().map(|h| Box::new(h) as Box<_>),
916            rejection_handler.take().map(|h| Box::new(h) as Box<_>),
917            can_gc,
918        );
919        let realm = enter_realm(global);
920        let comp = InRealm::Entered(&realm);
921        sink_write_promise.append_native_handler(&handler, comp, can_gc);
922    }
923
924    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-desired-size>
925    pub(crate) fn get_desired_size(&self) -> f64 {
926        // Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
927        let desired_size = self.strategy_hwm - self.queue.total_size.get().clamp(0.0, f64::MAX);
928        desired_size.clamp(desired_size, self.strategy_hwm)
929    }
930
931    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-backpressure>
932    fn get_backpressure(&self) -> bool {
933        // Let desiredSize be ! WritableStreamDefaultControllerGetDesiredSize(controller).
934        let desired_size = self.get_desired_size();
935
936        // Return true if desiredSize ≤ 0, or false otherwise.
937        desired_size == 0.0 || desired_size.is_sign_negative()
938    }
939
940    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-get-chunk-size>
941    pub(crate) fn get_chunk_size(
942        &self,
943        cx: SafeJSContext,
944        global: &GlobalScope,
945        chunk: SafeHandleValue,
946        can_gc: CanGc,
947    ) -> f64 {
948        // If controller.[[strategySizeAlgorithm]] is undefined, then:
949        let Some(strategy_size) = self.strategy_size.borrow().clone() else {
950            // Assert: controller.[[stream]].[[state]] is not "writable".
951            let Some(stream) = self.stream.get() else {
952                unreachable!("Controller should have a stream");
953            };
954            assert!(!stream.is_writable());
955
956            // Return 1.
957            return 1.0;
958        };
959
960        // Let returnValue be the result of performing controller.[[strategySizeAlgorithm]],
961        // passing in chunk, and interpreting the result as a completion record.
962        let result = strategy_size.Call__(chunk, ExceptionHandling::Rethrow, can_gc);
963
964        match result {
965            // Let chunkSize be result.[[Value]].
966            Ok(size) => size,
967            Err(error) => {
968                // If result is an abrupt completion,
969
970                // Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, returnValue.[[Value]]).
971                // Create a rooted value for the error.
972                rooted!(in(*cx) let mut rooted_error = UndefinedValue());
973                error.to_jsval(cx, global, rooted_error.handle_mut(), can_gc);
974                self.error_if_needed(cx, rooted_error.handle(), global, can_gc);
975
976                // Return 1.
977                1.0
978            },
979        }
980    }
981
982    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-write>
983    pub(crate) fn write(
984        &self,
985        cx: SafeJSContext,
986        global: &GlobalScope,
987        chunk: SafeHandleValue,
988        chunk_size: f64,
989        can_gc: CanGc,
990    ) {
991        // Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
992        let enqueue_result = self
993            .queue
994            .enqueue_value_with_size(EnqueuedValue::Js(ValueWithSize {
995                value: Heap::boxed(chunk.get()),
996                size: chunk_size,
997            }));
998
999        // If enqueueResult is an abrupt completion,
1000        if let Err(error) = enqueue_result {
1001            // Perform ! WritableStreamDefaultControllerErrorIfNeeded(controller, enqueueResult.[[Value]]).
1002            // Create a rooted value for the error.
1003            rooted!(in(*cx) let mut rooted_error = UndefinedValue());
1004            error.to_jsval(cx, global, rooted_error.handle_mut(), can_gc);
1005            self.error_if_needed(cx, rooted_error.handle(), global, can_gc);
1006
1007            // Return.
1008            return;
1009        }
1010
1011        // Let stream be controller.[[stream]].
1012        let Some(stream) = self.stream.get() else {
1013            unreachable!("Controller should have a stream");
1014        };
1015
1016        // If ! WritableStreamCloseQueuedOrInFlight(stream) is false and stream.[[state]] is "writable",
1017        if !stream.close_queued_or_in_flight() && stream.is_writable() {
1018            // Let backpressure be ! WritableStreamDefaultControllerGetBackpressure(controller).
1019            let backpressure = self.get_backpressure();
1020
1021            // Perform ! WritableStreamUpdateBackpressure(stream, backpressure).
1022            stream.update_backpressure(backpressure, global, can_gc);
1023        }
1024
1025        // Perform ! WritableStreamDefaultControllerAdvanceQueueIfNeeded(controller).
1026        self.advance_queue_if_needed(cx, global, can_gc);
1027    }
1028
1029    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-error-if-needed>
1030    pub(crate) fn error_if_needed(
1031        &self,
1032        cx: SafeJSContext,
1033        error: SafeHandleValue,
1034        global: &GlobalScope,
1035        can_gc: CanGc,
1036    ) {
1037        // Let stream be controller.[[stream]].
1038        let Some(stream) = self.stream.get() else {
1039            unreachable!("Controller should have a stream");
1040        };
1041
1042        // If stream.[[state]] is "writable",
1043        if stream.is_writable() {
1044            // Perform ! WritableStreamDefaultControllerError(controller, e).
1045            self.error(&stream, cx, error, global, can_gc);
1046        }
1047    }
1048
1049    /// <https://streams.spec.whatwg.org/#writable-stream-default-controller-error>
1050    pub(crate) fn error(
1051        &self,
1052        stream: &WritableStream,
1053        cx: SafeJSContext,
1054        e: SafeHandleValue,
1055        global: &GlobalScope,
1056        can_gc: CanGc,
1057    ) {
1058        // Let stream be controller.[[stream]].
1059        // Done above with the argument.
1060
1061        // Assert: stream.[[state]] is "writable".
1062        assert!(stream.is_writable());
1063
1064        // Perform ! WritableStreamDefaultControllerClearAlgorithms(controller).
1065        self.clear_algorithms();
1066
1067        // Perform ! WritableStreamStartErroring(stream, error).
1068        stream.start_erroring(cx, global, e, can_gc);
1069    }
1070}
1071
1072impl WritableStreamDefaultControllerMethods<crate::DomTypeHolder>
1073    for WritableStreamDefaultController
1074{
1075    /// <https://streams.spec.whatwg.org/#ws-default-controller-error>
1076    fn Error(&self, cx: SafeJSContext, e: SafeHandleValue, realm: InRealm, can_gc: CanGc) {
1077        // Let state be this.[[stream]].[[state]].
1078        let Some(stream) = self.stream.get() else {
1079            unreachable!("Controller should have a stream");
1080        };
1081
1082        // If state is not "writable", return.
1083        if !stream.is_writable() {
1084            return;
1085        }
1086
1087        let global = GlobalScope::from_safe_context(cx, realm);
1088
1089        // Perform ! WritableStreamDefaultControllerError(this, e).
1090        self.error(&stream, cx, e, &global, can_gc);
1091    }
1092
1093    /// <https://streams.spec.whatwg.org/#ws-default-controller-signal>
1094    fn Signal(&self) -> DomRoot<AbortSignal> {
1095        // Return this.[[abortController]]’s signal.
1096        self.abort_controller.signal()
1097    }
1098}