diff --git a/packages/broker/package.json b/packages/broker/package.json index eaeaab104..543bda6e3 100644 --- a/packages/broker/package.json +++ b/packages/broker/package.json @@ -58,6 +58,9 @@ }, "testMatch": [ "**/tests/**/*.spec.ts" + ], + "setupFiles": [ + "/../../jest-setup-runtime.js" ] }, "gitHead": "56081823b559bb68b77a8781957af5d9c2e019a7" diff --git a/packages/broker/src/broker.ts b/packages/broker/src/broker.ts index ce2c72359..a0be6a2ba 100644 --- a/packages/broker/src/broker.ts +++ b/packages/broker/src/broker.ts @@ -272,10 +272,34 @@ export class BrokerLockItem { ) { } + async [Symbol.asyncDispose] () { + await this.release(); + } + + /** + * Disposable way of acquiring a lock. Automatically releases the lock when the returned object is disposed. + * + * @example + * ```typescript + * async function doSomething() { + * async using hold = lock.hold(); + * + * // do stuff + * + * // when out of scope, lock is automatically released. + * } + * ``` + */ + async hold() { + await this.acquire(); + return this; + } + /** * Returns true if the current lock object is the holder of the lock. * * This does not check whether the lock is acquired by someone else. + * Use isReserved() if you want to check that. */ get acquired(): boolean { return this.releaser !== undefined; diff --git a/packages/broker/tests/broker.spec.ts b/packages/broker/tests/broker.spec.ts index f62203c2c..4163dece3 100644 --- a/packages/broker/tests/broker.spec.ts +++ b/packages/broker/tests/broker.spec.ts @@ -106,6 +106,19 @@ test('lock', async () => { expect(lock1.acquired).toBe(false); }); +test('lock dispose', async () => { + const lock = new BrokerLock(await adapterFactory()); + + const lock1 = lock.item('my-lock', { ttl: 500 }); + + { + await using hold = await lock1.hold(); + expect(lock1.acquired).toBe(true); + } + + expect(lock1.acquired).toBe(false); +}); + test('lock2', async () => { const lock = new BrokerLock(await adapterFactory()); @@ -171,7 +184,7 @@ test('queue message process exactly once options for broker channel', async () = await channel.produce({ id: 3, username: 'peter' }); - expect(consumed).toBe(1) + expect(consumed).toBe(1); }); test('queue message process exactly once with deduplication interval options for broker channel', async () => {