Skip to content

Commit

Permalink
feat(broker): await using BrokerLockItem.hold() for better resource…
Browse files Browse the repository at this point in the history
… management

```
const broker = new BrokerLock(...);

{
   await using hold = await broker.item('my-lock', { ttl: 500 }).hold();

   //lock automatically released here.
}
```
  • Loading branch information
marcj committed Jan 29, 2024
1 parent e555ac8 commit 7917fb1
Show file tree
Hide file tree
Showing 4 changed files with 43 additions and 1 deletion.
2 changes: 2 additions & 0 deletions jest-setup-runtime.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Symbol.dispose ??= Symbol("Symbol.dispose");
Symbol.asyncDispose ??= Symbol("Symbol.asyncDispose");
3 changes: 3 additions & 0 deletions packages/broker/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,9 @@
},
"testMatch": [
"**/tests/**/*.spec.ts"
],
"setupFiles": [
"<rootDir>/../../jest-setup-runtime.js"
]
},
"gitHead": "56081823b559bb68b77a8781957af5d9c2e019a7"
Expand Down
24 changes: 24 additions & 0 deletions packages/broker/src/broker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
15 changes: 14 additions & 1 deletion packages/broker/tests/broker.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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());

Expand Down Expand Up @@ -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 () => {
Expand Down

0 comments on commit 7917fb1

Please sign in to comment.