Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prevent memory leak when writing before ready #183

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 10 additions & 3 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,12 @@ function openFile (file, sonic) {
sonic.emit('ready')
}

if (sonic._reopening) {
if (sonic._reopening || sonic.destroyed) {
return
}

// start
if (!sonic._writing && sonic._len > sonic.minLength && !sonic.destroyed) {
if ((!sonic._writing && sonic._len > sonic.minLength) || sonic._flushPending) {
sonic._actualWrite()
}
}
Expand Down Expand Up @@ -103,6 +103,7 @@ function SonicBoom (opts) {
this._ending = false
this._reopening = false
this._asyncDrainScheduled = false
this._flushPending = false
this._hwm = Math.max(minLength || 0, 16387)
this.file = null
this.destroyed = false
Expand Down Expand Up @@ -337,16 +338,22 @@ function writeBuffer (data) {
}

function callFlushCallbackOnDrain (cb) {
this._flushPending = true
const onDrain = () => {
// only if _fsync is false to avoid double fsync
if (!this._fsync) {
fs.fsync(this.fd, cb)
fs.fsync(this.fd, (err) => {
this._flushPending = false
cb(err)
})
} else {
this._flushPending = false
cb()
}
this.off('error', onError)
}
const onError = (err) => {
this._flushPending = false
cb(err)
this.off('drain', onDrain)
}
Expand Down
43 changes: 43 additions & 0 deletions test/flush.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -373,4 +373,47 @@ function buildTests (test, sync) {

t.ok(stream.write('hello world\n'))
})

test('call flush cb when writing and trying to flush before ready (on async)', (t) => {
t.plan(4)

const fakeFs = Object.create(fs)
const SonicBoom = proxyquire('../', {
fs: fakeFs
})

fakeFs.open = fsOpen

const dest = file()
const stream = new SonicBoom({
fd: dest,
// only async as sync is part of the constructor so the user will not be able to call write/flush
// before ready
sync: false,

// to not trigger write without calling flush
minLength: 4096
})

stream.on('ready', () => {
t.pass('ready emitted')
})

function fsOpen (...args) {
process.nextTick(() => {
// try writing and flushing before ready and in the middle of opening
t.pass('fake fs.open called')
t.ok(stream.write('hello world\n'))

// calling flush
stream.flush((err) => {
if (err) t.fail(err)
else t.pass('flush cb called')
})

fakeFs.open = fs.open
fs.open(...args)
})
}
})
}