Skip to content

Commit 793812b

Browse files
author
Luca Forstner
committed
Bufferify
1 parent 07d85ce commit 793812b

1 file changed

Lines changed: 16 additions & 14 deletions

File tree

packages/node/src/integrations/http/SentryHttpInstrumentation.ts

Lines changed: 16 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -360,12 +360,9 @@ function getBreadcrumbData(request: http.ClientRequest): Partial<SanitizedReques
360360
* This way, we only read the body if the user also consumes the body, ensuring we do not change any behavior in unexpected ways.
361361
*/
362362
function patchRequestToCaptureBody(req: IncomingMessage, isolationScope: Scope): void {
363+
let bodyByteLength = 0;
363364
const chunks: Buffer[] = [];
364365

365-
function getChunksSize(): number {
366-
return chunks.reduce((acc, chunk) => acc + chunk.byteLength, 0);
367-
}
368-
369366
/**
370367
* We need to keep track of the original callbacks, in order to be able to remove listeners again.
371368
* Since `off` depends on having the exact same function reference passed in, we need to be able to map
@@ -386,16 +383,21 @@ function patchRequestToCaptureBody(req: IncomingMessage, isolationScope: Scope):
386383
if (event === 'data') {
387384
const callback = new Proxy(listener, {
388385
apply: (target, thisArg, args: Parameters<typeof listener>) => {
389-
// If we have already read more than the max body length, we stop adding chunks
390-
// To avoid growing the memory indefinitely if a response is e.g. streamed
391-
if (getChunksSize() < MAX_BODY_BYTE_LENGTH) {
392-
const chunk = args[0] as Buffer;
393-
chunks.push(chunk);
394-
} else if (DEBUG_BUILD) {
395-
logger.log(
396-
INSTRUMENTATION_NAME,
397-
`Dropping request body chunk because maximum body length of ${MAX_BODY_BYTE_LENGTH}b is exceeded.`,
398-
);
386+
try {
387+
const chunk = args[0] as Buffer | string;
388+
const bufferifiedChunk = Buffer.from(chunk);
389+
390+
if (bodyByteLength < MAX_BODY_BYTE_LENGTH) {
391+
chunks.push(bufferifiedChunk);
392+
bodyByteLength += bufferifiedChunk.length;
393+
} else if (DEBUG_BUILD) {
394+
logger.log(
395+
INSTRUMENTATION_NAME,
396+
`Dropping request body chunk because maximum body length of ${MAX_BODY_BYTE_LENGTH}b is exceeded.`,
397+
);
398+
}
399+
} catch {
400+
// noop
399401
}
400402

401403
return Reflect.apply(target, thisArg, args);

0 commit comments

Comments
 (0)