-
Notifications
You must be signed in to change notification settings - Fork 416
feat(http2): add a pooled, multiplexed HTTP/2 http.Client #1956
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
demolaf
wants to merge
14
commits into
dart-lang:master
Choose a base branch
from
demolaf:pooled-http2-client
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 5 commits
Commits
Show all changes
14 commits
Select commit
Hold shift + click to select a range
0b1021f
feat(http2): add generic ClientPool<T> with unit tests
demolaf 1e7e56e
feat(http2): add Http2Client, a pooled multiplexed http.Client
demolaf 894b94c
feat(http2): expose Http2Client via package:http2/client.dart
demolaf 4a874cb
chore(http2): changelog entry for Http2Client
demolaf 258830f
fix(http2): retry once when a pooled connection was closed by the peer
demolaf 2c8ae6c
fix(http2): default empty :path to / and strip HTTP/1.x connection-sp…
demolaf 2376148
fix(http2): throw ClientException instead of an internal pool error a…
demolaf 6955e30
fix(http2): exclude failed resources from idle-capacity calculation
demolaf 5d1a7f4
chore(http2): mark ClientPool.opCount @visibleForTesting
demolaf 059cf76
docs(http2): ClientPool.size is used by production code, not just tests
demolaf 84c0d66
refactor(http2): use collection's .sum instead of manual fold sums
demolaf 0ca6c5c
style(http2): use braces for single-statement ifs in _sendOverHttp2
demolaf 3279971
style(http2): use a case pattern for _maybeCompleteDrain's null check
demolaf 659e447
test(http2): drop redundant comment on self-signed test cert bypass
demolaf File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| // Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file | ||
| // for details. All rights reserved. Use of this source code is governed by a | ||
| // BSD-style license that can be found in the LICENSE file. | ||
|
|
||
| import 'dart:io'; | ||
|
|
||
| import 'package:http2/client.dart'; | ||
|
|
||
| /// Sends several concurrent requests through a single [Http2Client], | ||
| /// demonstrating that they share pooled HTTP/2 connections instead of each | ||
| /// opening their own. | ||
| void main(List<String> args) async { | ||
| if (args.length != 1) { | ||
| print('Usage: dart pooled_client.dart <HTTPS_URI>'); | ||
| exit(1); | ||
| } | ||
|
|
||
| final uri = Uri.parse(args[0]); | ||
| final client = Http2Client(); | ||
|
|
||
| try { | ||
| final responses = await Future.wait( | ||
| List.generate(5, (_) => client.get(uri)), | ||
| ); | ||
| for (final response in responses) { | ||
| print('${response.statusCode}: ${response.body.length} bytes'); | ||
| } | ||
| print('Connections used: ${client.connectionCount}'); | ||
| } finally { | ||
| // Waits for the requests above to finish before closing every | ||
| // connection - see Http2Client.terminate(). | ||
| await client.terminate(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| // Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file | ||
| // for details. All rights reserved. Use of this source code is governed by a | ||
| // BSD-style license that can be found in the LICENSE file. | ||
|
|
||
| /// A pooled, multiplexed `package:http` `Client` backed by HTTP/2 | ||
| /// connections. | ||
| /// | ||
| /// See [Http2Client]. | ||
| library; | ||
|
|
||
| import 'src/http2_client.dart' show Http2Client; | ||
|
|
||
| export 'src/http2_client.dart' show Http2Client; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| // Copyright (c) 2026, the Dart project authors. Please see the AUTHORS file | ||
| // for details. All rights reserved. Use of this source code is governed by a | ||
| // BSD-style license that can be found in the LICENSE file. | ||
|
|
||
| import 'dart:async'; | ||
|
|
||
| class _PooledResource<T> { | ||
| _PooledResource(this.future); | ||
| final Future<T> future; | ||
| int inFlight = 0; | ||
| bool failed = false; | ||
| } | ||
|
|
||
| /// A pool of resources of type [T]. | ||
| /// | ||
| /// Packs load onto the most-full resource under [maxConcurrentOperations] | ||
| /// (rather than spreading evenly across resources), opens a new resource | ||
| /// once existing ones are full, stops routing new work to a resource once an | ||
| /// operation on it throws, and garbage-collects idle resources past | ||
| /// [maxIdleResources]. | ||
| class ClientPool<T> { | ||
| ClientPool( | ||
| Future<T> Function() create, { | ||
| required this.maxConcurrentOperations, | ||
| required Future<void> Function(T resource) destroy, | ||
| this.maxIdleResources = 1, | ||
| }) : _create = create, | ||
| _destroy = destroy; | ||
|
|
||
| final Future<T> Function() _create; | ||
| final Future<void> Function(T resource) _destroy; | ||
| final int maxConcurrentOperations; | ||
| final int maxIdleResources; | ||
|
|
||
| final _resources = <_PooledResource<T>>[]; | ||
| var _terminated = false; | ||
| Completer<void>? _drained; | ||
|
|
||
| /// The number of resources currently in the pool. For testing. | ||
| int get size => _resources.length; | ||
|
|
||
| /// The number of in-flight operations across every resource. For testing. | ||
| int get opCount => | ||
|
demolaf marked this conversation as resolved.
Outdated
|
||
| _resources.fold(0, (total, resource) => total + resource.inFlight); | ||
|
|
||
| /// Runs [operation] on an available (or newly created) resource. | ||
| Future<R> run<R>(Future<R> Function(T resource) operation) async { | ||
| if (_terminated) { | ||
| throw StateError('This pool has already been terminated.'); | ||
| } | ||
|
|
||
| final pooled = _acquire(); | ||
| pooled.inFlight++; | ||
| try { | ||
| return await operation(await pooled.future); | ||
| } catch (_) { | ||
| pooled.failed = true; | ||
| rethrow; | ||
| } finally { | ||
| pooled.inFlight--; | ||
| if (_terminated) { | ||
| _maybeCompleteDrain(); | ||
| } else { | ||
| await _collectIfIdle(pooled); | ||
| } | ||
| } | ||
| } | ||
|
|
||
| // Synchronous (no `await`), so concurrent calls can't race each other | ||
| // into both creating a resource before either sees the other's. | ||
| _PooledResource<T> _acquire() { | ||
| _PooledResource<T>? selected; | ||
| for (final resource in _resources) { | ||
| if (resource.failed) continue; | ||
| if (resource.inFlight < maxConcurrentOperations && | ||
| (selected == null || resource.inFlight > selected.inFlight)) { | ||
| selected = resource; | ||
| } | ||
| } | ||
| if (selected != null) return selected; | ||
|
|
||
| final resource = _PooledResource<T>(_create()); | ||
| _resources.add(resource); | ||
| return resource; | ||
| } | ||
|
|
||
| Future<void> _collectIfIdle(_PooledResource<T> resource) async { | ||
| if (resource.inFlight > 0) return; | ||
| if (!resource.failed && !_hasExcessIdleCapacity) return; | ||
|
|
||
| _resources.remove(resource); | ||
| try { | ||
| await _destroy(await resource.future); | ||
| } catch (_) { | ||
| // Best-effort: a failure here must not shadow the caller's own | ||
| // request error, since this runs inside run()'s finally block. | ||
| } | ||
| } | ||
|
|
||
| bool get _hasExcessIdleCapacity { | ||
| final idleCapacity = _resources.fold( | ||
|
demolaf marked this conversation as resolved.
Outdated
|
||
| 0, | ||
| (total, resource) => | ||
| total + (maxConcurrentOperations - resource.inFlight), | ||
| ); | ||
| return idleCapacity > maxIdleResources * maxConcurrentOperations; | ||
| } | ||
|
|
||
| void _maybeCompleteDrain() { | ||
| final drained = _drained; | ||
|
demolaf marked this conversation as resolved.
Outdated
|
||
| if (drained != null && !drained.isCompleted && opCount == 0) { | ||
| drained.complete(); | ||
| } | ||
| } | ||
|
|
||
| /// Waits for in-flight operations to finish, then destroys every | ||
| /// resource in the pool. No further operations can run afterward. | ||
| Future<void> terminate() async { | ||
| _terminated = true; | ||
|
|
||
| if (opCount > 0) { | ||
| _drained = Completer<void>(); | ||
| await _drained!.future; | ||
| } | ||
|
|
||
| for (final resource in _resources) { | ||
| try { | ||
| await _destroy(await resource.future); | ||
| } catch (_) { | ||
| // Best-effort: one resource failing to close shouldn't stop the | ||
| // rest from being destroyed. | ||
| } | ||
| } | ||
| _resources.clear(); | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.