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

Function readStreamToBufferWithLimit

apps/sim/lib/core/utils/stream-limits.ts:93–145  ·  view source on GitHub ↗
(
  stream: ReadableStream<Uint8Array> | null | undefined,
  options: ReadStreamWithLimitOptions
)

Source from the content-addressed store, hash-verified

91}
92
93export async function readStreamToBufferWithLimit(
94 stream: ReadableStream<Uint8Array> | null | undefined,
95 options: ReadStreamWithLimitOptions
96): Promise<Buffer> {
97 if (!stream) return Buffer.alloc(0)
98
99 const reader = stream.getReader()
100 const chunks: Buffer[] = []
101 let totalBytes = 0
102 const abortFromSignal = () => {
103 void reader.cancel(options.signal?.reason).catch(() => {})
104 }
105
106 try {
107 if (options.signal?.aborted) {
108 await reader.cancel(options.signal.reason).catch(() => {})
109 throw toError(options.signal.reason ?? new Error('Aborted'))
110 }
111 options.signal?.addEventListener('abort', abortFromSignal, { once: true })
112
113 while (true) {
114 if (options.signal?.aborted) {
115 await reader.cancel(options.signal.reason).catch(() => {})
116 throw toError(options.signal.reason ?? new Error('Aborted'))
117 }
118
119 const { done, value } = await reader.read()
120 if (options.signal?.aborted) {
121 throw toError(options.signal.reason ?? new Error('Aborted'))
122 }
123 if (done) break
124 if (!value) continue
125
126 totalBytes += value.byteLength
127 if (totalBytes > options.maxBytes) {
128 await reader.cancel().catch(() => {})
129 throw new PayloadSizeLimitError({
130 label: options.label,
131 maxBytes: options.maxBytes,
132 observedBytes: totalBytes,
133 })
134 }
135
136 await options.onChunk?.(value, totalBytes)
137 chunks.push(Buffer.from(value))
138 }
139 } finally {
140 options.signal?.removeEventListener('abort', abortFromSignal)
141 reader.releaseLock()
142 }
143
144 return Buffer.concat(chunks, totalBytes)
145}
146
147export async function readNodeStreamToBufferWithLimit(
148 stream: NodeJS.ReadableStream | null | undefined,

Callers 11

readMcpJsonBodyWithLimitFunction · 0.90
readJsonBodyWithLimitFunction · 0.90
parseOptionalJsonBodyFunction · 0.90
parseWebhookBodyFunction · 0.90
readExecuteRequestBodyFunction · 0.90
readJsonRpcBodyFunction · 0.90
readAgentMailBodyFunction · 0.90
readFormDataWithLimitFunction · 0.85
consumeOrCancelBodyFunction · 0.85

Calls 5

toErrorFunction · 0.90
cancelMethod · 0.80
concatMethod · 0.80
readMethod · 0.45
pushMethod · 0.45

Tested by

no test coverage detected