Jaguar-dart / client

Contains various packages for client side

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Resty: timeout support

jaumard opened this issue · comments

As dart http doesn't support read timeout, would be nice if resty provide this functionality instead of still having to use Future.timeout

A quick solution to at least force a timeout globally on the client is:

resty_io_client.dart:

import 'package:http/http.dart';
import 'package:http/io_client.dart';

class RestyIOClient extends IOClient {
  Duration timeout;
  RestyIOClient([inner]) : super(inner);
  Future<StreamedResponse> send(BaseRequest request) async {
    return timeout != null
        ? super.send(request).timeout(timeout)
        : super.send(request);
  }
}

Example usage:

Route('http://test.com').withClient(
      RestyIOClient()..timeout = const Duration(seconds: 2),
    );

Note that it is possible to set timeouts directly on the http client, but in my case those didn't get triggered,
as it was a 504 error which does accept the connection (not sure why idleTimeout didn't kick in either):

Route('http://test.com').withClient(
      RestyIOClient(
        HttpClient()
          ..connectionTimeout = const Duration(seconds: 2)
          ..idleTimeout = const Duration(seconds: 3)
          ..userAgent = 'Test Agent',
      )..timeout = Duration(seconds: 2),
    );

One benefit of Future.timeout is it will always behave as expected.

For reference; dio is also solves this issue using Future.timeout: https://github.com/flutterchina/dio/blob/master/package_src/lib/src/adapter.dart#L100-L134