Skip to content
Myr

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

4 files+192 added−7 removed

modified:source/core/Ky.ts+19 added-1 removed
13 unmodified lines
14 SearchParamsOption,15} from '../types/options.js';16import {type ResponsePromise} from '../types/ResponsePromise.js';17import type {StandardSchemaV1} from '../types/standard-schema.js';18import {limitResponseSize, streamRequest, streamResponse} from '../utils/body.js';18import {19 getProgressCallbackError,20 limitResponseSize,21 streamRequest,22 streamResponse,23} from '../utils/body.js';24import {25 cloneShallow,26 cloneDeep,27 mergeHeaders,28 mergeHooks,
778 unmodified lines
807 await this.#throwProcessedError(this.#userProvidedAbortSignal.reason);808 }809810 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 }816817 // 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 lines
1280 this.#abortController?.abort();1281 throw new TimeoutError(request);1282 }12831284 // 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 }12901291 if (isRawNetworkError(error)) {1292 throw new NetworkError(request, {cause: error as Error});1293 }1294
89 unmodified lines
modified:source/utils/body.ts+39 added-5 removed
1import type {Options} from '../types/options.js';1import type {Options, Progress} from '../types/options.js';2import {responseTypes, usualFormBoundarySize} from '../core/constants.js';3import {ResponseSizeError} from '../errors/ResponseSizeError.js';45const encoder = new TextEncoder();6const 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.9const 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.11const nullBodyStatuses = new Set([101, 103, 204, 205, 304]);1213// eslint-disable-next-line @typescript-eslint/no-restricted-types
38 unmodified lines
5253const 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 };6667 // 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);7172 if (previousChunk) {
6 unmodified lines
79 // If we were to use 0.99 here, percent could potentially go backwards.80 percent = 1 - Number.EPSILON;81 }8269 onProgress?.({percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes}, previousChunk);83 report({percent, totalBytes: Math.max(totalBytes, transferredBytes), transferredBytes}, previousChunk);84 }8586 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);9596 return progressStream;97};9899/**100The error thrown by a progress callback while reporting on the given stream, if the callback threw.101*/102export const getProgressCallbackError = (stream: ReadableStream | undefined): unknown =>103 stream ? progressCallbackErrors.get(stream)?.() : undefined;104105const 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 }113114 if (response.body && getError) {115 responseSizeErrors.set(response.body, getError);116117 // Chromium replaces stream errors with a generic TypeError in native body methods.
27 unmodified lines
145 // 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 }153154 if (response.body && getProgressError) {155 progressCallbackErrors.set(response.body, getProgressError);156 }157158 return copyResponseMetadata(clone, response);159 },160 writable: true,161 configurable: true,
59 unmodified lines
modified:test/browser.ts+35 added
49 unmodified lines
50test.afterEach(async () => {51 await server.close();52});5354browserTest('cloning a response preserves download progress callback errors', [chromium], async (t, page) => {55 server.get('/', (_request, response) => {56 response.end('body');57 });5859 await page.goto(server.url);60 await addKyScriptToPage(page);6162 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);7374 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);8586 t.deepEqual(result, {sameError: true, errorName: 'Error', message: 'download progress failed'});87});8889defaultBrowsersTest('maxResponseSize limits response bytes', async (t, page) => {90 server.get('/', (_request, response) => {91 response.end('🦄');92 });
747 unmodified lines
modified:test/stream.ts+99 added-1 removed
1import test from 'ava';2import ky, {type Progress} from '../source/index.js';2import ky, {isNetworkError, type Progress} from '../source/index.js';3import {createLargeBlob} from './helpers/create-large-file.js';4import {createHttpTestServer} from './helpers/create-http-test-server.js';5import {parseRawBody, parseJsonBody} from './helpers/parse-body.js';6
1172 unmodified lines
1179 transferredBytes: 2,1180 totalBytes: 2,1181 });1182});11831184// 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`.1187test('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 });11951196 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());12041205 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});12111212test('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 });12191220 // 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());12331234 t.is(error.message, 'upload progress failed');1235 t.is(beforeRetryCalls, 0);1236});12371238test('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 });12441245 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());12591260 t.is(error.message, 'upload progress failed');1261 t.deepEqual(seen, ['Error: upload progress failed']);1262});12631264test('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 });12691270 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());12771278 t.is(error, callbackError);1279 t.false(isNetworkError(error));1280});