Skip to content

Commit

Permalink
Fix memory leak in waitDevice method (#75)
Browse files Browse the repository at this point in the history
* Fix memory leak in waitDevice method

* add unit test for waitDevice method to cover memory leak scenario

* apply requested changes to adapter spec
  • Loading branch information
Raffone17 authored Nov 10, 2024
1 parent f426428 commit 79213f0
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 5 deletions.
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()
})
})

0 comments on commit 79213f0

Please sign in to comment.