| OLD | NEW |
| (Empty) |
| 1 // Copyright (c) 2014, the Dart project authors. Please see the AUTHORS file | |
| 2 // for details. All rights reserved. Use of this source code is governed by a | |
| 3 // BSD-style license that can be found in the LICENSE file. | |
| 4 | |
| 5 library http_throttle; | |
| 6 | |
| 7 import 'dart:async'; | |
| 8 | |
| 9 import 'package:http/http.dart'; | |
| 10 import 'package:pool/pool.dart'; | |
| 11 | |
| 12 /// A middleware client that throttles the number of concurrent requests. | |
| 13 /// | |
| 14 /// As long as the number of requests is within the limit, this works just like | |
| 15 /// a normal client. If a request is made beyond the limit, the underlying HTTP | |
| 16 /// request won't be sent until other requests have completed. | |
| 17 class ThrottleClient extends BaseClient { | |
| 18 final Pool _pool; | |
| 19 final Client _inner; | |
| 20 | |
| 21 /// Creates a new client that allows no more than [maxActiveRequests] | |
| 22 /// concurrent requests. | |
| 23 /// | |
| 24 /// If [inner] is passed, it's used as the inner client for sending HTTP | |
| 25 /// requests. It defaults to `new http.Client()`. | |
| 26 ThrottleClient(int maxActiveRequests, [Client inner]) | |
| 27 : _pool = new Pool(maxActiveRequests), | |
| 28 _inner = inner == null ? new Client() : inner; | |
| 29 | |
| 30 Future<StreamedResponse> send(BaseRequest request) { | |
| 31 return _pool.request().then((resource) { | |
| 32 return _inner.send(request).then((response) { | |
| 33 var stream = response.stream.transform( | |
| 34 new StreamTransformer.fromHandlers(handleDone: (sink) { | |
| 35 resource.release(); | |
| 36 sink.close(); | |
| 37 })); | |
| 38 return new StreamedResponse(stream, response.statusCode, | |
| 39 contentLength: response.contentLength, | |
| 40 request: response.request, | |
| 41 headers: response.headers, | |
| 42 isRedirect: response.isRedirect, | |
| 43 persistentConnection: response.persistentConnection, | |
| 44 reasonPhrase: response.reasonPhrase); | |
| 45 }); | |
| 46 }); | |
| 47 } | |
| 48 | |
| 49 void close() => _inner.close(); | |
| 50 } | |
| OLD | NEW |