Skip to content

Commit

Permalink
fix: pool.destroy to clean up async resources (#86)
Browse files Browse the repository at this point in the history
  • Loading branch information
AriPerkkio authored Apr 21, 2024
1 parent f86e829 commit 994802b
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
5 changes: 3 additions & 2 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1161,8 +1161,9 @@ class Tinypool extends EventEmitterAsyncResource {
})
}

destroy() {
return this.#pool.destroy()
async destroy() {
await this.#pool.destroy()
this.emitDestroy()
}

get options(): FilledOptions {
Expand Down
46 changes: 43 additions & 3 deletions test/pool-destroy.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import { createHook } from 'async_hooks'
import { dirname, resolve } from 'path'
import { Tinypool } from 'tinypool'
import { fileURLToPath } from 'url'

const sleep = async (num: number) =>
await new Promise((res) => setTimeout(res, num))

const __dirname = dirname(fileURLToPath(import.meta.url))

test('can destroy pool while tasks are running', async () => {
Expand All @@ -24,3 +22,45 @@ test('destroy after initializing should work (#43)', async () => {
expect(pool.run({})).rejects.toThrow(/Terminating worker thread/)
setImmediate(() => pool.destroy())
})

test('cleans up async resources', async () => {
let onCleanup = () => {}
const waitForCleanup = new Promise<void>((r) => (onCleanup = r))
const timeout = setTimeout(() => {
throw new Error('Timeout waiting for async resource destroying')
}, 2_000).unref()

const ids = new Set<number>()

const hook = createHook({
init(asyncId, type) {
if (type === 'Tinypool') {
ids.add(asyncId)
}
},
destroy(asyncId) {
if (ids.has(asyncId)) {
ids.delete(asyncId)
onCleanup()
clearTimeout(timeout)
}
},
})
hook.enable()

const pool = new Tinypool({
filename: resolve(__dirname, 'fixtures/eval.js'),
maxThreads: 1,
minThreads: 1,
})

await pool.run('42')

expect(ids.size).toBe(1)

await pool.destroy()
await waitForCleanup

expect(ids.size).toBe(0)
hook.disable()
})

0 comments on commit 994802b

Please sign in to comment.