Skip to content

Commit 12ec456

Browse files
committed
fix(mobile): cancel the session's download when a response body is cancelled before its first event
Signed-off-by: Tom Brow <[email protected]>
1 parent 6d64ad1 commit 12ec456

2 files changed

Lines changed: 36 additions & 7 deletions

File tree

‎mobile/lib/shared/http/app_http_client.dart‎

Lines changed: 22 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -93,16 +93,31 @@ class SharedSessionClient extends http.BaseClient {
9393
_inFlight.remove(abort);
9494
rethrow;
9595
}
96-
Stream<List<int>> body() async* {
97-
try {
98-
yield* response.stream;
99-
} finally {
100-
_inFlight.remove(abort);
96+
// A controller, not an async* wrapper: async* never listens to the
97+
// session's stream when cancelled before its first event, so the
98+
// session would keep downloading a body nobody reads.
99+
late final StreamSubscription<List<int>> inner;
100+
final body = StreamController<List<int>>(sync: true);
101+
body
102+
..onListen = () {
103+
inner = response.stream.listen(
104+
body.add,
105+
onError: body.addError,
106+
onDone: () {
107+
_inFlight.remove(abort);
108+
body.close();
109+
},
110+
);
101111
}
102-
}
112+
..onPause = (() => inner.pause())
113+
..onResume = (() => inner.resume())
114+
..onCancel = () {
115+
_inFlight.remove(abort);
116+
return inner.cancel();
117+
};
103118

104119
return http.StreamedResponse(
105-
http.ByteStream(body()),
120+
http.ByteStream(body.stream),
106121
response.statusCode,
107122
contentLength: response.contentLength,
108123
request: response.request,

‎mobile/test/shared/http/app_http_client_test.dart‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,9 +61,16 @@ void main() {
6161

6262
test('finished requests hold no abort trigger until close', () async {
6363
var fired = 0;
64+
var sessionBodyCancelled = false;
6465
final client = SharedSessionClient(
6566
MockClient.streaming((request, _) async {
6667
(request as http.Abortable).abortTrigger?.then((_) => fired++);
68+
if (request.url.path == '/video') {
69+
final body = StreamController<List<int>>(
70+
onCancel: () => sessionBodyCancelled = true,
71+
);
72+
return http.StreamedResponse(body.stream, 500);
73+
}
6774
final status = request.url.path == '/missing' ? 404 : 200;
6875
return http.StreamedResponse(Stream.value([1]), status);
6976
}),
@@ -79,6 +86,13 @@ void main() {
7986
);
8087
expect(missing.statusCode, 404);
8188
await pumpEventQueue();
89+
// A body cancelled before its first event still cancels the session's
90+
// download.
91+
final video = await client.send(
92+
http.Request('GET', Uri.parse('https://relay.example/video')),
93+
);
94+
await video.stream.listen(null).cancel();
95+
expect(sessionBodyCancelled, isTrue);
8296
final ownAborts = fired;
8397

8498
client.close();

0 commit comments

Comments
 (0)