|
1 | 1 | // Reads HTTP request and response bodies with timeout and byte limits. |
2 | 2 | import type { IncomingMessage, ServerResponse } from "node:http"; |
3 | 3 | import { clearTimeout as clearNodeTimeout, setTimeout as setNodeTimeout } from "node:timers"; |
| 4 | +import { toErrorObject } from "@openclaw/normalization-core/error-coercion"; |
4 | 5 | import { resolveTimerTimeoutMs } from "@openclaw/normalization-core/number-coercion"; |
5 | 6 | import { formatErrorMessage } from "./errors.js"; |
6 | 7 | import { parseStrictNonNegativeInteger } from "./parse-finite-number.js"; |
@@ -126,7 +127,8 @@ function advanceRequestBodyChunk( |
126 | 127 | }; |
127 | 128 | } |
128 | 129 |
|
129 | | -async function readResponseChunkWithIdleTimeout( |
| 130 | +/** Reads one chunk, rejecting and cancelling the reader after an idle timeout. */ |
| 131 | +export async function readChunkWithIdleTimeout( |
130 | 132 | reader: ReadableStreamDefaultReader<Uint8Array>, |
131 | 133 | chunkTimeoutMs: number, |
132 | 134 | onIdleTimeout?: (params: { chunkTimeoutMs: number }) => Error, |
@@ -165,7 +167,7 @@ async function readResponseChunkWithIdleTimeout( |
165 | 167 | (error: unknown) => { |
166 | 168 | clear(); |
167 | 169 | if (!timedOut) { |
168 | | - reject(toHttpBodyError(error, "Non-Error rejection")); |
| 170 | + reject(toErrorObject(error, "Non-Error rejection")); |
169 | 171 | } |
170 | 172 | }, |
171 | 173 | ); |
@@ -207,7 +209,7 @@ async function readResponsePrefix( |
207 | 209 | try { |
208 | 210 | while (true) { |
209 | 211 | const { done, value } = options?.chunkTimeoutMs |
210 | | - ? await readResponseChunkWithIdleTimeout( |
| 212 | + ? await readChunkWithIdleTimeout( |
211 | 213 | reader, |
212 | 214 | options.chunkTimeoutMs, |
213 | 215 | options.onIdleTimeout, |
@@ -313,20 +315,6 @@ export async function readResponseTextSnippet( |
313 | 315 | return prefix.truncated ? `${collapsed}…` : collapsed; |
314 | 316 | } |
315 | 317 |
|
316 | | -function toHttpBodyError(value: unknown, fallbackMessage: string): Error { |
317 | | - if (value instanceof Error) { |
318 | | - return value; |
319 | | - } |
320 | | - if (typeof value === "string") { |
321 | | - return new Error(value); |
322 | | - } |
323 | | - const error = new Error(fallbackMessage, { cause: value }); |
324 | | - if ((typeof value === "object" && value !== null) || typeof value === "function") { |
325 | | - Object.assign(error, value); |
326 | | - } |
327 | | - return error; |
328 | | -} |
329 | | - |
330 | 318 | export async function readRequestBodyWithLimit( |
331 | 319 | req: IncomingMessage, |
332 | 320 | options: ReadRequestBodyOptions, |
|
0 commit comments