Skip to content

Commit

Permalink
Use on-exit-leak-free
Browse files Browse the repository at this point in the history
  • Loading branch information
mcollina committed Jul 7, 2021
1 parent ff3073a commit 8580145
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 10 deletions.
35 changes: 25 additions & 10 deletions lib/transport.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,27 @@ const { join, isAbsolute } = require('path')

const ThreadStream = require('thread-stream')

function setupOnExit (stream) {
/* istanbul ignore if */
if (global.WeakRef && global.WeakMap && global.FinalizationGroup) {
// 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
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@
"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",
Expand Down

0 comments on commit 8580145

Please sign in to comment.