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

Fix memory leak in waitDevice method #75

Merged
merged 3 commits into from
Nov 10, 2024
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
12 changes: 7 additions & 5 deletions src/Adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,12 +161,14 @@ class Adapter {
cancellable.push(() => clearTimeout(handler))
})

const device = await Promise.race([discoveryHandler, timeoutHandler])

for (const cancel of cancellable) {
cancel()
try {
const device = await Promise.race([discoveryHandler, timeoutHandler])
return device
} finally {
for (const cancel of cancellable) {
cancel()
}
}
return device
}

/**
Expand Down
27 changes: 27 additions & 0 deletions test/Adapter.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -142,4 +142,31 @@ describe('waitDevice', () => {

return res
})

test('clear intervals and timeouts after fail', async () => {
jest.useFakeTimers()

const adapter = new Adapter(dbus, 'hci0')

adapter.helper.children.mockResolvedValue([
'dev_11_11_11_11_11_11',
'dev_22_22_22_22_22_22',
'dev_33_33_33_33_33_33'
])

const timeout = 500
const discoveryInterval = 100

const spyClearInterval = jest.spyOn(global, 'clearInterval')
const spyClearTimeout = jest.spyOn(global, 'clearTimeout')

const waitDevicePromise = adapter.waitDevice('44:44:44:44:44:44', timeout, discoveryInterval)

jest.advanceTimersByTime(timeout)

await expect(waitDevicePromise).rejects.toThrow('operation timed out')

expect(spyClearInterval).toHaveBeenCalled()
expect(spyClearTimeout).toHaveBeenCalled()
})
})