Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / streams / readable_stream_tee.lucb

#==============================================================================================
#
#   readable_stream_tee - what teeing a byte stream with a default reader keeps:
#   ReadableByteStreamTeeParams and the default read request that feeds both branches
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Streams/ReadableStreamTee.cpp (lines 159-320), as part of the
#       ReadableStream stand-in of DESIGN.md §3.6 (region p2s). Teeing a default stream (lines
#       20-157) and the BYOB branch (lines 322-488) are phase 4.
#
#       Copyright (c) 2025, Tim Flynn <trflynn89@ladybird.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: ReadableByteStreamTeeParams =============================================================

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:163 Web::Streams::Detail::ReadableByteStreamTeeParams::ReadableByteStreamTeeParams,
## with the default member initializers (the reasons undefined; the flags and branches are the zeroed cell's).
pub func streams_readable_byte_stream_tee_params_construct(this: StreamsReadableByteStreamTeeParams*, reader: StreamsReadableStreamReader):
    this.reason1 = js_undefined()
    this.reason2 = js_undefined()
    this.reader = reader

## `realm.create<Detail::ReadableByteStreamTeeParams>(reader)`.
pub func realm_create_streams_readable_byte_stream_tee_params(realm: Realm*, reader: StreamsReadableStreamReader) -> StreamsReadableByteStreamTeeParams*:
    let this = (StreamsReadableByteStreamTeeParams*)web_allocate_cell(realm, &streams_readable_byte_stream_tee_params_class)
    streams_readable_byte_stream_tee_params_construct(this, reader)
    web_initialize_cell(this.cell(), realm)
    return this

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:168 Web::Streams::Detail::ReadableByteStreamTeeParams::visit_edges (override).
pub func streams_readable_byte_stream_tee_params_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (StreamsReadableByteStreamTeeParams*)base
    gc.cell_visit_edges_impl(base, visitor)
    js_visit_value(visitor, this.reason1)
    js_visit_value(visitor, this.reason2)
    gc.cell_visitor_visit_t(visitor, this.branch1)
    gc.cell_visitor_visit_t(visitor, this.branch2)
    gc.cell_visitor_visit_t(visitor, this.pull1_algorithm)
    gc.cell_visitor_visit_t(visitor, this.pull2_algorithm)
    streams_visit_readable_stream_reader(visitor, this.reader)

# mark: ReadableByteStreamTeeDefaultReadRequest =================================================

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:181 Web::Streams::Detail::ReadableByteStreamTeeDefaultReadRequest::ReadableByteStreamTeeDefaultReadRequest.
func streams_readable_byte_stream_tee_default_read_request_construct(this: StreamsReadableByteStreamTeeDefaultReadRequest*, realm: Realm*, stream: StreamsReadableStream*, params: StreamsReadableByteStreamTeeParams*, cancel_promise: JsPromiseCapability*):
    this.m_realm = realm
    this.m_stream = stream
    this.m_params = params
    this.m_cancel_promise = cancel_promise

## `realm.heap().allocate<Detail::ReadableByteStreamTeeDefaultReadRequest>(realm, stream, params, cancel_promise)`.
pub func heap_allocate_streams_readable_byte_stream_tee_default_read_request(heap: gc.Heap*, realm: Realm*, stream: StreamsReadableStream*, params: StreamsReadableByteStreamTeeParams*, cancel_promise: JsPromiseCapability*) -> StreamsReadableByteStreamTeeDefaultReadRequest*:
    let this = (StreamsReadableByteStreamTeeDefaultReadRequest*)web_heap_allocate_cell(heap, &streams_readable_byte_stream_tee_default_read_request_class)
    gc.heap_defer_gc(heap)
    streams_readable_byte_stream_tee_default_read_request_construct(this, realm, stream, params, cancel_promise)
    gc.heap_undefer_gc(heap)
    return this

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:193 Web::Streams::Detail::ReadableByteStreamTeeDefaultReadRequest::visit_edges (override).
pub func streams_readable_byte_stream_tee_default_read_request_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (StreamsReadableByteStreamTeeDefaultReadRequest*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t_2(visitor, this.m_realm)
    gc.cell_visitor_visit_t_2(visitor, this.m_stream)
    gc.cell_visitor_visit_t_2(visitor, this.m_params)
    gc.cell_visitor_visit_t_2(visitor, this.m_cancel_promise)

## The captures of on_chunk's microtask, `[this, chunk]`.
struct StreamsReadableByteStreamTeeDefaultReadRequestOnChunk:
    var this: StreamsReadableByteStreamTeeDefaultReadRequest*
    var chunk: JsValue

## on_chunk's microtask: enqueue the chunk into branch1 and a clone of it into branch2.
func streams_readable_byte_stream_tee_default_read_request_on_chunk_microtask(context: void*?):
    let captures = (StreamsReadableByteStreamTeeDefaultReadRequestOnChunk*)(context else trap("no captures"))
    let this = captures.this
    let params = this.m_params
    let chunk = captures.chunk

    var execution_context: HtmlTemporaryExecutionContext = ---
    html_temporary_execution_context_construct_realm(&execution_context, this.m_realm, HtmlTemporaryExecutionContextCallbacksEnabled.yes)
    defer html_temporary_execution_context_destruct(&execution_context)

    let controller1 = streams_readable_stream_byte_controller(params.branch1 else trap("VERIFY: branch1"))
    let controller2 = streams_readable_stream_byte_controller(params.branch2 else trap("VERIFY: branch2"))

    # 1. Set readAgainForBranch1 to false.
    params.read_again_for_branch1 = false

    # 2. Set readAgainForBranch2 to false.
    params.read_again_for_branch2 = false

    # 3. Let chunk1 and chunk2 be chunk.
    let chunk1 = chunk
    var chunk2 = chunk

    # 4. If canceled1 is false and canceled2 is false,
    if not params.canceled1 and not params.canceled2:
        # 1. Let cloneResult be CloneAsUint8Array(chunk).
        let chunk_view = realm_create_idl_array_buffer_view(this.m_realm, js_value_as_object(chunk))
        let clone_result = streams_clone_as_uint8_array(this.m_realm, chunk_view) catch:
            # 2. If cloneResult is an abrupt completion,
            let completion = bind_exception_to_throw_completion(realm_vm(this.m_realm), idl_take_pending_exception())

            # 1. Perform ! ReadableByteStreamControllerError(branch1.[[controller]], cloneResult.[[Value]]).
            streams_readable_byte_stream_controller_error_2(controller1, js_completion_value(&completion))

            # 2. Perform ! ReadableByteStreamControllerError(branch2.[[controller]], cloneResult.[[Value]]).
            streams_readable_byte_stream_controller_error_2(controller2, js_completion_value(&completion))

            # 3. Resolve cancelPromise with ! ReadableStreamCancel(stream, cloneResult.[[Value]]).
            let cancel_result = streams_readable_stream_cancel_2(this.m_stream, js_completion_value(&completion))

            idl_resolve_promise(this.m_realm, this.m_cancel_promise, js_value_from_object(js_promise_capability_promise(cancel_result)))

            # 4. Return.
            return

        # 3. Otherwise, set chunk2 to cloneResult.[[Value]].
        chunk2 = clone_result

    # 5. If canceled1 is false, perform ! ReadableByteStreamControllerEnqueue(branch1.[[controller]], chunk1).
    if not params.canceled1:
        streams_readable_byte_stream_controller_enqueue_2(controller1, chunk1) else trap("MUST: ReadableByteStreamControllerEnqueue")

    # 6. If canceled2 is false, perform ! ReadableByteStreamControllerEnqueue(branch2.[[controller]], chunk2).
    if not params.canceled2:
        streams_readable_byte_stream_controller_enqueue_2(controller2, chunk2) else trap("MUST: ReadableByteStreamControllerEnqueue")

    # 7. Set reading to false.
    params.reading = false

    # 8. If readAgainForBranch1 is true, perform pull1Algorithm.
    if params.read_again_for_branch1:
        let pull1_algorithm = params.pull1_algorithm else trap("VERIFY: pull1Algorithm")
        _ = ak.function0_call(&pull1_algorithm.function)
    # 9. Otherwise, if readAgainForBranch2 is true, perform pull2Algorithm.
    elif params.read_again_for_branch2:
        let pull2_algorithm = params.pull2_algorithm else trap("VERIFY: pull2Algorithm")
        _ = ak.function0_call(&pull2_algorithm.function)

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:203 Web::Streams::Detail::ReadableByteStreamTeeDefaultReadRequest::on_chunk (override).
## https://streams.spec.whatwg.org/#ref-for-read-request-chunk-steps④
pub func streams_readable_byte_stream_tee_default_read_request_on_chunk_impl(base: StreamsReadRequest*, chunk: JsValue):
    let this = (StreamsReadableByteStreamTeeDefaultReadRequest*)base
    # 1. Queue a microtask to perform the following steps:
    let captures = new StreamsReadableByteStreamTeeDefaultReadRequestOnChunk(this = this, chunk = chunk) else trap("out of memory")
    html_queue_a_microtask(none, gc.create_function0(realm_heap(this.m_realm), ak.Function0[unit](call = streams_readable_byte_stream_tee_default_read_request_on_chunk_microtask, context = captures)))

    # NOTE: The microtask delay here is necessary because it takes at least a microtask to detect errors, when we
    #       use reader.[[closedPromise]] below. We want errors in stream to error both branches immediately, so we
    #       cannot let successful synchronously-available reads happen ahead of asynchronously-available errors.

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:280 Web::Streams::Detail::ReadableByteStreamTeeDefaultReadRequest::on_close (override).
## https://streams.spec.whatwg.org/#ref-for-read-request-close-steps③
pub func streams_readable_byte_stream_tee_default_read_request_on_close_impl(base: StreamsReadRequest*):
    let this = (StreamsReadableByteStreamTeeDefaultReadRequest*)base
    let params = this.m_params
    let controller1 = streams_readable_stream_byte_controller(params.branch1 else trap("VERIFY: branch1"))
    let controller2 = streams_readable_stream_byte_controller(params.branch2 else trap("VERIFY: branch2"))

    # 1. Set reading to false.
    params.reading = false

    # 2. If canceled1 is false, perform ! ReadableByteStreamControllerClose(branch1.[[controller]]).
    if not params.canceled1:
        streams_readable_byte_stream_controller_close_2(controller1) else trap("MUST: ReadableByteStreamControllerClose")

    # 3. If canceled2 is false, perform ! ReadableByteStreamControllerClose(branch2.[[controller]]).
    if not params.canceled2:
        streams_readable_byte_stream_controller_close_2(controller2) else trap("MUST: ReadableByteStreamControllerClose")

    # 4. If branch1.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch1.[[controller]], 0).
    if not ak.singly_linked_list_is_empty(&controller1.m_pending_pull_intos):
        streams_readable_byte_stream_controller_respond(controller1, 0) else trap("MUST: ReadableByteStreamControllerRespond")

    # 5. If branch2.[[controller]].[[pendingPullIntos]] is not empty, perform ! ReadableByteStreamControllerRespond(branch2.[[controller]], 0).
    if not ak.singly_linked_list_is_empty(&controller2.m_pending_pull_intos):
        streams_readable_byte_stream_controller_respond(controller2, 0) else trap("MUST: ReadableByteStreamControllerRespond")

    # 6. If canceled1 is false or canceled2 is false, resolve cancelPromise with undefined.
    if not params.canceled1 or not params.canceled2:
        idl_resolve_promise(this.m_realm, this.m_cancel_promise, js_undefined())

## Ported from Libraries/LibWeb/Streams/ReadableStreamTee.cpp:315 Web::Streams::Detail::ReadableByteStreamTeeDefaultReadRequest::on_error (override).
## https://streams.spec.whatwg.org/#ref-for-read-request-error-steps④
pub func streams_readable_byte_stream_tee_default_read_request_on_error_impl(base: StreamsReadRequest*, error_: JsValue):
    let this = (StreamsReadableByteStreamTeeDefaultReadRequest*)base
    _ = error_
    # 1. Set reading to false.
    this.m_params.reading = false