Skip to content

Commit ccb8a51

Browse files
Dillon Nysdnys1
authored andcommitted
fix(aws_common): Close HTTP client when stream is done
Only close a client we created when the streaming of the response is complete, otherwise we may prematurely terminate the underlying connection. commit-id:e4caee26
1 parent f7a987c commit ccb8a51

File tree

2 files changed

+20
-6
lines changed

2 files changed

+20
-6
lines changed

packages/aws_common/lib/src/http/aws_http_request.dart

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import 'package:async/async.dart';
2020
import 'package:aws_common/aws_common.dart';
2121
import 'package:http/http.dart' as http;
2222
import 'package:meta/meta.dart';
23+
import 'package:stream_transform/stream_transform.dart';
2324

2425
/// {@template aws_common.aws_http_request}
2526
/// A parameterized HTTP request.
@@ -109,18 +110,30 @@ abstract class AWSBaseHttpRequest implements Closeable {
109110
/// If [client] is not provided, a short-lived one is created for this request.
110111
Future<AWSStreamedHttpResponse> send([http.Client? client]) async {
111112
final useClient = client ?? http.Client();
113+
114+
// Closes the HTTP client, but only if we created it.
115+
void closeClient() {
116+
if (client == null) {
117+
useClient.close();
118+
}
119+
}
120+
112121
try {
113122
final resp = await useClient.send(httpRequest);
114123
return AWSStreamedHttpResponse(
115124
headers: resp.headers,
116125
statusCode: resp.statusCode,
117-
body: resp.stream,
126+
body: resp.stream.tap(
127+
null,
128+
// Wait until the body has been read before closing the client,
129+
// since chunked requests require that the client not be closed
130+
// until they're complete.
131+
onDone: closeClient,
132+
),
118133
);
119-
} finally {
120-
// Only close a client we created.
121-
if (client == null) {
122-
useClient.close();
123-
}
134+
} on Object {
135+
closeClient();
136+
rethrow;
124137
}
125138
}
126139

packages/aws_common/pubspec.yaml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ dependencies:
1313
collection: ^1.15.0
1414
http: ^0.13.4
1515
meta: ^1.7.0
16+
stream_transform: ^2.0.0
1617
uuid: 3.0.6
1718

1819
dev_dependencies:

0 commit comments

Comments
 (0)