fix: add back global string limit gracefully returning a valid json string

This commit is contained in:
Spencer
2026-04-15 15:48:15 +00:00
parent dd4d7301ba
commit 8481d977bb
2 changed files with 25 additions and 0 deletions
+17
View File
@@ -124,6 +124,23 @@ describe('truncateForTelemetry', () => {
);
});
it('should enforce a global payload string limit without breaking JSON', () => {
const obj = {
a: 'x'.repeat(100),
b: 'y'.repeat(100),
};
// Capping global string length to 50
const result = truncateForTelemetry(obj, 100, 100, 4, 50) as string;
// It should replace the entire object with a valid JSON string indicating truncation
expect(result).toBe(
'"[TRUNCATED: Payload exceeded global limit of 50 characters. Original length: 215]"',
);
// Prove it remains perfectly parseable JSON
expect(() => JSON.parse(result)).not.toThrow();
});
it('should stringify objects unchanged if within maxLength', () => {
const obj = { a: 1 };
expect(truncateForTelemetry(obj, 100)).toBe(JSON.stringify(obj));
+8
View File
@@ -67,6 +67,7 @@ export function truncateForTelemetry(
maxStringLength = 10000,
maxArrayLength = 100,
maxDepth = 4,
maxGlobalStringLength = 50000,
): AttributeValue | undefined {
const truncateObj = (v: unknown, depth: number): unknown => {
if (typeof v === 'string') {
@@ -149,6 +150,13 @@ export function truncateForTelemetry(
const stringified = safeJsonStringify(truncated);
if (stringified.length > maxGlobalStringLength) {
const graphemes = Array.from(stringified);
if (graphemes.length > maxGlobalStringLength) {
return `"[TRUNCATED: Payload exceeded global limit of ${maxGlobalStringLength} characters. Original length: ${graphemes.length}]"`;
}
}
return stringified as AttributeValue;
}