MCPcopy
hub / github.com/simstudioai/sim / readNodeStreamToBufferWithLimit

Function readNodeStreamToBufferWithLimit

apps/sim/lib/core/utils/stream-limits.ts:147–221  ·  view source on GitHub ↗
(
  stream: NodeJS.ReadableStream | null | undefined,
  options: ReadStreamWithLimitOptions
)

Source from the content-addressed store, hash-verified

145}
146
147export async function readNodeStreamToBufferWithLimit(
148 stream: NodeJS.ReadableStream | null | undefined,
149 options: ReadStreamWithLimitOptions
150): Promise<Buffer> {
151 if (!stream) return Buffer.alloc(0)
152
153 return new Promise((resolve, reject) => {
154 const chunks: Buffer[] = []
155 let totalBytes = 0
156 let settled = false
157
158 const finish = (callback: () => void) => {
159 if (settled) return
160 settled = true
161 cleanup()
162 callback()
163 }
164
165 const cleanup = () => {
166 stream.off('data', onData)
167 stream.off('end', onEnd)
168 stream.off('error', onError)
169 options.signal?.removeEventListener('abort', onAbort)
170 }
171
172 const onAbort = () => {
173 if ('destroy' in stream && typeof stream.destroy === 'function') {
174 stream.destroy(toError(options.signal?.reason ?? new Error('Aborted')))
175 }
176 finish(() => reject(toError(options.signal?.reason ?? new Error('Aborted'))))
177 }
178
179 const onData = (chunk: Buffer | Uint8Array | string) => {
180 const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)
181 totalBytes += buffer.byteLength
182
183 if (totalBytes > options.maxBytes) {
184 if ('destroy' in stream && typeof stream.destroy === 'function') {
185 stream.destroy()
186 }
187 finish(() =>
188 reject(
189 new PayloadSizeLimitError({
190 label: options.label,
191 maxBytes: options.maxBytes,
192 observedBytes: totalBytes,
193 })
194 )
195 )
196 return
197 }
198
199 void options.onChunk?.(buffer, totalBytes)
200 chunks.push(buffer)
201 }
202
203 const onEnd = () => {
204 finish(() => resolve(Buffer.concat(chunks, totalBytes)))

Callers 3

downloadFromBlobFunction · 0.90
downloadFromS3Function · 0.90

Calls 2

onMethod · 0.80
onAbortFunction · 0.70

Tested by

no test coverage detected