Skip to content

fix(dio): unsubscribe from response stream when downstream subscription is cancelled - #2644

Open
Safeer-Hussain wants to merge 1 commit into
cfug:mainfrom
Safeer-Hussain:fix/stream-subscription-cancel-2618
Open

Safeer-Hussain wants to merge 1 commit into
cfug:mainfrom
Safeer-Hussain:fix/stream-subscription-cancel-2618

Conversation

@Safeer-Hussain

Copy link
Copy Markdown

Motivation

When requesting a stream response (ResponseType.stream) or consuming response body bytes directly from handleResponseStream, downstream callers may cancel their StreamSubscription before the entire body has been delivered.

In #2588, onPause and onResume were added to StreamController<Uint8List> responseSink to propagate backpressure to the upstream socket, but onCancel was omitted. As a result, cancelling the downstream subscription left the adapter's underlying response subscription active:

  • Sockets and HTTP/2 streams remained open and continued consuming bandwidth over the wire.
  • Underlying network resources and byte buffers were prevented from being garbage-collected.
  • receiveTimeout timers continued running in the background.

Closes #2618

Solution

  1. Reordered the local declarations in handleResponseStream so stopWatchReceiveTimeout() is declared before responseSink.
  2. Added an onCancel hook to responseSink that:
    • Stops the receiveTimeout stopwatch and timer (stopWatchReceiveTimeout()).
    • Closes the ResponseBody (response.close()).
    • Cancels and returns the upstream subscription's cancel future (return responseSubscription.cancel()).

Verification

Added a unit test to test/response/response_stream_test.dart:

  • Verified that cancelling the returned stream's subscription immediately sets source.hasListener to false, triggers ResponseBody.close(), and cancels the receive timeout watch.
  • Confirmed the test fails on unpatched code (expected: false, actual: true) and passes with this fix.
  • Ran dart analyze --fatal-infos, dart format --set-exit-if-changed, and dart test clean.

Attribution

Implementation and tests by Antigravity (Google DeepMind).

Co-Authored-By: Antigravity antigravity@google.com

@Safeer-Hussain
Safeer-Hussain requested a review from a team as a code owner November 24, 2026 18:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Cancelling a response stream subscription leaves the adapter response subscribed

1 participant