From: Jérôme Benoit Date: Mon, 14 Aug 2023 18:06:08 +0000 (+0200) Subject: feat: add support for async kill handler X-Git-Tag: v2.6.26~32 X-Git-Url: https://git.piment-noir.org/?a=commitdiff_plain;h=07588f306649b9df235aaf65de4842e99532ed6a;p=poolifier.git feat: add support for async kill handler Signed-off-by: Jérôme Benoit --- diff --git a/src/worker/abstract-worker.ts b/src/worker/abstract-worker.ts index 512a822d..493ca0b2 100644 --- a/src/worker/abstract-worker.ts +++ b/src/worker/abstract-worker.ts @@ -326,8 +326,15 @@ export abstract class AbstractWorker< */ protected handleKillMessage (message: MessageValue): void { this.stopCheckActive() - this.opts.killHandler?.() - this.emitDestroy() + if (isAsyncFunction(this.opts.killHandler)) { + (this.opts.killHandler?.() as Promise) + .then(() => this.emitDestroy()) + .catch(EMPTY_FUNCTION) + } else { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + this.opts.killHandler?.() as void + this.emitDestroy() + } } /** diff --git a/src/worker/worker-options.ts b/src/worker/worker-options.ts index 97d4a30a..f829dcb3 100644 --- a/src/worker/worker-options.ts +++ b/src/worker/worker-options.ts @@ -20,7 +20,7 @@ export type KillBehavior = keyof typeof KillBehaviors /** * Handler called when a worker is killed. */ -export type KillHandler = () => void +export type KillHandler = () => void | Promise /** * Options for workers. diff --git a/tests/worker/abstract-worker.test.js b/tests/worker/abstract-worker.test.js index 6582961f..46370777 100644 --- a/tests/worker/abstract-worker.test.js +++ b/tests/worker/abstract-worker.test.js @@ -136,14 +136,15 @@ describe('Abstract worker test suite', () => { expect(worker.opts.killHandler.calledOnce).toBe(true) }) - // it('Verify that async kill handler is called when worker is killed', () => { - // const worker = new ClusterWorker(() => {}, { - // killHandler: sinon.stub().resolves() - // }) - // worker.isMain = false - // worker.handleKillMessage() - // expect(worker.opts.killHandler.calledOnce).toBe(true) - // }) + it('Verify that async kill handler is called when worker is killed', () => { + const killHandlerStub = sinon.stub().returns() + const worker = new ClusterWorker(() => {}, { + killHandler: async () => Promise.resolve(killHandlerStub()) + }) + worker.isMain = false + worker.handleKillMessage() + expect(killHandlerStub.calledOnce).toBe(true) + }) it('Verify that handleError() method works properly', () => { const error = new Error('Error as an error')