Skip to content
This repository was archived by the owner on Jun 21, 2023. It is now read-only.

Commit 3c6e48f

Browse files
committed
⚡️ Update transform stream to parse only on pretty
TLDR; Remove `JSON.parse`/`JSON.stringify` in main transform stream, when the `pretty` option is disabled. **Context** Using cosmas we had several issues with OOM during logging. The issue can be reproduced with the following snippet: ```js const message = { text: '.'.repeat(4e6) } mb = (s) => `${((encodeURI(s).split(/%..|./).length - 1)/2**20).toFixed(2)} MB` // --> 3.81 MB (node index.js, crashes with the 20 MB limit as cosmas) // console.log(mb(JSON.stringify(message))) // OOM (node --max-old-space-size=20 index.js) (20 MB) require('cosmas').default({}).info(message) // OK (node --max-old-space-size=20 index.js) require('pino').default().info(message) ``` ``` "cosmas": "^3.0.7", "pino": "^7.4.0" ``` While the pino logger logs the thing without issues, cosmas log crashes. This is caused by `JSON.parse`/`JSON.stringify`, which has surprisingly demanding memory requirements (20 MB insufficient for stringifying 4 MB JSON). This pair of functions is used in the main transform stream. The only utility now is that it allows for `pretty` option, where `inspect` is used, however it bubbles through both functions even if you don't need it (effectively just adding a newline to the output). Now the parsing/stringifying is only applied when `pretty` option is used. It is assumed that it will only be used on dev environment, where logging large data should not be an issue regarding memory safety. After the change, all the tests pass and the snippet no longer crashes on OOM.
1 parent 413af6e commit 3c6e48f

1 file changed

Lines changed: 3 additions & 7 deletions

File tree

src/streams.ts

Lines changed: 3 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -8,16 +8,12 @@ const getDefaultTransformStream = (options: CosmasOptions & { messageKey: string
88
class DefaultTransformStream extends Transform {
99
// tslint:disable-next-line:function-name
1010
public _transform(chunk: any, _encoding: string, callback: TransformCallback) {
11-
const obj = JSON.parse(chunk);
12-
let res;
13-
1411
if (options.pretty) {
15-
res = util.inspect(obj, { colors: true, showHidden: true, depth: Infinity });
12+
const res = util.inspect(JSON.parse(chunk), { colors: true, showHidden: true, depth: Infinity });
13+
this.push(`${res}\n`);
1614
} else {
17-
res = JSON.stringify(obj);
15+
this.push(chunk);
1816
}
19-
20-
this.push(`${res}\n`);
2117
callback();
2218
}
2319
}

0 commit comments

Comments
 (0)