Skip to content

Truly independent web browser

LibWeb: Move a fetch request's body stream to the JS Request

Luke Wilde707354a741b0
diff --git a/Libraries/LibWeb/Fetch/FetchMethod.cpp b/Libraries/LibWeb/Fetch/FetchMethod.cpp
index 30d3df8644e..75d74858155 100644
--- a/Libraries/LibWeb/Fetch/FetchMethod.cpp
+++ b/Libraries/LibWeb/Fetch/FetchMethod.cpp
@@ -91,7 +91,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
// 4. If requestObject’s signal is aborted, then:
if (request_object->signal()->aborted()) {
// 1. Abort the fetch() call with p, request, null, and requestObject’s signal’s abort reason.
- abort_fetch(*promise_capability, request, nullptr, request_object->signal()->reason());
+ abort_fetch(*promise_capability, request_object, nullptr, request_object->signal()->reason());
// 2. Return p.
return promise_capability;
@@ -123,7 +123,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
// 12. Set controller to the result of calling fetch given request and processResponse given response being these
// steps:
- auto process_response = [locally_aborted, promise_capability, request, response_object_holder, controller_holder, &relevant_realm](GC::Ref<Infrastructure::Response> response) {
+ auto process_response = [locally_aborted, promise_capability, request_object, response_object_holder, controller_holder, &relevant_realm](GC::Ref<Infrastructure::Response> response) {
// 1. If locallyAborted is true, then abort these steps.
if (locally_aborted->value())
return;
@@ -138,7 +138,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
auto deserialized_error = deserialize_serialized_abort_reason(relevant_realm, *controller_holder->controller());
// 2. Abort the fetch() call with p, request, responseObject, and deserializedError.
- abort_fetch(*promise_capability, request, response_object_holder->response_object, deserialized_error);
+ abort_fetch(*promise_capability, request_object, response_object_holder->response_object, deserialized_error);
// 3. Abort these steps.
return;
@@ -164,10 +164,15 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
};
Infrastructure::FetchAlgorithms::Input fetch_algorithms_input { Engine::BodyIntent::DeliverStreamToConsumerAgent };
fetch_algorithms_input.process_response = move(process_response);
+ // AD-HOC: Request holds its body's source and length, and requestObject its stream, which fetching reads for a
+ // body without a source. Its reader is acquired here, not when fetching reads the stream, so that script
+ // cannot lock the stream first.
+ if (auto body = request_object->body_impl(); body && !body->source().has_value())
+ fetch_algorithms_input.request_body_reader = Infrastructure::FetchAlgorithms::RequestBodyReader { *body, MUST(body->stream()->get_a_reader()) };
controller_holder->set_controller(Fetching::fetch(realm, request, Infrastructure::FetchAlgorithms::create(move(fetch_algorithms_input))));
// 11. Add the following abort steps to requestObject’s signal:
- (void)request_object->signal()->add_abort_algorithm([locally_aborted, request, controller_holder, promise_capability, request_object, response_object_holder, &relevant_realm] {
+ (void)request_object->signal()->add_abort_algorithm([locally_aborted, controller_holder, promise_capability, request_object, response_object_holder, &relevant_realm] {
dbgln_if(WEB_FETCH_DEBUG, "Fetch: Request object signal's abort algorithm called");
// 1. Set locallyAborted to true.
@@ -183,7 +188,7 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
HTML::TemporaryExecutionContext execution_context { relevant_realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
// 4. Abort the fetch() call with p, request, responseObject, and requestObject’s signal’s abort reason.
- abort_fetch(*promise_capability, request, response_object_holder->response_object, request_object->signal()->reason());
+ abort_fetch(*promise_capability, request_object, response_object_holder->response_object, request_object->signal()->reason());
});
// 13. Return p.
@@ -191,18 +196,19 @@ GC::Ref<WebIDL::Promise> fetch(JS::Realm& realm, RequestInfo const& input, Bindi
}
// https://fetch.spec.whatwg.org/#abort-fetch
-void abort_fetch(WebIDL::Promise const& promise, GC::Ref<Infrastructure::Request> request, GC::Ptr<Response> response_object, JS::Value error)
+// NB: request is given as the Request object holding its body's stream.
+void abort_fetch(WebIDL::Promise const& promise, GC::Ref<Request> request_object, GC::Ptr<Response> response_object, JS::Value error)
{
- dbgln_if(WEB_FETCH_DEBUG, "Fetch: Aborting fetch with: request @ {}, error = {}", request.ptr(), error);
+ dbgln_if(WEB_FETCH_DEBUG, "Fetch: Aborting fetch with: request @ {}, error = {}", request_object->request().ptr(), error);
// 1. Reject promise with error.
// NOTE: This is a no-op if promise has already fulfilled.
WebIDL::reject_promise(promise, error);
// 2. If request’s body is non-null and is readable, then cancel request’s body with error.
- if (auto* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>(); body != nullptr && (*body)->stream()->is_readable()) {
+ if (auto body = request_object->body_impl(); body && body->stream()->is_readable()) {
// NOTE: Cancel here is different than the cancel method of stream and refers to https://streams.spec.whatwg.org/#readablestream-cancel
- (*body)->stream()->cancel(error);
+ body->stream()->cancel(error);
}
// 3. If responseObject is null, then return.
diff --git a/Libraries/LibWeb/Fetch/FetchMethod.h b/Libraries/LibWeb/Fetch/FetchMethod.h
index fea46e1ed1a..4aefa311c6f 100644
--- a/Libraries/LibWeb/Fetch/FetchMethod.h
+++ b/Libraries/LibWeb/Fetch/FetchMethod.h
@@ -15,6 +15,6 @@
namespace Web::Fetch {
GC::Ref<WebIDL::Promise> fetch(JS::Realm&, RequestInfo const& input, Bindings::RequestInit const& init);
-void abort_fetch(WebIDL::Promise const&, GC::Ref<Infrastructure::Request>, GC::Ptr<Response>, JS::Value error);
+void abort_fetch(WebIDL::Promise const&, GC::Ref<Request>, GC::Ptr<Response>, JS::Value error);
}
diff --git a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
index 73a1dafa39c..7543516088e 100644
--- a/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
+++ b/Libraries/LibWeb/Fetch/Fetching/Fetching.cpp
@@ -307,8 +307,8 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:
fetch_params->set_has_response_body_transfer_lease(create_response_body_transfer_lease == CreateResponseBodyTransferLease::Yes);
// 9. If request’s body is a byte sequence, then set request’s body to request’s body as a body.
- if (auto const* buffer = request.body().get_pointer<ByteBuffer>())
- request.set_body(Infrastructure::byte_sequence_as_body(realm, buffer->bytes()));
+ if (auto* buffer = request.body().get_pointer<ByteBuffer>())
+ request.set_body(Infrastructure::FetchBody::from_bytes(Core::ImmutableBytes::adopt(move(*buffer))));
// AD-HOC: The blob URL entry of request’s URL is resolved here, when the fetch starts, so that scheme fetch needs no
// page. It is the entry of request’s current URL there, since no redirect leads to a blob URL.
@@ -454,7 +454,7 @@ GC::Ref<Infrastructure::FetchController> fetch(JS::Realm& realm, Infrastructure:
auto body_length = request.body().visit(
[](Empty) -> u64 { return 0; },
[](ByteBuffer const& buffer) -> u64 { return buffer.size(); },
- [](GC::Ref<Infrastructure::Body> body) -> u64 { return body->length().value_or(0); });
+ [](Infrastructure::FetchBody const& body) -> u64 { return body.length().value_or(0); });
request.set_keepalive_quota_reservation(request.client_snapshot()->keepalive_quota_accountant->reserve(body_length));
}
}
@@ -1585,7 +1585,7 @@ GC::Ref<PendingResponse> http_fetch(JS::Realm& realm, Infrastructure::FetchParam
// 3. If request’s service-workers mode is "all", then:
if (request->service_workers_mode() == Infrastructure::Request::ServiceWorkersMode::All) {
// 1. Let requestForServiceWorker be a clone of request.
- auto request_for_service_worker = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);
+ auto request_for_service_worker = request->clone();
if (WebDriver::BiDi::g_network_events_enabled)
request_for_service_worker->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());
@@ -1866,7 +1866,7 @@ GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm& realm, Infrastructure::F
// return a network error.
if (internal_response->status() != 303
&& !request->body().has<Empty>()
- && !request->body().get<GC::Ref<Infrastructure::Body>>()->source().has_value()) {
+ && !request->body().get<Infrastructure::FetchBody>().source().has_value()) {
return PendingResponse::create(request, Infrastructure::Response::network_error("Request has body but no body source"_string));
}
@@ -1908,8 +1908,8 @@ GC::Ptr<PendingResponse> http_redirect_fetch(JS::Realm& realm, Infrastructure::F
// request’s body’s source.
// NOTE: request’s body’s source’s nullity has already been checked.
if (!request->body().has<Empty>()) {
- auto [body, _] = safely_extract_body(realm, *request->body().get<GC::Ref<Infrastructure::Body>>()->source());
- request->set_body(body);
+ auto source = *request->body().get<Infrastructure::FetchBody>().source();
+ request->set_body(Infrastructure::FetchBody::from_bytes(source));
}
// 15. Let timingInfo be fetchParams’s timing info.
@@ -2003,7 +2003,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
// NOTE: Implementations are encouraged to avoid teeing request’s body’s stream when request’s body’s
// source is null as only a single body is needed in that case. E.g., when request’s body’s source
// is null, redirects and authentication will end up failing the fetch.
- http_request = request->clone(realm, Infrastructure::Request::BodyCloning::FromSource);
+ http_request = request->clone();
if (WebDriver::BiDi::g_network_events_enabled)
http_request->set_webdriver_bidi_network_request(request->webdriver_bidi_network_request());
@@ -2034,8 +2034,8 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
include_credentials = HTTP::Cookie::IncludeCredentials::No;
// 5. Let contentLength be httpRequest’s body’s length, if httpRequest’s body is non-null; otherwise null.
- auto content_length = http_request->body().has<GC::Ref<Infrastructure::Body>>()
- ? http_request->body().get<GC::Ref<Infrastructure::Body>>()->length()
+ auto content_length = http_request->body().has<Infrastructure::FetchBody>()
+ ? http_request->body().get<Infrastructure::FetchBody>().length()
: Optional<u64> {};
// 6. Let contentLengthHeaderValue be null.
@@ -2361,15 +2361,14 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
// 2. If request’s body is non-null, then:
if (!request->body().has<Empty>()) {
// 1. If request’s body’s source is null, then return a network error.
- auto const& source = request->body().get<GC::Ref<Infrastructure::Body>>()->source();
+ auto source = request->body().get<Infrastructure::FetchBody>().source();
if (!source.has_value()) {
returned_pending_response->resolve(Infrastructure::Response::network_error("Request has body but no body source"_string));
return;
}
// 2. Set request’s body to the body of the result of safely extracting request’s body’s source.
- auto [body, _] = safely_extract_body(realm, *source);
- request->set_body(body);
+ request->set_body(Infrastructure::FetchBody::from_bytes(*source));
}
// 3. If request’s use-URL-credentials flag is unset or isAuthenticationFetch is true, then:
@@ -2430,7 +2429,7 @@ GC::Ref<PendingResponse> http_network_or_cache_fetch(JS::Realm& realm, Infrastru
// - isNewConnectionFetch is false
&& is_new_connection_fetch == IsNewConnectionFetch::No
// - request’s body is null, or request’s body is non-null and request’s body’s source is non-null
- && (request->body().has<Empty>() || request->body().get<GC::Ref<Infrastructure::Body>>()->source().has_value())
+ && (request->body().has<Empty>() || request->body().get<Infrastructure::FetchBody>().source().has_value())
// then:
) {
// 1. If fetchParams is canceled, then return the appropriate network error for fetchParams.
@@ -2547,8 +2546,8 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
else if (auto const& client = request->client_snapshot())
load_request.set_top_level_creation_url(client->top_level_creation_url);
- if (auto const* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>()) {
- if (auto const& source = (*body)->source(); source.has_value())
+ if (auto const* body = request->body().get_pointer<Infrastructure::FetchBody>()) {
+ if (auto const& source = body->source(); source.has_value())
load_request.set_body(MUST(source->copy_to_byte_buffer()));
}
@@ -2754,21 +2753,22 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
}
}
// 2. Otherwise, if body is non-null:
- else if (auto const* body = request->body().get_pointer<GC::Ref<Infrastructure::Body>>()) {
+ else if (auto const* body = request->body().get_pointer<Infrastructure::FetchBody>()) {
// 1. Let processBodyChunk given bytes be these steps:
- auto process_body_chunk = GC::create_function(GC::Heap::the(), [&fetch_params](ByteBuffer bytes) {
+ // NB: The steps read only bytes's length, so they are given it.
+ auto process_body_chunk = [&fetch_params](u64 length) {
// 1. If fetchParams is canceled, then abort these steps.
if (fetch_params.is_canceled())
return;
// 2. Run this step in parallel: transmit bytes.
- // NB: The whole body was handed to RequestServer above, from body's source.
+ // NB: A body's source was handed to RequestServer above.
// 3. If fetchParams’s process request body chunk length is non-null, then run fetchParams’s process
// request body chunk length given bytes’s length.
if (fetch_params.algorithms()->process_request_body_chunk_length())
- fetch_params.algorithms()->process_request_body_chunk_length()(bytes.size());
- });
+ fetch_params.algorithms()->process_request_body_chunk_length()(length);
+ };
// 2. Let processEndOfBody be these steps:
auto process_end_of_body = GC::create_function(GC::Heap::the(), [&fetch_params]() {
@@ -2799,7 +2799,24 @@ GC::Ref<PendingResponse> nonstandard_resource_loader_file_or_http_network_fetch(
// 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, processBodyError, and
// fetchParams’s task destination.
- (void)(*body)->incrementally_read(realm, process_body_chunk, process_end_of_body, process_body_error, fetch_params.task_destination());
+ // AD-HOC: A request holds its body's source and length but not its stream. A body with a source is read as its
+ // stream would give it, as one chunk of the whole source, and a body without one through the reader
+ // fetch() acquired for its stream.
+ if (auto const& source = body->source(); source.has_value()) {
+ if (auto length = source->size(); length > 0) {
+ Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), GC::create_function(GC::Heap::the(), [process_body_chunk, length] {
+ process_body_chunk(length);
+ }));
+ }
+ Infrastructure::queue_fetch_task(fetch_params.controller(), fetch_params.task_destination(), process_end_of_body);
+ } else if (auto const& request_body_reader = fetch_params.algorithms()->request_body_reader(); request_body_reader.has_value()) {
+ // FIXME: Send the bytes read here to RequestServer, which only receives a body's source.
+ auto process_body_chunk_bytes = GC::create_function(GC::Heap::the(), [process_body_chunk](ByteBuffer bytes) {
+ process_body_chunk(bytes.size());
+ });
+ HTML::TemporaryExecutionContext const execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
+ request_body_reader->body->incrementally_read_loop(request_body_reader->reader, fetch_params.task_destination(), process_body_chunk_bytes, process_end_of_body, process_body_error);
+ }
}
return pending_response;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
index d74ce3d6443..2452a54a90e 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.cpp
@@ -7,6 +7,8 @@
#include <LibGC/Heap.h>
#include <LibJS/Runtime/VM.h>
#include <LibWeb/Fetch/Infrastructure/FetchAlgorithms.h>
+#include <LibWeb/Fetch/Infrastructure/HTTP/Bodies.h>
+#include <LibWeb/Streams/ReadableStreamDefaultReader.h>
namespace Web::Fetch::Infrastructure {
@@ -27,7 +29,8 @@ GC::Ref<FetchAlgorithms> FetchAlgorithms::create(Input input)
process_early_hints_response,
process_response,
process_response_end_of_body,
- process_response_consume_body);
+ process_response_consume_body,
+ move(input.request_body_reader));
}
GC::Ref<FetchAlgorithms> FetchAlgorithms::with_body_intent(Engine::BodyIntent body_intent) const
@@ -39,7 +42,8 @@ GC::Ref<FetchAlgorithms> FetchAlgorithms::with_body_intent(Engine::BodyIntent bo
m_process_early_hints_response,
m_process_response,
m_process_response_end_of_body,
- m_process_response_consume_body);
+ m_process_response_consume_body,
+ m_request_body_reader);
}
FetchAlgorithms::FetchAlgorithms(
@@ -49,7 +53,8 @@ FetchAlgorithms::FetchAlgorithms(
ProcessEarlyHintsResponseHeapFunction process_early_hints_response,
ProcessResponseHeapFunction process_response,
ProcessResponseEndOfBodyHeapFunction process_response_end_of_body,
- ProcessResponseConsumeBodyHeapFunction process_response_consume_body)
+ ProcessResponseConsumeBodyHeapFunction process_response_consume_body,
+ Optional<RequestBodyReader> request_body_reader)
: m_body_intent(body_intent)
, m_process_request_body_chunk_length(process_request_body_chunk_length)
, m_process_request_end_of_body(process_request_end_of_body)
@@ -57,6 +62,7 @@ FetchAlgorithms::FetchAlgorithms(
, m_process_response(process_response)
, m_process_response_end_of_body(process_response_end_of_body)
, m_process_response_consume_body(process_response_consume_body)
+ , m_request_body_reader(move(request_body_reader))
{
}
@@ -69,6 +75,10 @@ void FetchAlgorithms::visit_edges(JS::Cell::Visitor& visitor)
visitor.visit(m_process_response);
visitor.visit(m_process_response_end_of_body);
visitor.visit(m_process_response_consume_body);
+ if (m_request_body_reader.has_value()) {
+ visitor.visit(m_request_body_reader->body);
+ visitor.visit(m_request_body_reader->reader);
+ }
}
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
index 329145477de..0b24dd5c5a5 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/FetchAlgorithms.h
@@ -40,6 +40,12 @@ public:
using ProcessResponseEndOfBodyHeapFunction = GC::Ref<GC::Function<ProcessResponseEndOfBodyFunction::FunctionType>>;
using ProcessResponseConsumeBodyHeapFunction = GC::Ref<GC::Function<ProcessResponseConsumeBodyFunction::FunctionType>>;
+ // A request body whose stream is the only place its bytes are, with the reader fetch() acquired for that stream.
+ struct RequestBodyReader {
+ GC::Ref<Body> body;
+ GC::Ref<Streams::ReadableStreamDefaultReader> reader;
+ };
+
struct Input {
explicit Input(Engine::BodyIntent body_intent)
: body_intent(body_intent)
@@ -53,12 +59,14 @@ public:
ProcessResponseFunction process_response;
ProcessResponseEndOfBodyFunction process_response_end_of_body;
ProcessResponseConsumeBodyFunction process_response_consume_body;
+ Optional<RequestBodyReader> request_body_reader;
};
[[nodiscard]] static GC::Ref<FetchAlgorithms> create(Input);
[[nodiscard]] GC::Ref<FetchAlgorithms> with_body_intent(Engine::BodyIntent) const;
Engine::BodyIntent body_intent() const { return m_body_intent; }
+ Optional<RequestBodyReader> const& request_body_reader() const { return m_request_body_reader; }
ProcessRequestBodyChunkLengthFunction const& process_request_body_chunk_length() const { return m_process_request_body_chunk_length->function(); }
ProcessRequestEndOfBodyFunction const& process_request_end_of_body() const { return m_process_request_end_of_body->function(); }
ProcessEarlyHintsResponseFunction const& process_early_hints_response() const { return m_process_early_hints_response->function(); }
@@ -76,7 +84,8 @@ private:
ProcessEarlyHintsResponseHeapFunction process_early_hints_response,
ProcessResponseHeapFunction process_response,
ProcessResponseEndOfBodyHeapFunction process_response_end_of_body,
- ProcessResponseConsumeBodyHeapFunction process_response_consume_body);
+ ProcessResponseConsumeBodyHeapFunction process_response_consume_body,
+ Optional<RequestBodyReader> request_body_reader);
Engine::BodyIntent m_body_intent;
ProcessRequestBodyChunkLengthHeapFunction m_process_request_body_chunk_length;
@@ -85,6 +94,7 @@ private:
ProcessResponseHeapFunction m_process_response;
ProcessResponseEndOfBodyHeapFunction m_process_response_end_of_body;
ProcessResponseConsumeBodyHeapFunction m_process_response_consume_body;
+ Optional<RequestBodyReader> m_request_body_reader;
};
}
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
index ee3537e4a26..0bc6043411c 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.cpp
@@ -83,36 +83,6 @@ GC::Ref<Body> Body::create(GC::Ref<Streams::ReadableStream> stream, FetchBody fe
return GC::Heap::the().allocate<Body>(stream, move(fetch_body));
}
-GC::Ref<Body> Body::create_from_source(JS::Realm& realm, FetchBody fetch_body)
-{
- VERIFY(fetch_body.source().has_value());
- HTML::TemporaryExecutionContext execution_context { realm, HTML::TemporaryExecutionContext::CallbacksEnabled::Yes };
-
- auto stream = Streams::ReadableStream::create(realm);
- auto pull_algorithm = GC::create_function(GC::Heap::the(), [&realm, stream, source = *fetch_body.source(), offset = size_t { 0 }]() mutable {
- // A BYOB pull may consume only the current view's length.
- auto remaining = source.size() - offset;
- auto pull_size = remaining;
- if (auto byte_length = stream->current_byob_request_view_byte_length(); byte_length.has_value())
- pull_size = min(remaining, *byte_length);
-
- if (pull_size > 0) {
- if (auto result = stream->pull_from_bytes(source.bytes().slice(offset, pull_size)); result.is_error()) {
- if (stream->is_readable())
- stream->error(WebIDL::exception_to_throw_completion(realm.vm(), realm, result.release_error()).release_value());
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- }
- offset += pull_size;
- }
- if (offset == source.size() && stream->is_readable())
- stream->close();
- return WebIDL::create_resolved_promise(realm, JS::js_undefined());
- });
- stream->set_up_with_byte_reading_support(realm, pull_algorithm);
-
- return create(stream, move(fetch_body));
-}
-
// NB: Source-backed bodies are complete even when their streams still have queued bytes.
Body::Body(GC::Ref<Streams::ReadableStream> stream, FetchBody fetch_body)
: m_stream(stream)
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
index 2eada85926b..129d8015a5d 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Bodies.h
@@ -31,6 +31,12 @@ public:
FetchBody() = default;
FetchBody(Optional<Core::ImmutableBytes> source, Optional<u64> length);
+ [[nodiscard]] static FetchBody from_bytes(Core::ImmutableBytes bytes)
+ {
+ auto length = bytes.size();
+ return FetchBody { move(bytes), length };
+ }
+
[[nodiscard]] Optional<Core::ImmutableBytes> const& source() const { return m_source; }
void set_source(Core::ImmutableBytes, Optional<u64> length);
[[nodiscard]] Optional<u64> const& length() const { return m_length; }
@@ -88,8 +94,6 @@ public:
using ProcessEndOfBodyCallback = GC::Ref<GC::Function<void()>>;
[[nodiscard]] static GC::Ref<Body> create(GC::Ref<Streams::ReadableStream>, FetchBody = {});
- // A body whose stream reads the source as it is pulled.
- [[nodiscard]] static GC::Ref<Body> create_from_source(JS::Realm&, FetchBody);
[[nodiscard]] GC::Ref<Streams::ReadableStream> stream() const { return *m_stream; }
void set_stream(GC::Ref<Streams::ReadableStream> value) { m_stream = value; }
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
index f330b36677f..524236b243b 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.cpp
@@ -43,7 +43,6 @@ Request::Request(NonnullRefPtr<HTTP::HeaderList> header_list)
void Request::visit_edges(JS::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
- visitor.visit(m_body);
visitor.visit(m_reserved_client);
visitor.visit(m_pending_responses);
visitor.visit(m_webdriver_bidi_network_request);
@@ -222,7 +221,7 @@ ByteString Request::byte_serialize_origin() const
}
// https://fetch.spec.whatwg.org/#concept-request-clone
-GC::Ref<Request> Request::clone(JS::Realm& realm, BodyCloning body_cloning) const
+GC::Ref<Request> Request::clone() const
{
// To clone a request request, run these steps:
// 1. Let newRequest be a copy of request, except for its body.
@@ -274,18 +273,8 @@ GC::Ref<Request> Request::clone(JS::Realm& realm, BodyCloning body_cloning) cons
new_request->m_navigation_timing_allow_values_list = m_navigation_timing_allow_values_list;
// 2. If request’s body is non-null, set newRequest’s body to the result of cloning request’s body.
- if (auto const* body = m_body.get_pointer<GC::Ref<Body>>()) {
- switch (body_cloning) {
- case BodyCloning::Tee:
- new_request->set_body((*body)->clone(realm));
- break;
- case BodyCloning::FromSource:
- // AD-HOC: The fetch algorithms never read both this clone's body and the request's (see the note on cloning
- // in HTTP-network-or-cache fetch), so the clone reads the source, and a body without one is shared.
- new_request->set_body((*body)->source().has_value() ? Body::create_from_source(realm, (*body)->fetch_body()) : *body);
- break;
- }
- }
+ // AD-HOC: A request's body has no stream; whatever holds its stream tees that stream itself.
+ new_request->set_body(m_body);
// 3. Return newRequest.
return new_request;
diff --git a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
index ec323de00c6..0369842ff3d 100644
--- a/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
+++ b/Libraries/LibWeb/Fetch/Infrastructure/HTTP/Requests.h
@@ -167,7 +167,7 @@ public:
// Members are implementation-defined
struct InternalPriority { };
- using BodyType = Variant<Empty, ByteBuffer, GC::Ref<Body>>;
+ using BodyType = Variant<Empty, ByteBuffer, FetchBody>;
using OriginType = Variant<Origin, URL::Origin>;
using PolicyContainerType = Variant<PolicyContainer, NonnullRefPtr<HTML::PolicyContainer const>>;
using ReferrerType = RequestReferrerType;
@@ -346,11 +346,7 @@ public:
[[nodiscard]] String serialize_origin() const;
[[nodiscard]] ByteString byte_serialize_origin() const;
- enum class BodyCloning : u8 {
- Tee,
- FromSource,
- };
- [[nodiscard]] GC::Ref<Request> clone(JS::Realm&, BodyCloning) const;
+ [[nodiscard]] GC::Ref<Request> clone() const;
void add_range_header(u64 first, Optional<u64> const& last);
void add_origin_header();
diff --git a/Libraries/LibWeb/Fetch/Request.cpp b/Libraries/LibWeb/Fetch/Request.cpp
index 3a5fb2c0b7b..ab45e3287fa 100644
--- a/Libraries/LibWeb/Fetch/Request.cpp
+++ b/Libraries/LibWeb/Fetch/Request.cpp
@@ -217,6 +217,7 @@ void Request::visit_edges(GC::Cell::Visitor& visitor)
{
Base::visit_edges(visitor);
visitor.visit(m_request);
+ visitor.visit(m_body);
visitor.visit(m_headers);
visitor.visit(m_signal);
}
@@ -236,11 +237,10 @@ GC::Ptr<Infrastructure::Body const> Request::body_impl() const
{
// Objects including the Body interface mixin have an associated body (null or a body).
// A Request object’s body is its request’s body.
- return m_request->body().visit(
- [](GC::Ref<Infrastructure::Body> const& b) -> GC::Ptr<Infrastructure::Body const> { return b; },
- [](Empty) -> GC::Ptr<Infrastructure::Body const> { return nullptr; },
- // A byte sequence will be safely extracted into a body early on in fetch.
- [](ByteBuffer const&) -> GC::Ptr<Infrastructure::Body const> { VERIFY_NOT_REACHED(); });
+ // NB: A body that fetching extracts again from the same source keeps this object's stream.
+ if (m_request->body().has<Empty>())
+ return nullptr;
+ return m_body;
}
// https://fetch.spec.whatwg.org/#concept-body-body
@@ -249,11 +249,10 @@ GC::Ptr<Infrastructure::Body> Request::body_impl()
{
// Objects including the Body interface mixin have an associated body (null or a body).
// A Request object’s body is its request’s body.
- return m_request->body().visit(
- [](GC::Ref<Infrastructure::Body>& b) -> GC::Ptr<Infrastructure::Body> { return b; },
- [](Empty) -> GC::Ptr<Infrastructure::Body> { return {}; },
- // A byte sequence will be safely extracted into a body early on in fetch.
- [](ByteBuffer&) -> GC::Ptr<Infrastructure::Body> { VERIFY_NOT_REACHED(); });
+ // NB: A body that fetching extracts again from the same source keeps this object's stream.
+ if (m_request->body().has<Empty>())
+ return nullptr;
+ return m_body;
}
// https://fetch.spec.whatwg.org/#request-create
@@ -625,16 +624,16 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::create_with_settings(HTML::Enviro
}
// 34. Let inputBody be input’s request’s body if input is a Request object; otherwise null.
- Optional<Infrastructure::Request::BodyType const&> input_body;
+ GC::Ptr<Infrastructure::Body> input_body;
if (input.has<GC::Ref<Request>>())
- input_body = input.get<GC::Ref<Request>>()->request()->body();
+ input_body = input.get<GC::Ref<Request>>()->body_impl();
// 35. If either init["body"] exists and is non-null or inputBody is non-null, and request’s method is `GET` or `HEAD`, then throw a TypeError.
- if (((init.body.has_value() && !init.body->has<Empty>()) || (input_body.has_value() && !input_body.value().has<Empty>())) && request->method().is_one_of("GET"sv, "HEAD"sv))
+ if (((init.body.has_value() && !init.body->has<Empty>()) || input_body) && request->method().is_one_of("GET"sv, "HEAD"sv))
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Method must not be GET or HEAD when body is provided"_utf16 };
// 36. Let initBody be null.
- Optional<Infrastructure::Request::BodyType> init_body;
+ GC::Ptr<Infrastructure::Body> init_body;
// 37. If init["body"] exists and is non-null, then:
if (init.body.has_value() && !init.body->has<Empty>()) {
@@ -653,13 +652,12 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::create_with_settings(HTML::Enviro
}
// 38. Let inputOrInitBody be initBody if it is non-null; otherwise inputBody.
- auto input_or_init_body = init_body.value_or<Optional<Infrastructure::Request::BodyType const&>>(input_body);
+ auto input_or_init_body = init_body ? init_body : input_body;
// 39. If inputOrInitBody is non-null and inputOrInitBody’s source is null, then:
- // FIXME: The spec doesn't check if inputOrInitBody is a body before accessing source.
- if (input_or_init_body.has_value() && input_or_init_body->has<GC::Ref<Infrastructure::Body>>() && !input_or_init_body->get<GC::Ref<Infrastructure::Body>>()->source().has_value()) {
+ if (input_or_init_body && !input_or_init_body->source().has_value()) {
// 1. If initBody is non-null and init["duplex"] does not exist, then throw a TypeError.
- if (init_body.has_value() && !init.duplex.has_value())
+ if (init_body && !init.duplex.has_value())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Body without source requires 'duplex' value to be set"_utf16 };
// 2. If this’s request’s mode is neither "same-origin" nor "cors", then throw a TypeError.
@@ -671,12 +669,10 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::create_with_settings(HTML::Enviro
}
// 40. Let finalBody be inputOrInitBody.
- Optional<Infrastructure::Request::BodyType> final_body;
- if (input_or_init_body.has_value())
- final_body = *input_or_init_body;
+ auto final_body = input_or_init_body;
// 41. If initBody is null and inputBody is non-null, then:
- if (!init_body.has_value() && input_body.has_value()) {
+ if (!init_body && input_body) {
// 1. If inputBody is unusable, then throw a TypeError.
if (input.has<GC::Ref<Request>>() && input.get<GC::Ref<Request>>()->is_unusable())
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Request is unusable"_utf16 };
@@ -684,13 +680,14 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::create_with_settings(HTML::Enviro
// 2. Set finalBody to the result of creating a proxy for inputBody.
// NB: The proxy is a new body whose stream is the proxy of inputBody's stream. It keeps inputBody's source and
// length, so that it can still be transmitted and recreated like inputBody.
- if (auto const* body = input_body->get_pointer<GC::Ref<Infrastructure::Body>>())
- final_body = Infrastructure::Body::create(create_a_proxy(relevant_settings_object, (*body)->stream()), (*body)->fetch_body());
+ final_body = Infrastructure::Body::create(create_a_proxy(relevant_settings_object, input_body->stream()), input_body->fetch_body());
}
// 42. Set this’s request’s body to finalBody.
- if (final_body.has_value())
- request_object->request()->set_body(final_body.release_value());
+ if (final_body) {
+ request_object->request()->set_body(final_body->fetch_body());
+ request_object->m_body = final_body;
+ }
return GC::Ref { *request_object };
}
@@ -825,7 +822,9 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::clone(JS::Realm& realm) const
return WebIDL::SimpleException { WebIDL::SimpleExceptionType::TypeError, "Request is unusable"_utf16 };
// 2. Let clonedRequest be the result of cloning this’s request.
- auto cloned_request = m_request->clone(realm, Infrastructure::Request::BodyCloning::Tee);
+ // NB: Cloning the body tees the stream held here.
+ auto cloned_request = m_request->clone();
+ auto cloned_body = body_impl() ? m_body->clone(realm) : GC::Ptr<Infrastructure::Body> {};
// 3. Assert: this’s signal is non-null.
VERIFY(m_signal);
@@ -835,6 +834,7 @@ WebIDL::ExceptionOr<GC::Ref<Request>> Request::clone(JS::Realm& realm) const
// 5. Let clonedRequestObject be the result of creating a Request object, given clonedRequest, this’s headers’s guard, clonedSignal and this’s relevant realm.
auto cloned_request_object = Request::create(cloned_request, m_headers->guard(), cloned_signal);
+ cloned_request_object->m_body = cloned_body;
// 6. Return clonedRequestObject.
return cloned_request_object;
diff --git a/Libraries/LibWeb/Fetch/Request.h b/Libraries/LibWeb/Fetch/Request.h
index fa0cff5d832..d3f1d6cf8c7 100644
--- a/Libraries/LibWeb/Fetch/Request.h
+++ b/Libraries/LibWeb/Fetch/Request.h
@@ -80,6 +80,9 @@ private:
// A Request object has an associated request (a request).
GC::Ref<Infrastructure::Request> m_request;
+ // The body of this's request, with its stream.
+ GC::Ptr<Infrastructure::Body> m_body;
+
// https://fetch.spec.whatwg.org/#request-headers
// A Request object also has an associated headers (null or a Headers object), initially null.
GC::Ptr<Headers> m_headers;
diff --git a/Libraries/LibWeb/HTML/NavigatorBeacon.cpp b/Libraries/LibWeb/HTML/NavigatorBeacon.cpp
index 322b76a5c7b..c35b7652646 100644
--- a/Libraries/LibWeb/HTML/NavigatorBeacon.cpp
+++ b/Libraries/LibWeb/HTML/NavigatorBeacon.cpp
@@ -79,7 +79,7 @@ WebIDL::ExceptionOr<bool> NavigatorBeaconPartial::send_beacon(Utf16View url, Fet
req->set_origin(origin); // origin: origin
req->set_keepalive(true); // keepalive: true
if (transmitted_data)
- req->set_body(GC::Ref<Fetch::Infrastructure::Body> { *transmitted_data }); // body: transmittedData
+ req->set_body(transmitted_data->fetch_body()); // body: transmittedData
req->set_mode(cors_mode); // mode: corsMode
req->set_credentials_mode(Fetch::Infrastructure::Request::CredentialsMode::Include); // credentials mode: include
req->set_initiator_type(Fetch::Infrastructure::Request::InitiatorType::Beacon); // initiator type: "beacon"
diff --git a/Libraries/LibWeb/ServiceWorker/Cache.cpp b/Libraries/LibWeb/ServiceWorker/Cache.cpp
index 9909a2f84e3..17e870c559e 100644
--- a/Libraries/LibWeb/ServiceWorker/Cache.cpp
+++ b/Libraries/LibWeb/ServiceWorker/Cache.cpp
@@ -827,7 +827,7 @@ GC::Ref<RequestResponseList> Cache::query_cache(JS::Realm& realm, GC::Ref<Fetch:
}
// 1. Let requestCopy be a copy of cachedRequest.
- auto request_copy = cached_request->clone(realm, Fetch::Infrastructure::Request::BodyCloning::Tee);
+ auto request_copy = cached_request->clone();
// 2. Let responseCopy be a copy of cachedResponse.
auto response_copy = cached_response->clone(realm);
@@ -851,7 +851,7 @@ WebIDL::ExceptionOr<bool> Cache::batch_cache_operations(JS::Realm& realm, GC::Re
auto backup_cache = GC::Heap::the().allocate<RequestResponseList>();
for (auto request_response : cache->elements()) {
- auto backup_request = request_response->request->clone(realm, Fetch::Infrastructure::Request::BodyCloning::Tee);
+ auto backup_request = request_response->request->clone();
auto backup_response = request_response->response->clone(realm);
auto backup_request_response = GC::Heap::the().allocate<RequestResponse>(backup_request, backup_response);
diff --git a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
index 702befe9b4e..a382e50d05c 100644
--- a/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
+++ b/Libraries/LibWeb/WebDriver/BiDi/Network.cpp
@@ -141,8 +141,8 @@ static JsonObject get_the_request_data(Request const& request, FetchTimingInfo c
JsonValue body_size;
if (auto const* bytes = request.body().get_pointer<ByteBuffer>())
body_size = bytes->size();
- else if (auto const* body = request.body().get_pointer<GC::Ref<Body>>(); body && (*body)->length().has_value())
- body_size = *(*body)->length();
+ else if (auto const* body = request.body().get_pointer<FetchBody>(); body && body->length().has_value())
+ body_size = *body->length();
result.set("bodySize"sv, move(body_size));
result.set("destination"sv, request.destination().has_value() ? request_destination_to_string(*request.destination()) : ""sv);
result.set("initiatorType"sv, request.initiator_type().has_value() ? JsonValue(initiator_type_to_string(*request.initiator_type()).to_utf16_string().to_utf8()) : JsonValue {});
diff --git a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
index 05604aa3db7..05e063bf86b 100644
--- a/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
+++ b/Libraries/LibWeb/XHR/XMLHttpRequest.cpp
@@ -798,7 +798,7 @@ WebIDL::ExceptionOr<void> XMLHttpRequest::send(NullableDocumentOrXMLHttpRequestB
// body
// This’s request body.
if (m_request_body)
- request->set_body(GC::Ref { *m_request_body });
+ request->set_body(m_request_body->fetch_body());
// client
// This’s relevant settings object.
diff --git a/Meta/Linters/check_libweb_realm_mentions.py b/Meta/Linters/check_libweb_realm_mentions.py
index 7b0bc527dbc..9b9699eadc8 100755
--- a/Meta/Linters/check_libweb_realm_mentions.py
+++ b/Meta/Linters/check_libweb_realm_mentions.py
@@ -43,12 +43,11 @@ ALLOWED_REALM_MENTIONS = {
"Crypto": (8, 383, "WebCrypto algorithms still use realms for buffer/key/promise materialization"),
"DOM": (10, 33, "DOM abort plumbing and node helpers still have callback/materialization realm use"),
"Fetch": (
- 24,
- 67,
+ 23,
+ 63,
"Fetch bodies, headers, requests, responses, and controllers still materialize JS values/streams; "
"the body receiver's delivery and close tasks carry the realm its stream is enqueued and closed in; "
- "BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm; "
- "a request clone's body materializes the stream that reads its source",
+ "BodyStreamPullSource materializes stream pulls and errors on the consumer side, in its stream's realm",
),
"FileAPI": (4, 11, "File/Blob/FileReader algorithms still create streams, buffers, and events in selected realms"),
"HTML": (
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-abort-after-redirect-keeps-request-body.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-after-redirect-keeps-request-body.txt
new file mode 100644
index 00000000000..f55680ca4c1
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-after-redirect-keeps-request-body.txt
@@ -0,0 +1,4 @@
+no redirect: AbortError, body used: true
+303 to a GET: AbortError, body used: true
+307 to a POST: AbortError, body used: true
+307 to a POST without an abort, body kept: true
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.txt
new file mode 100644
index 00000000000..79058bb83b7
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.txt
@@ -0,0 +1,2 @@
+cancel: AbortError
+fetch: AbortError
diff --git a/Tests/LibWeb/Text/expected/Fetch/fetch-locks-a-request-body-stream.txt b/Tests/LibWeb/Text/expected/Fetch/fetch-locks-a-request-body-stream.txt
new file mode 100644
index 00000000000..930bed3ba7a
--- /dev/null
+++ b/Tests/LibWeb/Text/expected/Fetch/fetch-locks-a-request-body-stream.txt
@@ -0,0 +1,3 @@
+locked: true
+getReader: TypeError
+fetch: resolved
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-abort-after-redirect-keeps-request-body.html b/Tests/LibWeb/Text/input/Fetch/fetch-abort-after-redirect-keeps-request-body.html
new file mode 100644
index 00000000000..a2859d84f50
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-abort-after-redirect-keeps-request-body.html
@@ -0,0 +1,67 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Aborting a fetch after a redirect that dropped its request's body, or extracted it again, rejects it with an
+ // AbortError. The fetch reads the Request object's body through a proxy, so that body is used either way, and is
+ // kept.
+ promiseTest(async () => {
+ const server = httpTestServer();
+ const token = crypto.randomUUID();
+ const corsHeaders = { "Access-Control-Allow-Origin": "*" };
+ const nextTask = () => new Promise(resolve => setTimeout(resolve, 0));
+
+ const createHeldEcho = (method, name) =>
+ server.createEcho(method, `/fetch-abort-after-redirect-${name}-${token}`, {
+ status: 200,
+ headers: corsHeaders,
+ wait_for_unblock: token,
+ });
+ const createRedirect = (status, name, location) =>
+ server.createEcho("POST", `/fetch-abort-after-redirect-${name}-${token}`, {
+ status,
+ headers: { ...corsHeaders, "Location": location },
+ });
+ const requestArrived = url => {
+ const recordedURL = `${server.baseURL}/recorded-request-headers${new URL(url).pathname}`;
+ return fetch(recordedURL, { cache: "no-store" }).then(
+ response => response.ok,
+ () => false
+ );
+ };
+
+ const abortWhileHeld = async (url, heldURL) => {
+ const request = new Request(url, { method: "POST", body: "body" });
+ const controller = new AbortController();
+ const fetched = fetch(request, { signal: controller.signal }).then(
+ () => "resolved",
+ error => error.name
+ );
+ while (!(await requestArrived(heldURL)))
+ await nextTask();
+ controller.abort();
+ return `${await fetched}, body used: ${request.bodyUsed}`;
+ };
+
+ // Every held echo is registered before the first request arrives.
+ const heldPostURL = await createHeldEcho("POST", "held-post");
+ const heldGetURL = await createHeldEcho("GET", "held-get");
+ const heldRedirectedPostURL = await createHeldEcho("POST", "held-redirected-post");
+ const seeOtherURL = await createRedirect(303, "see-other", heldGetURL);
+ const temporaryRedirectURL = await createRedirect(307, "temporary-redirect", heldRedirectedPostURL);
+
+ println(`no redirect: ${await abortWhileHeld(heldPostURL, heldPostURL)}`);
+ println(`303 to a GET: ${await abortWhileHeld(seeOtherURL, heldGetURL)}`);
+ println(`307 to a POST: ${await abortWhileHeld(temporaryRedirectURL, heldRedirectedPostURL)}`);
+
+ const redirectedPostURL = await server.createEcho("POST", `/fetch-abort-after-redirect-redirected-post-${token}`, {
+ status: 200,
+ headers: corsHeaders,
+ });
+ const unheldRedirectURL = await createRedirect(307, "unheld-temporary-redirect", redirectedPostURL);
+ const redirected = new Request(unheldRedirectURL, { method: "POST", body: "body" });
+ await (await fetch(redirected)).text();
+ println(`307 to a POST without an abort, body kept: ${redirected.body !== null}`);
+
+ await fetch(`${server.baseURL}/unblock/${token}`);
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.html b/Tests/LibWeb/Text/input/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.html
new file mode 100644
index 00000000000..4d8fff6805b
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-abort-before-transmission-cancels-the-request-body-stream.html
@@ -0,0 +1,28 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // Aborting a fetch before it transmits its request body cancels the body's stream, which the fetch has held a
+ // reader of since it started.
+ promiseTest(async () => {
+ const url = await httpTestServer().createEcho("POST", "/fetch-abort-before-transmission-cancels-the-request-body-stream", {
+ status: 200,
+ headers: { "Access-Control-Allow-Origin": "*" },
+ body: "",
+ });
+ const controller = new AbortController();
+ const stream = new ReadableStream({
+ cancel(reason) {
+ println(`cancel: ${reason.name}`);
+ },
+ });
+
+ const fetched = fetch(url, { method: "POST", body: stream, duplex: "half", signal: controller.signal });
+ controller.abort();
+ try {
+ await fetched;
+ println("fetch: resolved");
+ } catch (error) {
+ println(`fetch: ${error.name}`);
+ }
+ });
+</script>
diff --git a/Tests/LibWeb/Text/input/Fetch/fetch-locks-a-request-body-stream.html b/Tests/LibWeb/Text/input/Fetch/fetch-locks-a-request-body-stream.html
new file mode 100644
index 00000000000..dc162d2f671
--- /dev/null
+++ b/Tests/LibWeb/Text/input/Fetch/fetch-locks-a-request-body-stream.html
@@ -0,0 +1,31 @@
+<!DOCTYPE html>
+<script src="../include.js"></script>
+<script>
+ // A fetch locks its request body's stream as it starts, before the CORS preflight that a body without a source
+ // needs, so script cannot take the stream the fetch reads.
+ promiseTest(async () => {
+ const url = await httpTestServer().createEcho("POST", "/fetch-locks-a-request-body-stream", {
+ status: 200,
+ headers: { "Access-Control-Allow-Origin": "*" },
+ body: "",
+ });
+ const stream = new ReadableStream({
+ pull(controller) {
+ controller.enqueue(new Uint8Array([1]));
+ controller.close();
+ },
+ });
+
+ const fetched = fetch(url, { method: "POST", body: stream, duplex: "half" });
+ println(`locked: ${stream.locked}`);
+ try {
+ stream.getReader();
+ println("getReader: succeeded");
+ } catch (error) {
+ println(`getReader: ${error.name}`);
+ }
+
+ await fetched;
+ println("fetch: resolved");
+ });
+</script>