Skip to content
New issue

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

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

Already on GitHub? # 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 2 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('legacy')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is there a specific reason for using the legacy implementation?


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, 'clearInterval')
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think that there's a mistake on this line.


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

jest.advanceTimersByTime(500)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you can specify here the timeout variable that you declared

Suggested change
jest.advanceTimersByTime(500)
jest.advanceTimersByTime(timeout)


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

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