MCPcopy Create free account
hub / github.com/Effect-TS/effect / readArrayBufferLimited

Function readArrayBufferLimited

packages/effect/src/http/HttpServerRequest.ts:1124–1172  ·  view source on GitHub ↗
(
  source: Request | Response,
  maxBytes: number,
  signal: AbortSignal
)

Source from the content-addressed store, hash-verified

1122}
1123
1124const readArrayBufferLimited = async (
1125 source: Request | Response,
1126 maxBytes: number,
1127 signal: AbortSignal
1128): Promise<ArrayBuffer> => {
1129 const header = source.headers.get("content-length")
1130 const contentLength = header !== null && /^\d+$/.test(header) ? Number(header) : undefined
1131 if (contentLength !== undefined && contentLength > maxBytes) {
1132 throw new BodyTooLargeError(maxBytes)
1133 }
1134 if (source.body === null) {
1135 return new ArrayBuffer(0)
1136 }
1137 // A constructed request can understate its content-length, so bytes are
1138 // counted on every runtime. Cancellation is not awaited, as the source's
1139 // cleanup may never settle.
1140 const limit = contentLength ?? maxBytes
1141 const reader = source.body.getReader()
1142 const cancel = () => {
1143 reader.cancel().catch(() => {})
1144 }
1145 signal.addEventListener("abort", cancel, { once: true })
1146 const chunks: Array<Uint8Array> = []
1147 let bytes = 0
1148 try {
1149 while (true) {
1150 const { done, value } = await reader.read()
1151 if (done) break
1152 bytes += value.byteLength
1153 if (bytes > limit) {
1154 cancel()
1155 throw bytes > maxBytes
1156 ? new BodyTooLargeError(maxBytes)
1157 : new Error(`Request body is longer than its content-length of ${contentLength}`)
1158 }
1159 chunks.push(value)
1160 }
1161 } finally {
1162 signal.removeEventListener("abort", cancel)
1163 reader.releaseLock()
1164 }
1165 const buffer = new Uint8Array(bytes)
1166 let offset = 0
1167 for (const chunk of chunks) {
1168 buffer.set(chunk, offset)
1169 offset += chunk.byteLength
1170 }
1171 return buffer.buffer
1172}
1173
1174/**
1175 * Attempts to construct an absolute `URL` for a server request safely.

Callers 2

arrayBufferMethod · 0.85
bytesFromWebFunction · 0.85

Calls 8

cancelFunction · 0.70
getMethod · 0.65
addEventListenerMethod · 0.65
readMethod · 0.65
pushMethod · 0.65
removeEventListenerMethod · 0.65
setMethod · 0.65
NumberFunction · 0.50

Tested by

no test coverage detected