Skip to content

Design an API to support aborting requests #424

Closed

Description

@natebosch

On the web HttpRequest supports abort: https://api.dart.dev/stable/2.8.1/dart-html/HttpRequest/abort.html

We have a proposal for adding abort on the dart:io HttpClientRequest: https://dart-review.googlesource.com/c/sdk/+/147339

We need to come up with a design for supporting abort through the interfaces in this package and validate that we can build it on both dart:html and dart:io implementations.

The easiest option might be to add a method on StreamedResponse. There is some precedent for that with IOStreamedResponse.detachSocket.

Future<Socket> detachSocket() async => _inner.detachSocket();
(we need to make sure the differences between these are clearly documented.

I do wonder if we need to consider some sort of support for the more convenient methods than send though...

cc @kevmoo @jakemac53 @grouma @zichangg @lrhn for thoughts

Activity

  1. zichangg commented on May 29, 2020

    @zichangg
  2. natebosch commented on May 29, 2020

    @natebosch
    MemberAuthor

    Here are a couple other options - I'm not advocating for these, just trying to brainstorm. Both of these are breaking changes for anyone with implements http.Client.

    Allow passing a Future back to the client to cancel it. We'd have some state that lets us abort if you give us back the exact same instance.

    var response = client.get(url);
    // something happens
    client.abort(response);

    Add a named argument to all the methods:

    var abortCompleter = Completer<void>();
    var response = client.get(url, abortOn: abortCompleter.future);
    // something happens
    abortCompleter.complete();

    The latter could pair well with a timeout argument. Passing timeout: Duration(seconds: 5) would have the same effect as passing abortOn: Future.delayed(Duration(seconds: 5))

  3. grouma commented on Jun 1, 2020

    @grouma
    Member

    I like the latter assuming a future that completes after the request has completed doesn't cause an issue.

  4. liranzairi commented on Aug 30, 2020

    @liranzairi

    Hey, in my app I want to give the user an option to abort while uploading a file. I saw that dart:io is going to support it soon. However I use http package in my app so I looked here and saw this thread. Do you think you'll support it too, soon? Thanks

  5. jakemac53 commented on Aug 31, 2020

    @jakemac53
    Contributor

    I think having an abort method on the response itself is really the ideal design here, for a few reasons:

    • It doesn't require the Client to keep track of outgoing requests. This is cleaner, more memory efficient, and less likely to result in memory leaks.
    • It is more intuitive as a user of the API - all the useful functionality is encapsulated on the response itself - you can pass that one object around to other parts of the code and they can decide to cancel it, etc. They don't also need a client, and you can decouple the knowledge about when to cancel from the service making the actual requests.
    • It allows you to synchronously cancel requests, instead of waiting an arbitrary amount of time for the event queue to catch up. This helps to mitigate race conditions between the cancellation and completion of the request, and it helps to waste less data by cancelling the request sooner.

    This does get a bit trickier to implement - you are left with a few not so great options:

    • Implement Future with some custom type, which beyond being considered an anti-pattern also raises some difficult questions around how you handle the cancel case. I think for this you could just complete with a special type of error, and not try to do what CancelableOperation does (with a special onCancel callback that complicates error handling).
    • Make a user-facing breaking change in the api to return some new type (possibly CancelableOperation).
  6. natebosch commented on Aug 31, 2020

    @natebosch
    MemberAuthor

    Do you think you'll support it too, soon?

    The trickiest part of this is rolling it out, I think no matter what design we use it's going to be a breaking change for anyone with a class which implements Client.

  7. natebosch commented on Jan 6, 2021

    @natebosch
    MemberAuthor
    • It doesn't require the Client to keep track of outgoing requests. This is cleaner, more memory efficient, and less likely to result in memory leaks.

    I don't think that will be difficult in any case. We don't need an extra collection - we can handle this all at the point where we have the HttpClientRequest or the HttpRequest.

    • It is more intuitive as a user of the API - all the useful functionality is encapsulated on the response itself - you can pass that one object around to other parts of the code and they can decide to cancel it, etc. They don't also need a client, and you can decouple the knowledge about when to cancel from the service making the actual requests.

    Attaching it to a StreamedResponse has the downside of pushing more users onto that API over http.get. I think cancellation (usually timeout) is a common enough use case that we want to support it on those APIs as well. Changing the return type from Future to CancelablleOperation is more breaking, and I'm not entirely convinced one way or the other whether it's a better API if we were starting from scratch.

    • It allows you to synchronously cancel requests, instead of waiting an arbitrary amount of time for the event queue to catch up. This helps to mitigate race conditions between the cancellation and completion of the request, and it helps to waste less data by cancelling the request sooner.

    I would expect that the typical case cancelations only happen after some async trigger either way. I think at most we could shave a microtask or 2, but I don't think that gives much power to typical usages. Which likely can't make many guarantees about behavior even if we give them a synchronous cancel.

  8. natebosch commented on Jan 6, 2021

    @natebosch
    MemberAuthor

    I'm running with the abortOn approach for now.

    One thing that's tricky here, I didn't realize the dart:io implementation causes the done future to complete as an error as opposed to never completing. I'm pretty sure the implementation in the browsers wouldn't do that.

    I think it would be easier to build the error behavior in the browser than to build the never-complete behavior for dart:io but probably either is possible.

    I don't have a strong opinion between completing as error on abort, or never completing on abort. One nice thing about the error approach is that if you do want to forward an error object and stack trace through it's possible to do so.

    cc @lrhn for opinions on completing as error vs never completing for aborted requests.

  9. jakemac53 commented on Jan 6, 2021

    @jakemac53
    Contributor

    I really don't think abortOn with a Future type is the right api here... it has a lot of downsides. Specifically since you can't cancel the future at all I think it will be prone to memory leaks, hung processes on exit, and other similar issues.

    How about just supporting the timeout argument which we can ensure is implemented better (using a timer which we can cancel) as opposed to a delayed future?

  10. aytunch commented on Jan 11, 2021

    @aytunch

    This is a must have feature. A lot of community backed packages are using this package at their core. And because there is not yet a abort functionality for downloads, there are huge amount of wasted data for Flutter users. This is really bad user experience when users check their data usage on their phones.

    I am not sure why people are so concerned about breaking changes. Flutter is still new. Breaking changes are to be expected and for a core functionality like this, I am sure devs wont complain.

    Imho what devs would really complain about could be a platform with APIs so hard to understand because they were patched for every new feature instead of getting redesigned. If we want Flutter to remain and feel fresh and different from the old and slow SDks then we have to live with breaking changes for a while.

    Personally, the lack of aborting is a big deal for us because we have a video heavy app and we are using flutter_cache_manager to pre-download some of the videos in the list. If the user scrolls even further, we would like to abort the started downloads and start new ones. But for now we are stuck with 10's of started downloads which will be just byte waste.

  11. added
    next-breaking-releaseIssues that are worth doing but need to wait for a breaking version bump
    on Jan 29, 2021
  12. fzyzcjy commented on Aug 2, 2021

    @fzyzcjy
  13. mleonhard commented on Aug 18, 2021

    @mleonhard
  14. kevmoo commented on Sep 13, 2021

    @kevmoo
    Member

    @natebosch – what's the current story here?

  15. natebosch commented on Sep 13, 2021

    @natebosch
    MemberAuthor

    This is still something we plan on looking at but we don't have a concrete plan.

  16. 36 remaining items

  17. JaffaKetchup commented on May 22, 2025

    @JaffaKetchup
    Contributor

    It looks like HttpClientRequest.abort does nothing after the request has been sent.

    Looking at https://api.flutter.dev/flutter/dart-io/HttpClientRequest/abort.html:

    If the connection has not yet completed, the request is aborted and the done future (also returned by close) is completed with the provided exception and stackTrace. If exception is omitted, it defaults to an HttpException, and if stackTrace is omitted, it defaults to StackTrace.empty.

    If the done future has already completed, aborting has no effect.

    done (which is returned by close) is:

    An HttpClientResponse future that will complete once the response is available.

    If an error occurs before the response is available, this future will complete with an error.

    So I would expect the abort to still do something until the response is available. In other words, I would expect it to be effective until we complete this line:

    var response = await stream.pipe(ioRequest) as HttpClientResponse;

    Therefore, I assume this means any response that the user manages to read for the IOClient will always be fully complete.

    This is not the case for BrowserClient.

    Does that make sense?

    I can screen record to show you why I think that explains the behaviour I see.

  18. brianquinlan commented on May 22, 2025

    @brianquinlan
    Collaborator

    It looks like HttpClientRequest.abort does nothing after the request has been sent.

    Looking at https://api.flutter.dev/flutter/dart-io/HttpClientRequest/abort.html:

    If the connection has not yet completed, the request is aborted and the done future (also returned by close) is completed with the provided exception and stackTrace. If exception is omitted, it defaults to an HttpException, and if stackTrace is omitted, it defaults to StackTrace.empty.
    If the done future has already completed, aborting has no effect.

    done (which is returned by close) is:

    An HttpClientResponse future that will complete once the response is available.
    If an error occurs before the response is available, this future will complete with an error.

    So I would expect the abort to still do something until the response is available. In other words, I would expect it to be effective until we complete this line:

    var response = await stream.pipe(ioRequest) as HttpClientResponse;
    Therefore, I assume this means any response that the user manages to read for the IOClient will always be fully complete.

    This is not the case for BrowserClient.

    Does that make sense?

    I can screen record to show you why I think that explains the behaviour I see.

    You could just start writing integration tests to verify the behavior. I'd be happy to send you some code to get started.

  19. JaffaKetchup commented on May 22, 2025

    @JaffaKetchup
    Contributor

    Yeah, that might be helpful thanks.

  20. brianquinlan commented on May 22, 2025

    @brianquinlan
    Collaborator

    I created a PR with some test ideas: #1777

    There are some scenarios that I considered interesting in this file:
    https://github.com/dart-lang/http/pull/1777/files#diff-1b0edc4ff03481f2fadadf18fbc7e6a828a0092275d13bd421c56b44b5eb3ca8R45

  21. JaffaKetchup commented on May 22, 2025

    @JaffaKetchup
    Contributor

    Ok, so some issues that seem to backup the difference in behaviour.

    With the IOClient and "after response, client still useable" request:

    test('after response, client still useable', () async {
          final abortTrigger = Completer<void>();
    
          final request = AbortableRequest(
            'GET',
            serverUrl,
            abortTrigger: abortTrigger.future,
          );
    
          final abortResponse = await client.send(request);
    
          abortTrigger.complete();
    
          bool triggeredAbortedRequest = false;
          try {
            await abortResponse.stream.drain<void>();
          } on AbortedRequest {
            triggeredAbortedRequest = true;
          }
    
          final response = await client.get(serverUrl);
          expect(response.statusCode, 200);
          expect(response.body, endsWith('9999\n'));
          expect(triggeredAbortedRequest, true);
        });

    triggeredAbortedRequest is false, and the test fails. IOClient does not throw and cannot throw AbortedRequest when reading the stream. It only happens on send. Since we cancel after send, it does not cause any error to throw.

    The test is successful on BrowserClient.


    This test seems potentially broken on both platforms:

        test('while streaming response', () async {
          final abortTrigger = Completer<void>();
    
          final request = AbortableRequest(
            'GET',
            serverUrl,
            abortTrigger: abortTrigger.future,
          );
          final response = await client.send(request);
    
          var i = 0;
          expect(
            response.stream.listen((data) {
              ++i;
              if (i == 1000) abortTrigger.complete();
            }).asFuture<void>(),
            throwsA(isA<AbortedRequest>()),
          );
          expect(i, 1000);
        }, skip: canStreamResponseBody ? false : 'does not stream response bodies');

    Why would the last expect statement wait for the loop to reach 1000? Should I have changed something here?
    I would also expect it to fail on IOClient in the same way as above.


    This test fails on IOClient and succeeds on BrowserClient:

        test('after response', () async {
          final abortTrigger = Completer<void>();
    
          final request = AbortableRequest(
            'GET',
            serverUrl,
            abortTrigger: abortTrigger.future,
          );
          final response = await client.send(request);
    
          abortTrigger.complete();
    
          expect(
            response.stream.single,
            throwsA(isA<AbortedRequest>()),
          );
        });
    Expected: throws <Instance of 'AbortedRequest'>
      Actual: <Instance of 'Future<List<int>>'>
       Which: threw StateError:<Bad state: Too many elements>
              stack 
              which is not an instance of 'AbortedRequest'

    I can't quite figure out what that response is saying. Too many elements? But anyway, same as before, IOClient only throws on send.


    I don't think it's possible to change the behaviour of IOClient to match BrowserClient since its under the control of dart:io. It might be possible to change the behaviour the other way to match, not sure the best way to do that. Is it even necessary?

  22. brianquinlan commented on May 22, 2025

    @brianquinlan
    Collaborator

    ...
    This test seems potentially broken on both platforms:

    test('while streaming response', () async {
      final abortTrigger = Completer<void>();
    
      final request = AbortableRequest(
        'GET',
        serverUrl,
        abortTrigger: abortTrigger.future,
      );
      final response = await client.send(request);
    
      var i = 0;
      expect(
        response.stream.listen((data) {
          ++i;
          if (i == 1000) abortTrigger.complete();
        }).asFuture<void>(),
        throwsA(isA<AbortedRequest>()),
      );
      expect(i, 1000);
    }, skip: canStreamResponseBody ? false : 'does not stream response bodies');
    

    Why would the last expect statement wait for the loop to reach 1000? Should I have changed something here? I would also expect it to fail on IOClient in the same way as above.

    The test is trying to confirm that you don't get any more data after you aport the request.

    ...

    I don't think it's possible to change the behaviour of IOClient to match BrowserClient since its under the control of dart:io. It might be possible to change the behaviour the other way to match, not sure the best way to do that. Is it even necessary?

    You can by proxying the Stream that HttpClient uses. Pseudocode:

    //       var response = await stream.pipe(ioRequest) as HttpClientResponse;
      final controller = StreamController<Uint8List>(onCancel: () {
        subscription.cancel();
      });
      final subscription = ioRequest.listen((data) {
        subscription.sink.add(data);
      }, onDone: () async {await subscription.sink.close(); });
    
      abortThing.then(() async {
        // If the controller is already closed then the stream has already been consumed
        // by the caller or there was already another error.
        if (!controller.isClosed)
          subscription.sink.addError(AbortedRequest(...));
          await subscription.sink.close();
      });
      // Pass `controller.stream` to _StreamedResponseWithUrl
  23. JaffaKetchup commented on May 23, 2025

    @JaffaKetchup
    Contributor

    @brianquinlan I'm not quite sure what that's trying to do.

    From my understanding:

    • stream.pipe(ioRequest)
      This pumps the stream (which is the request body) into the opened connection, then closes the request/connection.
    • On closing the ioRequest, which happens within pipe, it returns the HTTP response

    So I'm not sure what you meant by ioRequest.listen - it can't be listened to.

    If abort is called after the pipe line, it is ineffective. Only after the pipe can we begin to read bytes. So I'm not sure it even makes sense to attempt to make the behaviour like BrowserClient.

  24. JaffaKetchup commented on May 23, 2025

    @JaffaKetchup
    Contributor

    I guess you could inject an error into the output byte stream where catchError is at the moment, is that what you were suggesting?

    I'm not sure it makes sense though, it would be a lie (the whole response is always available at that point).

  25. brianquinlan commented on May 23, 2025

    @brianquinlan
    Collaborator

    @brianquinlan I'm not quite sure what that's trying to do.

    From my understanding:

    • stream.pipe(ioRequest)
      This pumps the stream (which is the request body) into the opened connection, then closes the request/connection.
    • On closing the ioRequest, which happens within pipe, it returns the HTTP response

    So I'm not sure what you meant by ioRequest.listen - it can't be listened to.

    Sorry, I meant you can listen to response.

    If abort is called after the pipe line, it is ineffective. Only after the pipe can we begin to read bytes. So I'm not sure it even makes sense to attempt to make the behaviour like BrowserClient.

    The entire premise of package:http is to provide a consistent interface across HTTP client implementations. That isn't always possible but, when it is possible (and I think that it is in this case), we try our best to make the Client's consistent.

    I'm not sure it makes sense though, it would be a lie (the whole response is always available at that point).

    dart:io HttpClient streams the response (otherwise it would be impossible to do downloads that don't fit into memory).

    Let me know if you can stuck on this and I can propose some code - if you do that could you upload what you have on your PR with my conformance tests included?

    Thanks again for working on this!

  26. JaffaKetchup commented on May 24, 2025

    @JaffaKetchup
    Contributor

    @brianquinlan

    I've made IOClient mostly work in the way we want.
    The limitation is that in the "while streaming response" test, the number of events received is larger than 1000 - it's always 1749. I would assume this is because of the way the events are emitted in batches. Even trying to use takeUntil instead of a custom implementation has the same issue, so I would assume it's unavoidable.
    May also need to tweak it a little more to respect onListen on the controller etc. (and only start the subscription on the response then) so it doesn't waste memory, but I'm not sure if that's necessary.

    I'm struggling to make BrowserClient meet the "while streaming response" test. In the event of abortion, it just completes the stream without an error. Additionally, it somehow only counts up to 13! I guess the solution is the same as for IOClient, but it's a little but more difficult to work with.

    I might be able to take a look tomorrow, but if you wanted to have a look in the meantime, everything is up to date with your tests and my changes.

  27. JaffaKetchup commented on May 25, 2025

    @JaffaKetchup
    Contributor

    #1773 is (pretty much) ready!

  28. brianquinlan commented on Jun 3, 2025

    @brianquinlan
    Collaborator

    #1773 is definitely moving us in the right direction but I'm worried that landing it will be hard because of the flaky failures in IOClient and the work needed to make RetryClient work (let me know if you disagree @JaffaKetchup !)

    What Client implementations do people care about? Because an alternative approach would be to incrementally support aborting requests i.e. we could start with BrowserClient, CupertinoHttp and CronetHttp. IOClient and RetryClient could display a warning saying that they don't support aborting requests if the abortTrigger future is completed e.g.

            unawaited(abortTrigger.whenComplete(() => print('IOClient does not support request cancellation. See https://github.com/dart-lang/http/issues/424));

    We could add support for IOClient whenever someone has the time to do so.

    Thoughts @natebosch @JaffaKetchup ?

  29. JaffaKetchup commented on Jun 3, 2025

    @JaffaKetchup
    Contributor

    Yeah, I can definitely see it might be tricky to get things working if I can't reproduce the issues :D

    I've made a small change on #1773, could you run the tests again? It's ugly and I don't know if I expect it to work, but if it does, that confirms something(???) :D.

    Unfortunately, the IO and browser clients are the ones I most care about - that's what we use by default in flutter_map (through the Client constructor). We do use RetryClient - I could work around that in the meantime - but again, ideally, it would be implemented. And looking at the pub.dev stats, the vast majority of users seem to be using the default clients (idk about retry) - so not implementing it fully but landing the feature wouldn't seem quite right IMO.

    Could there be the option of disabling abortion for streamed requests for the time being - or simply refusing to abort requests while the data is being streamed in?

    If it turns out we need to make a change to the Dart SDK, that complicates things ofc. I would hope that's not necessary though.

    But as I'm very short on time for the next couple few weeks, and you are as well, I think leaving it for a few weeks is fine. Afterall, even if we managed to land it before your holiday somehow, I couldn't make good use of it for a few weeks. After that I'll have more time to figure things out (hopefully). Ofc if someone else wants it in the meantime... ;D

    On a sort-of related note, I noticed https://pub.dev/packages/fetch_client. Doesn't the http implementation now use fetch as well? And after we've implemented this, wouldn't they both have the same feature set?

  30. brianquinlan commented on Jul 8, 2025

    @brianquinlan
    Collaborator

    Thanks to the great work of @JaffaKetchup, package:http now supports the ability to abort requests.

    You can read more about how to use the feature in the documentation.

    Right now the feature is in beta and it would be great if everyone interested in this feature could try it out and report any issues that you find. You can do so by specifying the beta version in your pubspec.yaml (don't worry, that syntax will pick up newer versions as they appear):

      http: ^1.5.0-beta
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    next-breaking-releaseIssues that are worth doing but need to wait for a breaking version bump

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions