Luce packages
LuceLuce BaseLuciaOS

dymokomi/luce-browser-engine

Source of release 0.6.1

0.6.1 / src / web / fetch / infrastructure / fetch_controller.lucb

#==============================================================================================
#
#   fetch_controller - Fetch::Infrastructure::FetchController: a fetch's state, timing and
#   abort reason, the next manual redirect, stopping a fetch and its queued fetch tasks; and
#   FetchControllerHolder
#
#   DESCRIPTION:
#       Port of Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp (lines 19-197) with
#       the inline members of FetchController.h (lines 41-62, 111-112). The pending request is
#       a WeakPtr<Requests::Request> in C++; a Requests::Request is a cell of the RequestClient
#       seam (region p2d) here, so the controller holds a gc.Weak to it. StructuredSerialize of
#       the abort reason is a closure stub (phase 3).
#
#       Copyright (c) 2022, Linus Groh <linusg@serenityos.org>
#       SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================

# mark: Creation ================================================================================

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:21 Web::Fetch::Infrastructure::FetchController::FetchController (private).
func fetch_controller_construct(this: FetchController*):
    # FetchController() = default: the default member initializers.
    this.m_state = FetchControllerState.ongoing
    this.m_next_fetch_task_id = 0

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:23 Web::Fetch::Infrastructure::FetchController::create.
pub func fetch_controller_create(vm: Vm*) -> FetchController*:
    # vm.heap().allocate<FetchController>()
    let heap = vm_heap(vm)
    let controller = (FetchController*)web_heap_allocate_cell(heap, &fetch_controller_class)
    gc.heap_defer_gc(heap)
    fetch_controller_construct(controller)
    gc.heap_undefer_gc(heap)
    return controller

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:28 Web::Fetch::Infrastructure::FetchController::visit_edges (override).
pub func fetch_controller_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (FetchController*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_full_timing_info)
    gc.cell_visitor_visit_t(visitor, this.m_report_timing_steps)
    gc.cell_visitor_visit_t(visitor, this.m_next_manual_redirect_steps)
    gc.cell_visitor_visit_t(visitor, this.m_fetch_params)

# mark: Setters and accessors ===================================================================

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:37 Web::Fetch::Infrastructure::FetchController::set_pending_request.
pub func fetch_controller_set_pending_request(this: FetchController*, request: RequestsRequest*?):
    # (A Requests::Request is a cell of the RequestClient seam: the WeakPtr is a gc.Weak to it.)
    this.m_pending_request = gc.make_weak[gc.Cell]((gc.Cell*?)(void*?)request)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:41 Web::Fetch::Infrastructure::FetchController::set_full_timing_info.
pub func fetch_controller_set_full_timing_info(this: FetchController*, full_timing_info: FetchTimingInfo*):
    this.m_full_timing_info = full_timing_info

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:42 Web::Fetch::Infrastructure::FetchController::set_report_timing_steps.
pub func fetch_controller_set_report_timing_steps(this: FetchController*, report_timing_steps: ak.Function1[JsObject*, unit]):
    this.m_report_timing_steps = gc.create_function1(vm_heap(js_cell_vm(this.js_cell())), report_timing_steps)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:44 Web::Fetch::Infrastructure::FetchController::state.
pub func fetch_controller_state(this: FetchController*) -> FetchControllerState:
    return this.m_state

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:47 Web::Fetch::Infrastructure::FetchController::set_next_manual_redirect_steps.
pub func fetch_controller_set_next_manual_redirect_steps(this: FetchController*, next_manual_redirect_steps: ak.Function0[unit]):
    this.m_next_manual_redirect_steps = gc.create_function0(vm_heap(js_cell_vm(this.js_cell())), next_manual_redirect_steps)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:54 Web::Fetch::Infrastructure::FetchController::set_fetch_params.
pub func fetch_controller_set_fetch_params(this: FetchController*, fetch_params: FetchParams*):
    this.m_fetch_params = fetch_params

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:57 Web::Fetch::Infrastructure::FetchController::set_inner_fetch_controller.
## FetchController.h declares it, but the donor defines it nowhere and nothing calls it (a call would not link).
pub func fetch_controller_set_inner_fetch_controller(this: FetchController*, arg0: FetchController*):
    trap("VERIFY_NOT_REACHED: Web::Fetch::Infrastructure::FetchController::set_inner_fetch_controller is declared but not defined")

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:62 Web::Fetch::Infrastructure::FetchController::next_fetch_task_id.
pub func fetch_controller_next_fetch_task_id(this: FetchController*) -> u64:
    # return m_next_fetch_task_id++;
    let id = this.m_next_fetch_task_id
    this.m_next_fetch_task_id = id + 1
    return id

# mark: Timing, manual redirects ================================================================

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:53 Web::Fetch::Infrastructure::FetchController::report_timing.
# https://fetch.spec.whatwg.org/#finalize-and-report-timing
pub func fetch_controller_report_timing(this: FetchController*, global: JsObject*):
    # 1. Assert: this’s report timing steps is not null.
    let report_timing_steps = this.m_report_timing_steps else trap("VERIFY: m_report_timing_steps")

    # 2. Call this’s report timing steps with global.
    ak.function1_call(&report_timing_steps.function, global)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:63 Web::Fetch::Infrastructure::FetchController::process_next_manual_redirect.
# https://fetch.spec.whatwg.org/#fetch-controller-process-the-next-manual-redirect
pub func fetch_controller_process_next_manual_redirect(this: FetchController*):
    # 1. Assert: controller’s next manual redirect steps are not null.
    let next_manual_redirect_steps = this.m_next_manual_redirect_steps else trap("VERIFY: m_next_manual_redirect_steps")

    # 2. Call controller’s next manual redirect steps.
    ak.function0_call(&next_manual_redirect_steps.function)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:73 Web::Fetch::Infrastructure::FetchController::extract_full_timing_info.
# https://fetch.spec.whatwg.org/#extract-full-timing-info
pub func fetch_controller_extract_full_timing_info(this: FetchController*) -> FetchTimingInfo*:
    # 1. Assert: this’s full timing info is not null.
    let full_timing_info = this.m_full_timing_info else trap("VERIFY: m_full_timing_info")

    # 2. Return this’s full timing info.
    return full_timing_info

# mark: Aborting and terminating ================================================================

## The lambda of abort's steps 4-5, `[](JS::VM& vm, JS::Value error, JS::Value fallback_error)`: StructuredSerialize(error),
## or StructuredSerialize(fallbackError) if that threw.
func fetch_controller_abort_structured_serialize(vm: Vm*, error_: JsValue, fallback_error: JsValue) -> ak.Vector[u8]:
    return html_structured_serialize(vm, error_) catch:
        _ = idl_take_pending_exception()
        recover html_structured_serialize(vm, fallback_error) else trap("MUST: StructuredSerialize(fallbackError)")

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:83 Web::Fetch::Infrastructure::FetchController::abort.
# https://fetch.spec.whatwg.org/#fetch-controller-abort
pub func fetch_controller_abort(this: FetchController*, realm: Realm*, error_: JsValue?):
    # 1. Set controller’s state to "aborted".
    this.m_state = FetchControllerState.aborted

    # 2. Let fallbackError be an "AbortError" DOMException.
    let fallback_error = js_value_from_object((JsObject*)idl_abort_error_create(realm, ak.utf16_string_from_str("Fetch was aborted")))

    # 3. Set error to fallbackError if it is not given.
    let error_value = error_ else fallback_error

    # 4. Let serializedError be StructuredSerialize(error). If that threw an exception, catch it, and let serializedError be StructuredSerialize(fallbackError).
    # 5. Set controller’s serialized abort reason to serializedError
    this.m_serialized_abort_reason = fetch_controller_abort_structured_serialize(realm_vm(realm), error_value, fallback_error)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:107 Web::Fetch::Infrastructure::FetchController::deserialize_a_serialized_abort_reason.
# https://fetch.spec.whatwg.org/#deserialize-a-serialized-abort-reason
pub func fetch_controller_deserialize_a_serialized_abort_reason(this: FetchController*, realm: Realm*) -> JsValue:
    # 1. Let fallbackError be an "AbortError" DOMException.
    let fallback_error = idl_abort_error_create(realm, ak.utf16_string_from_str("Fetch was aborted"))

    # 2. Let deserializedError be fallbackError.
    var deserialized_error = js_value_from_object((JsObject*)fallback_error)

    # 3. If abortReason is non-null, then set deserializedError to StructuredDeserialize(abortReason, realm).
    #    If that threw an exception or returned undefined, then set deserializedError to fallbackError.
    if let serialized_abort_reason = this.m_serialized_abort_reason:
        let deserialized_error_or_exception: JsValue? = html_structured_deserialize(realm_vm(realm), serialized_abort_reason, realm) catch:
            _ = idl_take_pending_exception()
            recover none
        if let value = deserialized_error_or_exception:
            if not js_value_is_undefined(value):
                deserialized_error = value

    # 4. Return deserializedError.
    return deserialized_error

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:129 Web::Fetch::Infrastructure::FetchController::terminate.
# https://fetch.spec.whatwg.org/#fetch-controller-terminate
pub func fetch_controller_terminate(this: FetchController*):
    # To terminate a fetch controller controller, set controller’s state to "terminated".
    this.m_state = FetchControllerState.terminated

# mark: Stopping a fetch ========================================================================

## The captures of stop_fetch's inner predicate, `[&](u64, HTML::TaskID task_id) { return task.id() == task_id; }`.
struct FetchControllerStopFetchTaskIdMatches:
    var task: HtmlTask*

## stop_fetch's inner predicate: whether a queued fetch task's HTML task id is the task's.
func fetch_controller_stop_fetch_task_id_matches(context: void*?, fetch_task_id: const u64*, task_id: const u64*) -> bool:
    let captures = (FetchControllerStopFetchTaskIdMatches*)(context else trap("stop_fetch: no captures"))
    return html_task_id(captures.task) == *task_id

## The captures of stop_fetch's task filter, `[&](auto const& task) { ... }` (ongoing_fetch_tasks by reference).
struct FetchControllerStopFetchTaskFilter:
    var ongoing_fetch_tasks: ak.HashMap[u64, u64, ak.U64Traits]*

## stop_fetch's task filter: removes the fetch tasks queued as `task` from ongoing_fetch_tasks and answers whether there
## were any.
func fetch_controller_stop_fetch_task_filter(context: void*?, task: HtmlTask*) -> bool:
    let captures = (FetchControllerStopFetchTaskFilter*)(context else trap("stop_fetch: no captures"))
    var task_id_matches = FetchControllerStopFetchTaskIdMatches(task = task)
    return ak.hash_map_remove_all_matching(captures.ongoing_fetch_tasks, ak.Function2[const u64*, const u64*, bool](call = fetch_controller_stop_fetch_task_id_matches, context = &task_id_matches))

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:135 Web::Fetch::Infrastructure::FetchController::stop_fetch.
pub func fetch_controller_stop_fetch(this: FetchController*):
    if this.m_state == FetchControllerState.aborted or this.m_state == FetchControllerState.terminated:
        return

    this.m_state = FetchControllerState.stopped

    let vm = js_cell_vm(this.js_cell())

    # AD-HOC: Some HTML elements need to stop an ongoing fetching process without causing any network error to be raised
    #         (which abort() and terminate() will both do). This is tricky because the fetch process runs across several
    #         nested Platform::EventLoopPlugin::deferred_invoke() invocations. For now, we "stop" the fetch process by
    #         cancelling any queued fetch tasks and then ignoring any callbacks.
    # (auto ongoing_fetch_tasks = move(m_ongoing_fetch_tasks): the member is left empty.)
    var ongoing_fetch_tasks = this.m_ongoing_fetch_tasks
    this.m_ongoing_fetch_tasks = ak.HashMap[u64, u64, ak.U64Traits]()

    var task_filter = FetchControllerStopFetchTaskFilter(ongoing_fetch_tasks = &ongoing_fetch_tasks)
    html_task_queue_remove_tasks_matching(html_event_loop_task_queue(html_main_thread_event_loop()), ak.Function1[HtmlTask*, bool](call = fetch_controller_stop_fetch_task_filter, context = &task_filter))

    if let fetch_params = this.m_fetch_params:
        let fetch_algorithms = fetch_algorithms_create(vm, FetchAlgorithmsInput())
        fetch_params_set_algorithms(fetch_params, fetch_algorithms)

    fetch_controller_stop_request(this)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:164 Web::Fetch::Infrastructure::FetchController::stop_request.
pub func fetch_controller_stop_request(this: FetchController*):
    assert(this.m_state == FetchControllerState.stopped)
    if let pending_request = gc.weak_ptr(&this.m_pending_request):
        requests_request_stop((RequestsRequest*)(void*)pending_request)
        this.m_pending_request = gc.make_weak[gc.Cell](none)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:173 Web::Fetch::Infrastructure::FetchController::fetch_task_queued.
pub func fetch_controller_fetch_task_queued(this: FetchController*, fetch_task_id: u64, event_id: u64):
    _ = ak.hash_map_set(&this.m_ongoing_fetch_tasks, fetch_task_id, event_id)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:178 Web::Fetch::Infrastructure::FetchController::fetch_task_complete.
pub func fetch_controller_fetch_task_complete(this: FetchController*, fetch_task_id: u64):
    _ = ak.hash_map_remove_k(&this.m_ongoing_fetch_tasks, fetch_task_id)

# mark: FetchControllerHolder ===================================================================

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:185 Web::Fetch::Infrastructure::FetchControllerHolder::FetchControllerHolder (private).
func fetch_controller_holder_construct(this: FetchControllerHolder*):
    # FetchControllerHolder() = default: m_controller is null.
    this.m_controller = none

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:187 Web::Fetch::Infrastructure::FetchControllerHolder::create.
pub func fetch_controller_holder_create(vm: Vm*) -> FetchControllerHolder*:
    # vm.heap().allocate<FetchControllerHolder>()
    let heap = vm_heap(vm)
    let holder = (FetchControllerHolder*)web_heap_allocate_cell(heap, &fetch_controller_holder_class)
    gc.heap_defer_gc(heap)
    fetch_controller_holder_construct(holder)
    gc.heap_undefer_gc(heap)
    return holder

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.cpp:192 Web::Fetch::Infrastructure::FetchControllerHolder::visit_edges (override).
pub func fetch_controller_holder_visit_edges_impl(base: gc.Cell*, visitor: gc.CellVisitor*):
    let this = (FetchControllerHolder*)base
    gc.cell_visit_edges_impl(base, visitor)
    gc.cell_visitor_visit_t(visitor, this.m_controller)

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:111 Web::Fetch::Infrastructure::FetchControllerHolder::controller.
pub func fetch_controller_holder_controller(this: FetchControllerHolder*) -> FetchController*?:
    return this.m_controller

## Ported from Libraries/LibWeb/Fetch/Infrastructure/FetchController.h:112 Web::Fetch::Infrastructure::FetchControllerHolder::set_controller.
pub func fetch_controller_holder_set_controller(this: FetchControllerHolder*, controller: FetchController*):
    this.m_controller = controller