Skip to content

Commit

Permalink
fix(utils): Normalize when serializing envelope (#5851)
Browse files Browse the repository at this point in the history
  • Loading branch information
lforst committed Sep 29, 2022
1 parent 76f87f0 commit 18cc680
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 2 deletions.
20 changes: 18 additions & 2 deletions packages/utils/src/envelope.ts
Expand Up @@ -8,6 +8,7 @@ import {
TextEncoderInternal,
} from '@sentry/types';

import { normalize } from './normalize';
import { dropUndefinedKeys } from './object';

/**
Expand Down Expand Up @@ -67,9 +68,24 @@ export function serializeEnvelope(envelope: Envelope, textEncoder?: TextEncoderI
}

for (const item of items) {
const [itemHeaders, payload] = item as typeof items[number];
const [itemHeaders, payload] = item;

append(`\n${JSON.stringify(itemHeaders)}\n`);
append(typeof payload === 'string' || payload instanceof Uint8Array ? payload : JSON.stringify(payload));

if (typeof payload === 'string' || payload instanceof Uint8Array) {
append(payload);
} else {
let stringifiedPayload: string;
try {
stringifiedPayload = JSON.stringify(payload);
} catch (e) {
// In case, despite all our efforts to keep `payload` circular-dependency-free, `JSON.strinify()` still
// fails, we try again after normalizing it again with infinite normalization depth. This of course has a
// performance impact but in this case a performance hit is better than throwing.
stringifiedPayload = JSON.stringify(normalize(payload));
}
append(stringifiedPayload);
}
}

return typeof parts === 'string' ? parts : concatBuffers(parts);
Expand Down
15 changes: 15 additions & 0 deletions packages/utils/test/envelope.test.ts
Expand Up @@ -58,6 +58,21 @@ describe('envelope', () => {
Uint8Array.from([7, 8, 9, 10, 11, 12]),
]);
});

it("doesn't throw when being passed a an envelope that contains a circular item payload", () => {
const chicken: { egg?: unknown } = {};
const egg = { chicken };
chicken.egg = chicken;

const env = createEnvelope<EventEnvelope>({ event_id: 'aa3ff046696b4bc6b609ce6d28fde9e2', sent_at: '123' }, [
[{ type: 'event' }, egg],
]);

const serializedEnvelope = serializeEnvelope(env, new TextEncoder());
const [, , serializedBody] = serializedEnvelope.toString().split('\n');

expect(serializedBody).toBe('{"chicken":{"egg":"[Circular ~]"}}');
});
});

describe('addItemToEnvelope()', () => {
Expand Down

0 comments on commit 18cc680

Please sign in to comment.