Skip to content

Commit a8a2da5

Browse files
authored
Ensure response body is read before timeout to avoid abort errors (#6518)
1 parent 55b82da commit a8a2da5

File tree

3 files changed

+27
-3
lines changed

3 files changed

+27
-3
lines changed

.changeset/olive-walls-build.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'hive': patch
3+
---
4+
5+
Ensure response body is read before timeout to avoid abort errors in S3 client (CDN)

packages/services/cdn-worker/src/aws.ts

Lines changed: 20 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,7 +196,26 @@ export class AwsClient {
196196
result: { type: 'success', response },
197197
});
198198

199-
return response;
199+
if (!response.body) {
200+
return response;
201+
}
202+
203+
// Read the body first, to make sure it won't be aborted by the signal (timeout)
204+
// If we get a timeout error during the body reading, we can't retry,
205+
// as it's out of the control of that function.
206+
// One example of it is when the res.text() is called with a delay due to application logic,
207+
// and the timeout is reached at that point. The read will be aborted.
208+
//
209+
// For this reason, I prefer to read the body first, make it part of the retry logic,
210+
// and only then return the response to the consumer,
211+
// even at the cost of higher memory footprint (like it matters...).
212+
const bodyText = await response.text();
213+
214+
return new Response(bodyText, {
215+
status: response.status,
216+
statusText: response.statusText,
217+
headers: response.headers,
218+
});
200219
}
201220

202221
console.log(

packages/services/cdn-worker/src/index.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ const handler: ExportedHandler<Env> = {
147147
if (i === retries) {
148148
const res = await fetched;
149149
if (res.ok) {
150-
return res.text();
150+
return await res.text();
151151
}
152152

153153
throw new Error(`Failed to fetch ${url}, status: ${res.status}`);
@@ -156,7 +156,7 @@ const handler: ExportedHandler<Env> = {
156156
try {
157157
const res = await fetched;
158158
if (res.ok) {
159-
return res.text();
159+
return await res.text();
160160
}
161161
} catch (error) {
162162
// Retry also when there's an exception

0 commit comments

Comments
 (0)