Skip to content

Commit

Permalink
Merge 28ce1ba into ff3073a
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Jul 7, 2021
2 parents ff3073a + 28ce1ba commit ade74ff
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 11 deletions.
4 changes: 4 additions & 0 deletions docs/api.md
Expand Up @@ -939,6 +939,10 @@ const transports = pino.transport({
pino(transports)
```

If `WeakRef`, `WeakMap` and `FinalizationRegistry` are available in the current runtime (v14.5.0+), then the thread
will be automatically terminated in case the stream or logger goes out of scope.
The `transport()` function adds a listener to `process.on('exit')` to ensure the worker is flushed and all data synced
before the process exits.

For more on transports, how they work, and how to create them see the [`Transports documentation`](/docs/transports.md).

Expand Down
35 changes: 25 additions & 10 deletions lib/transport.js
Expand Up @@ -6,6 +6,27 @@ const { join, isAbsolute } = require('path')

const ThreadStream = require('thread-stream')

function setupOnExit (stream) {
/* istanbul ignore next */
if (global.WeakRef && global.WeakMap && global.FinalizationRegistry) {
// This is leak free, it does not leave event handlers
const onExit = require('on-exit-leak-free')

onExit.register(stream, autoEnd)

stream.on('close', function () {
onExit.unregister(stream)
})
} else {
const fn = autoEnd.bind(null, stream)
process.on('exit', fn)

stream.on('close', function () {
process.removeListener('exit', fn)
})
}
}

function buildStream (filename, workerData, workerOpts) {
const stream = new ThreadStream({
filename,
Expand All @@ -18,21 +39,15 @@ function buildStream (filename, workerData, workerOpts) {
stream.unref()

if (workerOpts.autoEnd !== false) {
// TODO possibly use FinalizationGroup to automatically remove
// this listener if the stream goes out scope.
process.on('exit', autoEnd)

stream.on('close', function () {
process.removeListener('exit', autoEnd)
})
setupOnExit(stream)
}
})

return stream
}

function autoEnd () {
stream.end()
}
function autoEnd (stream) {
stream.end()
}

function transport (fullOptions) {
Expand Down
3 changes: 2 additions & 1 deletion package.json
Expand Up @@ -101,11 +101,12 @@
"fast-redact": "^3.0.0",
"fast-safe-stringify": "^2.0.7",
"get-caller-file": "^2.0.5",
"on-exit-leak-free": "^0.1.0",
"pino-abstract-transport": "^0.2.0",
"pino-std-serializers": "^4.0.0",
"quick-format-unescaped": "^4.0.3",
"sonic-boom": "^2.1.0",
"thread-stream": "^0.10.0"
"thread-stream": "^0.11.0"
},
"tsd": {
"directory": "test/types"
Expand Down

0 comments on commit ade74ff

Please sign in to comment.