Surface progress callback errors instead of a NetworkError
Before adoption: this commit came in with the history the project adopted, so no landing records it.
A throwing `onUploadProgress` callback errors the request body stream. The runtime reports that stream failure as a generic network error, so Ky wrapped it in a `NetworkError` and the callback error was replaced by a misleading message. `isNetworkError()` then returned true for a user error, which also made the failure retriable.
authored by Sindre Sorhus · committed by Sindre Sorhus · parent 83c711c · Browse files · 4 files·+192 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+192 added−7 removed
- tests:+134 added−1 removed
- other:+58 added−6 removed
Provenance
- Commit
a2dfbd7- Tree
ee8c185- Author
Sindre Sorhus <sindresorhus@gmail.com>- Committer
Sindre Sorhus <sindresorhus@gmail.com>- Parent
83c711c
4 files changed+192 added−7 removed
modified:source/core/Ky.ts+19 added-1 removed
13 unmodified lines14 SearchParamsOption,15 } from '../types/options.js';16 import {type ResponsePromise} from '../types/ResponsePromise.js';17 import type {StandardSchemaV1} from '../types/standard-schema.js';18-import {limitResponseSize, streamRequest, streamResponse} from '../utils/body.js';18 import {19+ getProgressCallbackError,20+ limitResponseSize,21+ streamRequest,22+ streamResponse,23+} from '../utils/body.js';24+import {25 cloneShallow,26 cloneDeep,27 mergeHeaders,28 mergeHooks,778 unmodified lines807 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason);808 }809 810 if (this.#getRemainingTotalTimeout() !== 0) {811+ // A throwing progress callback errors the response stream, which a browser may report as a raw `TypeError` that would otherwise be mistaken for a dropped connection. Surface the callback error instead.812+ const progressCallbackError = getProgressCallbackError(response.body ?? undefined);813+ if (progressCallbackError !== undefined) {814+ await this.#throwProcessedError(progressCallbackError);815+ }816+817 // A connection dropped while streaming the body surfaces as a raw runtime `TypeError`. Wrap it like fetch-phase network errors so it is recognizable and runs `beforeError` hooks.818 // This only happens on the awaited path, so a body that fails after the timeout already won does not run the hooks again.819 if (isRawNetworkError(error)) {820 await this.#throwProcessedError(new NetworkError(this.#getResponseRequest(response), {cause: error as Error}));459 unmodified lines1280 this.#abortController?.abort();1281 throw new TimeoutError(request);1282 }1283 1284+ // 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.1285+ const progressCallbackError = getProgressCallbackError(this.#originalRequest?.body ?? undefined);1286+ if (progressCallbackError !== undefined) {1287+ // eslint-disable-next-line @typescript-eslint/only-throw-error -- The callback can throw any value, and non-Error throws are propagated as-is elsewhere.1288+ throw progressCallbackError;1289+ }1290+1291 if (isRawNetworkError(error)) {1292 throw new NetworkError(request, {cause: error as Error});1293 }1294 89 unmodified linesmodified:source/utils/body.ts+39 added-5 removed
1-import type {Options} from '../types/options.js';1+import type {Options, Progress} from '../types/options.js';2 import {responseTypes, usualFormBoundarySize} from '../core/constants.js';3 import {ResponseSizeError} from '../errors/ResponseSizeError.js';4 5 const encoder = new TextEncoder();6 const responseSizeErrors = new WeakMap<ReadableStream, () => ResponseSizeError | undefined>();7+// Errors thrown by a progress callback, keyed by the stream the callback reports on.8+// A throwing progress callback is a user error, but the runtime reports the resulting stream failure as a network error, so Ky needs the original error to surface it as-is.9+const progressCallbackErrors = new WeakMap<ReadableStream, () => unknown>();10 // The `Response` constructor rejects a body for these statuses, but some browsers (for example, Chromium and WebKit) still expose an empty body stream on such responses, so they must not be wrapped.11 const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);12 13 // eslint-disable-next-line @typescript-eslint/no-restricted-types38 unmodified lines52 53 const withProgress = (stream: ReadableStream<Uint8Array>, totalBytes: number, onProgress: Options['onDownloadProgress'] | Options['onUploadProgress']): ReadableStream<Uint8Array> => {54 let previousChunk: Uint8Array | undefined;55 let transferredBytes = 0;56+ let progressCallbackError: unknown;57+ const report = (progress: Progress, chunk: Uint8Array) => {58+ try {59+ onProgress?.(progress, chunk);60+ } catch (error) {61+ // Remember the error so Ky can surface it instead of the network error the runtime reports for the failed stream.62+ progressCallbackError = error;63+ throw error;64+ }65+ };66 67+ // The transformer only runs after construction, so its error accessor can be registered immediately afterwards.54- return stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({68+ const progressStream: ReadableStream<Uint8Array> = stream.pipeThrough(new TransformStream<Uint8Array, Uint8Array>({69 transform(currentChunk, controller) {70 controller.enqueue(currentChunk);71 72 if (previousChunk) {6 unmodified lines79 // If we were to use 0.99 here, percent could potentially go backwards.80 percent = 1 - Number.EPSILON;81 }82 69- onProgress?.({percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes}, previousChunk);83+ report({percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes}, previousChunk);84 }85 86 previousChunk = currentChunk;87 },88 flush() {89 const finalChunk = previousChunk ?? new Uint8Array();90 transferredBytes += finalChunk.byteLength;77- onProgress?.({percent: 1, totalBytes: transferredBytes, transferredBytes}, finalChunk);91+ report({percent: 1, totalBytes: transferredBytes, transferredBytes}, finalChunk);92 },93 }));94+ progressCallbackErrors.set(progressStream, () => progressCallbackError);95+96+ return progressStream;97 };98 99+/**100+The error thrown by a progress callback while reporting on the given stream, if the callback threw.101+*/102+export const getProgressCallbackError = (stream: ReadableStream | undefined): unknown =>103+ stream ? progressCallbackErrors.get(stream)?.() : undefined;104+105 const copyResponseMetadata = (response: Response, originalResponse: Response, getError = originalResponse.body ? responseSizeErrors.get(originalResponse.body) : undefined): Response => {106 const nativeClone = response.clone.bind(response);107+ const getProgressError = response.body108+ ? progressCallbackErrors.get(response.body) ?? (originalResponse.body ? progressCallbackErrors.get(originalResponse.body) : undefined)109+ : undefined;110+ if (response.body && getProgressError) {111+ progressCallbackErrors.set(response.body, getProgressError);112+ }113+114 if (response.body && getError) {115 responseSizeErrors.set(response.body, getError);116 117 // Chromium replaces stream errors with a generic TypeError in native body methods.27 unmodified lines145 // Keep the shim replaceable like `Response.prototype.clone` for instrumentation and mocks.146 clone: {147 value() {148 const clone = nativeClone();119- // Cloning replaces the original body too, so retain the error accessor on both branches.149+ // Cloning replaces the original body too, so retain the error accessors on both branches.150 if (response.body && getError) {151 responseSizeErrors.set(response.body, getError);152 }153 154+ if (response.body && getProgressError) {155+ progressCallbackErrors.set(response.body, getProgressError);156+ }157+158 return copyResponseMetadata(clone, response);159 },160 writable: true,161 configurable: true,59 unmodified linesmodified:test/browser.ts+35 added
49 unmodified lines50 test.afterEach(async () => {51 await server.close();52 });53 54+browserTest('cloning a response preserves download progress callback errors', [chromium], async (t, page) => {55+ server.get('/', (_request, response) => {56+ response.end('body');57+ });58+59+ await page.goto(server.url);60+ await addKyScriptToPage(page);61+62+ const result = await page.evaluate(async (url: string) => {63+ const callbackError = new Error('download progress failed');64+ const pending = globalThis.ky(url, {65+ retry: 0,66+ onDownloadProgress() {67+ throw callbackError;68+ },69+ });70+ const response = await pending;71+ const clone = response.clone();72+ void clone.body?.cancel().catch(() => undefined);73+74+ try {75+ await pending.text();76+ return {sameError: false, errorName: 'none', message: 'none'};77+ } catch (error) {78+ return {79+ sameError: error === callbackError,80+ errorName: (error as Error).name,81+ message: (error as Error).message,82+ };83+ }84+ }, server.url);85+86+ t.deepEqual(result, {sameError: true, errorName: 'Error', message: 'download progress failed'});87+});88+89 defaultBrowsersTest('maxResponseSize limits response bytes', async (t, page) => {90 server.get('/', (_request, response) => {91 response.end('🦄');92 });747 unmodified linesmodified:test/stream.ts+99 added-1 removed
1 import test from 'ava';2-import ky, {type Progress} from '../source/index.js';2+import ky, {isNetworkError, type Progress} from '../source/index.js';3 import {createLargeBlob} from './helpers/create-large-file.js';4 import {createHttpTestServer} from './helpers/create-http-test-server.js';5 import {parseRawBody, parseJsonBody} from './helpers/parse-body.js';6 1172 unmodified lines1179 transferredBytes: 2,1180 totalBytes: 2,1181 });1182 });1183+1184+// A throwing progress callback is a user-space error, so it must surface as that error rather than as a1185+// network failure. Upload progress runs inside the request body stream, where the runtime reports any stream1186+// error as a `TypeError: fetch failed` that Ky would otherwise classify as a `NetworkError`.1187+test('a throwing upload progress callback propagates its own error', async t => {1188+ const server = await createHttpTestServer(t, {bodyParser: false});1189+ let requestCount = 0;1190+ server.post('/', async (request, response) => {1191+ requestCount++;1192+ await parseRawBody(request);1193+ response.end('ok');1194+ });1195+1196+ const callbackError = new Error('upload progress failed');1197+ const error = await t.throwsAsync(ky.post(server.url, {1198+ body: 'x'.repeat(1024),1199+ retry: 0,1200+ onUploadProgress() {1201+ throw callbackError;1202+ },1203+ }).text());1204+1205+ t.is(error, callbackError);1206+ t.is(error.name, 'Error');1207+ t.is(error.message, 'upload progress failed');1208+ t.false(isNetworkError(error));1209+ t.is(requestCount, 0);1210+});1211+1212+test('a throwing upload progress callback is not retried as a network error', async t => {1213+ const server = await createHttpTestServer(t, {bodyParser: false});1214+ let beforeRetryCalls = 0;1215+ server.post('/', async (request, response) => {1216+ await parseRawBody(request);1217+ response.end('ok');1218+ });1219+1220+ // A `NetworkError` would be retried for this method, which would re-send the body of a failed callback.1221+ const error = await t.throwsAsync(ky.post(server.url, {1222+ body: 'x'.repeat(1024),1223+ retry: {limit: 2, delay: () => 0, methods: ['post']},1224+ hooks: {1225+ beforeRetry: [() => {1226+ beforeRetryCalls++;1227+ }],1228+ },1229+ onUploadProgress() {1230+ throw new Error('upload progress failed');1231+ },1232+ }).text());1233+1234+ t.is(error.message, 'upload progress failed');1235+ t.is(beforeRetryCalls, 0);1236+});1237+1238+test('a throwing upload progress callback is visible to beforeError hooks', async t => {1239+ const server = await createHttpTestServer(t, {bodyParser: false});1240+ server.post('/', async (request, response) => {1241+ await parseRawBody(request);1242+ response.end('ok');1243+ });1244+1245+ const seen: string[] = [];1246+ const error = await t.throwsAsync(ky.post(server.url, {1247+ body: 'x'.repeat(1024),1248+ retry: 0,1249+ hooks: {1250+ beforeError: [({error}) => {1251+ seen.push(`${error.name}: ${error.message}`);1252+ return error;1253+ }],1254+ },1255+ onUploadProgress() {1256+ throw new Error('upload progress failed');1257+ },1258+ }).text());1259+1260+ t.is(error.message, 'upload progress failed');1261+ t.deepEqual(seen, ['Error: upload progress failed']);1262+});1263+1264+test('a throwing download progress callback propagates its own error', async t => {1265+ const server = await createHttpTestServer(t);1266+ server.get('/', (_request, response) => {1267+ response.end('body');1268+ });1269+1270+ const callbackError = new Error('download progress failed');1271+ const error = await t.throwsAsync(ky(server.url, {1272+ retry: 0,1273+ onDownloadProgress() {1274+ throw callbackError;1275+ },1276+ }).text());1277+1278+ t.is(error, callbackError);1279+ t.false(isNetworkError(error));1280+});