Repository navigation
refactor: transfer fetch response pipes directly - #53263
deepak1556 wants to merge 11 commits into
Conversation
MarshallOfSound
left a comment
There was a problem hiding this comment.
The endpoint handoff is a good direction and removes a lot of code. Two items block: the FusePipes CHECK crashes the main process on any redirect through the proxy pattern, and an upstream disconnect before the headers hangs net.fetch. The other comments are behaviour changes from the old relay. We need to keep the old behaviour, or call out the change.
df53060 to
9222ef2
Compare
The initial untouched net.fetch relay avoided sending most response chunks
through JavaScript, but SimpleURLLoader::DownloadAsStream had already consumed
the original response body pipe. Relaying therefore still required a second
data pipe, buffered chunks, and recovery of a prefix already pulled into JS.
Before this change:
```
upstream URLLoader
|
| original response body pipe
v
SimpleURLLoader::BodyReader
|
| string_view chunks
v
ResponseBody
|
+-- before hold --> IncomingMessage --> Readable.toWeb()
|
`-- after hold
|
+-- buffered pending chunks
+-- prefix already pulled into JavaScript
|
v
newly-created destination data pipe
|
v
protocol URLLoaderClient
```
Interpose TransferableURLLoader between SimpleURLLoader and the upstream
URLLoaderFactory instead. It owns both upstream endpoints and retains the
original response body pipe before SimpleURLLoader can consume it.
After this change:
```
SimpleURLLoader
|
| CreateLoaderAndStart()
v
TransferableURLLoader
|
v
upstream URLLoader
OnReceiveResponse(head, original body pipe)
|
v
TransferableURLLoader
|
+-- first JavaScript read
| |
| +-- mark the body as consumed
| +-- read through a cppgc FetchResponseBodyReader
| +-- pin the destination ArrayBuffer backing store
| `-- reconcile pipe EOF with the original completion status
|
`-- untouched protocol response
|
+-- move the original body pipe
+-- unbind URLLoaderClientEndpoints
+-- fuse the destination URLLoader endpoint
`-- forward the original or already-received completion status
|
v
protocol URLLoaderClient
``
The response body now has a one way disposition:
```
unclaimed --> reading
|
`------> transferred
```
Keep SimpleURLLoader in control of request construction, redirects,
authentication, uploads, and cross-factory restarts. Only final response body
ownership is intercepted. This preserves existing net.request behavior while
allowing untouched net.fetch responses to use endpoint handoff.
Avoid fusing mojo pipes that may already have carried redirect messages. Proxy both URLLoader directions instead so redirects remain transferable.
Forward a failure to SimpleURLLoader when the target client pipe closes before response headers, preventing the fetch promise from hanging.
Unbind the target URLLoaderClient receiver before releasing the old SimpleURLLoader client so outstanding upload responders remain valid.
Keep a weak cancellation hook to the transferred endpoint proxy so an inner fetch AbortSignal can still terminate the request after handoff.
Error the response stream with the signal reason before cancelling the native loader so body consumers continue to receive an AbortError.
Release native endpoints when JavaScript reaches EOF or an error, notify the wrapper of completion, and immediately release responses without bodies.
Key transfer metadata by Response while separately tracking the original body identity, preserving sniffed MIME data without transferring a cloned stream.
Copy each completed read into a Uint8Array so consumers do not retain the full 64 KiB backing store for every small chunk.
A protocol handler can return an untouched net.fetch() response to an outer custom protocol request. After the handoff, the outer request owns the original response body pipe, while the inner Fetch and its AbortSignal still control the underlying network request. Normal Mojo cancellation is asynchronous and is not ordered with response bytes already buffered in the data pipe. This allowed an outer body read to consume more data after the inner Fetch had been aborted. Add a weak local cancellation connection that marks the current body owner as aborted immediately, while retaining the normal Mojo path to cancel and clean up the actual network request. Runtime coverage also exposed lifetime assumptions previously hidden by the buffered relay. Avoid shadowing the loader's ref-counting Release() operation, ignore expected SimpleURLLoader teardown after handoff, and report post header failures through the Fetch body instead of as duplicate request errors. Preserve buffered bytes for ordinary network errors, support manual redirect responses, and release endpoints promptly in every terminal state.
4a4e985 to
5122350
Compare
|
@deepak1556 Needs a rebase |
MarshallOfSound
left a comment
There was a problem hiding this comment.
Thanks for working through the last round. Went over the new head and there are a few more, the first one I think blocks.
|
|
||
| void TransferableURLLoader::ReleaseResponse() { | ||
| DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); | ||
| CHECK_NE(disposition_, Disposition::kTransferred); |
There was a problem hiding this comment.
This CHECK is reachable from a protocol handler now. TakeResponse() leaves transferable_body_ set on the wrapper (for the cancel hook) and protocol.ts hands off fetchResponse.loader without locking res.body, so if the handler touches the Response after returning it (await res.text(), res.clone(), or returns the same cached Response a second time so we fall back to Readable.fromWeb(res.body)), pull() → Read() returns ERR_UNEXPECTED for kTransferred → FetchResponseBodyReader::OnReadCompleted → OnTransferableBodyComplete → ReleaseResponse() → this. Before this PR that was a TypeError in JS, now it takes out the main process.
I think either OnTransferableBodyComplete should no-op once we've transferred, or protocol.ts should lock/cancel res.body when it takes the loader so the late read fails in JS.
| std::optional<PendingURLLoaderResponse> SimpleURLLoaderWrapper::TakeResponse() { | ||
| if (!transferable_body_) | ||
| return std::nullopt; | ||
| auto response = transferable_body_->TakeResponse(); | ||
| if (!response) | ||
| return std::nullopt; | ||
| loader_.reset(); | ||
| url_loader_factory_.reset(); | ||
| keep_alive_.Clear(); |
There was a problem hiding this comment.
Clearing keep_alive_ here means nothing native roots the inner request's JS graph once the protocol.handle callback returns. undici only links the caller's signal to the Request's internal controller through a WeakRef, so signal → req.signal listener → r.abort() → _urlLoader.cancel() → TransferredURLLoader::Cancel is an unrooted island and goes away at the next GC; after that controller.abort() / AbortSignal.timeout() on the inner fetch is a silent no-op and the transferred body keeps streaming. The old RelayTo() kept keep_alive_ = this for the relay's lifetime which is what made the timeout-proxy case work.
The new keeps the inner fetch abort signal connected after transfer spec passes because nothing collects before abort(); stick a v8Util.requestGarbageCollectionForTesting() in front of it like the neighbouring test does and I'd expect reader.read() to hang. We probably want the wrapper rooted for as long as the TransferredURLLoader is live and cleared from its completion.
| void OnTargetURLLoaderClientDisconnected(); | ||
| void CompletePendingRead(); | ||
|
|
||
| raw_ptr<Delegate> delegate_; |
There was a problem hiding this comment.
Nit: this is a raw_ptr from a ref-counted object to the cppgc SimpleURLLoaderWrapper, which is the thing the cppgc section in CLAUDE.md says not to do. It's fine today because every teardown path nulls it before the wrapper can go, but the loader is shared (FetchResponseBodyReader::loader_, the protect ref) and ~SimpleURLLoaderWrapper never clears it, so it's one refactor away from dangling. SimpleURLLoaderClient already holds the same edge as a WeakPersistent<WeakCell<SimpleURLLoaderWrapper>>, can we do that here too.
| int64_t current_position, | ||
| int64_t total_size, | ||
| OnUploadProgressCallback callback) { | ||
| DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_); | ||
| CHECK(simple_url_loader_client_.is_bound()); | ||
| simple_url_loader_client_->OnUploadProgress(current_position, total_size, | ||
| std::move(callback)); | ||
| } |
There was a problem hiding this comment.
Follow-on from the responder comment last round: the transfer path is sorted (TakeResponse unbinds the target receiver first) but on the JS-read path OnTransferableResponseStarted does loader_.reset() while target_url_loader_client_receiver_ is still bound. If the network service's last periodic OnUploadProgress is still parked in simple_url_loader_client_ when that happens, ~ResponderThunk raises an error on the still-bound endpoint, the real pipe resets, and we report ERR_FAILED and drop the body. Needs an upload long enough to get a progress tick plus a main-thread stall across headers arriving, so it'll show up as intermittent ERR_FAILED on POST/PUT. Simplest thing is probably to ack progress locally here and forward with a no-op callback so we never own an upstream responder.
| r.on('redirect', (statusCode, _method, _newUrl, redirectHeaders) => { | ||
| if (req.redirect !== 'manual') return; | ||
| const headers = new Headers(); | ||
| for (const [k, v] of Object.entries(redirectHeaders)) { | ||
| headers.set(k, Array.isArray(v) ? v.join(', ') : v); | ||
| } | ||
| p.resolve( | ||
| new Response(null, { | ||
| headers, | ||
| status: statusCode | ||
| }) | ||
| ); | ||
| r.abort(); | ||
| }); |
There was a problem hiding this comment.
This changes what net.fetch(url, { redirect: 'manual' }) does: previously there was no 'redirect' listener so ClientRequest died with Redirect was cancelled and the promise rejected, now it resolves with a synthesized null-body 3xx. I don't mind the new behaviour (it's arguably better) but it's a public API change riding in a semver/none refactor with no docs/api/net.md line or api-net-spec coverage, and the shape matches neither WHATWG (opaqueredirect, status 0) nor undici (real 3xx with body). Can we split it out, or at least note + doc + spec it here?
Description of Change
The initial untouched net.fetch relay avoided sending most response chunks through JavaScript, but SimpleURLLoader::DownloadAsStream had already consumed the original response body pipe. Relaying therefore still required a second data pipe, buffered chunks, and recovery of a prefix already pulled into JS.
Before this change:
Interpose TransferableURLLoader between SimpleURLLoader and the upstream URLLoaderFactory instead. It owns both upstream endpoints and retains the original response body pipe before SimpleURLLoader can consume it.
After this change:
The response body now has a one way disposition:
Keep SimpleURLLoader in control of request construction, redirects, authentication, uploads, and cross-factory restarts. Only final response body ownership is intercepted. This preserves existing net.request behavior while allowing untouched net.fetch responses to use endpoint handoff.
This removes:
This endpoint owning transaction model also provides a basis for consolidating the routing work from #53115 and #53204. Once this lands, session routing requirements can be represented as one immutable policy snapshot and the IO thread URLLoaderFactory gate can produce one explicit route decision:
ObservedURLLoader, ProxyingURLLoaderFactory::InProgressRequest, and TransferableURLLoader can then share URLLoaderClientEndpoints ownership conventions without forcing their different behavior into one base class.
The immutable HeaderRules proposed by #53222 can later become another input to this policy decision. Direct requests would apply those rules through the IO thread TrustedHeaderClient, while requests selected for the blocking proxy would apply the same snapshot before JS listeners. That keeps header rules, webRequest listener masks, and protocol interception under one routing policy instead of adding another independent fast path.
Release Notes
Notes: none