Skip to content
Myr

Progress from a declared content-length, and a throwing callback is never retried

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Sindre Sorhus · committed by Sindre Sorhus · parent bd0e26f · Browse files · 5 files+154 added−5 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

5 files+154 added−5 removed

  • tests:+121 added−0 removed
  • other:+33 added−5 removed

5 files+154 added−5 removed

modified:source/core/Ky.ts+11 added
470 unmodified lines
471 #originalRequest?: Request;472 #requestBodyCanBeCancelled = false;473 readonly #userProvidedAbortSignal: AbortSignal | undefined;474 readonly #beforeRetryHookErrors = new WeakSet<Error>();475 // Errors thrown by a user callback that runs while the request is in flight. Retrying would re-send the body and476 // run the callback again, so they are never retriable, whatever `shouldRetry` says.477 readonly #inFlightCallbackErrors = new WeakSet<Error>();478 #cachedNormalizedOptions: NormalizedOptions | undefined;479 readonly #startTime: number | undefined;480 #returnedResponseFromBeforeRetryHook = false;481 readonly #responseRequests = new WeakMap<Response, Request>();
193 unmodified lines
675 return Math.min(retry.backoffLimit, jitteredDelay);676 }677678 async #calculateRetryDelay(error: unknown) {679 if (isError(error) && this.#inFlightCallbackErrors.has(error)) {680 throw error;681 }682683 const retry = normalizeRetryOptions(this.#options.retry);684 if (this.#retryCount >= Math.min(retry.limit, this.#retryLimit)) {685 throw error;686 }
734 unmodified lines
14211422 // The upload progress wrapper errors the request body stream when its callback throws, which the runtime reports as a network failure. Surface the callback error instead.1423 const progressCallbackError = getProgressCallbackError(this.#originalRequest?.body ?? undefined);1424 if (progressCallbackError !== undefined) {1425 if (isError(progressCallbackError)) {1426 this.#inFlightCallbackErrors.add(progressCallbackError);1427 }14281429 // eslint-disable-next-line @typescript-eslint/only-throw-error -- The callback can throw any value, and non-Error throws are propagated as-is elsewhere.1430 throw progressCallbackError;1431 }1432
95 unmodified lines
modified:source/types/options.ts+3 added-1 removed
289 unmodified lines
290 @param chunk - Data that was received. When an empty response body stream completes, the callback receives an empty chunk.291292 `content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, which means the percentage cannot be calculated while downloading.293294 Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.294 Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them. A `HEAD` response has no body either, but it is not a null body status, so a single completion event is reported from `content-length`.295296 When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.297298 @example
18 unmodified lines
317318 @param progress - Object containing upload progress information.319 @param chunk - Data that was sent. When an empty request body stream completes, the callback receives an empty chunk.320321 A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`.322323 @example324 ```325 import ky from 'ky';326
222 unmodified lines
modified:source/utils/body.ts+16 added-3 removed
194 unmodified lines
195 return copyResponseMetadata(new Response(body, response), response, () => sizeError ?? getOriginalSizeError?.());196};197198export const streamResponse = (response: Response, onDownloadProgress: Options['onDownloadProgress']) => {199 if (nullBodyStatuses.has(response.status)) {200 return response;201 }202203 // A HEAD response has no body even on an ordinary status, so there is nothing to stream, but the download is204 // still complete. Report that from the declared length alone so a progress bar finishes instead of hanging.205 if (!response.body) {206 const totalBytes = Math.max(0, Number(response.headers.get('content-length')) || 0);207 onDownloadProgress?.({percent: 1, totalBytes, transferredBytes: totalBytes}, new Uint8Array());208 return response;209 }210211 // See `limitResponseSize`: there is nothing left to stream and nothing to report once a hook consumed the body.200 if (!response.body || response.bodyUsed || response.body.locked || nullBodyStatuses.has(response.status)) {212 if (response.bodyUsed || response.body.locked) {213 return response;214 }215216 // `content-length` counts encoded bytes on the wire, while the progress stream counts the bytes after decompression. Using it for a content-coded response would report a total below what actually arrives, so every event would sit at ~100%. The total is then unknown, which `Progress` already models with `0`. `identity` is a registered no-op coding (RFC 9110 §8.4.2), so it leaves the length valid.
11 unmodified lines
228 if (!request.body || request.keepalive || request.mode === 'no-cors' || !(request instanceof globalThis.Request)) {229 return request;230 }231220 // Use original body for size calculation since request.body is already a stream221 const totalBytes = getBodySize(originalBody ?? request.body);232 // Use original body for size calculation since request.body is already a stream. A `ReadableStream` measures 0, so fall back to a `content-length` the caller declared. Browsers drop that header from a request, so this only helps outside browsers.233 const totalBytes = getBodySize(originalBody ?? request.body)234 || Math.max(0, Number(request.headers.get('content-length')) || 0);235236 return new Request(request, {237 // @ts-expect-error - Types are outdated.238 duplex: 'half',
7 unmodified lines
modified:test/stream.ts+121 added
1405 unmodified lines
1406 // 1024 of 8192 bytes on the first event, so the percentage has to climb from there.1407 t.is(progressEvents[0]?.percent, 0.125);1408 });1409}14101411// A `ReadableStream` body measures 0, so the upload estimate stayed 0 and the percentage never moved, even when the request itself declared a `content-length`. The download path already falls back to that header.1412test('upload progress uses a declared content-length when the body size is unknown', async t => {1413 const progressEvents: Progress[] = [];1414 let body = '';14151416 await ky.post('https://example.com', {1417 body: new ReadableStream<Uint8Array>({1418 start(controller) {1419 controller.enqueue(new TextEncoder().encode('a'.repeat(1024)));1420 controller.enqueue(new TextEncoder().encode('a'.repeat(1024)));1421 controller.close();1422 },1423 }),1424 headers: {'content-length': '2048'},1425 retry: 0,1426 async fetch(request) {1427 body = await request.clone().text();1428 return new Response('ok');1429 },1430 onUploadProgress(progress) {1431 progressEvents.push(progress);1432 },1433 }).text();14341435 t.is(body.length, 2048);1436 t.deepEqual(progressEvents.at(-1), {percent: 1, totalBytes: 2048, transferredBytes: 2048});1437 t.is(progressEvents[0]?.totalBytes, 2048);1438 t.true(progressEvents[0]!.percent > 0, 'the first event should not sit at 0%');1439});14401441test('upload progress still prefers the body it can measure', async t => {1442 const progressEvents: Progress[] = [];14431444 await ky.post('https://example.com', {1445 body: 'x'.repeat(10),1446 headers: {'content-length': '2048'},1447 retry: 0,1448 async fetch(request) {1449 await request.text();1450 return new Response('ok');1451 },1452 onUploadProgress(progress) {1453 progressEvents.push(progress);1454 },1455 }).text();14561457 t.is(progressEvents.at(-1)?.totalBytes, 10);1458});14591460// A HEAD response has no body even on a normal status, so the `!response.body` guard returned early and the1461// callback never fired. The readme only carves out null body *statuses*.1462for (const [label, headers] of [1463 ['a declared length', {'content-length': '1000'}],1464 ['no declared length', {}],1465] as Array<[string, Record<string, string>]>) {1466 test(`download progress completes for a HEAD response with ${label}`, async t => {1467 const progressEvents: Progress[] = [];14681469 const response = await ky('https://example.com', {1470 method: 'HEAD',1471 async fetch() {1472 return new Response(null, {status: 200, headers});1473 },1474 onDownloadProgress(progress, chunk) {1475 progressEvents.push(progress);1476 t.is(chunk.byteLength, 0);1477 },1478 });14791480 t.is(response.status, 200);1481 t.is(progressEvents.length, 1);1482 const expectedTotal = Number(headers['content-length'] ?? 0);1483 t.deepEqual(progressEvents[0], {percent: 1, totalBytes: expectedTotal, transferredBytes: expectedTotal});1484 });1485}14861487test('download progress stays silent for a null body status', async t => {1488 let calls = 0;1489 const response = await ky('https://example.com', {1490 async fetch() {1491 return new Response(null, {status: 204});1492 },1493 onDownloadProgress() {1494 calls++;1495 },1496 });14971498 t.is(response.status, 204);1499 t.is(calls, 0);1500});15011502// A throwing progress callback is a user-space error, but `#fetch()` rethrows it as a plain `Error`, so a `shouldRetry` that returns `true` for everything re-sent the body and ran the callback again.1503test('a throwing upload progress callback is not retried even when `shouldRetry` returns true', async t => {1504 const {server, getRequestCount} = await createUploadProgressTestServer(t);1505 let callbackCalls = 0;1506 let beforeRetryCalls = 0;15071508 await t.throwsAsync(ky.post(server.url, {1509 body: 'x'.repeat(1024),1510 retry: {1511 limit: 3,1512 methods: ['post'],1513 delay: () => 0,1514 shouldRetry: () => true,1515 },1516 hooks: {1517 beforeRetry: [() => {1518 beforeRetryCalls++;1519 }],1520 },1521 onUploadProgress() {1522 callbackCalls++;1523 throw new Error('upload progress failed');1524 },1525 }).text(), {message: 'upload progress failed'});15261527 t.is(getRequestCount(), 0);1528 t.is(callbackCalls, 1);1529 t.is(beforeRetryCalls, 0);1530});
modified:readme.md+3 added-1 removed
762 unmodified lines
763- `chunk` is an instance of `Uint8Array` containing the data that was received. When an empty response body stream completes, the callback receives an empty chunk.764765`content-length` is only used as the total for a response that is not content-coded, since it counts encoded bytes while the progress stream counts the bytes after decompression. A compressed response therefore reports `totalBytes: 0` until it completes, so the percentage cannot be calculated while downloading.766767Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them.767Responses with a [null body status](https://fetch.spec.whatwg.org/#null-body-status) are not streamed, so no progress events are emitted for them. A `HEAD` response has no body either, but it is not a null body status, so a single completion event is reported from `content-length`.768769When the callback throws, the error is reported by Ky's body method shortcuts. A response read directly with `response.text()` or `response.json()` may instead report the runtime's own stream error, such as Chromium's generic `TypeError`.770771```js
23 unmodified lines
795 - `transferredBytes` is the number of bytes transferred so far.796 - `totalBytes` is the total number of bytes to be transferred. This is an estimate and may be 0 for an empty transfer or when the total size cannot be determined.797- `chunk` is an instance of `Uint8Array` containing the data that was sent. When an empty request body stream completes, the callback receives an empty chunk.798799A `ReadableStream` body cannot be measured, so `totalBytes` falls back to a `content-length` header you set. Browsers do not allow that header on a request, so there the total stays `0`.800801```js802import ky from 'ky';803804const response = await ky.post('https://example.com/upload', {
1105 unmodified lines