This repository was archived by the owner on Jun 21, 2023. It is now read-only.
Commit 3c6e48f
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
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
8 | 8 | | |
9 | 9 | | |
10 | 10 | | |
11 | | - | |
12 | | - | |
13 | | - | |
14 | 11 | | |
15 | | - | |
| 12 | + | |
| 13 | + | |
16 | 14 | | |
17 | | - | |
| 15 | + | |
18 | 16 | | |
19 | | - | |
20 | | - | |
21 | 17 | | |
22 | 18 | | |
23 | 19 | | |
| |||
0 commit comments